Process Internals

 < Day Day Up > 

This section describes the key Windows process data structures. Also listed are key kernel variables, performance counters, and functions and tools that relate to processes.

Data Structures

Each Windows process is represented by an executive process (EPROCESS) block. Besides containing many attributes relating to a process, an EPROCESS block contains and points to a number of other related data structures. For example, each process has one or more threads represented by executive thread (ETHREAD) blocks. (Thread data structures are explained in the section "Thread Internals" later in this chapter.) The EPROCESS block and its related data structures exist in system space, with the exception of the process environment block (PEB), which exists in the process address space (because it contains information that is modified by user-mode code).

In addition to the EPROCESS block, the Windows subsystem process (Csrss) maintains a parallel structure for each Windows process that executes a Windows program. Also, the kernelmode part of the Windows subsystem (Win32k.sys) has a per-process data structure that is created the first time a thread calls a Windows USER or GDI function that is implemented in kernel mode.

Figure 6-1 is a simplified diagram of the process and thread data structures. Each data structure shown in the figure is described in detail in this chapter.

Figure 6-1. Data structures associated with processes and threads


First let's focus on the process block. (We'll get to the thread block in the section "Thread Internals" later in the chapter.) Figure 6-2 shows the key fields in an EPROCESS block.

Figure 6-2. Structure of an executive process block


EXPERIMENT: Displaying the Format of an EPROCESS Block

For a list of the fields that make up an EPROCESS block and their offsets in hexadecimal, type dt _eprocess in the kernel debugger. (See Chapter 1 for more information on the kernel debugger and how to perform kernel debugging on the local system.) The output (truncated for the sake of space) looks like this:

lkd> dt _eprocess nt!_EPROCESS    +0x000Pcb              : _KPROCESS    +0x06cProcessLock      : _EX_PUSH_LOCK    +0x070CreateTime       : _LARGE_INTEGER    +0x078ExitTime         : _LARGE_INTEGER    +0x080RundownProtect   : _EX_RUNDOWN_REF    +0x084UniqueProcessId  : Ptr32Void    +0x088ActiveProcessLinks : _LIST_ENTRY    +0x090QuotaUsage       : [3]  Uint4B    +0x09cQuotaPeak        : [3]  Uint4B    +0x0a8CommitCharge     : Uint4B    +0x0acPeakVirtualSize  : Uint4B    +0x0b0VirtualSize      : Uint4B    +0x0b4SessionProcessLinks : _LIST_ENTRY    +0x0bcDebugPort        : Ptr32Void    +0x0c0ExceptionPort    : Ptr32Void    +0x0c4ObjectTable      : Ptr32_HANDLE_TABLE    +0x0c8Token            : _EX_FAST_REF    +0x0ccWorkingSetLock   : _FAST_MUTEX    +0x0ecWorkingSetPage   : Uint4B    +0x0f0AddressCreationLock : _FAST_MUTEX    +0x110HyperSpaceLock   : Uint4B    +0x114ForkInProgress   : Ptr32_ETHREAD    +0x118HardwareTrigger  : Uint4B

Note that the first field (Pcb) is actually a substructure, the kernel process block (KPROCESS), which is where scheduling-related information is stored. To display the format of the kernel process block, type dt_kprocess:

lkd>dt _kprocess nt!_KPROCESS    +0x000Header           : _DISPATCHER_HEADER    +0x010ProfileListHead  : _LIST_ENTRY    +0x018DirectoryTableBase : [2]Uint4B    +0x020LdtDescriptor    : _KGDTENTRY    +0x028Int21Descriptor  : _KIDTENTRY    +0x030IopmOffset       : Uint2B    +0x032Iopl             : UChar    +0x033Unused           : UChar    +0x034ActiveProcessors : Uint4B    +0x038KernelTime       : Uint4B    +0x03cUserTime         : Uint4B    +0x040ReadyListHead    : _LIST_ENTRY    +0x048SwapListEntry    : _SINGLE_LIST_ENTRY    +0x04cVdmTrapcHandler  : Ptr32Void    +0x050ThreadListHead   : _LIST_ENTRY    +0x058ProcessLock      : Uint4B    +0x05cAffinity         : Uint4B    +0x060StackCount       : Uint2B    +0x062BasePriority     : Char    +0x063ThreadQuantum    : Char    +0x064AutoAlignment    : UChar    +0x065State            : UChar    +0x066ThreadSeed       : UChar    +0x067DisableBoost     : UChar    +0x068PowerState       : UChar    +0x069DisableQuantum   : UChar    +0x06aIdealNode        : UChar    +0x06bSpare            : UChar

