Chris Cant - Writing Windows WDM Device Drivers

Здесь есть возможность читать онлайн «Chris Cant - Writing Windows WDM Device Drivers» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Lawrence, Kansas 66046, ISBN: , Издательство: R & D Books, Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Writing Windows WDM Device Drivers: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Writing Windows WDM Device Drivers»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Writing Windows WDM Device Drivers — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Writing Windows WDM Device Drivers», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

The extern "C" directive is used to ensure that the compiler uses the correct linkage to reference kernel routines. The driver entry point, DriverEntry, must have extern "C" to ensure it is found.

The #pragma code_seg preprocessor directive is used to force routines into certain code segments. The INIT code segment is discarded after the driver has initialized itself, and the PAGE segment contains code that can be paged out of kernel memory. Using segments helps to lower a driver's memory usage.

Only routines that run at PASSIVE_LEVEL IRQL can be paged from memory. All the dispatch routines in the Wdm1 driver operate at PASSIVE_LEVEL so they can be put in the PAGE segment. Routines that are not given a segment are never paged from memory.

If writing C code, you can use the alloc_text pragma instead to set the code segment of named routines.

Header Files

The Wdm1.h header file is included in all the source files. Wdm1.h first includes the main DDK header file for WDM projects, wdm.h. If you were writing NT style drivers, you would use the similar ntddk.h. You may find that you need to include some other DDK header files for particular types of drivers.

Next, a device extension structure is defined. This structure is where a driver can hold any information it needs about a device (more on this later).

The GUIDs.H header defines a Globally Unique Identifier (GUID) for the Wdm1 device interface. The next chapter shows how this GUID is used by Win32 user mode applications to find Wdm1 devices. I used the guidgen utility to generate this GUID in the DEFINE_GUID format. I defined several consecutive GUIDs at once for all the examples in this book.

Finally, the IOCTL.H header defines the IOCTL codes that Wdm1 supports. These are explained in Chapter 7.

Driver Entry Module

Init.cpp contains the driver entry point. Listing 4.5 shows this routine, which must be called DriverEntry and use C linkage.

The Plug and Play Manager locates the correct driver and calls DriverEntry to initialize the driver (at PASSIVE_IRQL). In DriverEntry, the main job is to store a series of call back routine pointers in the passed DriverObject. This DRIVER_OBJECT structure is used by the operating system to store any information relevant to the driver. A separate structure is used later to store information about each device.

In Wdm1, DriverEntry sets a whole series of callback routines. These routines are called by the kernel when a device is added and when IRPs need to be sent to the driver. The WdmUnload routine, later in Init.cpp, does nothing at this stage.

Finally, DriverEntry returns an NTSTATUS value of STATUS_SUCCESS. Almost all driver routines have to return a NTSTATUS value, from the list in the NTSTATUS.H DDK header file. Note that these error codes do not correspond to Win32 error codes. The kernel does the necessary mapping between the two types of error code.

Listing 4.5 DriverEntry routine

extern "C"

NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath) {

NTSTATUS status = STATUS_SUCCESS;

//…

// Export other driver entry points…

DriverObject->DriverExtension->AddDevice = Wdm1AddDevice;

DriverObject->DriverUnload = Wdm1Unload;

DriverObject->MajorFunction[IRP_MJ_CREATE] = Wdm1Create;

DriverObject->MajorFunction[IRP_MJ_CLOSE] = Wdm1Close;

DriverObject->MajorFunction[IRP_MJ_PNP] = Wdm1Pnp;

DriverObject->MajorFunction[IRP_MJ_POWER] = Wdm1Power;

DriverObject->MajorFunction[IRP_MJ_READ] = Wdm1Read;

DriverObject->MajorFunction[IRP_MJ_WRITE] = Wdm1Write;

DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = Wdm1DeviceControl;

DriverObject->MajorFunction[IRP_MJ_SYSTEM_CONTROL] = Wdm1SystemControl;

// …

return status;

}

Version Resource

Wdm1.rc simply defines a version resource block with version and copyright information.

Accessing the Registry

The RegistryPath parameter to DriverEntry contains the registry key of the driver. The Wdm1 code does not currently use its RegistryPath parameter. However, it is common for drivers to use its registry key to store parameters for the whole driver. Therefore, I present the ReadReg routine shown in Listing 4.6. This reads two values from the driver's registry path Parameters subkey. The first value is a ULONG obtained from the value named UlongValue. The second value is a string obtained from the default value for the Parameters key.

Eventually ReadReg needs to call the RtlQueryRegistryValues kernel routine to read both the registry values in one fell swoop. One of the parameters is the absolute registry path, as a NULL-terminated wide string. The driver registry path is supplied in a UNICODE_STRING structure. Although this contains a wide string buffer, it may not necessarily be NULL-terminated. Unfortunately, this means that we have to laboriously make a copy of the string, simply to add on that dratted NULL-terminating character.

The first section of ReadReg does this job. It works out the length of buffer required and uses ExAllocatePool to allocate the memory from the paged pool. The RtlCopyMemory function is used to copy the bulk of the string over and RtlZeroMemory zeroes that all-important last character. You can do the copy and zero by hand if you want, though it should be more efficient to call the kernel functions.

Listing 4.6 ReadReg

void ReadReg(IN PUNICODE_STRING DriverRegistryPath) {

// Make zero terminated copy of driver registry path

USHORT FromLen = DriverRegistryPath->Length;

PUCHAR wstrDriverRegistryPath = (PUCHAR)ExAnocatePool(PagedPool, FromLen+sizeof(WCHAR));

if( wstrDriverRegistryPath==NULL) return;

RtlCopyMemory(wstrDriverRegistryPath, DriverRegistryPath->Buffer, FromLen);

RtlZeroMemory(wstrDriverRegistryPath+FromLen, sizeof(WCHAR));

// Initialise our ULONG and UNICODE_STRING values

ULONG UlongValue = –1;

UNICODE_STRING UnicodeString;

UnicodeString.Buffer = NULL;

UnicodeString.MaximumLength = 0;

UnicodeString.Length = 0;

// Build up our registry query table

RTL_QUERY_REGISTRY_TABLE QueryTable[4];

RtlZeroMemory(QueryTable, sizeof(QueryTable));

QueryTable[0].Name = L"Parameters";

QueryTable[0].Flags = RTL_QUERY_REGISTRY_SUBKEY;

QueryTable[0].EntryContext = NULL;

QueryTable[1].Name = L"UlongValue";

QueryTable[1].Flags = RTL_QUERY_REGISTRY_DIRECT;

OueryTable[1].EntryContext = &UlongValue;

QueryTable[2].Name = L""; // Default value

QueryTable[2].Flags = RTL_QUERY_REGISTRY_DIRECT;

QueryTable[2].EntryContext = &UnicodeString;

// Issue query

NTSTATUS status = RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE, (PWSTR)wstrDriverRegistryPath, QueryTable, NULL, NULL);

// Print results

DebugPrint("ReadReg %x: UlongValue %x UnicodeString %T", status.UlongValue, &UnicodeString);

// Do not forget to free buffers

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Writing Windows WDM Device Drivers»

Представляем Вашему вниманию похожие книги на «Writing Windows WDM Device Drivers» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Writing Windows WDM Device Drivers»

Обсуждение, отзывы о книге «Writing Windows WDM Device Drivers» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x