這是一個比較簡單的問題,在 REGON 的源碼中可以找到實現的相關代碼,我只是把它們整理封裝了一下。
//
// Process name max length: by bytes
// (This value is 16 bytes in RegMon)
//
#define MAX_PROC_NAME_LEN 256
//
// This is the offset into a KPEB of the current process name. This is determined
// dynamically by scanning the process block belonging to the GUI for its name.
//
ULONG ProcessNameOffset = 0;
//----------------------------------------------------------------------
//
// GetProcessNameOffset
//
// In an effort to remain version-independent, rather than using a
// hard-coded into the KPEB (Kernel Process Environment Block), we
// scan the KPEB looking for the name, which should match that
// of the GUI process
//
//----------------------------------------------------------------------
ULONG
GetProcessNameOffset(
VOID
)
{
PEPROCESS curproc;
int i;
curproc = PsGetCurrentProcess();
//
// Scan for 12KB, hopping the KPEB never grows that big!
//
for( i = 0; i < 3*PAGE_SIZE; i++ ) {
if( !strncmp( "System", (PCHAR) curproc + i, strlen("System") )) {
return i;
}
}
//
// Name not found - oh, well
//
return 0;
}
//----------------------------------------------------------------------
//
// initialization interface
//
//----------------------------------------------------------------------
//
// initialize the ProcessNameOffset when the driver is loading.
// (Call in DriverEntry())
//
NTSTATUS
ProcessInfo_LoadInit()
{
ProcessNameOffset = GetProcessNameOffset();
return STATUS_SUCCESS;
}
//----------------------------------------------------------------------
//
// GetCurrentProcessName
//
// Uses undocumented data structure offsets to obtain the name of the
// currently executing process.
//
//----------------------------------------------------------------------
PCHAR
GetCurrentProcessName()
{
PEPROCESS curproc;
char *nameptr;
ULONG i;
static CHAR szName[MAX_PROC_NAME_LEN];
//
// We only try and get the name if we located the name offset
//
if( ProcessNameOffset ) {
//
// Get a pointer to the current process block
//
curproc = PsGetCurrentProcess();
//
// Dig into it to extract the name. Make sure to leave enough room
// in the buffer for the appended process ID.
//
nameptr = (PCHAR) curproc + ProcessNameOffset;
strncpy( szName, nameptr, MAX_PROC_NAME_LEN-1 );
szName[MAX_PROC_NAME_LEN-1] = 0;
/* for 64 bit system
#if defined(_M_IA64)
sprintf( szName + strlen(szName), ":%I64d", PsGetCurrentProcessId());
#else
sprintf( szName + strlen(szName), ":%d", (ULONG) PsGetCurrentProcessId());
#endif
//*/
} else {
strcpy( szName, "???");
}
return szName;
}