如何将参数传递给 ZwCreateThreadEx 例程?

How pass parameters to ZwCreateThreadEx routine?

下面的代码可以很好地创建分离的线程,而无需传递任何数据类型参数。现在我想知道如何将参数传递给调用 ZwCreateThreadEx 时执行的方法?

例如,如何传递一个HANDLE类型和一个类型UNICODE_STRING?

我的实际代码:

#include "stdafx.h"
#include <conio.h>
#include <windows.h>
#include <Winternl.h>

#pragma comment(lib,"ntdll.lib")

void WINAPI ContinueExecution(LPVOID param)
{
    printf("This thread is hidden from debugger!"); 
}

NTSTATUS(NTAPI *ZwCreateThreadEx) (
    _Out_ PHANDLE ThreadHandle,
    _In_ ACCESS_MASK DesiredAccess,
    _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
    _In_ HANDLE ProcessHandle,
    _In_ PVOID StartRoutine,
    _In_opt_ PVOID Argument,
    _In_ ULONG CreateFlags,
    _In_opt_ ULONG_PTR ZeroBits,
    _In_opt_ SIZE_T StackSize,
    _In_opt_ SIZE_T MaximumStackSize,
    _In_opt_ PVOID AttributeList
    );

NTSTATUS(NTAPI *ZwClose)(IN HANDLE ObjectHandle);

#if (NTDDI_VERSION >= NTDDI_VISTA)
#define THREAD_ALL_ACCESS         (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | \
    0xFFFF)
#else
#define THREAD_ALL_ACCESS         (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | \
    0x3FF)
#endif

#define THREAD_CREATE_FLAGS_HIDE_FROM_DEBUGGER      0x00000004
#define ZwCurrentProcess() ( (HANDLE)(LONG_PTR) -1 ) 

int _tmain(int argc, _TCHAR* argv[])
{

    HANDLE hThread = 0;
    HMODULE hNtdll = GetModuleHandleA("ntdll");

    ZwCreateThreadEx = (NTSTATUS(NTAPI *) (PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES, HANDLE, PVOID, PVOID, ULONG, ULONG_PTR, SIZE_T, SIZE_T, PVOID)) GetProcAddress(hNtdll, "ZwCreateThreadEx");
    if (ZwCreateThreadEx == NULL) return FALSE;

    ZwClose = (NTSTATUS(NTAPI *)(IN HANDLE ObjectHandle)) GetProcAddress(hNtdll, "ZwClose");
    if (ZwClose == NULL) return FALSE;

    {
        NTSTATUS ntStat = ZwCreateThreadEx(&hThread, THREAD_ALL_ACCESS, 0, ZwCurrentProcess(), (LPTHREAD_START_ROUTINE)ContinueExecution, 0, THREAD_CREATE_FLAGS_HIDE_FROM_DEBUGGER, 0, 0, 0, 0);

        if (ntStat >= 0)
        {
            WaitForSingleObject(hThread, INFINITE);
        }
        else
        {
            printf("NtCreateThreadEx failed!");
        }

        ZwClose(hThread);

    }

    _getch();

    return 0;
}

如果您想将多个值传递给您的线程函数,您将需要一个结构来保存这些值。并且根据代码设计,可能需要动态分配结构实例(如果它是调用 ZwCreateThreadEx 的函数的本地实例,则在线程实际运行时它可能不再有效)。

正如 Martin James 所说,您随后会将指向该结构实例的指针作为 Argument 参数传递。