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

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

Интервал:

Закладка:

Сделать

return false;

}

// Fill in standard parts of the packet

Packet->ErrorCode = ErrorCode;

Packet->UniqueErrorValue = 0;

// Fill in IRP related fields

Packet->MajorFunctionCode = 0;

Packet->RetryCount = 0;

Packet->FinalStatus = 0;

Packet->SequenceNumber = 0;

Packet->IoControlCode = 0;

if (Irp!=NULL) {

PIO_STACK_LOCATION IrpStack = IoGetCurrentIrpStackLocation(Irp);

Packet->MajorFunctionCode = IrpStack->MajorFunction;

Packet->FinalStatus = Irp->IoStatus.Status;

if (IrpStack->MajorFunction==IRP_MJ_DEVICE_CONTROL || IrpStack->MajorFunction==IRP_MJ_INTERNAL_DEVICE_CONTROL)

Packet->IoControlCode = IrpStack->Parameters.DeviceIoControl.IoControlCode;

}

// Fill in dump data

if (DumpDataCount>0) {

Packet->DumpDataSize = (USHORT)(sizeof(ULONG)*DumpDataCount);

for (int i=0; iDumpData[i] = DumpData[i];

} else Packet->DumpDataSize = 0;

// Fill in insertion strings after DumpData

Packet->NumberOfStrings = (USHORT)StringCount;

if (StringCount>0) {

Packet->StringOffset = sizeof(IO_ERROR_L0G_PACKET) + (DumpDataCount-1) * sizeof(ULONG);

PUCHAR pInsertionString = (PUCHAR)Packet + Packet->StringOffset;

// Add each new string to the end

for (int i=0; i

RtlMoveMemory(pInsertionString, Strings[i], StringSizes[i]);

pInsertionString += StringSizes[i];

}

}

// Log the message

IoWriteErrorLogEntry(Packet);

if (StringSizes!=NULL) ExFreePool(StringSizes);

return true;

}

To make LogEvent easier to use, Wdm3 provides a function called Wdm3EventMessage that simply takes an ANSI string as an argument. This is passed as a wide string to LogEvent to be inserted in the WDM3_MESSAGE message. Wdm3EventMessage is shown in Listing 13.6.

Listing 13.6 Wdm3EventMessage routines

void Wdm3EventMessage(const char* Msg) {

int MsgLen = GetAnsiStringSize(Msg);

int wMsgLen = MsgLen*2;

PWSTR wMsg = (PWSTR)ExAllocatePool(NonPagedPool,wMsgLen);

if (wMsg==NULL) return;

// Brutally make into a wide string

for (int i=0; i

PWSTR Strings[1] = { wMsg };

LogEvent(WDM3_MESSAGE, NULL, // IRP

NULL, 0, // dump data

Strings, 1); // strings

ExFreePool(wMsg);

}

Testing Wdm3 Events

The Wdm3EventMessage function is called in a few places in the Wdm3 driver as a test. Wdm3Unload sends a message "Unload", Wdm3AddDevice sends "AddDevice", and Wdm3Pnp sends "PnP xx" where "xx" represents the Plug and Play minor function code, in hex.

Installing and reinstalling a Wdm3 device should generate several events in the System event log. The events are generated in both the free and checked build versions. Remember to refresh the Event Viewer display to see any new events.

Conclusion

You should use NT events to report any problem events in NT 3.51, NT 4, and Windows 2000 drivers. The two relevant kernel function calls are just stubs in Windows 98, so you can safely generate events in WDM device drivers.

Chapter 14

DebugPrint

This chapter looks at a fully-fledged driver, DebugPrint. The DebugPrint software lets you use formatted print trace statements in your code and view the output in the DebugPrint Monitor Win32 program.

Along the way, I cover the following important device driver topics.

• System threads

• Dispatcher objects: events, Mutexes, and semaphores

• Linked lists

• File I/O in drivers

• Queuing IRPs

• Basic cancel routines

• Win32 overlapped I/O requests

Design Specification

The main design requirement for the DebugPrint software is that test drivers can do formatted prints that appear in a user mode application running on the same PC as the driver. The software must work under Windows 98 and Windows 2000. It should be easy for developers to include trace statements in their code. They should be able to use trace statements in most types of driver code.

This specification does not include source level debugging or breakpoints.

Design Implementation

Figure 14.1 shows the design used in the DebugPrint software. The figure shows that more than one test driver can run at the same time. In each test driver, the trace output is first stored internally in an EventList doubly-linked list. A DebugPrint system thread in the driver code reads the EventList and writes the events to the DebugPrint driver.

The DebugPrint driver write routine stores the trace events in its own EventList. The DebugPrint Monitor application issues read requests to the DebugPrint driver to read the trace events. These are then displayed to the user in the DebugPrint Monitor window.

An alternative design might have removed the DebugPrint driver. The test driver DebugPrint system thread could then have written the trace events directly to a disk file. However, it is unclear whether it is possible to lock such a file so that "simultaneous" accesses by the test drivers and DebugPrint Monitor would be handled properly. Writing to a disk file would also be slower.

Figure 14.1 DebugPrint design

The DebugPrint software, therefore, consists of the following three different pieces of code.

• Code added to the test driver to produce events

• The DebugPrint driver

• The DebugPrint Monitor application

Test Driver Code

As explained in Chapter 6, a driver writer has to add DebugPrint.c [31] Since writing this chapter, the test driver DebugPrint code has changed from C++ to C. The code on the book software disk is slightly different from the code printed in this chapter, though they are functionally identical. and DebugPrint.h source files to their driver project to support DebugPrint calls. These routines ensure that the trace statement output is sent to the DebugPrint driver. It should eventually be possible to put all the code in DebugPrint.c into a static library or DLL that is linked with test drivers.

The main job performed by the DebugPrint code in each test driver is to write events to the DebugPrint driver. The kernel provides several routines to call other drivers, including ZwCreateFile, ZwWriteFile , and ZwClose . The documentation for these functions says that these functions can only be called at PASSIVE_LEVEL IRQL. This means that they cannot be called directly from some sorts of driver code.

In my initial design, I ignored this issue. However, I soon ran into another problem that was more difficult to track down. Eventually, I worked out that calls to ZwWriteFile have to be made in the same process context as ZwCreateFile . The DDK documentation did not make this point prominently. In my initial design, I used ZwCreateFile in the test driver DriverEntry routine. However, the print routines using ZwWriteFile could naturally be called in dispatch routines, which are usually not running in the same process context.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x