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
- Автор:
- Издательство:R & D Books
- Жанр:
- Год:неизвестен
- Город:Lawrence, Kansas 66046
- ISBN:0-87930-565-7
- Рейтинг книги:5 / 5. Голосов: 1
-
Избранное:Добавить в избранное
- Отзывы:
-
Ваша оценка:
- 100
- 1
- 2
- 3
- 4
- 5
Writing Windows WDM Device Drivers: краткое содержание, описание и аннотация
Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Writing Windows WDM Device Drivers»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.
Writing Windows WDM Device Drivers — читать онлайн бесплатно полную книгу (весь текст) целиком
Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Writing Windows WDM Device Drivers», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
Figure 5.2 WinObj tool screenshot
The Wdm1 driver could have given its first device object a kernel name of \device\ Wdm1device0 and called IoCreateSymbolicLink to create a symbolic link with the name \??\Wdm1dev1. A Win32 program would then have been able to open \\.\Wdm1dev1 using CreateFile.
Note that C strings represent each \ character as "\\", so you would have to pass " \\\\.\\Wdm1dev1" to CreateFile .
If this technique is used, you must keep track of how many devices are in use, so you can generate the correct names. If you use a global variable to keep the device count, you must use it carefully to ensure that simultaneous accesses do not corrupt its value. Achieve this using the InterlockedIncrement function that atomically increments a LONG value. This can be run at any IRQL and on paged memory. There are companion decrement, exchange, and compare functions.
Explicit kernel and symbolic link names are used most often in NT style drivers, which create devices in their DriverEntry routine. In this case, counting devices is easy, as you can be sure that no other part of your code will be trying to increment the device count.
You can use the QueryDosDevice Win32 function to get a list of all the symbolic link names currently available. For each symbolic link, you can call QueryDosDevice again to find the kernel name. QueryDosDevice is supposed to run in Windows 98, but I did not succeed in getting it to work. In NT and W2000, you can use the DefineDosDevice Win32 function to change symbolic links. You can experiment with both these commands using the dosdev utility in the W2000 DDK.
Device Interfaces
The Wdm1 driver uses a device interface to make its devices visible to Win32 programs. The idea is that each Wdm1 device makes a defined Application Programmer Interface (API) available. A Globally Unique Identifier (GUID) is used to identify this interface.
The device interface that each Wdm1 device exposes is the set of commands that a Win32 programmer can use to access the device. A Wdm1 device responds to Win32 CreateFile, ReadFile, WriteFile, DeviceIoControl , and CloseHandle calls in a defined way. For example, a Wdm1 device is nonexclusive, so more than one thread can open it at the same time.
The Wdm1 driver's job is to implement a memory buffer that is shared by all the Wdm1 devices. Any writes extend the buffer, if necessary. Reads do not extend the buffer. Four IOCTLs are supported: Zero buffer, remove buffer, get buffer size, and get buffer.
One benefit of device interfaces is that another driver could be written that also implements the Wdm1 API. As long as it does this faithfully, there is no reason why a Win32 program should notice the difference between the new driver and Wdm1.
While it seems unlikely that the Wdm1 device interface will be copied by others, this technique is very useful for other types of drivers. For example, audio miniport drivers should implement the IMiniport COM interface. This is identified using the IID_IMiniport GUID and means that the driver implements two functions, GetDescription and DataRangeIntersection .
Implementing a device interface for Wdm1 devices is straightforward. First, a new 16-byte GUID must be generated using the guidgen tool. Then, include code to register the Wdm1 device interface for each Wdm1 FDO device object.
Generating GUIDs
To get a suitable new GUID, run the guidgen tool in the Platform SDK or the VC++ executables directory. Figure 5.3 shows the window that appears. guidgen can generate GUIDs in formats suitable for four different uses. For driver header file definitions, choose the DEFINE_ GUID(…) option. Pressing the Copy button copies the necessary code to the clipboard. Paste it into your header and amend the text <> to define your own identifier.
Microsoft says that all GUIDs that guidgen generates are unique.
If you need to allocate a series of identifiers, press the New GUID button as often as necessary and copy each one to the relevant header file. Each new GUID increments the last digit of the first eight characters of the GUID. For example, the next GUID after the one shown in the screenshot starts {F4886541… }. In this book, I often use the form {F4886540… } as an abbreviation for the full GUID {F4886540-749E-11d2-B677-00C0DFE4C1F3}.
Figure 5.3 guidgen tool
The definition of WDM1_GUID in GUIDs.h is shown in Listing 5.3. There is a final twist in the tail for GUID definitions. One of the driver modules, Pnp.cpp in Wdm1, must have the following preprocessor directive before including GUIDs.h to formally declare WDM1_GUID. [12] If you are only compiling in W2000, you can include initguid.h instead.
#define INITGUID
Listing 5.3 WDM1_GUID definition in GUIDs.h
// Wdm1 device interface GUID
// {C0CF0640-5F6E-11d2-B677-00C0DFE4C1F31
DEFINE_GUID(WDM1_GUID, 0xc0cf0640, 0x5f6e, 0x11d2, 0xb6, 0x77, 0x0, 0xc0, 0xdf, 0xe4, 0xc1, 0xf3);
Device Interface Registration
Wdm1 does not give a kernel device name to its device object and does not use IoCreateSymbolicLink to create a device name accessible to Win32 programs. Instead, the Wdm1 AddDevice routine calls IoRegisterDeviceInterface to register its interface as shown in Listing 5.4. It does this after creating its device but before attaching it to the device stack. IoRegisterDeviceInterface creates a Win32 symbolic link name connection to the Wdm1 device object. This is stored in the device extension ifSymLinkNamefield .
The Wdm1AddDevice code checks the return value from IoRegisterDeviceInterface. If this call fails, it tidies up properly by deleting the FDO and returning the status error code.
The final step is to enable the device interface by calling IoSetDeviceInterfaceState, at IRQL PASSIVE_LEVEL In subsequent drivers, the device interface is only enabled when the PnP Start Device message has been received.
Listing 5.4 Wdm1 Pnp.cpp Device Interface code
// Register and enable our device interface
status = IoRegisterDeviceInterface(pdo, &WDM1_GUID, NULL, &dx->ifSymLinkName);
if (!NT_SUCCESS(status)) {
IoDeleteDevice(fdo);
return status;
}
IoSetDeviceInterfaceState(&dx->ifSymLinkName, TRUE);
Table 5.3 IoRegisterDeviceInterface function
NTSTATUS IoRegisterDeviceInterface |
|
|---|---|
| Parameter | Description |
IN PDEVICE_OBJECT PhysicalDeviceObject |
The device PDO |
IN CONST GUID *InterfaceClassGuid |
The GUID being registered |
IN PUNICODE_STRING ReferenceString |
Usually NULL. A reference string becomes part of the interface name and so can be used to distinguish between different interfaces to the same device. |
OUT PUNICODE_STRING SymbolicLinkName |
The output interface symbolic link name. Do not forget to free the Unicode string buffer using RtlFreeUnicodeString when finished with it. |
The code in Wdm1Pnp to handle device removal has to be altered, as well. First, the device interface has to be disabled. Then, it must free the memory buffer allocated for the interface symbolic link name. It does not have to Unregister the device interface.
IoSetDeviceInterfaceState(&dx->ifSymLinkName, FALSE);
Интервал:
Закладка:
Похожие книги на «Writing Windows WDM Device Drivers»
Представляем Вашему вниманию похожие книги на «Writing Windows WDM Device Drivers» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Writing Windows WDM Device Drivers» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.
