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

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

Интервал:

Закладка:

Сделать

RtlFreeUnicodeString(&dx->ifSytnLinkName);

Device Interface Notes

As mentioned in the last chapter, registering a device interface creates a registry entry in the HKLM\System\CurrentControlSet\Control\DeviceClasses key. A subkey named after the GUID and further subkeys for each device implements that GUID. Drivers can use IoOpenDeviceInterfaceRegistryKey to open a handle to this registry key. For example, you might want to add a FriendlyName value to this key using an INF file AddInterface section, as described in Chapter 11. Win32 applications can use SetupDiOpenDeviceInterfaceRegKey to open this same key and retrieve the friendly name.

Device interface registrations can be removed from user mode, if necessary.

A driver can register that a device supports more than one device interface if desired.

IoGetDeviceInterfaces can be used by a driver to find a list of symbolic links to devices that support a specific device interface.

Behind the scenes, Windows generates a kernel device name for your device. This might be something like \devi ce\004059. The symbolic link name generated by IoRegisterDeviceInterface looks like \DosDevices\000000000000001c#{c0cf0640…}. The WinObj entry for the symbolic link looks like \??\Root#UNKN0WN#0000#{C0CF0640…}.

Win32 Device Interface Access

We are ready — at last — to access a Wdm1 device. The Wdm1Test program opens a connection to the Wdm1 driver and puts it through its paces. Remember that all the calls in this section are to Win32 routines, not to the kernel.

The source code for the Wdm1Test program is in the Wdm1\exe directory. The book software has a Visual Studio WDM Book workspace, which includes a project for the Wdm1Test program. The Wdm1Test code in Wdm1Test.cpp is listed at the end of the chapter.

Wdm1Test is a standard Win32 console application. When run, it appears in a DOS box. As it is a standard Win32 program, you can debug it in Visual Studio as normal (e.g., step through the code).

There are two points to note about the Wdm1Test project. The first is that it includes the c:\98ddk\inc\win98\setupapi.h header file. The VC++ 5 version of this file is seriously out of date, so the code specifically includes the Windows 98 DDK version. The second special setting required is to ensure that c:\98ddk\lib\i386\free\setupapi.lib is listed in the Link property page Output/library modules section of the Project settings.

Getting a Device's Interface Name

The GetDeviceViaInterface routine in Wdm1Test.cpp opens a handle to a device, given the device interface's GUID, as shown in Listing 5.5. GetDeviceViaInterface has a second parameter, instance, which is the zero-based index into the count of available devices. The total number of devices cannot be determined in advance; simply call GetDeviceViaInterface until NULL is returned.

The Wdm1Test main function calls GetDeviceViaInterface with WDM1_GUID and 0 as parameters to open the first available Wdm1 device. Special steps must be taken again to ensure that WDM1_GUID is declared properly. In one module #include "initguid.h" before including the GUID header file.

Listing 5.5 GetDeviceViaInterface

HANDLE GetDeviceViaInterface(GUID* pGuid, DWORD instance) {

// Get handle to relevant device information set

HDEVINFO info = SetupDiGetClassDevs(pGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);

if (info==INVALID_HANDLE_VALUE) {

printf("No HDEVINFO available for this GUID\n");

return NULL;

}

// Get interface data for the requested instance

SP_INTERFACE_DEVICE_DATA ifdata;

ifdata.cbSize = sizeof(ifdata);

if (!SetupDiEnumDeviceInterfaces(info, NULL, pGuid, instance, &ifdata)) {

printf("No SP_INTERFACE_DEVICE_DATA available for this GUID instance \n");

SetupDiDestroyDeviceInfoList(info);

return NULL;

}

// Get size of symbolic link name

DWORD ReqLen;

SetupDiGetDeviceInterfaceDetail(info, &ifdata, NULL, 0, &ReqLen, NULL);

PSP_INTERFACE_DEVICE_DETAIL_DATA ifDetail = (PSP_INTERFACE_DEVICE_DETAIL_DATA)(new char[ReqLen]);

if (ifDetail==NULL) {

SetupDiDestroyDeviceInfoList(info);

return NULL;

}

// Get symbolic link name

ifDetail->cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA);

if (!SetupDiGetDeviceInterfaceDetail(info, &ifdata, ifDetail, ReqLen, NULL, NULL)) {

SetupDiDestroyDeviceInfoList(info);

delete ifDetail;

return NULL;

}

printf("Symbolic link is %s\n",ifDetail->DevicePath):

// Open file

HANDLE rv = CreateFile(ifDetail->DevicePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

delete ifDetail;

SetupDiDestroyDevicelnfoList(info);

return rv;

}

The Win32 call to SetupDiGetClassDevs opens a "device information set" about devices with the specified GUID. The DIGCF_PRESENT and DIGCF_INTERFACEDEVICE flags ensure that only devices that are present are found.

SetupDiEnumDeviceInterfaces is then called to retrieve a SP_INTERFACE_DEVICE_DATA context structure of information about the device instance in which you are interested. GetDeviceViaInterface tries to retrieve information about only one instance, but you might want to find all instances by incrementing the MemberIndex parameter from 0 until SetupDiEnumDeviceInterfaces fails and GetLastError returns ERROR_NO_MORE_ITEMS.

The next task is to obtain the symbolic link name for the instance that has been found. This string is in the PSP_INTERFACE_DEVICE_DETAIL_DATA ifDetail structure returned by a call to SetupDiGetDeviceInterfaceDetail . SetupDiGetDeviceInterfaceDetail must be called twice. The first call retrieves the required size for ifDetail, while the second actually gets the structure.

Eventually ifDetail->DevicePath contains the filename that is used to open a handle to the relevant Wdm1 device. This filename is passed to CreateFile and then ifDetail is deleted. Do not forget to call SetupDiDestroyDeviceInfoList on all paths to close the device information set.

The call to CreateFile in GetDeviceViaInterface uses a pretty standard set of parameters. As noted before, you can change the share and access modes, if necessary. Further, the device can be opened for overlapped nonblocking access. Overlapped access works for devices in Windows 98, NT, and Windows 2000 and lets an application issue an I/O request and get on with other work while the request is being processed. The detailed explanation of the DebugPrint Monitor program in Chapter 14 gives an example of this technique.

Running Wdm1Test

Simply run Wdm1Test.exe in the Wdm1\exe\Release directory. Make sure that the Wdm1 driver is installed. Wdm1Test is a console application running in a DOS box. Press the Enter key to exit the program.

If you run Wdm1Test in W2000, the output should look like that given in Listing 5.6. The first time round, Test 2 is designed to fail; subsequent tests should succeed. In Windows 98, the output is different, as it does not seem to support the SetFilePointer function on devices, such as Wdm1.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x