Windows NT Driver >> Pascal

Thread


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

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

main.pas

unit main;

interface
  uses 
    DDDK;
    
  const 
    DEV_NAME = '\Device\MyDriver';
    SYM_NAME = '\DosDevices\MyDriver';
    IOCTL_START = $222000; // CTL_CODE(FILE_DEVICE_UNKNOWN, 0x800, METHOD_BUFFERED, FILE_ANY_ACCESS)
    IOCTL_STOP = $222004; // CTL_CODE(FILE_DEVICE_UNKNOWN, 0x801, METHOD_BUFFERED, FILE_ANY_ACCESS)
    
  function _DriverEntry(pOurDriver:PDriverObject; pOurRegistry:PUnicodeString):NTSTATUS; stdcall;

implementation
var 
  bExit: ULONG;
  pThread: Handle;
  
procedure MyThread(pParam:Pointer); stdcall;
var
  ps: Pointer;
  tt: LARGE_INTEGER;

begin
  tt.HighPart:= tt.HighPart or -1;
  tt.LowPart:= ULONG(-10000000);
  ps:= IoGetCurrentProcess();
  ps:= Pointer(Integer(ps) + $174);
  DbgPrint('Current process: %s', [ps]);
  while Integer(bExit) = 0 do
  begin
    KeDelayExecutionThread(KernelMode, FALSE, @tt);
    DbgPrint('Sleep 1s', []);
  end;
  DbgPrint('Exit MyThread', []);
  PsTerminateSystemThread(STATUS_SUCCESS);
end;

function IrpOpen(pOurDevice:PDeviceObject; pIrp:PIrp):NTSTATUS; stdcall;
begin
  DbgPrint('IRP_MJ_CREATE', []);
  Result:= STATUS_SUCCESS;
  pIrp^.IoStatus.Information:= 0;
  pIrp^.IoStatus.Status:= Result;
  IoCompleteRequest(pIrp, IO_NO_INCREMENT);
end;

function IrpClose(pOurDevice:PDeviceObject; pIrp:PIrp):NTSTATUS; stdcall;
begin
  DbgPrint('IRP_MJ_CLOSE', []);
  Result:= STATUS_SUCCESS;
  pIrp^.IoStatus.Information:= 0;
  pIrp^.IoStatus.Status:= Result;
  IoCompleteRequest(pIrp, IO_NO_INCREMENT);
end;

function IrpIOCTL(pOurDevice:PDeviceObject; pIrp:PIrp):NTSTATUS; stdcall;
var
  code: ULONG;
  hThread: Handle;
  status: NTSTATUS;
  psk: PIoStackLocation;

begin
  psk:= IoGetCurrentIrpStackLocation(pIrp);
  code:= psk^.Parameters.DeviceIoControl.IoControlCode;
  case code of 
  IOCTL_START:begin
    DbgPrint('IOCTL_START', []);
    bExit:= 0;
    status:= PsCreateSystemThread(@hThread, THREAD_ALL_ACCESS, Nil, Handle(-1), Nil, MyThread, pOurDevice);
    if NT_SUCCESS(status) then
    begin
      ObReferenceObjectByHandle(hThread, THREAD_ALL_ACCESS, Nil, KernelMode, @pThread, Nil);
      ZwClose(hThread);
    end;
  end;
  IOCTL_STOP:begin
    DbgPrint('IOCTL_STOP', []);
    bExit:= 1;
    KeWaitForSingleObject(Pointer(pThread), Executive, KernelMode, False, Nil);
    ObDereferenceObject(pThread);
  end;
  end;
  
  Result:= STATUS_SUCCESS;
  pIrp^.IoStatus.Information:= 0;
  pIrp^.IoStatus.Status:= Result;
  IoCompleteRequest(pIrp, IO_NO_INCREMENT);
end;

procedure Unload(pOurDriver:PDriverObject); stdcall;
var
  szSymName: TUnicodeString;

begin
  RtlInitUnicodeString(@szSymName, SYM_NAME);
  IoDeleteSymbolicLink(@szSymName);
  IoDeleteDevice(pOurDriver^.DeviceObject);
end;

function _DriverEntry(pOurDriver:PDriverObject; pOurRegistry:PUnicodeString):NTSTATUS; stdcall;
var
  suDevName: TUnicodeString;
  szSymName: TUnicodeString;
  pOurDevice: PDeviceObject;
  
begin
  RtlInitUnicodeString(@suDevName, DEV_NAME);
  RtlInitUnicodeString(@szSymName, SYM_NAME);
  Result:= IoCreateDevice(pOurDriver, 0, @suDevName, FILE_DEVICE_UNKNOWN, 0, FALSE, pOurDevice);

  if NT_SUCCESS(Result) then
  begin
    pOurDriver^.MajorFunction[IRP_MJ_CREATE]:= @IrpOpen;
    pOurDriver^.MajorFunction[IRP_MJ_CLOSE]  := @IrpClose;
    pOurDriver^.MajorFunction[IRP_MJ_DEVICE_CONTROL] := @IrpIOCTL;
    pOurDriver^.DriverUnload := @Unload;
    pOurDevice^.Flags:= pOurDevice^.Flags or DO_BUFFERED_IO;
    pOurDevice^.Flags:= pOurDevice^.Flags and not DO_DEVICE_INITIALIZING;
    Result:= IoCreateSymbolicLink(@szSymName, @suDevName);
  end;
end;
end.

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

app.pas

program main;

{$APPTYPE CONSOLE}

uses
  Windows,
  Messages,
  SysUtils,
  Variants,
  Classes,
  Graphics,
  Controls,
  Forms,
  DIALOGS;

const
  METHOD_BUFFERED = 0;
  METHOD_IN_DIRECT = 1;
  METHOD_OUT_DIRECT = 2;
  METHOD_NEITHER = 3;
  FILE_ANY_ACCESS = 0;
  FILE_DEVICE_UNKNOWN = $22;

var
  fd: DWORD;
  ret: DWORD;
  start_code: DWORD;
  stop_code: DWORD;
  
begin
  fd:= CreateFile('\\.\MyDriver', GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ, Nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  if (fd <> INVALID_HANDLE_VALUE) then
  begin
    start_code:= (FILE_DEVICE_UNKNOWN shl 16) or (FILE_ANY_ACCESS shl 14) or ($800 shl 2) or (METHOD_BUFFERED);
    stop_code:= (FILE_DEVICE_UNKNOWN shl 16) or (FILE_ANY_ACCESS shl 14) or ($801 shl 2) or (METHOD_BUFFERED);
    DeviceIoControl(fd, start_code, Nil, 0, Nil, 0, ret, Nil);
    Sleep(3000);
    DeviceIoControl(fd, stop_code, Nil, 0, Nil, 0, ret, Nil);
    CloseHandle(fd);
  end else
  begin
    WriteLn(Output, 'failed to open mydriver');
  end;
end.

結果


返回上一頁