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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

if (UnicodeString.Buffer!=NULL) ExFreePool(UnicodeString.Buffer);

ExFreePool(wstrDriverRegistryPath);

}

The UNICODE_STRING Structure

This is how the UNICODE_STRING type is defined.

typedef struct _UNICODE_STRING {

USHORT Length;

USHORT MaximumLength;

PWSTR Buffer;

} UNICODE_STRING, *PUNICODE_STRING;

The Buffer field points to a wide 16-bit character buffer. The character string is not usually NULL-terminated. Instead, the Length field gives the current size of the string in bytes. The MaximumLength field gives the maximum size of the string that can fit in the buffer in bytes. This design is used to avoid reallocating string buffers too often. However, it does make manipulating Unicode strings a bit awkward. Table 4.6 shows all the kernel routines that you can use with Unicode strings.

Just in case you were interested, you do not have to use these kernel routines to access Unicode strings. You can fiddle with a string structure however you like, as long as it is in a valid format when passed to the kernel.

Table 4.6 UNICODE_STRING functions

RtlAnsiStringToUnicodeString Converts an ANSI string to a Unicode string, optionally allocating a buffer.
RtlAppendUnicodeStringToString Append one Unicode string to another, up to the length ofthe destination buffer.
RtlAppendUnicodeToString Append a wide string to a Unicode string, up to the length of the destination buffer.
RtlCompareUnicodeString Compares two Unicode strings, optionally case-insensitive.
RtlCopyUnicodeString Copies one Unicode string to another, up to the length of the destination buffer.
RtlEqualUnicodeString Returns TRUE if the two Unicode strings are equal, optionally case-insensitive.
RtlFreeUnicodeString Frees the Unicode string buffer memory from the pool.
RtlInitUnicodeString Sets the Unicode string buffer to point to the given wide string, and sets the length fields to match.
RtlIntegerToUnicodeString Converts a ULONG value to a Unicode string in the specified base. The string buffer must have been initialized beforehand.
RtlPrefixUnicodeString† Sees if one Unicode string is a prefix of another, optionally case-insensitive.
RtlUnicodeStringToAnsiString Converts a Unicode string into ANSI. If you ask for the destination ANSI buffer to be allocated, free it eventually with RtlFreeAnsiString.
RtlUnicodeStringToInteger Converts a Unicode string to an integer.
RtlUpcaseUnicodeString† Converts a Unicode string into uppercase, optionally allocating a buffer.

†NT/W2000 only

ReadReg declares the variables that will receive the values from the registry. For a UNICODE_STRING , its Buffer, Length, and MaximumLength fields have to be initialized. In this case, these fields are initialized to NULL and zero. The call to RtlQueryRegistryValues will allocate a Buffer and set the length fields.

In most cases, a UNICODE_STRING's buffer needs to be set up correctly. If you want to store an unchanging wide string value in a Unicode string, use the RtlInitUnicodeString function. The Unicode string Buffer is set to point to the passed string and the Length and Maximum-Length strings are set to the length of the string [10] Be careful if initializing strings in paged code segments or code segments that are discarded after initialization. The Buffer data has the attributes of the underlying code segment and so may not be available when you want to access it. Chapter 14 gives an example in which I initially got this wrong. .

RtlInitUnicodeString(&UnicodeString, L"\\Device\\Wdm1");

If you wish to work with the contents of a Unicode string, you need to provide the wide string buffer. Use code like this.

const int MAX_CHARS = 30;

UNICODE_STRING UnicodeString;

WCHAR UnicodeStringBuffer[MAX_CHARS];

UnicodeString.Buffer = UnicodeStringBuffer;

UnicodeString.MaximumLength = MAX_CHARS*2;

UnicodeString.Length = 0;

In this case, the buffer is on the stack. If you want to use the Unicode string after this routine has completed, you must allocate the buffer from pool memory. Do not forget to free this memory once you have finished using the string.

Calling RtlQueryRegistryValues

You must send a query table array to RtlQueryRegistryValues . This array details the actions that you want to do. The last entry in the query table must be zeroed to indicate the end of the list. This is achieved when the entire query table is zeroed using RtlZeroMemory in ReadReg .

There is a wide range of options available when querying the registry. The Flags field in each query table element indicates the action you want to do. The first query listed previously uses RTL_QUERY_REGISTRY_SUBKEY, which means that the Name field contains the subkey for subsequent queries.

The following queries both set the Flags field to RTL_QUERY_REGISTRY_DI RECT. In this case, the Name field contains the registry value name, and the EntryContext field contains a pointer to the variable to receive the value. You have to trust that no one has fiddled with the value types so that a string is returned when you were expecting a ULONG.

A safer approach (not used here) is to pass the name of a callback routine in the QueryRoutine field and set the Flags field to zero. Your routine is called for each value found, and indicates the type of the found value.

The remaining parameters to RtlQueryRegistryValues give even more flexibility. RTL_REGISTRY_ABSOLUTE indicates that the Path parameter is an absolute registry path. Various other useful options can be given (e.g., if the Path is relative to the HKLM\Systcm\CurrentControlSet\Services key).

RtlQueryRegistryValues only returns STATUS_SUCCESS if all the queries were processed correctly and all the registry values were found. The code in ReadReg simply displays the return status and the values retrieved. If using this routine for real, you will probably want to store the values in global variables.

Operating system version

You can use a registry setting to determine at run time whether you are running in W98 or not. In NT and W2000 the following registry value is available, HKLM\System\CurrentControlSet\Control\ProductOptions\ProductType. The value is "WinNT" for the Workstation/Professional Windows version and either "LanmanNT" or "ServerNT" for the Server/Enterprise version. In W98 this registry value should not be available.

Installing Wdm1

That's enough on the Wdm1 code so far. The compiled driver, Wdm1.sys, is provided on the CD in free and checked build versions. However, you can recompile it if you wish.

Normally, Windows detects when a device is installed and prompts for the necessary drivers if they cannot be found already in the system. Full details of the driver selection process are given later.

For the virtual Wdm1 device, use the Control Panel "Add New Hardware" applet wizard. The process is basically the same for Windows 98 and Windows 2000.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x