Enumerating Windows Processes

来源:互联网 发布:ubuntu复制目录命令 编辑:程序博客网 时间:2024/04/27 20:58

 

Download source code for this article (.zip, 193KB)
Original article (in Russian)
 

Introduction

Win32 offers several methods to enumerate currently running processes. Unfortunately, none of them works on every Win32 platform. Software developers have to combine several methods in their applications to ensure they will run on every Windows version.

In this article we will examine the following enumeration methods:

  • Using Process Status Helper (PSAPI) library
  • Using ToolHelp32 API
  • Using the undocumented ZwQuerySystemInformation function
  • Using performance counters
  • Using Windows Management Instrumentation interfaces
We will illustrate each method with a function that follows the prototype shown below:

// this callback function is called for each process in the enumeration typedef BOOL (CALLBACK * PFNENUMPROC)( IN DWORD dwProcessId, // process identifier IN PCTSTR pszProcessName, // process name IN LPARAM lParam // application-defined parameter ); // this function enumerates processes BOOL EnumProcesses_Method( IN PCTSTR pszMachineName, // computer name IN PFNENUMPROC pfnEnumProc, // application-defined callback function IN LPARAM lParam // application-defined parameter ); 
The enumeration function calls an application-defined callback function for each running process, passing process information as the callback function arguments. The callback function is supposed to deal with the process information in according to the application logic. For example, in the demo application for this article, it adds an item to the list of processes.

Some of methods covered in this article allows enumeration of processes on remote computers, therefore the enumeration function prototype has the pszMachineName parameter. The NULL value for this parameter means enumeration of processes on the local machine.

Method 1. Using Process Status Helper Library

The Process Status Helper library, also known as PSAPI, offers a set of functions that return certain information about processes and device drivers. The library is shipped with Windows 2000/XP and also available as a redistributable package for Windows NT 4.0.

For process enumeration purposes, PSAPI provides the EnumProcesses function that returns an array of identifiers of currently running processes. Below is the source code of the EnumProcesses_PsApi function that implements process enumeration using PSAPI.

onclick="toggleCode('1')"> Listing 1. Enumerating processes with PSAPI

Note that we link with PSAPI.DLL dynamically, loading the library with LoadLibrary and then obtaining addresses of necessary functions using GetProcAddress. This will allow us to include this function into an application that has to run on Windows 9x/Me, where PSAPI.DLL is not available. We will use this technique when implementing other enumeration methods, too.

The EnumProcesses function does not provide a way to know how much space is needed to receive all the identifiers. To deal with this limitation, we call EnumProcesses in a loop, increasing the the buffer size until the returned array size becomes less than the buffer size we allocated.
Since we want to obtain not only identifiers of processes but also their names, we have to do some additional work. For each process, we first get its handle with OpenProcess and then call EnumProcessModules, which returns a list of modules loaded into the process address space. The first module in the list is always the module representing the EXE-file used to create the process, so we get this handle and pass it to the GetModuleFileNameEx function (which is also a part of PSAPI) to obtain a path to the EXE-file. Finally, we strip path information from the file name and use this value as a process name.
Note the special handling of two processes in the source code of EnumProcesses_PsApi. We need to handle the System Idle Process, which identifier is always zero, and the System Process, which identifier depends on the operating system version, separately, because OpenProcess does not allow to obtain a handle to these processes and fails with ERROR_ACCESS_DENIED error.
If you run the demo application accompanying this article, you'll find that for at least one process the name is returned as "(name unavailable)". Using the Task Manager, it is easy to determine that this process is CSRSS.EXE. As it turns out, the system assigns such a security descriptor for this process, so it doesn't allow opening the process with access rights necessary to obtain its name.
On one hand, we could use the same approach as with two system processes. However, there is no guarantee that the identifier of this process is always the same. On the other hand, this issue can be resolved by enabling the SE_DEBUG_NAME privilege. When this privilege is turned on, the calling thread can open process handles with any access rights regardless the security descriptor assigned to the process. Since this privilege opens great opportunities to peneterate system security, it is normally granted only to system administrators. Because of this, we decided to not include the code for enabling this privilege into the EnumProcesses_PsApi function. If necessary, you can enable this privilege before calling EnumProcesses_PsApi, and the function will be able to return a name for the CSRSS.EXE process as well.

Method 2. Using ToolHelp32 API

Microsoft Corporation had added a set of functions named ToolHelp API to Windows 3.1 to get independed software vendors access to system information which was previously available only to Microsoft engineers. When Windows 95 was born, these functions migrated into the new system with ToolHelp32 name.

