Программирование драйверов Windows

Приложение для тестирования драйвера


Простое консольное приложение выполняет несложные операции в последовательной манере. Здесь нет сложных одновременных обращений из многих потоков. Тестирование сводится к передаче в драйвер 17 байт и последующему ожиданию от него ответа, размером 34 байта. Разумеется, драйвер может возвратить только полученные ранее данные, ни байтом больше.

Сборку приложения можно осуществлять при помощи такого файла Sources:

TARGETNAME=test TARGETTYPE=PROGRAM UMTYPE=console UMENTRY=main UMBASE=0x400000 TARGETPATH=. INCLUDES= $(BASEDIR)\inc

SOURCES=test.cpp

А это, собственно, исходный код тестового приложения: //======================================================================= // Файл тестовой программы test.cpp //=======================================================================

#include &#60windows.h&#62 #include &#60stdio.h&#62

// Предварительное объявление int ReadWrite(HANDLE devHandle);

#define BUFFSIZE (17) static unsigned char outBuffer[BUFFSIZE], inBuffer[BUFFSIZE*2];

int __cdecl main() { printf("\n\n\n\n\nParallel Port CheckIt Loopback Device Test Program.\n" );

HANDLE devHandle; devHandle = CreateFile( "\\\\.\\LPTPORT0", GENERIC_READ | GENERIC_WRITE, 0, // share mode none NULL, // no security OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); // no template

if ( devHandle == INVALID_HANDLE_VALUE ) { printf("Error: can not open device PLPTPORT0. Win32 errno %d\n", GetLastError() ); return -1; } printf("Congratulation. LPTPORT0 device is open.\n\n"); //========================================== DWORD i=3,j=0; for ( ; j&#60sizeof(outBuffer); ) outBuffer[j++] = (unsigned char)i++; //========================================== //for(i=0; i&#60 100000; i++) //{ int result = ReadWrite(devHandle); // if(result) break; //} //========================================== // Завершение работы if ( ! CloseHandle(devHandle) ) { printf("\n Error during CloseHandle: errno %d.\n", GetLastError() ); return 5; } printf("\n\n\n Device LPTPORT0 successfully closed.
Normal exit.\n"); return 0; }



//========================================================================== // Выделим запись и чтение данных в отдельную функцию: // int ReadWrite(HANDLE devHandle) { //========================================== // Передача данных драйверу printf("Writing to LPTPORT0 device...\n");

DWORD bytesWritten, outCount = sizeof(outBuffer); if ( !WriteFile(devHandle, outBuffer, outCount, &bytesWritten, NULL) ) { printf("Error during WriteFile: errno %d.\n", GetLastError() ); return 1; } if ( outCount != bytesWritten ) // если не все передалось: { printf("Error: while wrote %d bytes, WriteFile reported %d bytes.\n", outCount, bytesWritten); return 2; } printf("Successfully written %d bytes.\n Buffer content was: \n", outCount); for (DWORD i=0; i&#60bytesWritten; i++ ) printf("%02X ",outBuffer[i]); //========================================== //Sleep(10); // Ожидание 10 миллисекунд //========================================== // Получение данных из драйвера printf("\n\nReading from device LPTPORT0...\n");

DWORD bytesRead, inCount = sizeof(inBuffer); if ( !ReadFile(devHandle, inBuffer, inCount, &bytesRead, NULL) ) { printf("Error during ReadFile: errno %d.\n", GetLastError() ); return 3; } if ( bytesRead != bytesWritten ) { // размер записанных и прочитанных данных не совпадает printf("Error: is to read %d bytes, but ReadFile reported %d bytes.\n", bytesWritten, inCount); return 4; } printf("Succesfully read %d bytes.\n Buffer content is: \n", bytesRead); for ( i=0; i&#60bytesRead; i++ ) printf( "%02X ", (UCHAR)inBuffer[i] ); return 0; // Нормальное завершение }

При запуске тестовой программы в консольном окне наблюдаем вывод на экран следующих сообщений:

L:\#ex_lpt\test\>test
Parallel Port CheckIt Loopback Device Test Program.
Congratulation. LPTPORT0 device is open.

Writing to LPTPORT0 device...
Successfully written 17 bytes.


Buffer content was:
03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13

Reading from device LPTPORT0... Successfully read 17 bytes. Buffer content is:
03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 00 01 02 03

Device LPTPORT0 successfully closed. Normal exit.

Поскольку через 4 разряда параллельного порта (что обусловлено конструкцией заглушки CheckIt) передается только младшая половина байта, то совпадение вторых цифр в строках, наблюдаемых на экране, является хорошим результатом, демонстрирующим правильный перенос данных.

Ниже приводится информация из отладочного вывода, перехваченного программой DebugView (log-файл этой программы). Средняя часть этого файла, сообщения с 28 по 90, опущена, поскольку в них содержится однообразная и малоинтересная информация.

00000000 0.00000000 LPTPORT: in DriverEntry, RegistryPath is:
00000001 0.00000223 \REGISTRY\MACHINE\SYSTEM\ControlSet001\Services\LPTPort.
00000002 0.00003911 LPTPORT: Interrupt 7 converted to kIrql = 8,
kAffinity = 1, kVector = 191(hex)
00000003 0.00004833 LPTPORT: Interrupt successfully connected.
00000004 0.00007878 LPTPORT: Symbolic Link is created: \DosDevices\LPTPORT0.
00000005 5.38805379 LPTPORT: in DispatchCreate now
00000006 5.38822867 LPTPORT: in DispatchWrite now
00000007 5.38823342 LPTPORT: DoNextTransfer:
00000008 5.38823985 LPTPORT: SendingOxO3 to port 378
00000009 5.38824487 LPTPORT: generating next interrupt...
00000010 5.38835690 LPTPORT: In Isr procedure, ISR_Irql=8
00000011 5.38836388 LPTPORT: We are now in DpcForIsr, currentIrql=2 xferCount = 0
00000012 5.38837115 LPTPORT: ReadDataSafely, currentIrql=8 ReadStatus=1F
ReadByte=03
00000013 5.38837422 LPTPORT:
00000014 5.38837785 LPTPORT: DoNextTransfer:
00000015 5.38838260 LPTPORT: Sending 0x04 to port 378
00000016 5.38838763 LPTPORT: generating next interrupt...
00000017 5.38849854 LPTPORT: In Isr procedure, ISR_Irql=8
00000018 5.38850524 LPTPORT: We are now in DpcForIsr, currentIrql=2 xferCount = 1
00000019 5.38851167 LPTPORT: ReadDataSafely, currentIrql=8 ReadStatus = 27


ReadByte = 04
00000020 5.38851446 LPTPORT:
00000021 5.38851781 LPTPORT: DoNextTransfer:
00000022 5. 38852228 LPTPORT: Sending 0x05 to port 378
00000023 5.38852731 LPTPORT: generating next interrupt...
00000024 5.38863822 LPTPORT: In Isr procedure, ISR_Irql=8
00000025 5.38864465 LPTPORT: We are now in DpcForIsr, currentIrql=2 xferCount = 2
00000026 5.38865135 LPTPORT: ReadDataSafely, currentIrql=8 ReadStatus = 2F
ReadByte = 05
00000027 5.38865442 LPTPORT: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
00000091 5.38991464 LPTPORT: DoNextTransfer:
00000092 5.38991939 LPTPORT: Sending 0x0F to port 378
00000093 5.38992442 LPTPORT: generating next interrupt...
00000094 5.39003533 LPTPORT: In Isr procedure, ISR_Irql=8
00000095 5.39004175 LPTPORT: We are now in DpcForIsr, currentIrql=2 xferCount = 12
00000096 5.39004874 LPTPORT: ReadDataSafely, currentIrql=8 ReadStatus = BF
ReadByte = 0F
00000097 5.39005181 LPTPORT:
00000098 5.39005516 LPTPORT: DoNextTransfer:
00000099 5.39005963 LPTPORT: Sending 0x00 to port 378
00000100 5.39006494 LPTPORT: generating next interrupt...
00000101 5.39017557 LPTPORT: In Isr procedure, ISR_Irql=8
00000102 5.39018199 LPTPORT: We are now in DpcForIsr, currentIrql=2
xferCount = 13
00000103 5.39018870 LPTPORT: ReadDataSafely, currentIrql=8 ReadStatus = 07
ReadByte = 00
00000104 5.39019177 LPTPORT:
00000105 5.39019512 LPTPORT: DoNextTransfer: 00000106 5.39019959 LPTPORT: Sending 0x01 to port 378
00000107 5.39020434 LPTPORT: generating next interrupt...
00000108 5.39031469 LPTPORT: In Isr procedure, ISR_Irql=8
00000109 5.39032112 LPTPORT: We are now in DpcForIsr, currentIrql=2 xferCount = 14
00000110 5.39032754 LPTPORT: ReadDataSafely, currentIrql=8 ReadStatus = 0F ReadByte = 01
00000111 5.39033061 LPTPORT:
00000112 5.39033425 LPTPORT: DoNextTransfer:
00000113 5.39033872 LPTPORT: Sending 0x02 to port 378
00000114 5.39034374 LPTPORT: generating next interrupt...


00000115 5. 39045493 LPTPORT: In Isr procedure, ISR_Irql=8
00000116 5.39046136 LPTPORT: We are now in DpcForIsr, currentIrql=2 xferCount = 15
00000117 5.39046778 LPTPORT: ReadDataSafely, currentIrql=8 ReadStatus = 17 ReadByte = 02
00000118 5.39047058 LPTPORT:
00000119 5.39047393 LPTPORT: DoNextTransfer:
00000120 5.39047840 LPTPORT: Sending 0x03 to port 378
00000121 5.39048315 LPTPORT: generating next interrupt...
00000122 5.39059350 LPTPORT: In Isr procedure, ISR_Irql=8
00000123 5.39059992 LPTPORT: We are now in DpcForIsr, currentIrql=2 xferCount = 16
00000124 5.39060663 LPTPORT: ReadDataSafely, currentIrql=8 ReadStatus = 1F ReadByte = 03
00000125 5.39060942 LPTPORT:
00000126 5.39061333 LPTPORT: We are now in DpcForIsr, all data transmitted.
00000127 5.39104691 LPTPORT: in DispatchRead now
00000128 5.39105166 LPTPORT: DispatchRead: 17 byted transferred.
00000129 5.39139639 LPTPORT: in DispatchClose now
00000130 10.93612205 LPTPORT: in DriverUnload now
00000131 10.93615557 LPTPORT: SymLink \DosDevices\LPTPORT0 deleted


Содержание раздела