Windows NT Driver >> C/C++

Thread


參考資訊:
1. Source Code
2. operating-system-ch4-multithread
3. user-level-threads-and-kernel-level-threads

Thread是一個最小的執行單位,一個Process可以產生多個Thread,在多核CPU上,產生的Thread可以同時的運作,這意謂著使用Thread技術可以用來改善效能,但是,每個Thread間的資料同步則是另一個課題,在此練習,司徒著重在教導使用者如何撰寫一個最基本的Thread,了解其架構後,使用者可以再更深入了解Thread需要面對的其它問題,而值得注意的是,Thread有區分User Thread和System Thread兩種,各有優缺點,細節可以參考如上的參考資訊。

main.c

#include <wdm.h>

#define IOCTL_START CTL_CODE(FILE_DEVICE_UNKNOWN, 0x800, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_STOP  CTL_CODE(FILE_DEVICE_UNKNOWN, 0x801, METHOD_BUFFERED, FILE_ANY_ACCESS)

#define DEV_NAME L"\\Device\\MyDriver"
#define SYM_NAME L"\\DosDevices\\MyDriver"

PVOID pThread=NULL;
volatile BOOLEAN bExit=FALSE;

VOID MyThread(PVOID pParam)
{
  LARGE_INTEGER stTime;

  stTime.HighPart|= -1;
  stTime.LowPart = -10000000;
  DbgPrint("Current process: %s", (char*)((ULONG)IoGetCurrentProcess() + 0x174));
  while(bExit != TRUE){
    KeDelayExecutionThread(KernelMode, FALSE, &stTime);
    DbgPrint("Sleep 1s");
  }
  DbgPrint("Exit MyThread");
  PsTerminateSystemThread(STATUS_SUCCESS);
}

void Unload(PDRIVER_OBJECT pOurDriver)
{
  UNICODE_STRING usSymboName;
           
  RtlInitUnicodeString(&usSymboName, L"\\DosDevices\\MyDriver");
  IoDeleteSymbolicLink(&usSymboName);
  IoDeleteDevice(pOurDriver->DeviceObject);
}

NTSTATUS IrpIOCTL(PDEVICE_OBJECT pOurDevice, PIRP pIrp)
{
  HANDLE hThread;
  NTSTATUS status;
  PIO_STACK_LOCATION psk = IoGetCurrentIrpStackLocation(pIrp);

  switch(psk->Parameters.DeviceIoControl.IoControlCode){
  case IOCTL_START:
    DbgPrint("IOCTL_START");
    bExit = FALSE;
    
    // user thread
    status = PsCreateSystemThread(&hThread, THREAD_ALL_ACCESS, NULL, (PHANDLE)-1, NULL, MyThread, (PVOID)pOurDevice);
    
    // system thread
    //status = PsCreateSystemThread(&hThread, THREAD_ALL_ACCESS, NULL, NULL, NULL, MyThread, pOurDevice);
    
    if(status == STATUS_SUCCESS){
      ObReferenceObjectByHandle(hThread, THREAD_ALL_ACCESS, NULL, KernelMode, &pThread, NULL);
      ZwClose(hThread);
    }
    break;
  case IOCTL_STOP:
    DbgPrint("IOCTL_STOP");
    bExit = TRUE;
    if(pThread != NULL){
      KeWaitForSingleObject(pThread, Executive, KernelMode, FALSE, NULL);
      ObDereferenceObject(pThread);
    }
    break;
  }
  pIrp->IoStatus.Information = 0;
  pIrp->IoStatus.Status = STATUS_SUCCESS;
  IoCompleteRequest(pIrp, IO_NO_INCREMENT);
  return STATUS_SUCCESS;
}

NTSTATUS IrpFile(PDEVICE_OBJECT pOurDevice, PIRP pIrp)
{
  PIO_STACK_LOCATION psk = IoGetCurrentIrpStackLocation(pIrp);

  switch(psk->MajorFunction){
  case IRP_MJ_CREATE:
    DbgPrint("IRP_MJ_CREATE");
    break;
  case IRP_MJ_CLOSE:
    DbgPrint("IRP_MJ_CLOSE");
    break;
  }
  IoCompleteRequest(pIrp, IO_NO_INCREMENT);
  return STATUS_SUCCESS;
}

NTSTATUS DriverEntry(PDRIVER_OBJECT pOurDriver, PUNICODE_STRING pOurRegistry)
{
  PDEVICE_OBJECT pOurDevice=NULL;
  UNICODE_STRING usDeviceName;
  UNICODE_STRING usSymboName;
      
  pOurDriver->MajorFunction[IRP_MJ_CREATE] =
  pOurDriver->MajorFunction[IRP_MJ_CLOSE] = IrpFile;
  pOurDriver->MajorFunction[IRP_MJ_DEVICE_CONTROL] = IrpIOCTL;
  pOurDriver->DriverUnload = Unload;
        
  RtlInitUnicodeString(&usDeviceName, L"\\Device\\MyDriver");
  IoCreateDevice(pOurDriver, 0, &usDeviceName, FILE_DEVICE_UNKNOWN, 0, FALSE, &pOurDevice);
  RtlInitUnicodeString(&usSymboName, L"\\DosDevices\\MyDriver");
  IoCreateSymbolicLink(&usSymboName, &usDeviceName);
  pOurDevice->Flags&= ~DO_DEVICE_INITIALIZING;
  pOurDevice->Flags|= DO_BUFFERED_IO;
  return STATUS_SUCCESS;
}

IrpIOCTL收到IOCTL_START後,產生一個新的Thread(注意有User和System區分),接著呼叫ZwClose(),值得注意的是,這個ZwClose()僅是釋放Handle的資源,實際Thread並不會被關閉,原因在於提前做ObReferenceObjectByHandle(),而當收到IOCTL_STOP,則設定bExit並等待Thread結束,最後呼叫ObDereferenceObject()釋放Object資源。

app.c

#define INITGUID
#include <windows.h>
#include <winioctl.h>
#include <strsafe.h>
#include <setupapi.h>
#include <stdio.h>
#include <stdlib.h>

#define IOCTL_START CTL_CODE(FILE_DEVICE_UNKNOWN, 0x800, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_STOP  CTL_CODE(FILE_DEVICE_UNKNOWN, 0x801, METHOD_BUFFERED, FILE_ANY_ACCESS)

int __cdecl main(int argc, char* argv[])
{
  HANDLE hFile = NULL;
  DWORD dwRet = 0;

  hFile = CreateFile("\\\\.\\MyDriver", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
  if (hFile == INVALID_HANDLE_VALUE) {
    printf("failed to open mydriver\n");
    return -1;
  }
  DeviceIoControl(hFile, IOCTL_START, NULL, 0, NULL, 0, &dwRet, NULL);
  Sleep(3000);
  DeviceIoControl(hFile, IOCTL_STOP, NULL, 0, NULL, 0, &dwRet, NULL);
  CloseHandle(hFile);
  return 0;
}

結果


返回上一頁