获取线程起始地址

时间:2012-04-15 04:30:45

标签: multithreading delphi process get

我正在编写一个进程查看器,它完成了99%,我只需要获取进程'线程的起始地址,但我不知道它是怎么做的。 谁能帮我? :/ THX

1 个答案:

答案 0 :(得分:7)

您可以使用NtQueryInformationThread函数将ThreadQuerySetWin32StartAddress枚举的THREAD_INFORMATION_CLASS值作为参数传递。

检查此示例应用

{$APPTYPE CONSOLE}

{$R *.res}

uses
  TlHelp32,
  Windows,
  SysUtils;


const
  THREAD_QUERY_INFORMATION   = $0040;
  STATUS_SUCCESS             = $00000000;
  ThreadQuerySetWin32StartAddress = 9;

type
  NTSTATUS = LONG;
  THREADINFOCLASS = DWORD;

function NtQueryInformationThread(
    ThreadHandle: THandle;  ThreadInformationClass: THREADINFOCLASS;
    ThreadInformation: Pointer; ThreadInformationLength: ULONG;  ReturnLength: PULONG): NTSTATUS; stdcall; external 'ntdll.dll';

function OpenThread(dwDesiredAccess: DWord;
                    bInheritHandle: Bool;
                    dwThreadId: DWord): DWord; stdcall; external 'kernel32.dll';


function GetThreadStartAddress(th32ThreadID : DWORD) : Pointer;
var
  hThread : THandle;
  ThreadStartAddress : Pointer;
begin
  Result:=0;
  hThread := OpenThread(THREAD_QUERY_INFORMATION , false, th32ThreadID);
  if (hThread = 0) then RaiseLastOSError;
  try
    if NtQueryInformationThread(hThread, ThreadQuerySetWin32StartAddress, @ThreadStartAddress, SizeOf(ThreadStartAddress), nil) = STATUS_SUCCESS then
      Result:=ThreadStartAddress
    else
    RaiseLastOSError;
  finally
      CloseHandle(hThread);
  end;
end;

function GetThreadsList(th32ProcessID:DWORD): Boolean;
var
  hSnapshot     : THandle;
  NextThread    : Boolean;
  TThreadEntry  : TThreadEntry32;
begin
  hSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); //Takes a snapshot of the all threads
  Result := (hSnapshot <> INVALID_HANDLE_VALUE);
  if Result then
    try
      TThreadEntry.dwSize := SizeOf(TThreadEntry);
      NextThread := Thread32First(hSnapshot, TThreadEntry);//get the first Thread
      while NextThread do
      begin
        if TThreadEntry.th32OwnerProcessID = th32ProcessID then //Check the owner Pid against the PID requested
            Writeln(Format('Thread Id %.8x Start Address %p',[TThreadEntry.th32ThreadID, GetThreadStartAddress(TThreadEntry.th32ThreadID)]));
        NextThread := Thread32Next(hSnapshot, TThreadEntry);//get the Next Thread
      end;
    finally
      CloseHandle(hSnapshot);
    end;
end;

begin
  try
    GetThreadsList(4028);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  readln;
end.

注意:要访问某些系统进程,您需要在应用中设置SeDebugPrivilege权限。