An alternate way to see the KPROCESS (and other substructures in the EPROCESS) is to use the recursion (-r) switch of the dt command. For example, typing dt _eprocess r1 will recurse and display all substructures one level deep.

The dt command shows the format of a process block, not its contents. To show an instance of an actual process, you can specify the address of an EPROCESS structure as an argument to the dt command. You can get the address of all the EPROCESS blocks in the system by using the !process 0 0 command. An annotated example of the output from this command is included later in this chapter.


Table 6-1 explains some of the fields in the preceding experiment in more detail and includes references to other places in the book where you can find more information about them. As we've said before and will no doubt say again, processes and threads are such an integral part of Windows that it's impossible to talk about them without referring to many other parts of the system. To keep the length of this chapter manageable, however, we've covered those related subjects (such as memory management, security, objects, and handles) elsewhere.

Table 6-1. Contents of the EPROCESS Block

Element

Purpose

Additional Reference

Kernel process (KPROCESS) block

Common dispatcher object header, pointer to the process page directory, list of kernel thread (KTHREAD) blocks belonging to the process, default base priority, quantum, affinity mask, and total kernel and user time for the threads in the process.

Thread Scheduling (Chapter 6)

Process identification

Unique process ID, creating process ID, name of image being run, window station process is running on.

 

Quota block

Limits on nonpaged pool, paged pool, and page file usage plus current and peak process nonpaged and paged pool usage. (Note: Several processes can share this structure: all the system processes point to the single systemwide default quota block; all the processes in the interactive session share a single quota block that Winlogon sets up.)

 

Virtual address descriptors (VADs)

Series of data structures that describes the status of the portions of the address space that exist in the process.

Virtual Address Descriptors (Chapter 7)

Working set information

Pointer to working set list (MMWSL structure); current, peak, minimum, and maximum working set size; last trim time; page fault count; memory priority; outswap flags; page fault history.

Working Sets (Chapter 7)

Virtual memory information

Current and peak virtual size, page file usage, hardware page table entry for process page directory.

Chapter 7

Exception local procedure call (LPC) port

Interprocess communication channel to which the process manager sends a message when one of the process's threads causes an exception.

Exception Dispatching (Chapter 3)

Debugging LPC port

Interprocess communication channel to which the process manager sends a message when one of the process's threads causes a debug event.

Local Procedure Calls (LPCs) (Chapter 3)

Access token (ACCESS_TOKEN)

Executive object describing the security profile of this process.

Chapter 8

Handle table

Address of per-process handle table.

Object Handles and the Process Handle Table (Chapter 3)

Device map

Address of object directory to resolve device name references in (supports multiple users).

Object Names (Chapter 3)

Process environment block (PEB)

Image information (base address, version numbers, module list), process heap information, and threadlocal storage utilization. (Note: The pointers to the process heaps start at the first byte after the PEB.)

Chapter 6

Windows subsystem process block (W32PROCESS)

Process details needed by the kernel-mode component of the Windows subsystem.

 


The kernel process (KPROCESS) block, which is part of the EPROCESS block, and the process environment block (PEB), which is pointed to by the EPROCESS block, contain additional details about the process object. The KPROCESS block (which is sometimes called the PCB, or process control block) is illustrated in Figure 6-3. It contains the basic information that the Windows kernel needs to schedule threads. (Page directories are covered in Chapter 7, and kernel thread blocks are described in more detail later in this chapter.)

Figure 6-3. Structure of the executive process block


The PEB, which lives in the user process address space, contains information needed by the image loader, the heap manager, and other Windows system DLLs that need to modify it from user mode. (The EPROCESS and KPROCESS blocks are accessible only from kernel mode.) The basic structure of the PEB is illustrated in Figure 6-4 and is explained in more detail later in this chapter.

Figure 6-4. Fields of the process environment block


EXPERIMENT: Examining the PEB

You can dump the PEB structure with the !peb command in the kernel debugger. To get the address of the PEB, use the !process command as follows:

lkd> !process PROCESS 8575f030 SessionId: 0 Cid: 08d0 Peb: 7ffdf000 ParentCid: 0360     DirBase: 1a81b000 ObjectTable: e12bd418 HandleCount: 66.     Image: windbg.exe

Then specify that address to the !peb command as follows:

lkd> !peb7ffdf000 PEB at 7ffdf000     InheritedAddressSpace:    No     ReadImageFileExecOptions: No     BeingDebugged:            No     ImageBaseAddress:         01000000     Ldr                       00181e90     Ldr.Initialized:          Yes     Ldr.InInitializationOrderModuleList: 00181f28 . 00183188     Ldr.InLoadOrderModuleList:           00181ec0 . 00183178     Ldr.InMemoryOrderModuleList:         00181ec8 . 00183180             BaseTimeStamp                      Module          1000000 40478dbd Mar 04 15:12:45 2004 C:\Program  Files \DebuggingToolsfor              Windows\windbg.exe         77f500003eb1b41a  May01  19:56:10  2003  C:\WINDOWS \System32\ntdll.dll         77e600003d6dfa28  Aug29  06:40:40  2002  C:\WINDOWS \system32\kernel32.dll          200000040476db2  Mar04  12:56:02  2004  C:\Program Files \DebuggingToolsfor              Windows\dbgeng.dll         .     SubSystemData:     00000000     ProcessHeap:       00080000     ProcessParameters: 00020000     WindowTitle:   'C:\Documents  and  Settings\AllUsers\Start   Menu\Programs\Debugging         Tools  for  Windows\WinDbg.lnk'     ImageFile:     'C:\ProgramFiles\DebuggingTools  forWindows \windbg.exe'     CommandLine:   '"C:\Program  Files\Debugging  Toolsfor   Windows\windbg.exe" '     DllPath:       'C:\ProgramFiles\DebuggingToolsforWindows;C: \WINDOWS\System32;C: \WINDOWS\system;C:\WINDOWS;.;C:\Program  Files\Windows   ResourceKits\Tools\;C:\WINDOWS\ system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\ProgramFiles \SupportTools\;c:\sysint ;C:\ProgramFiles\ATI  Technologies\ATIControl  Panel;C: \ProgramFiles\Resource  Kit\;C: \PROGRA~1\CA\Common\SCANEN~1;C:\PROGRA~1\CA\eTrust\ANTIVI~1;C: \ProgramFiles\Common     Files\RoxioShared\DLLShared;C:\SFU\common\'     Environment:    00010000         =::=::\         ALLUSERSPROFILE=C:\Documents  andSettings\All  Users         APPDATA=C:\Documents  and  Settings\dsolomon\ApplicationData     


Kernel Variables

A few key kernel global variables that relate to processes are listed in Table 6-2. These variables are referred to later in the chapter, when the steps in creating a process are described.

Table 6-2. Process-Related Kernel Variables

Variable

Type

Description

PsActiveProcessHead

Queue header

List head of process blocks

PsIdleProcess

EPROCESS

Idle process block

PsInitialSystemProcess

Pointer to EPROCESS

Pointer to the process block of the initial system process that contains the system threads

PspCreateProcessNotifyRoutine

Array of pointers

Array of pointers to routines to be called on process creation and deletion (maximum of eight)

PspCreateProcessNotifyRoutineCount

DWORD

Count of registered process notification routines

PspLoadImageNotifyRoutine

Array of pointers

Array of pointers to routines to be called on image load

PspLoadImageNotifyRoutineCount

DWORD

Count of registered imageload notification routines

PspCidTable

Pointer to HANDLE_TABLE

Handle table for process and thread client IDs


Performance Counters

Windows maintains a number of counters with which you can track the processes running on your system; you can retrieve these counters programmatically or view them with the Performance tool. Table 6-3 lists the performance counters relevant to processes (except for memory management and I/O-related counters, which are described in Chapters 7 and 9, respectively).

Table 6-3. Process-Related Performance Counters

Object: Counter

Function

Process: % Privileged Time

