Use synchronous events to drive proactive notification applications

1. Synchronization events

Initialize, wait, and set data structures KEVENTto achieve synchronization between multiple threads. For example, if you want main thread A to do something after waiting for thread B to complete something, you can configure KEVENT事件waiting in main thread A, and after completing the operation in thread B, KEVENT事件you can set what is waiting.

Examples are as follows:

// 定义一个事件
KEVENT event;
// 事件初始化
KeInitializeEvent(&event, SynchronizationEvent, FALSE);

<!-- more --> 

// ......

// 主线程A中:
// 在此处等待 KEVENT 事件。若该事件没有被设置,则会一直阻塞在这里继续等待。
KeWaitForSingleObject(&event, Executive, KernelMode, 0, 0);

// ......

// 线程B中:
// 在此处设置 KEVENT 事件。一旦设置了此事件,前面等待的地方将继续执行。
KeSetEvent(&event, 0, TRUE);

The prototypes of several functions are as follows:

VOID
KeInitializeEvent(
  IN PRKEVENT Event,  // 所定义的事件
  IN EVENT_TYPE Type,   // 事件类型,分为 SynchronizationEvent 和 NotificationEvent 两种
  IN BOOLEAN State      // 初始化状态,一般设置为 FALSE,即等待者需要等待设置后才能通过。
);
LONG
KeSetEvent(
  IN PREVENT event,     // 要设置的事件
  IN KPRIORITY Increment, // 提升优先权
  IN BOOLEAN Wait         // 表示是否后面马上紧跟一个 KeWaitSingleObject 来等待这个时间,一般设置为 TRUE(事件初始化之后,一般就要开始等待了)。
);

Second, the implementation of the driver active notification application

Application: Open a thread, send an IOCTL request to the driver within the thread, and wait for the IOCTL to return; the main thread continues to perform other operations.

Driver: Wait for a synchronization event event in the IOCTL dispatch function (DeviceIoControl), when the synchronization event is set (Set) elsewhere in the driver, trigger the response to the previously waiting IOCTL request.

3. Test results

Test Results

It can be seen that if it is a serial operation, the application sends an IOCTL request to the driver ①. While the driver is waiting for the arrival of data serving the request, the application will not send other IOCTL requests. In this case, it can respond normally, which is equivalent to blocking the IOCTL channel. If it is a parallel operation, the application sends an IOCTL request ② to the driver. While the driver is waiting for the data to serve the request, the application sends an IOCTL request ③ to the driver. After testing, the driver cannot receive the request, which proves again that the IOCTL channel is blocked. block.


References:

  1. "Windows Kernel Security and Driver Development" 4.4.3 & 5.3
  2. Microsoft Doc - Windows Driver: Defining and Using an Event Object

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324746739&siteId=291194637