The Windows NT operating system from very beginning provides an interface known as "performance data" to obtain similar information. This interface is very intricate and inconvenient (to be honest, beginning with Windows NT 4.0, Microsoft provides the Performance Data Helper library that greatly simplifies accessing performance data; we will use this library in one of our methods). Rumors are the Windows NT development team was refusing to include ToolHelp32 API into the system for long time, but anyway, starting with Windows 2000, you can see this API in the Windows NT family of operating systems.
When using ToolHelp32 API, we first create a snapshot of the list of processes with the CreateToolhelp32Snapshot function and then walk through the list using Process32First and Process32Next functions. The PROCESSENTRY32 structure, which is filled by these functions, contains all the information we need. Below is the source code of the EnumProcesses_ToolHelp function that implements process enumeration using ToolHelp32 API.

onclick="toggleCode('2')"> Listing 2. Enumerating processes with ToolHelp32 API

Before calling Process32First or Process32Next, we have to initialize the dwSize field of the PROCESSENTRY32 structure with the structure size. The functions, in their turn, fill this field with the number of bytes stored into the structure. We compare this value with the offset of the szExeFile field to determine whether the process name was returned.


Method 3. Using the ZwQuerySystemInformation function

Despite the fact that a documented way exists to obtain the list of processes using performance data, the Windows NT Task Manager never used it. Instead, it calls the undocumented ZwQuerySystemInformation function. This function is exported from NTDLL.DLL and provides access to various system information and, in particular, to the list of currently running processes.

