[高分求助] Windows下通过PID得到程序完整路径(包括svchost.exe)的方法
关于这个问题,我已经翻了不少网页了。不论是 GetModuleFileNameEx 还是 CreateToolhelp32Snapshot,都无法得到一些特定进程,如svchost.exe的完整路径。
请问这个问题可能实现吗?Windows任务管理器里很神奇的可以查阅到完整路径,里面究竟是如何实现的呢?
这是本人之前编写的一个小软件Netmon中遇到的一个问题,今天突然翻出来一狠心就GPL了,但是一直存在这个问题,特此发帖请教。
软件的介绍页面如下:
http://www.cnblogs.com/F-32/archive/2013/01/19/2867806.html
[解决办法]
ZwQueryInformationProcess
////////////////////////////////////////////////
//函数功能:通过进程ID获得进程的对应路径
//参 数:输入:dwProcessId,进程ID
// 输出:ProcessImagePath,进程所在路径,
// 这个变量必须先分配好空间
//返 回 值:NTSTATUS
////////////////////////////////////////////////
NTSTATUS
GetProcessImagePath(
IN ULONG dwProcessId,
OUT PUNICODE_STRING ProcessImagePath
)
{
NTSTATUS Status;
HANDLE hProcess;
PEPROCESS pEprocess;
ULONG returnedLength;
ULONG bufferLength;
PVOID buffer;
PUNICODE_STRING imageName;
PAGED_CODE(); // this eliminates the possibility of the IDLE Thread/Process
if (NULL == ZwQueryInformationProcess)
{
UNICODE_STRING routineName;
RtlInitUnicodeString(&routineName, L"ZwQueryInformationProcess");
ZwQueryInformationProcess =
(QUERY_INFO_PROCESS) MmGetSystemRoutineAddress(&routineName);
if (NULL == ZwQueryInformationProcess)
{
DbgPrint("Cannot resolve ZwQueryInformationProcess\n");
}
}
Status = PsLookupProcessByProcessId((HANDLE)dwProcessId, &pEprocess);
if (!NT_SUCCESS(Status))
return Status;
//Wdm中定义的全局变量 PsProcessType
Status = ObOpenObjectByPointer(pEprocess, // Object
OBJ_KERNEL_HANDLE, // HandleAttributes
NULL, // PassedAccessState OPTIONAL
GENERIC_READ, // DesiredAccess
*PsProcessType, // ObjectType
KernelMode, // AccessMode
&hProcess);
if (!NT_SUCCESS(Status))
return Status;
//
// Step one - get the size we need
//
Status = ZwQueryInformationProcess( hProcess,
ProcessImageFileName,
NULL, // buffer
0, // buffer size
&returnedLength);
if (STATUS_INFO_LENGTH_MISMATCH != Status)
{
return Status;
}
//
// Is the passed-in buffer going to be big enough for us?
// This function returns a single contguous buffer model...
//
bufferLength = returnedLength - sizeof(UNICODE_STRING);
if (ProcessImagePath->MaximumLength < bufferLength)
{
ProcessImagePath->Length = (USHORT) bufferLength;
return STATUS_BUFFER_OVERFLOW;
}
//
// If we get here, the buffer IS going to be big enough for us, so
// let's allocate some storage.
//
buffer = ExAllocatePoolWithTag(PagedPool, returnedLength, 'ipgD');
if (NULL == buffer)
{
return STATUS_INSUFFICIENT_RESOURCES;
}
//
// Now lets go get the data
//
Status = ZwQueryInformationProcess( hProcess,
ProcessImageFileName,
buffer,
returnedLength,
&returnedLength);
if (NT_SUCCESS(Status))
{
//
// Ah, we got what we needed
//
imageName = (PUNICODE_STRING) buffer;
RtlCopyUnicodeString(ProcessImagePath, imageName);
}
ZwClose(hProcess);
//
// free our buffer
//
ExFreePool(buffer);
//
// And tell the caller what happened.
//
return Status;
}