experiment : thread on drv

PsCreateSystemThread原型

NTSTATUS 
  PsCreateSystemThread(
    OUT PHANDLE  ThreadHandle,
    IN ULONG  DesiredAccess,
    IN POBJECT_ATTRIBUTES  ObjectAttributes  OPTIONAL,
    IN HANDLE  ProcessHandle  OPTIONAL,
    OUT PCLIENT_ID  ClientId  OPTIONAL,
    IN PKSTART_ROUTINE  StartRoutine,
    IN PVOID  StartContext
    );



typedef
VOID
(*PKSTART_ROUTINE) (
    IN PVOID StartContext
    );


函数声明

void    CreateThreadForTest();
void    ThreadForTest(IN PVOID pContext);


建立线程

    /// the code on DriverEntry
    CreateThreadForTest();


运行结果

kd> g
>> CreateThreadForTest
>> ThreadForTest
<< ThreadForTest
<< CreateThreadForTest
<< DriverEntry


函数实现

void    CreateThreadForTest()
{
    HANDLE      hThread     =   NULL;
    PVOID       pObjWait    =   NULL;
    NTSTATUS    ntStatus    =   STATUS_SUCCESS;
    KIRQL       IrqlOrg     =   0;

    DbgPrint(">> CreateThreadForTest\r\n");

    /// PsCreateSystemThread IRQL = PASSIVE_LEVEL
    if (PASSIVE_LEVEL != KeGetCurrentIrql())
    {
        DbgPrint("err: DISPATCH_LEVEL != KeGetCurrentIrql()\r\n");
        return;
    }

    ntStatus = PsCreateSystemThread(
        & hThread, // OUT PHANDLE  ThreadHandle,
        0, // IN ULONG  DesiredAccess,
        NULL, // IN POBJECT_ATTRIBUTES  ObjectAttributes  OPTIONAL,
        (HANDLE)0, // IN HANDLE  ProcessHandle  OPTIONAL,
        NULL, // OUT PCLIENT_ID  ClientId  OPTIONAL,
        ThreadForTest, // IN PKSTART_ROUTINE  StartRoutine,
        NULL // IN PVOID  StartContext
        );

    if (!NT_SUCCESS(ntStatus))
    {
        DbgPrint("err : ThreadTestLookasideListPage create failed\r\n");
        return;
    }

    ntStatus = ObReferenceObjectByHandle(
        hThread, // IN HANDLE  Handle,
        THREAD_ALL_ACCESS, // IN ACCESS_MASK  DesiredAccess,
        NULL, // IN POBJECT_TYPE  ObjectType  OPTIONAL,
        KernelMode, // IN KPROCESSOR_MODE  AccessMode,
        &pObjWait, // OUT PVOID  *Object,
        NULL // OUT POBJECT_HANDLE_INFORMATION  HandleInformation  OPTIONAL
        );

    if (!NT_SUCCESS(ntStatus))
    {
        DbgPrint("err : ObReferenceObjectByHandle\r\n");
        return;
    }

    /// 阻塞等待线程结束
    KeWaitForSingleObject(
        pObjWait, // IN PVOID  Object,
        Executive, // IN KWAIT_REASON  WaitReason,
        KernelMode, // IN KPROCESSOR_MODE  WaitMode,
        FALSE, // IN BOOLEAN  Alertable,
        NULL // IN PLARGE_INTEGER  Timeout OPTIONAL
        );

    ObDereferenceObject(pObjWait);

    DbgPrint("<< CreateThreadForTest\r\n");
    return;
}

void    ThreadForTest(IN PVOID pContext)
{
    DbgPrint(">> ThreadForTest\r\n");

    DbgPrint("<< ThreadForTest\r\n");
}



你可能感兴趣的:(experiment : thread on drv)