The ZwQuerySystemInformation function has the following prototype [2]:
NTSTATUS ZwQuerySystemInformation( IN ULONG SystemInformationClass, // information class IN OUT PVOID SystemInformation, // information buffer IN ULONG SystemInformationLength, // size of information buffer OUT PULONG ReturnLength OPTIONAL // receives information length ); 

SystemInformationClass

Specifies the type of the information to retrieve. We are interested in the SystemProcessesAndThreadsInformation (5).


SystemInformation

Pointer to a buffer that receives the information requested.


SystemInformationLength

Specifies the size of the receiving buffer.


ReturnLength

Optional pointer to a variable into which the function stores the number of bytes actually written into the output buffer.

The format of processes and threads information buffer is described by the SYSTEM_PROCESS_INFORMATION structure, which contains almost all the information displayed by the Task Manager. Below you can find the source code for the EnumProcesses_NtApi function that implements process enumeration using ZwQuerySystemInformation.

onclick="toggleCode('3')"> Listing 3. Enumerating processes using ZwQuerySystemInformation

When calling ZwQuerySystemInformation, it is difficult to predict which buffer size will be enough to receive all the information. Thus, we start with a 32K buffer and increase its size until the function returns success.

The SYSTEM_PROCESS_INFORMATION structure is a variable-size structure, the NextEntryDelta field specifies the offset to the next structure in the array. This field allows us to ignore the difference in size of the fixed part of the structure between Windows NT 4.0 and Windows 2000, where the IoCounters field was added to the structure.

Method 4. Using Performance Counters

As it was already noted, the Windows NT operating system from very beginning had an interface to obtain various system information in the form of performance counters. This interface is far from intuitive. In order to get the information, you have to read a value with a specially formed name from the HKEY_PERFORMANCE_DATA registry key. The information is returned in the form of deeply nested structures, many of which are of variable size. Dealing with these data structures requires a certain degree of diligence.

Fortunately, the situation had changed with introducing the Performance Data Helper (PDH) library in Windows NT 4.0. This library provides more convenient interface to performance data. However, the library wasn't being shipped with Windows NT 4.0, it was available as a redistributable in the Microsoft Platform SDK. Beginning with Windows 2000, PDH became a part of the system.
A detailed discussion of performance monitoring is beyond the scope of this article. Just let me note that the Windows NT performance monitoring architecture defines a concept of an object, for which performance counting is made. Examples of objects are processor and disk drive. Each object can have one or more instances along with a set of performance counters. Our ultimate goal is to enumerate all instances of the object named "Process", finding the value of the performance counter "ID Process" for each instance. Below is the code of the EnumProcesses_PerfData function, which uses PDH for process enumeration.

onclick="toggleCode('4')"> Listing 4. Enumerating processes using PDH

We return instance names as process names. If you run the demo application, you'll see that instance names are names of EXE-files of corresponding processes without an extension.

Object names and performance counter names are localizable. That means that, for example, on Russian version of Windows NT, process object and process identifier counter are no longer called "Process" and "ID Process", localized names are used instead. To get the localized names and format a full path to the performance counter we are interested in, we use a helper function named PerfFormatCounterPath. Its source code is provided below.

onclick="toggleCode('5')"> Listing 5. PerfFormatCounterPath source code

We use PdhLookupPerfNameByIndex to obtain localized names from corresponding indices. Indices of standard objects and performance counters are well-defined and don't depend on the operating system version, thus it is safe to specify them directly in the code.

Note, among all process enumeration methods we discussed so far, this is the first method that allows to enumerate processes on another machine. All we have to do is to set the machine name in the szMachineName field of the PDH_COUNTER_PATH_ELEMENTS structure.

Method 5. Using Windows Management Instrumentation

Windows Management Instrumentation (WMI) is Microsoft implementation of the Web-Based Enterprise Management (WBEM) initiative. WBEM provides a point of integration through which data from different management sources can be uniformly accessed, and it complements and extends existing management protocols such as SNMP. WBEM is based on the Common Information Model (CIM) schema, which is an industry standard maintained by DMTF (Distributed Management Task Force). WMI is included in Windows 2000 and Windows XP, but is also available as a redistributable package for Windows 9x/Me and Windows NT 4.0.

Any detailed discussion of WMI extends beyond the scope of this article. I'll just present the code that enumerates processes using WMI interfaces.

onclick="toggleCode('6')"> Listing 6. Enumerating processes using WMI interfaces

The fact that WMI is based on the COM technology saves us from explicit loading of necessary libraries as we did in all previous methods. The same fact requires you to initialize COM run-time before calling the process enumeration function. In an MFC application you can do it with AfxOleInit, in other cases you should use CoInitialize or CoInitializeEx functions.

Furthermore, using WMI requires initialization of the COM security with a call to CoInitializeSecurity:
 CoInitializeSecurity( NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_CONNECT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, 0); 
Note, same as the previous process enumeration method, this method allows enumeration of processes on remote machines. To enumerate processes remotely, you should specify computer name to IWbemLocator::ConnectServer.

Important note: Remote process enumeration in the form as it presented in this article will work only if the current user of the local machine has administrative privileges on the remote machine. The samples provided above do not allow to change credentials with which a connection to the remote machine is made. To specify alternative credentials in PDH method, you should call NetUseAdd or WNetAddConnection2 to establish a connection with IPC$ resource on the remote machine prior to calling the enumeration function. In WMI method, you should use standard COM methods for supplying alternative credentials.

Wrap Up

Well, we've seen five different methods to enumerate processes on Windows. None of them is universal, since there is alvays a Windows version there a particular method won't run. The table below summarizes applicability of the described methods.


 Windows 9x/MeWindows NT 4.0Windows 2000/XP
Method 1NoYes*Yes
Method 2YesNoYes
Method 3NoYesYes
Method 4NoYes*Yes
Method 5Yes*Yes*Yes
* Requires installation of additional components.
Using this table and the functions provided in the previous sections, it is easy to make a function for process enumeration, which will work on all Windows versions. For example, if you want to use PSAPI on Windows NT/2000/XP and ToolHelp32 API on Windows 9x/Me, such a function can look like following:

BOOL MyEnumProcesses( IN PFNENUMPROC pfnEnumProc, IN LPARAM lParam ) { OSVERSIONINFO osvi; osvi.dwOSVersionInfoSize = sizeof(osvi); if (osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) return EnumProcesses_ToolHelp(pfnEnumProc, lParam); else if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) return EnumProcesses_PsApi(pfnEnumProc, lParam); else return SetLastError(ERROR_CALL_NOT_IMPLEMENTED), FALSE; } 
This acticle is accompanied by a small demo application, ambitiously named Process Viewer, that demonstrates all five methods presented in the article. The implementation of all methods is in enumproc.h and enumproc.cpp files. I tried to arrange sources in such a way to make easier their reuse in other projects. To build the application you will need Microsoft Platform SDK. Happy coding!


References

  1. HOWTO: Enumerate Applications in Win32, Q175030, Microsoft Knowledge Base.
  2. Gary Nebbett, Windows NT/2000 Native API Reference. New Riders Publishing, 2000.
  3. INFO: Using PDH APIs Correctly in a Localized Language, Q287159, Microsoft Knowledge Base.
<!-- article copyright -->
原创粉丝点击