Describes the percentage of time that the threads in the process have run in kernel mode during a specified interval.

Process: % Processor Time

Describes the percentage of CPU time that the threads in the process have used during a specified interval. This count is the sum of % Privileged Time and % User Time.

Process: % User Time

Describes the percentage of time that the threads in the process have run in user mode during a specified interval.

Process: Elapsed Time

Describes the total elapsed time in seconds since this process was created.

Process: ID Process

Returns the process ID. This ID applies only while the process exists because process IDs are reused.

Process: Creating Process ID

Returns the process ID of the creating process. This value isn't updated if the creating process exits.

Process: Thread Count

Returns the number of threads in the process.

Process: Handle Count

Returns the number of handles open in the process.


Relevant Functions

For reference purposes, some of the Windows functions that apply to processes are described in Table 6-4. For further information, consult the Windows API documentation in the MSDN Library.

Table 6-4. Process-Related Functions

Function

Description

CreateProcess

Creates a new process and thread using the caller's security identification

CreateProcessAsUser

Creates a new process and thread with the specified alternate security token

CreateProcessWithLogonW

Creates a new process and thread to run under the credentials of the specified username and password

CreateProcessWithTokenW

Creates a new process and thread with the specified alternate security token, with additional options such as allowing the user profile to be loaded

OpenProcess

Returns a handle to the specified process object

ExitProcess

Ends a process, and notifies all attached DLLs

TerminateProcess

Ends a process without notifying the DLLs

FlushInstructionCache

Empties the specified process's instruction cache

GetProcessTimes

Obtains a process's timing information, describing how much time the process has spent in user and kernel mode

GetExitCodeProcess

Returns the exit code for a process, indicating how and why the process shut down

GetCommandLine

Returns a pointer to the command-line string passed to the current process

GetCurrentProcess

Returns a pseudo handle for the current process

GetCurrentProcessId

Returns the ID of the current process

GetProcessVersion

Returns the major and minor versions of the Windows version on which the specified process expects to run

GetStartupInfo

Returns the contents of the STARTUPINFO structure specified during CreateProcess

GetEnvironmentStrings

Returns the address of the environment block

GetEnvironmentVariable

Returns a specific environment variable

Get/SetProcessShutdownParameters

Defines the shutdown priority and number of retries for the current process

GetGuiResources

Returns a count of User and GDI handles


EXPERIMENT: Using the Kernel Debugger !process Command

The kernel debugger !process command displays a subset of the information in an EPROCESS block. This output is arranged in two parts for each process. First you see the information about the process, as shown here (when you don't specify a process address or ID, !process lists information for the active process on the current CPU):

lkd> !process PROCESS  8575f030    SessionId: 0    Cid:  08d0    Peb: 7ffdf000   ParentCid: 0360     DirBase: 1a81b000    ObjectTable:  e12bd418 HandleCount: 65.     Image:windbg.exe     VadRoot  857f05e0 Vads  71 Clone 0  Private  1152.   Modified98. Locked 1.     DeviceMap e1e96c88     Token                                e1f5b8a8     ElapsedTime                          1:23:06.0219     UserTime                             0:00:11.0897     KernelTime                           0:00:07.0450     QuotaPoolUsage[PagedPool]            38068     QuotaPoolUsage[NonPagedPool]         2840     Working Set Sizes (now,min,max)      (2552,  50,  345)   (10208KB, 200KB, 1380KB)     PeakWorkingSetSize                   2715     VirtualSize                          41  Mb     PeakVirtualSize                      41  Mb     PageFaultCount                       3658     MemoryPriority                       BACKGROUND     BasePriority                         8     CommitCharge                         1566

After the basic process output comes a list of the threads in the process. That output is explained in the "Experiment: Using the Kernel Debugger !thread Command" section later in the chapter. Other commands that display process information include !handle, which dumps the process handle table (which is described in more detail in the section "Object Handles and the Process Handle Table" in Chapter 3). Process and thread security structures are described in Chapter 8.


     < Day Day Up > 


    Microsoft Windows Internals
    Microsoft Windows Internals (4th Edition): Microsoft Windows Server 2003, Windows XP, and Windows 2000
    ISBN: 0735619174
    EAN: 2147483647
    Year: 2004
    Pages: 158

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net