Skip to content

Instantly share code, notes, and snippets.

@ntddk
Created July 5, 2014 17:26
Show Gist options
  • Save ntddk/06168de9b91ec2b0ab87 to your computer and use it in GitHub Desktop.
Save ntddk/06168de9b91ec2b0ab87 to your computer and use it in GitHub Desktop.
GetProcessIdOfThread() on Windows XP
#include <Windows.h>
#include <winternl.h>
typedef struct _CLIENT_ID
{
PVOID UniqueProcess;
PVOID UniqueThread;
} CLIENT_ID, *PCLIENT_ID;
typedef LONG KPRIORITY;
typedef struct _THREAD_BASIC_INFORMATION {
NTSTATUS ExitStatus;
PVOID TebBaseAddress;
CLIENT_ID ClientId;
KAFFINITY AffinityMask;
KPRIORITY Priority;
KPRIORITY BasePriority;
} THREAD_BASIC_INFORMATION, *PTHREAD_BASIC_INFORMATION;
ULONG GetProcessIdFromThreadId(
__in ULONG ThreadId)
{
auto NtQueryInformationThreadPtr = reinterpret_cast<decltype(NtQueryInformationThread)*>(GetProcAddress(GetModuleHandle(TEXT("ntdll")), "NtQueryInformationThread"));
if (!NtQueryInformationThreadPtr)
return 0;
HANDLE Thread = OpenThread(THREAD_QUERY_INFORMATION, FALSE, ThreadId);
if (!Thread)
return 0;
ULONG u = 0;
THREAD_BASIC_INFORMATION d = {0};
ULONG r = NtQueryInformationThreadPtr(Thread, (THREADINFOCLASS)0, &d, sizeof(d), &u);
CloseHandle(Thread);
if (!NT_SUCCESS(r))
return 0;
return reinterpret_cast<ULONG>(d.ClientId.UniqueProcess);
}
int _tmain(int argc, _TCHAR* argv[])
{
ULONG Tid = (argc == 1) ? GetCurrentThreadId() : _tcstoul(argv[1], NULL, 10);
ULONG Pid = GetProcessIdFromThreadId(Tid);
printf("Tid = %lu , Pid1 = %lu\n", Tid, Pid);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment