Process Hacker Discussion Forum

 
Zorkov Igor
Member
Posts: 112
Joined: 18 Jan 2011 10:11
OS: Windows 7, 10
Contact:

Delphi: Get the image file name of any process from any user

18 Jan 2011 10:33

Get the image file name of any process from any user on Vista and above
http://wj32.wordpress.com/2010/03/30/ge ... and-above/


Delphi translation
[delphi]
type
NTSTATUS = Integer;

const
STATUS_SUCCESS = NTSTATUS($00000000);
STATUS_INFO_LENGTH_MISMATCH = NTSTATUS($C0000004);

type
UNICODE_STRING = packed record
Length,
MaximumLength: WORD;
Buffer: PWideChar;
end;
TUnicodeString = UNICODE_STRING;
PUnicodeString = ^TUnicodeString;

SYSTEM_PROCESS_IMAGE_NAME_INFORMATION = packed record
ProcessId: Cardinal;
ImageName: UNICODE_STRING;
end;
PSYSTEM_PROCESS_IMAGE_NAME_INFORMATION = ^SYSTEM_PROCESS_IMAGE_NAME_INFORMATION;

type
TNtQuerySystemInformation = function(SystemInformationClass: LongInt;SystemInformation: Pointer;SystemInformationLength: ULONG; ReturnLength: PDWORD): Integer; stdcall;

var
NtQuerySystemInformation: TNtQuerySystemInformation;

function _DOSFileName(lpDeviceFileName: PWideChar; var FileName: WideString): Boolean;
var
lpDeviceName: array[0..1024] of WideChar;
lpDrive: WideString;
actDrive: WideChar;
begin
Result := False;
FileName := '';
for actDrive := 'A' to 'Z' do
begin
lpDrive := WideString(actDrive) + ':';
if (QueryDosDeviceW(PWideChar(lpDrive), lpDeviceName, 1024) <> 0) then
begin
if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, lpDeviceName, lstrlenW(lpDeviceName),
lpDeviceFileName, lstrlenW(lpDeviceName)) = CSTR_EQUAL) then
begin
FileName := WideString(lpDeviceFileName);
Delete(FileName, 1, lstrlenW(lpDeviceName));
FileName := WideString(lpDrive) + FileName;
Result := True;
Break;
end;
end;
end;
end;

function _GetImagePath_Vista(ProcessId: Cardinal): WideString;
var
ReturnStatus: NTSTATUS;
ImageNameInformation: SYSTEM_PROCESS_IMAGE_NAME_INFORMATION;
begin
Result:= '';
if (@NtQuerySystemInformation = nil) then
Exit;
ImageNameInformation.ProcessId := ProcessId;
ImageNameInformation.ImageName.Length := 0;
ImageNameInformation.ImageName.MaximumLength := $1000;
GetMem(ImageNameInformation.ImageName.Buffer, $1000);
ReturnStatus := NtQuerySystemInformation(88, @ImageNameInformation, SizeOf(ImageNameInformation), nil);
try
if ReturnStatus = STATUS_SUCCESS then
_DOSFileName(ImageNameInformation.ImageName.Buffer, Result);
finally
FreeMem(ImageNameInformation.ImageName.Buffer);
ImageNameInformation.ImageName.Buffer := nil;
end;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
hLibrary: Cardinal;
begin
hLibrary := LoadLibrary('ntdll.dll');
if hLibrary <> 0 then
@NtQuerySystemInformation := GetProcAddress(hLibrary, 'NtQuerySystemInformation');
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
Caption:= _GetImagePath_Vista(388)
end
[/delphi]