Basic Debugging

A debugger is an application that enables a developer to observe and correct programming errors. This overview describes the basic debugging functions provided by Windows.

  • About Basic Debugging
  • Debugging Reference
Microsoft Platform SDK, February 2001 Edition.
This content last built on Thursday, February 01, 2001.


About Basic Debugging

The debugging functions can be used to create a basic, event-driven debugger. Event-driven means that the debugger is notified every time certain events occur in the process being debugged. Notification enables the debugger to take appropriate action in response to the events.

Debug Support from Process, Thread, and Exception Functions describes the debugging-specific features of certain process, thread, and exception-handling functions.

Creating a Basic Debugger describes using the basic debugging functions to create a simple debugger. These functions enable an application to wait for debugging events, cause breakpoint exceptions, transfer execution control to the debugger, and so on.

Debugging Events describes the debug event mechanism. Debugging events cause the system to notify the debugger.


Debug Support from Process, Thread, and Exception Functions

Some functions essential to debugging are actually classified as process, thread, or exception-handling functions. For a description of how to start a process that is going to be debugged, see Process Functions. For information on how to examine and manipulate the context and execution of a thread, see Thread Functions. For a description of how a debugger should handle exceptions, see Exception Handling Functions.


Process Functions for Debugging

The CreateProcess function enables a debugger to start a process and debug it. The fdwCreate parameter of CreateProcess is used to specify the type of debugging operation. If the DEBUG_PROCESS flag is specified for the parameter, a debugger debugs the new process and all of the process's descendants, provided that the descendants are created without the DEBUG_PROCESS flag.

If the DEBUG_PROCESS and DEBUG_ONLY_THIS_PROCESS flags are specified for fdwCreate, a debugger debugs the new process but none of its descendants.

One debugger can debug another by creating a process with the DEBUG_PROCESS flag. The new process (the debugger being debugged) must then create a process with the DEBUG_PROCESS flag.

The OpenProcess function enables a debugger to obtain the identifier of an existing process. (The DebugActiveProcess function uses this identifier to attach the debugger to the process.) Typically, debuggers open a process with the PROCESS_VM_READ and PROCESS_VM_WRITE flags. Using these flags enables the debugger to read from and write to the virtual memory of the process by using the ReadProcessMemory and WriteProcessMemory functions. For more information, see Processes and Threads.


Thread Functions for Debugging

The CreateThread function creates a new thread for a process. Debuggers typically need to examine or change the contents of a thread's registers. To accomplish this, a debugger must obtain a handle to the thread by using the DuplicateHandle function and specifying the appropriate access to the thread (THREAD_GET_CONTEXT, THREAD_SET_CONTEXT, or both). The OpenThread function enables a debugger to obtain the identifier of an existing thread.

A process with appropriate access to a thread can examine the thread's registers by using the GetThreadContext function and set the contents of the thread's registers by using the SetThreadContext function.

A process can also obtain THREAD_SUSPEND_RESUME access to a thread. This type of access enables a debugger to control a thread's execution with the SuspendThread and ResumeThread functions. For more information about threads, see Processes and Threads.


Exception Functions for Debugging

Platform SDK: Debugging and Error Handling

Exception Handling Functions for Debugging

When an exception occurs in a process that is being debugged, the system notifies the debugger by passing the exception to it. This is known as first-chance notification. The system then suspends all threads in the process being debugged.

If the debugger does not handle the exception, the system attempts to locate an appropriate exception handler. If the system cannot locate an appropriate one, the system again notifies the debugger that an exception has occurred. This is known as last-chance notification. If the debugger does not handle the exception after the last-chance notification, the system terminates the process being debugged.

For more information, see Debugger Exception Handling.


Creating a Basic Debugger

Debugging a Running Process describes attaching the debugger to a running process. Writing the Debugger's Main Loop describes the functions used in the debugger's main loop of execution.

Although most of the debugging functions are used to create a debugger, several functions are designed for use in the process being debugged. For more information, see Communicating with the Debugger.


Debugging a Running Process

To debug a process that is already running, the debugger should use DebugActiveProcess with the process identifier retrieved by OpenProcess. DebugActiveProcess attaches the debugger to the active process. In this case, only the active process can be debugged; its child processes cannot. The debugger must have appropriate access to the executing process to use DebugActiveProcess. For more information about access rights, see Access Control.

After the debugger has either created or attached itself to the process it intends to debug, the system notifies the debugger of all debugging events that occur in the process, and, if specified, in any child processes. For more information about debugging events, see Debugging Events.

To detach from the process being debugged, the debugger should use the DebugActiveProcessStop function.


Writing the Debugger's Main Loop

The debugger uses the WaitForDebugEvent function at the beginning of its main loop. This function blocks the debugger until a debugging event occurs. When the debugging event occurs, the system suspends all threads in the process being debugged and notifies the debugger of the event.

The debugger can interact with the user, or manipulate the state of the process being debugged, by using the GetThreadContext, GetThreadSelectorEntry, ReadProcessMemory, SetThreadContext, and WriteProcessMemory functions. GetThreadSelectorEntry returns the descriptor table entry for a specified selector and thread. Debuggers use the descriptor table entry to convert a segment-relative address to a linear virtual address. The ReadProcessMemory and WriteProcessMemory functions require linear virtual addresses.

Debuggers frequently read the memory of the process being debugged and write the memory that contains instructions to the instruction cache. After the instructions are written, the debugger calls the FlushInstructionCache function to execute the cached instructions.

The debugger uses the ContinueDebugEvent function at the end of its main loop. This function allows the process being debugged to continue executing.

The following example uses the WaitForDebugEvent and ContinueDebugEvent functions to illustrate how a simple debugger might be organized.

DEBUG_EVENT DebugEv;                   // debugging event information
DWORD dwContinueStatus = DBG_CONTINUE; // exception continuation

for(;;)
{

// Wait for a debugging event to occur. The second parameter indicates
// that the function does not return until a debugging event occurs.

    WaitForDebugEvent(&DebugEv, INFINITE);

// Process the debugging event code.

    switch (DebugEv.dwDebugEventCode)
    {
        case EXCEPTION_DEBUG_EVENT:
        // Process the exception code. When handling
        // exceptions, remember to set the continuation
        // status parameter (dwContinueStatus). This value
        // is used by the ContinueDebugEvent function.

            switch (DebugEv.u.Exception.ExceptionRecord.ExceptionCode)
            {
                case EXCEPTION_ACCESS_VIOLATION:
                // First chance: Pass this on to the system.
                // Last chance: Display an appropriate error.

                case EXCEPTION_BREAKPOINT:
                // First chance: Display the current
                // instruction and register values.

                case EXCEPTION_DATATYPE_MISALIGNMENT:
                // First chance: Pass this on to the system.
                // Last chance: Display an appropriate error.

                case EXCEPTION_SINGLE_STEP:
                // First chance: Update the display of the
                // current instruction and register values.

                case DBG_CONTROL_C:
                // First chance: Pass this on to the system.
                // Last chance: Display an appropriate error.

                // Handle other exceptions.
            }

        case CREATE_THREAD_DEBUG_EVENT:
        // As needed, examine or change the thread's registers
        // with the GetThreadContext and SetThreadContext functions;
        // and suspend and resume thread execution with the
        // SuspendThread and ResumeThread functions.

        case CREATE_PROCESS_DEBUG_EVENT:
        // As needed, examine or change the registers of the
        // process's initial thread with the GetThreadContext and
        // SetThreadContext functions; read from and write to the
        // process's virtual memory with the ReadProcessMemory and
        // WriteProcessMemory functions; and suspend and resume
        // thread execution with the SuspendThread and ResumeThread
        // functions.

        case EXIT_THREAD_DEBUG_EVENT:
        // Display the thread's exit code.

        case EXIT_PROCESS_DEBUG_EVENT:
        // Display the process's exit code.

        case LOAD_DLL_DEBUG_EVENT:
        // Read the debugging information included in the newly
        // loaded DLL.

        case UNLOAD_DLL_DEBUG_EVENT:
        // Display a message that the DLL has been unloaded.

        case OUTPUT_DEBUG_STRING_EVENT:
        // Display the output debugging string.

    }

// Resume executing the thread that reported the debugging event.

ContinueDebugEvent(DebugEv.dwProcessId,
    DebugEv.dwThreadId, dwContinueStatus);

}


Communicating with the Debugger

The OutputDebugString function sends a string from the process being debugged to the debugger by generating an OUTPUT_DEBUG_STRING_EVENT debugging event. A process can detect whether it is being debugged by calling the IsDebuggerPresent function.

The DebugBreak function causes a breakpoint exception in the current process. A breakpoint is a location in a program where execution is stopped to allow the developer to examine the program's code, variables, and register values and, as necessary, to make changes, continue execution, or terminate execution.

The FatalExit function terminates the current process and gives execution control to the debugger, but unlike DebugBreak, it does not generate an exception. This function should only be used as a last resort, because it does not always free the process's memory or close its files.


Debugging Events

A debugging event is an incident in the process being debugged that causes the system to notify the debugger. Debugging events include creating a process, creating a thread, loading a dynamic-link library (DLL), unloading a DLL, sending an output string, and generating an exception.

If a debugging event occurs while a debugger is waiting for one, the system fills the DEBUG_EVENT structure specified by WaitForDebugEvent with information describing the event.

When the system notifies the debugger of a debugging event, it also suspends all threads in the affected process. The threads do not resume execution until the debugger continues the debugging event by using ContinueDebugEvent. The following debugging events may occur while a process is being debugged.

Debugging event Description
CREATE_PROCESS_DEBUG_EVENT Generated whenever a new process is created in a process being debugged or whenever the debugger begins debugging an already active process. The system generates this debugging event before the process begins to execute in user mode and before the system generates any other debugging events for the new process.

The DEBUG_EVENT structure contains a CREATE_PROCESS_DEBUG_INFO structure. This structure includes a handle to the new process, a handle to the process's image file, a handle to the process's initial thread, and other information that describes the new process.

The handle to the process has PROCESS_VM_READ and PROCESS_VM_WRITE access. If a debugger has these types of access to a thread, it can read and write to the process's memory by using the ReadProcessMemory and WriteProcessMemory functions.

The handle to the process's image file has GENERIC_READ access and is opened for read-sharing.

The handle to the process's initial thread has THREAD_GET_CONTEXT, THREAD_SET_CONTEXT, and THREAD_SUSPEND_RESUME access to the thread. If a debugger has these types of access to a thread, it can read from and write to the thread's registers by using the GetThreadContext and SetThreadContext functions and can suspend and resume the thread by using the SuspendThread and ResumeThread functions.
CREATE_THREAD_DEBUG_EVENT Generated whenever a new thread is created in a process being debugged or whenever the debugger begins debugging an already active process. This debugging event is generated before the new thread begins to execute in user mode.

The DEBUG_EVENT structure contains a CREATE_THREAD_DEBUG_INFO structure. This structure includes a handle to the new thread and the thread's starting address. The handle has THREAD_GET_CONTEXT, THREAD_SET_CONTEXT, and THREAD_SUSPEND_RESUME access to the thread. If a debugger has these types of access to a thread, it can read from and write to the thread's registers by using the GetThreadContext and SetThreadContext functions and can suspend and resume the thread by using the SuspendThread and ResumeThread functions.
EXCEPTION_DEBUG_EVENT Generated whenever an exception occurs in the process being debugged. Possible exceptions include attempting to access inaccessible memory, executing breakpoint instructions, attempting to divide by zero, or any other exception noted in Structured Exception Handling.

The DEBUG_EVENT structure contains an EXCEPTION_DEBUG_INFO structure. This structure describes the exception that caused the debugging event.

Besides the standard exception conditions, an additional exception code can occur during console process debugging. The system generates a DBG_CONTROL_C exception code when CTRL+C is input to a console process that handles CTRL+C signals and is being debugged. This exception code is not meant to be handled by applications. An application should never use an exception handler to deal with it. It is raised only for the benefit of the debugger and is only used when a debugger is attached to the console process.

If a process is not being debugged or if the debugger passes on the DBG_CONTROL_C exception unhandled (through the gn command), the application's list of handler functions is searched, as documented for the SetConsoleCtrlHandler function.

If the debugger handles the DBG_CONTROL_C exception (through the gh command), an application will not notice the CTRL+C except in code like this.

while ((inputChar = getchar()) != EOF) ...

or

while (gets(inputString)) ...

Thus, the debugger cannot be used to stop the read wait in such code from terminating.
EXIT_PROCESS_DEBUG_EVENT Generated whenever the last thread in a process being debugged exits. This debugging event occurs immediately after the system unloads the process's DLLs and updates the process's exit code.

The DEBUG_EVENT structure contains an EXIT_PROCESS_DEBUG_INFO structure that specifies the exit code.

The debugger deallocates any internal structures associated with the process on receipt of this debugging event. The system closes the debugger's handle to the exiting process and all of the process's threads. The debugger should not close these handles.
EXIT_THREAD_DEBUG_EVENT Generated whenever a thread that is part of a process being debugged exits. The system generates this debugging event immediately after it updates the thread's exit code.

The DEBUG_EVENT structure contains an EXIT_THREAD_DEBUG_INFO structure that specifies the exit code.

This debugging event does not occur if the exiting thread is the last thread of a process. In this case, the EXIT_PROCESS_DEBUG_EVENT debugging event occurs instead.

The debugger deallocates any internal structures associated with the thread on receipt of this debugging event. The system closes the debugger's handle to the exiting thread. The debugger should not close this handle.

LOAD_DLL_DEBUG_EVENT Generated whenever a process being debugged loads a DLL. This debugging event occurs when the system loader resolves links to a DLL or when the debugged process uses the LoadLibrary function. This debugging event only occurs the first time the system attaches a DLL to the virtual address space of a process.

The DEBUG_EVENT structure contains a LOAD_DLL_DEBUG_INFO structure. This structure includes a handle to the newly loaded DLL, the base address of the DLL, and other information that describes the DLL.

Typically, a debugger loads a symbol table associated with the DLL on receipt of this debugging event.
OUTPUT_DEBUG_STRING_EVENT Generated when a process being debugged uses the OutputDebugString function.

The DEBUG_EVENT structure contains an OUTPUT_DEBUG_STRING_INFO structure. This structure specifies the address, length, and format of the debugging string.
UNLOAD_DLL_DEBUG_EVENT Generated whenever a process being debugged unloads a DLL by using the FreeLibrary function. This debugging event only occurs the last time a DLL is unloaded from a process's address space (that is, when the DLL's usage count is zero).

The DEBUG_EVENT structure contains an UNLOAD_DLL_DEBUG_INFO structure. This structure specifies the base address of the DLL in the address space of the process that unloads the DLL.

Typically, a debugger unloads a symbol table associated with the DLL upon receiving this debugging event.

When a process exits, the system automatically unloads the process's DLLs, but does not generate an UNLOAD_DLL_DEBUG_EVENT debugging event.


Debugging Reference

The following elements are used with debugging.

  • Debugging Functions
  • Debugging Structures


Debugging Functions

The following functions are used with debugging.

Function | Description
ContinueDebugEvent | Enables a debugger to continue a thread that previously reported a debugging event.
DebugActiveProcess | Enables a debugger to attach to an active process and debug it.
DebugActiveProcessStop | Stops the debugger from debugging the specified process.
DebugBreak | Causes a breakpoint exception to occur in the current process.
DebugSetProcessKillOnExit | Sets the action to be performed when the debugging thread exits.
FatalExit | Transfers execution control to the debugger.
FlushInstructionCache | Flushes the instruction cache for the specified process.
GetThreadContext | Retrieves the context of the specified thread.
GetThreadSelectorEntry | Retrieves a descriptor table entry for the specified selector and thread.
IsDebuggerPresent | Determines whether the calling process is running under the context of a debugger.
OutputDebugString | Sends a string to the debugger for display.
ReadProcessMemory | Reads data from an area of memory in a specified process.
SetThreadContext | Sets the context for the specified thread.
WaitForDebugEvent | Waits for a debugging event to occur in a process being debugged.
WriteProcessMemory | Writes data to an area of memory in a specified process.


ContinueDebugEvent

The ContinueDebugEvent function enables a debugger to continue a thread that previously reported a debugging event.

BOOL ContinueDebugEvent(
  DWORD dwProcessId,       // process to continue
  DWORD dwThreadId,        // thread to continue
  DWORD dwContinueStatus   // continuation status
);

Parameters

dwProcessId
[in] Handle to the process to continue.
dwThreadId
[in] Handle to the thread to continue. The combination of process identifier and thread identifier must identify a thread that has previously reported a debugging event.
dwContinueStatus
[in] Specifies how to continue the thread that reported the debugging event.

If the DBG_CONTINUE flag is specified for this parameter and the thread specified by the dwThreadId parameter previously reported an EXCEPTION_DEBUG_EVENT debugging event, the function stops all exception processing and continues the thread. For any other debugging event, this flag simply continues the thread.

If the DBG_EXCEPTION_NOT_HANDLED flag is specified for this parameter and the thread specified by dwThreadId previously reported an EXCEPTION_DEBUG_EVENT debugging event, the function continues exception processing. If this is a first-chance exception event, the search and dispatch logic of the structured exception handler is used; otherwise, the process is terminated. For any other debugging event, this flag simply continues the thread.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Only the thread that created dwProcessId with the CreateProcess function can call ContinueDebugEvent.

After the ContinueDebugEvent function succeeds, the specified thread continues. Depending on the debugging event previously reported by the thread, different actions occur. If the continued thread previously reported an EXIT_THREAD_DEBUG_EVENT debugging event, ContinueDebugEvent closes the handle the debugger has to the thread. If the continued thread previously reported an EXIT_PROCESS_DEBUG_EVENT debugging event, ContinueDebugEvent closes the handles the debugger has to the process and to the thread.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Basic Debugging Overview, Debugging Functions, CreateProcess


DebugActiveProcess

The DebugActiveProcess function enables a debugger to attach to an active process and debug it.

BOOL DebugActiveProcess(
  DWORD dwProcessId   // process to be debugged
);

Parameters

dwProcessId
[in] Specifies the identifier for the process to be debugged. The debugger gets debugging access to the process as if it created the process with the DEBUG_ONLY_THIS_PROCESS flag. See the Remarks section for more details.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

To stop debugging the process, you must exit the process or call the DebugActiveProcessStop function. Exiting the debugger will also exit the process unless you use the DebugSetProcessKillOnExit function.

The debugger must have appropriate access to the target process; it must be able to open the process for PROCESS_ALL_ACCESS access. On Windows 95/98, the debugger has appropriate access if the process identifier is valid. However, on Windows NT/Windows 2000, DebugActiveProcess can fail if the target process was created with a security descriptor that grants the debugger anything less than full access. Note that if the debugging process has the SE_DEBUG_NAME privilege granted and enabled, it can debug any process.

After the system checks the process identifier and determines that a valid debugging attachment is being made, the function returns TRUE. The debugger is then expected to wait for debugging events by using the WaitForDebugEvent function. The system suspends all threads in the process and sends the debugger events representing the current state of the process.

The system sends the debugger a single CREATE_PROCESS_DEBUG_EVENT debugging event representing the process specified by the dwProcessId parameter. The lpStartAddress member of the CREATE_PROCESS_DEBUG_INFO structure is NULL.

For each thread currently part of the process, the system sends a CREATE_THREAD_DEBUG_EVENT debugging event. The lpStartAddress member of the CREATE_THREAD_DEBUG_INFO structure is NULL.

For each dynamic-link library (DLL) currently loaded into the address space of the target process, the system sends a LOAD_DLL_DEBUG_EVENT debugging event. The system arranges for the first thread in the process to execute a breakpoint instruction after it resumes. Continuing this thread causes it to return to whatever it was doing before the debugger was attached.

After all of this has been done, the system resumes all threads in the process. When the first thread in the process resumes, it executes a breakpoint instruction that causes an EXCEPTION_DEBUG_EVENT debugging event to be sent to the debugger. All future debugging events are sent to the debugger by using the normal mechanism and rules.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Basic Debugging Overview, Debugging Functions, CreateProcess, CREATE_PROCESS_DEBUG_INFO, CREATE_THREAD_DEBUG_INFO, DebugActiveProcessStop, WaitForDebugEvent


DebugActiveProcessStop

[This is preliminary documentation and subject to change.]

The DebugActiveProcessStop function stops the debugger from debugging the specified process.

BOOL DebugActiveProcessStop(
  DWORD dwProcessId
);

Parameters

dwProcessId
[in] Specifies the process identifier of the process to stop debugging.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Basic Debugging Overview, Debugging Functions, DebugActiveProcess


DebugBreak

The DebugBreak function causes a breakpoint exception to occur in the current process so that the calling thread can signal the debugger and force it to take some action. If the process is not being debugged, the search logic of a standard exception handler is used. In most cases, this causes the calling process to terminate because of an unhandled breakpoint exception.

VOID DebugBreak(VOID);

Parameters

This function has no parameters.

Return Values

This function does not return a value.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Basic Debugging Overview, Debugging Functions, DebugActiveProcess


DebugSetProcessKillOnExit

[This is preliminary documentation and subject to change.]

The DebugSetProcessKillOnExit function sets the action to be performed when the debugging thread exits.

BOOL DebugSetProcessKillOnExit (
  BOOL KillOnExit
);

Parameters

KillOnExit
[in] If this parameter is TRUE, the debug thread, on exit, will kill the process being debugged. Otherwise, the debug thread, on exit, will detach from the process being debugged.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Basic Debugging Overview, Debugging Functions, DebugActiveProcessStop


FatalExit

The FatalExit function transfers execution control to the debugger. The behavior of the debugger thereafter is specific to the type of debugger used.

VOID FatalExit(
  int ExitCode   // error code
);

Parameters

ExitCode
[in] Specifies the error code associated with the exit.

Return Values

This function does not return a value.

Remarks

An application should only use FatalExit for debugging purposes. It should not call the function in a retail version of the application because doing so will terminate the application.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Basic Debugging Overview, Debugging Functions, FatalAppExit


FlushInstructionCache

The FlushInstructionCache function flushes the instruction cache for the specified process.

BOOL FlushInstructionCache(
  HANDLE hProcess,        // handle to process
  LPCVOID lpBaseAddress,  // base of region to flush
  SIZE_T dwSize           // length of region to flush
);

Parameters

hProcess
[in] Handle to a process whose instruction cache is to be flushed.
lpBaseAddress
[in] Pointer to the base of the region to be flushed. This parameter can be NULL.
dwSize
[in] Specifies the length, in bytes, of the region to be flushed if the lpBaseAddress parameter is not NULL.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Windows NT/2000 or later: Applications should call FlushInstructionCache if they generate or modify code in memory. The CPU cannot detect the change, and may execute the old code it cached.

Windows 95/98/Me: The FlushInstructionCache function has no effect; it always returns TRUE.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Basic Debugging Overview, Debugging Functions


GetThreadContext

The GetThreadContext function retrieves the context of the specified thread.

BOOL GetThreadContext(
  HANDLE hThread,       // handle to thread with context
  LPCONTEXT lpContext   // context structure
);

Parameters

hThread
[in] Handle to the thread whose context is to be retrieved.

Windows NT/2000 or later: The handle must have THREAD_GET_CONTEXT access to the thread. For more information, see Thread Security and Access Rights.

lpContext
[in/out] Pointer to the CONTEXT structure that receives the appropriate context of the specified thread. The value of the ContextFlags member of this structure specifies which portions of a thread's context are retrieved. The CONTEXT structure is highly computer specific. Currently, there are CONTEXT structures defined for Intel, MIPS, Alpha, and PowerPC processors. Refer to the WinNt.h header file for definitions of these structures.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The GetThreadContext function is used to retrieve the context of the specified thread. The function allows a selective context to be retrieved based on the value of the ContextFlags member of the CONTEXT structure. The thread handle identified by the hThread parameter is typically being debugged, but the function can also operate when it is not being debugged.

You cannot get a valid context for a running thread. Use the SuspendThread function to suspend the thread before calling GetThreadContext.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Basic Debugging Overview, Debugging Functions, CONTEXT, SetThreadContext, SuspendThread


GetThreadSelectorEntry

The GetThreadSelectorEntry function retrieves a descriptor table entry for the specified selector and thread.

BOOL GetThreadSelectorEntry(
  HANDLE hThread,              // handle to thread
  DWORD dwSelector,            // number of selector value
  LPLDT_ENTRY lpSelectorEntry  // descriptor table entry
);

Parameters

hThread
[in] Handle to the thread containing the specified selector.

Windows NT/2000 or later: The handle must have THREAD_QUERY_INFORMATION access. For more information, see Thread Security and Access Rights.

dwSelector
[in] Specifies the global or local selector value to look up in the thread's descriptor tables.
lpSelectorEntry
[out] Pointer to an LDT_ENTRY structure that receives a copy of the descriptor table entry if the specified selector has an entry in the specified thread's descriptor table. This information can be used to convert a segment-relative address to a linear virtual address.

Return Values

If the function succeeds, the return value is nonzero. In that case, the structure pointed to by the lpSelectorEntry parameter receives a copy of the specified descriptor table entry.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

GetThreadSelectorEntry is only functional on x86-based systems. For systems that are not x86-based, the function returns FALSE.

Debuggers use this function to convert segment-relative addresses to linear virtual addresses. The ReadProcessMemory and WriteProcessMemory functions use linear virtual addresses.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Basic Debugging Overview, Debugging Functions, LDT_ENTRY, ReadProcessMemory, WriteProcessMemory


IsDebuggerPresent

The IsDebuggerPresent function determines whether the calling process is running under the context of a debugger.

BOOL IsDebuggerPresent(VOID);

Parameters

This function has no parameters.

Return Value

If the current process is running in the context of a debugger, the return value is nonzero.

If the current process is not running in the context of a debugger, the return value is zero.

Remarks

This function allows an application to determine whether or not it is being debugged, so that it can modify its behavior. For example, an application could provide additional information using the OutputDebugString function if it is being debugged.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Basic Debugging Overview, Debugging Functions, OutputDebugString


OutputDebugString

The OutputDebugString function sends a string to the debugger for display.

VOID OutputDebugString(
  LPCTSTR lpOutputString   // string to be displayed
);

Parameters

lpOutputString
[in] Pointer to the null-terminated string to be displayed.

Return Values

This function does not return a value.

Remarks

If the application has no debugger, the system debugger displays the string. If the application has no debugger and the system debugger is not active, OutputDebugString does nothing.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Basic Debugging Overview, Debugging Functions


ReadProcessMemory

The ReadProcessMemory function reads data from an area of memory in a specified process. The entire area to be read must be accessible, or the operation fails.

BOOL ReadProcessMemory(
  HANDLE hProcess,              // handle to the process
  LPCVOID lpBaseAddress,        // base of memory area
  LPVOID lpBuffer,              // data buffer
  SIZE_T nSize,                 // number of bytes to read
  SIZE_T * lpNumberOfBytesRead  // number of bytes read
);

Parameters

hProcess
[in] Handle to the process whose memory is being read. The handle must have PROCESS_VM_READ access to the process.
lpBaseAddress
[in] Pointer to the base address in the specified process from which to read. Before any data transfer occurs, the system verifies that all data in the base address and memory of the specified size is accessible for read access. If this is the case, the function proceeds; otherwise, the function fails.
lpBuffer
[out] Pointer to a buffer that receives the contents from the address space of the specified process.
nSize
[in] Specifies the requested number of bytes to read from the specified process.
lpNumberOfBytesRead
[out] Pointer to a variable that receives the number of bytes transferred into the specified buffer. If lpNumberOfBytesRead is NULL, the parameter is ignored.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

The function fails if the requested read operation crosses into an area of the process that is inaccessible.

Remarks

ReadProcessMemory copies the data in the specified address range from the address space of the specified process into the specified buffer of the current process. Any process that has a handle with PROCESS_VM_READ access can call the function. The process whose address space is read is typically, but not necessarily, being debugged.

The entire area to be read must be accessible. If it is not, the function fails as noted previously.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Basic Debugging Overview, Debugging Functions, WriteProcessMemory


SetThreadContext

The SetThreadContext function sets the context for the specified thread.

BOOL SetThreadContext(
  HANDLE hThread,            // handle to thread
  CONST CONTEXT *lpContext   // context structure
);

Parameters

hThread
[in] Handle to the thread whose context is to be set.

Windows NT/2000 or later: The handle must have the THREAD_SET_CONTEXT access right to the thread. For more information, see Thread Security and Access Rights.

lpContext
[in] Pointer to the CONTEXT structure that contains the context to be set in the specified thread. The value of the ContextFlags member of this structure specifies which portions of a thread's context to set. Some values in the CONTEXT structure that cannot be specified are silently set to the correct value. This includes bits in the CPU status register that specify the privileged processor mode, global enabling bits in the debugging register, and other states that must be controlled by the operating system.

Return Values

If the context was set, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The function allows the selective context to be set based on the value of the ContextFlags member of the context structure. The thread handle identified by the hThread parameter is typically being debugged, but the function can also operate even when it is not being debugged.

Do not try to set the context for a running thread; the results are unpredictable. Use the SuspendThread function to suspend the thread before calling SetThreadContext.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Basic Debugging Overview, Debugging Functions, CONTEXT, GetThreadContext, SuspendThread


WaitForDebugEvent

The WaitForDebugEvent function waits for a debugging event to occur in a process being debugged.

BOOL WaitForDebugEvent(
  LPDEBUG_EVENT lpDebugEvent,  // debug event information
  DWORD dwMilliseconds         // time-out value
);

Parameters

lpDebugEvent
[out] Pointer to a DEBUG_EVENT structure that receives information about the debugging event.
dwMilliseconds
[in] Specifies the number of milliseconds to wait for a debugging event. If this parameter is zero, the function tests for a debugging event and returns immediately. If the parameter is INFINITE, the function does not return until a debugging event has occurred.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Only the thread that created the process being debugged can call WaitForDebugEvent.

When a CREATE_PROCESS_DEBUG_EVENT occurs, the debugger application receives a handle to the image file of the process being debugged, a handle to the process being debugged, and a handle to the initial thread of the process being debugged in the DEBUG_EVENT structure. The DEBUG_EVENT members these handles are returned in are u.CreateProcessInfo.hFile, u.CreateProcessInfo.hProcess, and u.CreateProcessInfo.hThread respectively. The system will close these handles. The debugger should not close these handles.

Similarly, when a CREATE_THREAD_DEBUG_EVENT occurs, the debugger application receives a handle to the thread whose creation caused the debugging event in the uCreateThread.hThread member of the DEBUG_EVENT structure. This handle should also not be closed by the debugger application, as it will be closed by the system.

Also, when a LOAD_DLL_DEBUG_EVENT occurs, the debugger application receives a handle to the loaded DLL in the u.LoadDll.hFile member of the DEBUG_EVENT structure. This handle should be closed by the debugger application by calling the CloseHandle function when the corresponding UNLOAD_DLL_DEBUG_EVENT occurs.

Warning Do not queue an asynchronous procedure call (APC) to a thread that calls WaitForDebugEvent.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Basic Debugging Overview, Debugging Functions, ContinueDebugEvent, DebugActiveProcess, DebugBreak, DEBUG_EVENT, OutputDebugString


WriteProcessMemory

The WriteProcessMemory function writes data to an area of memory in a specified process. The entire area to be written to must be accessible, or the operation fails.

BOOL WriteProcessMemory(
  HANDLE hProcess,                // handle to process
  LPVOID lpBaseAddress,           // base of memory area
  LPVOID lpBuffer,                // data buffer
  SIZE_T nSize,                   // count of bytes to write
  SIZE_T * lpNumberOfBytesWritten // count of bytes written
);

Parameters

hProcess
[in] Handle to the process whose memory is to be modified. The handle must have PROCESS_VM_WRITE and PROCESS_VM_OPERATION access to the process.
lpBaseAddress
[in] Pointer to the base address in the specified process to which data will be written. Before any data transfer occurs, the system verifies that all data in the base address and memory of the specified size is accessible for write access. If this is the case, the function proceeds; otherwise, the function fails.
lpBuffer
[in] Pointer to the buffer that contains data to be written into the address space of the specified process.
nSize
[in] Specifies the requested number of bytes to write into the specified process.
lpNumberOfBytesWritten
[out] Pointer to a variable that receives the number of bytes transferred into the specified process. This parameter is optional. If lpNumberOfBytesWritten is NULL, the parameter is ignored.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError. The function will fail if the requested write operation crosses into an area of the process that is inaccessible.

Remarks

WriteProcessMemory copies the data from the specified buffer in the current process to the address range of the specified process. Any process that has a handle with PROCESS_VM_WRITE and PROCESS_VM_OPERATION access to the process to be written to can call the function. The process whose address space is being written to is typically, but not necessarily, being debugged.

The entire area to be written to must be accessible. If it is not, the function fails as noted previously.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Basic Debugging Overview, Debugging Functions, ReadProcessMemory


Debugging Structures

The following structures are used with debugging.

CONTEXT
CREATE_PROCESS_DEBUG_INFO
CREATE_THREAD_DEBUG_INFO
DEBUG_EVENT
EXCEPTION_DEBUG_INFO
EXIT_PROCESS_DEBUG_INFO
EXIT_THREAD_DEBUG_INFO
LDT_ENTRY
LOAD_DLL_DEBUG_INFO
OUTPUT_DEBUG_STRING_INFO
RIP_INFO
UNLOAD_DLL_DEBUG_INFO


CONTEXT

A CONTEXT structure contains processor-specific register data. The system uses CONTEXT structures to perform various internal operations. Currently, there are CONTEXT structures defined for Intel, MIPS, Alpha, and PowerPC, processors. Refer to the header file WinNT.h for definitions of these structures.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winnt.h; include Windows.h.

See Also

Basic Debugging Overview, Debugging Structures


CREATE_PROCESS_DEBUG_INFO

The CREATE_PROCESS_DEBUG_INFO structure contains process creation information that can be used by a debugger.

typedef struct _CREATE_PROCESS_DEBUG_INFO {
  HANDLE hFile;
  HANDLE hProcess;
  HANDLE hThread;
  LPVOID lpBaseOfImage;
  DWORD dwDebugInfoFileOffset;
  DWORD nDebugInfoSize;
  LPVOID lpThreadLocalBase;
  LPTHREAD_START_ROUTINE lpStartAddress;
  LPVOID lpImageName;
  WORD fUnicode;
} CREATE_PROCESS_DEBUG_INFO, *LPCREATE_PROCESS_DEBUG_INFO;

Members

hFile
Handle to the process's image file. If this member is NULL, the handle is not valid. Otherwise, the debugger can use the member to read from and write to the image file.
hProcess
Handle to the process. If this member is NULL, the handle is not valid. Otherwise, the debugger can use the member to read from and write to the process's memory.
hThread
Handle to the initial thread of the process identified by the hProcess member. If hThread is NULL, the handle is not valid. Otherwise, the debugger has THREAD_GET_CONTEXT, THREAD_SET_CONTEXT, and THREAD_SUSPEND_RESUME access to the thread, allowing the debugger to read from and write to the registers of the thread and to control execution of the thread.
lpBaseOfImage
Pointer to the base address of the executable image that the process is running.
dwDebugInfoFileOffset
Specifies the offset to the debugging information in the file identified by the hFile member. The system expects the debugging information to be in Microsoft® CodeView® version 4.0 format. This format is currently a derivative of COFF (Common Object File Format).
nDebugInfoSize
Specifies the size, in bytes, of the debugging information in the file. If this value is zero, there is no debugging information.
lpThreadLocalBase
Pointer to a block of data. At offset 0x2C into this block is another pointer, called ThreadLocalStoragePointer, that points to an array of per-module thread local storage blocks. This gives a debugger access to per-thread data in the threads of the process being debugged using the same algorithms that a compiler would use.
lpStartAddress
Pointer to the starting address of the thread. This value may only be an approximation of the thread's starting address, because any application with appropriate access to the thread can change the thread's context by using the SetThreadContext function.
lpImageName
Pointer to the filename associated with the hFile parameter. This parameter may be NULL, or it may contain the address of a string pointer in the address space of the process being debugged. That address may, in turn, either be NULL or point to the actual filename. If fUnicode is a nonzero value, the name string is Unicode; otherwise, it is ANSI.

This member is strictly optional. Debuggers must be prepared to handle the case where lpImageName is NULL or *lpImageName (in the address space of the process being debugged) is NULL. Specifically, the system does not provide an image name for a create process event, and will not likely pass an image name for the first DLL event. The system also does not provide this information in the case of debug events that originate from a call to the DebugActiveProcess function.

fUnicode
Indicates whether a file name specified by the lpImageName member is Unicode or ANSI. A nonzero value indicates Unicode; zero indicates ANSI.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

Basic Debugging Overview, Debugging Structures, CREATE_THREAD_DEBUG_INFO, DebugActiveProcess, DEBUG_EVENT, LOAD_DLL_DEBUG_INFO, SetThreadContext


CREATE_THREAD_DEBUG_INFO

The CREATE_THREAD_DEBUG_INFO structure contains thread-creation information that can be used by a debugger.

typedef struct _CREATE_THREAD_DEBUG_INFO {
  HANDLE hThread;
  LPVOID lpThreadLocalBase;
  LPTHREAD_START_ROUTINE lpStartAddress;
} CREATE_THREAD_DEBUG_INFO, *LPCREATE_THREAD_DEBUG_INFO;

Members

hThread
Handle to the thread whose creation caused the debugging event. If this member is NULL, the handle is not valid. Otherwise, the debugger has THREAD_GET_CONTEXT, THREAD_SET_CONTEXT, and THREAD_SUSPEND_RESUME access to the thread, allowing the debugger to read from and write to the registers of the thread and control execution of the thread.
lpThreadLocalBase
Pointer to a block of data. At offset 0x2C into this block is another pointer, called ThreadLocalStoragePointer, that points to an array of per-module thread local storage blocks. This gives a debugger access to per-thread data in the threads of the process being debugged using the same algorithms that a compiler would use.
lpStartAddress
Pointer to the starting address of the thread. This value may only be an approximation of the thread's starting address, because any application with appropriate access to the thread can change the thread's context by using the SetThreadContext function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

Basic Debugging Overview, Debugging Structures, CREATE_PROCESS_DEBUG_INFO, DEBUG_EVENT, LOAD_DLL_DEBUG_INFO, SetThreadContext


DEBUG_EVENT

The DEBUG_EVENT structure describes a debugging event.

typedef struct _DEBUG_EVENT {
  DWORD dwDebugEventCode;
  DWORD dwProcessId;
  DWORD dwThreadId;
  union {
      EXCEPTION_DEBUG_INFO Exception;
      CREATE_THREAD_DEBUG_INFO CreateThread;
      CREATE_PROCESS_DEBUG_INFO CreateProcessInfo;
      EXIT_THREAD_DEBUG_INFO ExitThread;
      EXIT_PROCESS_DEBUG_INFO ExitProcess;
      LOAD_DLL_DEBUG_INFO LoadDll;
      UNLOAD_DLL_DEBUG_INFO UnloadDll;
      OUTPUT_DEBUG_STRING_INFO DebugString;
      RIP_INFO RipInfo;
  } u;
} DEBUG_EVENT, *LPDEBUG_EVENT;

Members

dwDebugEventCode
Specifies a debugging event code that identifies the type of debugging event. This parameter can be one of the following values.
Value | Meaning
EXCEPTION_DEBUG_EVENT | Reports an exception debugging event. The value of u.Exception specifies an EXCEPTION_DEBUG_INFO structure.
CREATE_THREAD_DEBUG_EVENT | Reports a create-thread debugging event. The value of u.CreateThread specifies a CREATE_THREAD_DEBUG_INFO structure.
CREATE_PROCESS_DEBUG_EVENT | Reports a create-process debugging event. The value of u.CreateProcessInfo specifies a CREATE_PROCESS_DEBUG_INFO structure.
EXIT_THREAD_DEBUG_EVENT | Reports an exit-thread debugging event. The value of u.ExitThread specifies an EXIT_THREAD_DEBUG_INFO structure.
EXIT_PROCESS_DEBUG_EVENT | Reports an exit-process debugging event. The value of u.ExitProcess specifies an EXIT_PROCESS_DEBUG_INFO structure.
LOAD_DLL_DEBUG_EVENT | Reports a load-dynamic-link-library (DLL) debugging event. The value of u.LoadDll specifies a LOAD_DLL_DEBUG_INFO structure.
UNLOAD_DLL_DEBUG_EVENT | Reports an unload-DLL debugging event. The value of u.UnloadDll specifies an UNLOAD_DLL_DEBUG_INFO structure.
OUTPUT_DEBUG_STRING_EVENT | Reports an output-debugging-string debugging event. The value of u.DebugString specifies an OUTPUT_DEBUG_STRING_INFO structure.
RIP_EVENT | Reports a RIP-debugging event (system debugging error). The value of u.RipInfo specifies a RIP_INFO structure.

dwProcessId
Specifies the identifier of the process in which the debugging event occurred. A debugger uses this value to locate the debugger's per-process structure. These values are not necessarily small integers that can be used as table indices.
dwThreadId
Specifies the identifier of the thread in which the debugging event occurred. A debugger uses this value to locate the debugger's per-thread structure. These values are not necessarily small integers that can be used as table indices.
u
Specifies additional information relating to the debugging event. This union takes on the type and value appropriate to the type of debugging event, as described in the dwDebugEventCode member.

Remarks

If the WaitForDebugEvent function succeeds, it fills in the members of a DEBUG_EVENT structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

Basic Debugging Overview, Debugging Structures, CREATE_PROCESS_DEBUG_INFO, CREATE_THREAD_DEBUG_INFO, EXIT_PROCESS_DEBUG_INFO, EXIT_THREAD_DEBUG_INFO, EXCEPTION_DEBUG_INFO, LOAD_DLL_DEBUG_INFO, OUTPUT_DEBUG_STRING_INFO, UNLOAD_DLL_DEBUG_INFO, WaitForDebugEvent


EXCEPTION_DEBUG_INFO

The EXCEPTION_DEBUG_INFO structure contains exception information that can be used by a debugger.

typedef struct _EXCEPTION_DEBUG_INFO {
  EXCEPTION_RECORD ExceptionRecord;
  DWORD dwFirstChance;
} EXCEPTION_DEBUG_INFO, *LPEXCEPTION_DEBUG_INFO;

Members

ExceptionRecord
Contains an EXCEPTION_RECORD structure with information specific to the exception. This includes the exception code, flags, address, a pointer to a related exception, extra parameters, and so on.
dwFirstChance
Indicates whether the debugger has previously encountered the exception specified by the ExceptionRecord member. If the dwFirstChance member is nonzero, this is the first time the debugger has encountered the exception. Debuggers typically handle breakpoint and single-step exceptions when they are first encountered. If this member is zero, the debugger has previously encountered the exception. This occurs only if, during the search for structured exception handlers, either no handler was found or the exception was continued.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

Basic Debugging Overview, Debugging Structures, DEBUG_EVENT, EXCEPTION_RECORD


EXIT_PROCESS_DEBUG_INFO

The EXIT_PROCESS_DEBUG_INFO structure contains an exiting process's exit code.

typedef struct _EXIT_PROCESS_DEBUG_INFO {
  DWORD dwExitCode;
} EXIT_PROCESS_DEBUG_INFO, *LPEXIT_PROCESS_DEBUG_INFO;

Members

dwExitCode
Specifies the exit code for the process.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

Basic Debugging Overview, Debugging Structures, DEBUG_EVENT


EXIT_THREAD_DEBUG_INFO

The EXIT_THREAD_DEBUG_INFO structure contains an exiting thread's exit code.

typedef struct _EXIT_THREAD_DEBUG_INFO {
  DWORD dwExitCode;
} EXIT_THREAD_DEBUG_INFO, *LPEXIT_THREAD_DEBUG_INFO;

Members

dwExitCode
Specifies the exit code for the thread.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

Basic Debugging Overview, Debugging Structures, DEBUG_EVENT


LDT_ENTRY

The LDT_ENTRY structure describes an entry in the descriptor table. This structure is valid only on x86-based systems.

typedef struct _LDT_ENTRY {
  WORD LimitLow;
  WORD BaseLow;
  union {
      struct {
          BYTE BaseMid;
          BYTE Flags1;
          BYTE Flags2;
          BYTE BaseHi;
      } Bytes;
      struct {
          DWORD BaseMid : 8;
          DWORD Type : 5;
          DWORD Dpl : 2;
          DWORD Pres : 1;
          DWORD LimitHi : 4;
          DWORD Sys : 1;
          DWORD Reserved_0 : 1;
          DWORD Default_Big : 1;
          DWORD Granularity : 1;
          DWORD BaseHi : 8;
      } Bits;
  } HighWord;
} LDT_ENTRY, *PLDT_ENTRY;

Members

LimitLow
Contains the low 16 bits of the address of the last byte in the segment.
BaseLow
Contains the low 16 bits of the base address of the segment.
HighWord
Contains the high two words of the descriptor. This member may be interpreted as bytes or collections of bits, depending on the level of detail required.

The members of the Bits structure are as follows.
Member | Contents
BaseMid | Middle bits (16–23) of the base address of the segment.
Type | Bitmask that indicates the type of segment. This member can be one of the following values:
Value | Meaning
0 | Read-only data segment
1 | Read-write data segment
2 | Unused segment
3 | Read-write expand-down data segment
4 | Execute-only code segment
5 | Executable-readable code segment
6 | Execute-only "conforming" code segment
7 | Executable-readable "conforming" code segment
Dpl | Privilege level of the descriptor. This member is an integer value in the range 0 (most privileged) through 3 (least privileged).
Pres | Present flag. This member is 1 if the segment is present in physical memory or 0 if it is not.
LimitHi | High bits (16–19) of the address of the last byte in the segment.
Sys | Space that is available to system programmers. This member might be used for marking segments in some system-specific way.
Reserved_0 | Reserved.
Default_Big Size of segment. If the segment is a data segment, this member contains 1 if the segment is larger than 64 kilobytes (K) or 0 if the segment is smaller than or equal to 64K.

If the segment is a code segment, this member contains 1 if the segment is a code segment and runs with the default (native mode) instruction set. This member contains 0 if the code segment is an 80286 code segment and runs with 16-bit offsets and the 80286-compatible instruction set.
Granularity | Granularity. This member contains 0 if the segment is byte granular, 1 if the segment is page granular.
BaseHi | High bits (24–31) of the base address of the segment.

The members of the Bytes structure are as follows.
Member | Contents
BaseMid | Middle bits (16–23) of the base address of the segment.
Flags1 | Values of the Type, Dpl, and Pres members in the Bits structure.
Flags2 | Values of the LimitHi, Sys, Reserved_0, Default_Big, and Granularity members in the Bits structure.
BaseHi | High bits (24–31) of the base address of the segment.

Remarks

The GetThreadSelectorEntry function fills this structure with information from an entry in the descriptor table. You can use this information to convert a segment-relative address to a linear virtual address.

The base address of a segment is the address of offset 0 in the segment. To calculate this value, combine the BaseLow, BaseMid, and BaseHi members.

The limit of a segment is the address of the last byte that can be addressed in the segment. To calculate this value, combine the LimitLow and LimitHi members.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winnt.h; include Windows.h.

See Also

Basic Debugging Overview, Debugging Structures, GetThreadSelectorEntry


LOAD_DLL_DEBUG_INFO

The LOAD_DLL_DEBUG_INFO structure contains information about a dynamic-link library (DLL) that has just been loaded.

typedef struct _LOAD_DLL_DEBUG_INFO {
  HANDLE hFile;
  LPVOID lpBaseOfDll;
  DWORD  dwDebugInfoFileOffset;
  DWORD  nDebugInfoSize;
  LPVOID lpImageName;
  WORD fUnicode;
} LOAD_DLL_DEBUG_INFO, *LPLOAD_DLL_DEBUG_INFO;

Members

hFile
Handle to the loaded DLL. If this member is NULL, the handle is not valid. Otherwise, the member is opened for reading and read-sharing in the context of the debugger.
lpBaseOfDll
Pointer to the base address of the DLL in the address space of the process loading the DLL.
dwDebugInfoFileOffset
Specifies the offset to the debugging information in the file identified by the hFile member. The system expects the debugging information to be in CodeView 4.0 format. This format is currently a derivative of Common Object File Format (COFF).
nDebugInfoSize
Specifies the size, in bytes, of the debugging information in the file. If this value is zero, there is no debugging information.
lpImageName
Pointer to the filename associated with hFile. This member may be NULL, or it may contain the address of a string pointer in the address space of the process being debugged. That address may, in turn, either be NULL or point to the actual filename. If fUnicode is a nonzero value, the name string is Unicode; otherwise, it is ANSI.

This member is strictly optional. Debuggers must be prepared to handle the case where lpImageName is NULL or *lpImageName (in the address space of the process being debugged) is NULL. Specifically, the system will never provide an image name for a create process event, and it will not likely pass an image name for the first DLL event. The system will also never provide this information in the case of debugging events that originate from a call to the DebugActiveProcess function.

fUnicode
Indicates whether a filename specified by lpImageName is Unicode or ANSI. A nonzero value for this member indicates Unicode; zero indicates ANSI.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

Basic Debugging Overview, Debugging Structures, CREATE_PROCESS_DEBUG_INFO, CREATE_THREAD_DEBUG_INFO, DebugActiveProcess, DEBUG_EVENT


OUTPUT_DEBUG_STRING_INFO

The OUTPUT_DEBUG_STRING_INFO structure contains the address, format, and length, in bytes, of a debugging string.

typedef struct _OUTPUT_DEBUG_STRING_INFO {
  LPSTR lpDebugStringData;
  WORD  fUnicode;
  WORD  nDebugStringLength;
} OUTPUT_DEBUG_STRING_INFO, *LPOUTPUT_DEBUG_STRING_INFO;

Members

lpDebugStringData
Pointer to the debugging string in the calling process's address space. The debugger can use the ReadProcessMemory function to retrieve the value of the string.
fUnicode
Specifies the format of the debugging string. If this member is zero, the debugging string is ANSI; if it is nonzero, the string is Unicode.
nDebugStringLength
Specifies the length, in characters, of the debugging string. The length includes the string's terminating null character.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

Basic Debugging Overview, Debugging Structures, DEBUG_EVENT, ReadProcessMemory


RIP_INFO

The RIP_INFO structure contains the error and address, format, and length, in bytes, of a debugging string.

typedef struct _RIP_INFO {
  DWORD  dwError;
  DWORD  dwType;
} RIP_INFO, *LPRIP_INFO;

Members

dwError
Specifies the error that caused the RIP debug event. For more information, see Error Handling.
dwType
Specifies additional information about the type of error that caused the RIP debug event. This member can be one of the following values.
Value | Meaning
SLE_ERROR | Indicates that invalid data was passed to the function that failed. This caused the application to fail.
SLE_MINORERROR | Indicates that invalid data was passed to the function, but the error probably will not cause the application to fail.
SLE_WARNING | Indicates that potentially invalid data was passed to the function, but the function completed processing.
0 | Indicates that only dwError was set.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

Basic Debugging Overview, Debugging Structures, DEBUG_EVENT


UNLOAD_DLL_DEBUG_INFO

The UNLOAD_DLL_DEBUG_INFO structure contains information about a dynamic-link library (DLL) that has just been unloaded.

typedef struct _UNLOAD_DLL_DEBUG_INFO {
  LPVOID lpBaseOfDll;
} UNLOAD_DLL_DEBUG_INFO, *LPUNLOAD_DLL_DEBUG_INFO;

Members

lpBaseOfDll
Pointer to the base address of the DLL in the address space of the process unloading the DLL.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

Basic Debugging Overview, Debugging Structures, DEBUG_EVENT


Debug Help Library

This overview describes the function set provided by the debug help library, DbgHelp.Dll. This DLL is redistributable. It contains a set a debugging support routines that allow you to work with a portable executable (PE) image.

  • About DbgHelp
  • Using DbgHelp
  • DbgHelp Reference

This DLL is included with Windows® 2000. To use this DLL on earlier systems, such as Windows NT® 4.0 or Windows 98, you can distribute the DLL with your application.


About DbgHelp

The following topics describe symbol files and the functionality provided by the library functions.

  • Symbol Files
  • Symbol Handling
  • Symbol Server
  • New 64-bit Support


Symbol Files

A symbol file contains the same debugging information that an executable file would contain. However, the information is stored in a debug (.dbg) file or a program database (.pdb), rather than the executable file. Therefore, you can install only the symbol files you will need during debugging. This reduces the file size of the executable, saving load time and disk storage.

Debuggers can determine whether an executable file or DLL contains debugging information by searching for the IMAGE_FILE_DEBUG_STRIPPED characteristic. If this characteristic is present, the debugging information exists in a symbol file.

To create a .dbg file, build your executable file with debugging information according to the directions for your build tools. Next, use the SplitSymbols function or the Rebase tool. The resulting .dbg file uses the PE format.

To create a .pdb file, build your executable file with debugging information according to the directions for your build tools.

The operating system dynamic-link libraries (DLL) have associated symbol (.dbg) files. These files are not installed during installation. To install the system symbol files, create a directory on your hard disk, and copy the files from your system installation compact disc (CD). The symbol files are located in the SUPPORT\DEBUG\I386\SYMBOLS directory tree.


Symbol Handling

The symbol handler functions give applications easy and portable access to the symbolic debugging information of an image. These functions should be used exclusively to ensure access to symbolic information. This is necessary because these functions isolate the application from the symbol format.

For more information, see the following topics:

  • Symbol Handler Initialization
  • Symbol Paths
  • Symbol Loading
  • Deferred Symbol Loading
  • Decorated Symbol Names
  • Finding Symbols
  • Symbol Handler Cleanup


Symbol Handler Initialization

The symbol handler is designed to track various sets of symbol files.

To initialize the symbol handler, call the SymInitialize function. The hProcess parameter can be a unique arbitrary number, a value returned from the GetCurrentProcess function, or the identifier of any running process. The fInvadeProcess parameter indicates whether the symbol handler should enumerate the modules loaded by the process and load symbols for each of its modules. If fInvadeProcess is TRUE, the hProcess parameter must be the value returned from GetCurrentProcess or the identifier of an existing process.

Using fInvadeProcess is a simple way to load all symbol files for a process. However, the symbol handler will not attempt to load symbols for modules subsequently loaded by the LoadLibrary function. You must use the SymLoadModule function in this case.


Symbol Paths

The library uses the symbol search path to locate debug symbols (.dbg file) for .dll, .exe, and .sys files by appending "\symbols" and "\dll" or "\exe" or "\sys" to the path. For example, the typical location of symbol files for .dll files is c:\mysymbols\symbols\dll. For .exe files, the location is c:\mysymbols\symbols\exe.

To specify where the symbol handler will search disk directories for symbol files, call the SymSetSearchPath function. Alternatively, you can specify a symbol search path in the UserSearchPath parameter of the SymInitialize function.

The UserSearchPath parameter in SymInitialize and the SearchPath parameter in SymSetSearchPath take a pointer to a null-terminated string that specifies a path, or series of paths separated by a semicolon. The symbol handler uses these paths to search for symbol files. If this parameter is specified as a non-null value, the symbol handler searches only the paths set by the application. If this parameter is NULL, the symbol handler first searches the current working directory of the application, then the system root directory (%windir%). If you set the _NT_SYMBOL_PATH or _NT_ALT_SYMBOL_PATH environment variable, the symbol handler searches for symbol files in the following order:

  1. The current working directory of the application.
  2. The _NT_SYMBOL_PATH environment variable.
  3. The _NT_ALT_SYMBOL_PATH environment variable.

To retrieve the search paths, call the SymGetSearchPath function.

The search path for program database (.pdb) files is different than the path for debug (.dbg) files. The algorithm is determined by the functionality of the symbol library. By default, Microsoft Visual C/C++ creates Microsoft format symbols, strips them from the image, and places them in a separate .pdb file. Typically, the .pdb file will be located in the directory that contains the executable image. Visual C/C++ embeds the absolute path to the .pdb file in the executable image. If the symbol handler cannot find the .pdb file in that location or if the .pdb file was moved to another directory, the symbol handler will locate the .pdb file using the search path described for .dbg files.


Symbol Loading

The symbol handler will load symbols when you call the SymInitialize function with the fInvadeProcess parameter set to TRUE or when you call the SymLoadModule function to specify a module. In either case, the symbol handler either loads the symbols or defers symbol loading until symbols are requested, depending on the options set by the SymSetOptions function.

The symbol handler can be used to retrieve symbolic information for any module; it does not need to be associated with a process specified in the SymInitialize call. To use an arbitrary module, specify the full path to the module image in the ImageName parameter. You can use a path to any executable module that has debugging information (.exe, .dll, .drv, .sys, .scr, .cpl, or .com). Use the BaseOfDll parameter to specify any load address, then symbol addresses will be based from that address.

It may not be necessary to keep a symbol module loaded through the duration of an application. To release the symbol module from the symbol handler's list of modules, use the SymUnLoadModule function. This function releases the memory allocated for the symbol module. To use symbols for that module again, you must call the SymLoadModule function even if the symbol deferred load option is set.


Deferred Symbol Loading

To conserve time and memory when working with many symbol files, use the SymSetOptions function to set the deferred symbol loading (SYMOPT_DEFERRED_LOADS) option, then use the SymLoadModule or SymInitialize function to load symbols deferred for all modules. The symbol handler will list symbols that are available for the modules, but will not map the debug information into memory until it is requested. This is the preferred method to efficiently use debugging symbols. The following functions will load the deferred symbols:

  • SymGetSymFromAddr
  • SymGetSymFromName
  • SymEnumerateSymbols
  • SymGetSymPrev
  • SymGetSymNext
  • SymFunctionTableAccess


Decorated Symbol Names

A decorated symbol name includes characters that distinguish how the symbol has been declared. For __stdcall functions, names include the "@" character and a decimal number that specifies the number of bytes in its function parameters. For example, the decorated name of the LoadLibrary function is LoadLibrary@4. For C++ functions the name decoration is more complex and varies from compiler to compiler.

To retrieve the undecorated symbol name, use the SymUnDName function. Alternatively, you can call the SymSetOptions function to request that the symbol handler always present symbols with undecorated names. You must set this option before loading the symbols because the symbol handler creates the symbol name tables at load time.


Finding Symbols

After a symbol file has been loaded into the symbol handler, an application can use the symbol locator functions to return symbol information for a specified address. These functions can also find a source code file name and line number location for an address.

Enumerating Symbol Files

To retrieve a list of all symbol files loaded by module name, call the SymEnumerateModules function. To retrieve a list of symbols for a given module, call the SymEnumerateSymbols function.

Retrieving Symbols by Address

To retrieve symbolic information for a specific address, use the SymGetSymFromAddr function. This function retrieves information and stores it in an IMAGEHLP_SYMBOL structure. Because symbol names are variable in length, you must provide additional buffer space following the IMAGEHLP_SYMBOL structure declaration. The following is an example using SymGetSymFromAddr:

DWORD dwAddress;
DWORD dwDisplacement;
BYTE      buffer[MAX_BUFFER_LENGTH];
PIMAGEHLP_SYMBOL pSymbol = (PIMAGEHLP_SYMBOL)buffer;

pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
SymGetSymFromAddr(hProcess, dwAddress, &dwDisplacement, pSymbol)

Note that hProcess is the handle to the process originally passed to the SymInitialize function, and dwAddress contains the address for which a symbol is to be located. The address does not need to be on a symbol boundary. If the address comes after the beginning of a symbol but before the end of the symbol (the beginning of the symbol plus the symbol size), the function will locate the symbol.

Retrieving Symbols by Symbol Name

To retrieve symbolic information in an IMAGEHLP_SYMBOL structure for a specific module and symbol name, use the SymGetSymFromName function. If deferred symbol loading is set, SymGetSymFromName will attempt to load the symbol file for a module if it has not already been loaded. To specify a module name along with a symbol name, use the syntax Module!SymName. The "!" character delimits the module name from the symbol name. The following is an example using SymGetSymFromName:

BYTE szSymbolName[MAX_SYMBOLNAME_LENGTH];
BYTE buffer[MAX_BUFFER_LENGTH];
PIMAGEHLP_SYMBOL pSymbol = (PIMAGEHLP_SYMBOL)buffer;

pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
SymGetSymFromName(hProcess, szSymbolName, pSymbol)

Note that hProcess is the handle to the process originally passed to SymInitialize, and szSymbolName is a null-terminated string that specifies the symbol name for which a symbol is to be located.

Retrieving Line Numbers by Address

To retrieve the source code location for a specific address, use the SymGetLineFromAddr function. This function fills an IMAGEHLP_LINE structure that includes the source file name and line number location referred to by the specified address. The following is an example using SymGetLineFromAddr:

DWORD dwAddress;
DWORD dwDisplacement;
IMAGEHLP_LINE line;

SymSetOptions(SYMOPT_LOAD_LINES);
...
line.SizeOfStruct = sizeof(IMAGEHLP_LINE);
SymGetLineFromAddr(hProcess, dwAddress, &dwDisplacement, &line);

Note that hProcess is the handle to the process originally passed to SymInitialize, and dwAddress contains the address for which the source file name and line number should be located.

Retrieving Line Numbers by Symbol Name

To retrieve source code location for a specific symbol name, use the SymGetLineFromName function. This function is similar to SymGetSymFromName, but retrieves an IMAGEHLP_LINE structure. To use SymGetLineFromAddr or SymGetLineFromName, you must set the load lines option (SYMOPT_LOAD_LINES) using the SymSetOptions function. The following is an example using SymGetLineFromName:

BYTE      szModuleName[MAX_PATH];
BYTE      szFileName[MAX_PATH];
DWORD dwLineNumber;
LONG     lDisplacement;
IMAGEHLP_LINE line;

SymSetOptions(SYMOPT_LOAD_LINES);
...
line.SizeOfStruct = sizeof(IMAGEHLP_LINE);
SymGetLineFromName(hProcess, szModuleName, szFileName, dwLineNumber, &lDisplacement, &line);

Note that hProcess is the handle to the process originally passed to SymInitialize. Also, szModuleName contains the source module name, which can be NULL. The szFileName parameter contains the source file name, and dwLineNumber contains the line number for which the virtual address should be retrieved.


Symbol Handler Cleanup

To free all the memory used by the symbol handler for a process, use the SymCleanup function. This function enumerates all loaded modules, frees each module, and frees the memory allocated for the list of modules. After you call SymCleanup, you cannot use the process handle in the symbol handling functions until you call the SymInitialize function.


Symbol Server

To set up symbols correctly for debugging can be a challenging task, particularly for kernel debugging. It often requires that you know the names and releases of all products on your computer. You must also ensure that the debugger can locate each set of related symbol files. Therefore, the symbol path can potentially contain many directories. Because of this complexity, you can spend a lot of debugging time simply trying to locate the correct symbol files.

To simplify debugging, Windows 2000 provides a symbol server that enables debuggers to automatically retrieve the correct symbol files without product names, releases, or build numbers. Every time DbgHelp needs to load symbols for a newly loaded module, it calls the symbol server to locate the appropriate symbol files. The symbol server locates each symbol file according to unique parameters such as the time stamp and image size.

For more information, see the following topics:

  • Using the Symbol Server
  • Implementing Your Own Symbol Server


Using the Symbol Server

The Windows 2000 debuggers use a symbol server to retrieve symbol files from a symbol store. The symbol server is implemented in Symsrv.dll. Symstore.exe is the companion tool that administrators can use to add and delete files from the symbol store.

Capabilities

Symsrv.dll can deliver symbol files from a centralized symbol store that contains symbol files from a variety of sources. The symbol store can also contain pointers to symbol files, so the symbol server can retrieve symbol files directly from their sources. The symbol server can also be used to separate a large symbol store into a smaller subset that is appropriate for a specialized debugging task. Finally, the symbol server can obtain symbol files from an ftp, http, or https source using the logon information provided by the operating system.

Setting the Symbol Path

To use the symbol server, Symsrv.dll must be installed in the same directory as the debugger. The symbol path must be set as follows:

set _NT_SYMBOL_PATH = symsrv*server_dll*param

The symsrv keyword indicates that the debugger should look for symbols using a symbol server. The next portion is the name of the symbol server DLL (Symsrv.dll in this case). The third portion is a parameter whose value is defined by the symbol server DLL. For Symsrv.dll, it can be one of the following strings.

String | Meaning
\\server\share | Load the symbol file from the specified server and share.
local_dir*\\server\share | Check for the symbol file in the local_dir directory. If it isn't there, download the symbol file from \\server\share into the same directory tree under local_dir. You can also specify an ftp, http, or https site.

For example, to use Symsrv.dll as the symbol server and the symbol store on \\bldsrv\symsrv, set the following symbol path:

set _NT_SYMBOL_PATH= symsrv*symsrv.dll*\\bldsrv\symsrv

To set the symbol path so that the debugger will copy symbol files from a symbol store, \\bldsrv\symsrv, to your local directory, c:\symsrv, use:

set _NT_SYMBOL_PATH=symsrv*symsrv.dll*c:\symsrv*\\bldsrv\symsrv

To set the symbol path so that the debugger will copy symbol files from an ftp site, ftp.microsoft.com/symbols, to your local directory, c:\symsrv, use:

set _NT_SYMBOL_PATH=symsrv*symsrv.dll*c:\symsrv*ftp://ftp.microsoft.com/symbols

To set the symbol path so that the debugger will copy symbol files from an http site, support.microsoft.com/symbols, to your local directory, c:\symsrv, use:

set _NT_SYMBOL_PATH=symsrv*symsrv.dll*c:\symsrv*http://support.microsoft.com/symbols

In addition, the symbol path may contain several paths separated by semicolons, with one or more of the paths being an entry for a symbol server. Using paths may locate more symbols than using only the symbol server. If a binary has a mismatched symbol file, the debugger cannot locate it using the symbol server because it checks only for the exact parameters. However, the debugger may find a mismatched symbol file with the correct name using the traditional symbol path and load it. Even though the file is technically not the correct symbol file, it may provide useful information.

Setting Up a Store

Symstore.exe is the utility that builds a symbol store. It stores symbols in a format that enables the debugger to look up the symbols based on the time stamp and size of the image (for a .dbg or executable file), or signature and age (for a .pdb file). The advantage of the symbol server over the traditional symbol storage format is that all symbols can be stored or referenced on the same server and retrieved by the debugger without any prior knowledge of which product contains the corresponding symbol.

Server Administration

Every call to Symstore is recorded as a transaction. There are two types of transactions: add and delete. When the symbol store is created, a directory under the root of the server is created called "000admin". The 000admin directory contains the following files: Server.txt, History.txt, and one file for each transaction. Server.txt contains a list of all transactions that are currently on the server. History.txt contains a chronological history of all transactions.

Each time Symstore is called, a new transaction number is created. Then a file is created in "000admin" whose name is this transaction number. This file contains a list of all the files or pointers that have been added to the symbol store during this transaction. If a transaction is deleted, Symstore will read through its transaction file to determine which files and pointers it should delete.

When a transaction is added, several items of information are added to Server.txt and History.txt for future lookup capability. The following is an example of a line in Server.txt and History.txt for an add transaction:

0000000096,add,ptr,10/09/99,00:08:32,Windows NT 4.0 SP 4,x86 fre 1.156c-RTM-2,Added from \\bldsrv\release,

This is a comma-separated line. The fields are defined as follows.

Field | Description
0000000096 | Transaction ID number, as created by Symstore.
add | Type of transaction. This field is either add or del.
ptr | Whether files or pointers were added. This field is either file or ptr.
10/09/99 | Date transaction occurred.
00:08:32 | Time transaction started.
Windows NT | Product.
x86 fre | Version (optional).
Added from | Comment (optional)
Unused | Reserved for later use.

Following are example lines from the transaction file 0000000096. Each line records the directory and the location of the file or pointer that was added to the directory.

canon800.dbg\35d9fd51b000,\\ntbuilds\release\usa\svcpack\sp4\1.156c-RTM-2\support\debug\i386\symbols\dll\canon800.dbg
canonlbp.dbg\35d9fd521c000,\\ntbuilds\release\usa\svcpack\sp4\1.156c-RTM-2\support\debug\i386\symbols\dll\canonlbp.dbg
certadm.dbg\352bf2f48000,\\ntbuilds\release\usa\svcpack\sp4\1.156c-RTM-2\support\debug\i386\symbols\dll\certadm.dbg
certcli.dbg\352bf2f1b000,\\ntbuilds\release\usa\svcpack\sp4\1.156c-RTM-2\support\debug\i386\symbols\dll\certcli.dbg
certcrpt.dbg\352bf04911000,\\ntbuilds\release\usa\svcpack\sp4\1.156c-RTM-2\support\debug\i386\symbols\dll\certcrpt.dbg
certenc.dbg\352bf2f7f000,\\ntbuilds\release\usa\svcpack\sp4\1.156c-RTM-2\support\debug\i386\symbols\dll\certenc.dbg

If this transaction is deleted, it will be removed from Server.txt and the following line will be added to History.txt:

0000000105,del,0000000096

The fields for the delete transaction are described as follows.

Field | Description
0000000105 | Transaction ID number, as created by Symstore.
del | Type of transaction. This field is either add or del.
0000000096 | Transaction that was deleted.

Symbol Store Format

The symbol store uses the file system as a database. The first directory level under the root consists of a subdirectory for each symbol file. The second directory level consists of a subdirectory for each version of the symbol file. The naming convention for .pdb files is signature followed by age. The naming convention for .dbg files is the time stamp followed by the image size. For example, after several versions of Acpi.dbg have been added to the store, the directory listing is as follows:

Directory of \\bldsrv\symsrv\Acpi.dbg
      <DIR>          .
      <DIR>          ..
      <DIR>          37cdb03962040
      <DIR>          37cdb04027740
      <DIR>          37e3eb1c62060
      <DIR>          37e3ebcc27760
      <DIR>          37ed151662060
      <DIR>          37ed15dd27760

Each of these directories can contain the following files:

  • The symbol file, Acpi.dbg.
  • A file, File.ptr, that contains a path to Acpi.dbg.
  • A file, Refs.ptr, that contains a list of all current locations for the symbol file. It is maintained and used by Symstore.

The contents of Refs.ptr are transactions. The following are example contents of Refs.ptr:

0000000001,file,\\bldsrv\symbols\2137\symbols\dll\acpi.dbg
0000000002,ptr,\\bldsrv\symbols\2138\symbols\dll\acpi.dbg
0000000003,ptr,\\bldsrv\symbols\2139\symbols\dll\acpi.dbg
0000000004,ptr,\\bldsrv\symbols\2140\symbols\dll\acpi.dbg

If the transactions are deleted, they are removed from this file, and the corresponding files and pointers are removed from the symbol store.

The following example adds symbol pointers for build 2137 to \\bldsrv\symsrv:

symstore add /r /p /f \\bldsrv\release\2137\symbols\retail\*.* /s \\bldsrv\symsrv /t "MyProject" /v "Build 2137" /c "Sample add"

The following example adds the actual symbol files for an application to \\mysrv\symsrv:

symstore add /r /f \\largeapp\bins\*.* /s \\mysrv\symsrv /t "My Application" /v "Build 42" /c "Sample add"


Implementing Your Own Symbol Server

To customize the symbol search, you can provide your own symbol server DLL. The central portion of the server is the code that communicates with DbgHelp to find the symbols. Every time DbgHelp needs to load symbols for a newly loaded module, it calls the symbol server to locate the appropriate symbol files. The symbol server locates each file according to unique parameters such as the time stamp or image size. The server returns a validated path to the requested file. To implement this, the server must export the SymbolServer function. The server should also support the SymbolServerSetOptions and SymbolServerGetOptions functions.

Furthermore, DbgHelp will call the SymbolServerClose function, if exported by the server.

Note DbgHelp supports the use of only one symbol server at a time, although it is possible to switch to another symbol server by changing the symbol path. This does not limit the symbol server from obtaining its symbol information from a single source. The server can support multiple source instances through the parameters passed to it when it is called. Furthermore, it can use its own syntax within the parameters to indicate the use of different technologies such as UNC paths, SQL database identifiers, or Internet specifications.

DbgHelp stores the name of a symbol file in multiple locations. Therefore, the server must return a file of the same name as that specified when the symbol was requested.


New 64-bit Support

Where necessary, the DbgHelp library has been widened to support 64-bit Windows. The original function and structure definitions are still in DbgHelp.h, but there are also 64-bit versions of these definitions. For example, DbgHelp.h contains definitions for SymLoadModule and SymLoadModule64. These definitions are nearly identical, but use different types for the return value and the BaseOfDll parameter. (The original version uses the DWORD type for these values and the 64-bit version uses the new DWORD64 type.)

The 64-bit library is supported on all platforms. Therefore, you can use it to write a 32-bit debugger that runs on Windows 2000 or a 64-bit debugger that runs on 64-bit Windows.

When writing new code, it is more efficient to use the 64-bit library. Internally, the original functions simply call the 64-bit functions to perform the work.

The following is a list of the 64-bit functions:

  • EnumerateLoadedModules64
  • EnumLoadedModulesProc64
  • FunctionTableAccessProc64
  • GetModuleBaseProc64
  • ReadProcessMemoryProc64
  • StackWalk64
  • SymbolRegisteredCallback64
  • SymbolRegisteredFunctionEntryCallback64
  • SymEnumerateModules64
  • SymEnumerateSymbols64
  • SymEnumModulesCallback64
  • SymEnumSymbolsCallback64
  • SymFunctionTableAccess64
  • SymGetLineFromAddr64
  • SymGetLineFromName64
  • SymGetLineNext64
  • SymGetLinePrev64
  • SymGetModuleBase64
  • SymGetModuleInfo64
  • SymGetModuleInfoEx64
  • SymGetSymbolInfo64
  • SymGetSymFromAddr64
  • SymGetSymFromName64
  • SymGetSymNext64
  • SymGetSymPrev64
  • SymLoadModule64
  • SymRegisterCallback64
  • SymRegisterFunctionEntryCallback64
  • SymUnDName64
  • SymUnloadModule64

The following is a list of the 64-bit structures:

  • ADDRESS64
  • IMAGEHLP_DEFERRED_SYMBOL_LOAD64
  • IMAGEHLP_DUPLICATE_SYMBOL64
  • IMAGEHLP_LINE64
  • IMAGEHLP_MODULE64
  • IMAGEHLP_SYMBOL64
  • KDHELP64
  • STACKFRAME64


Using DbgHelp

The following topics demonstrate how an application can use the symbol handler functions:

  • Initializing the Symbol Handler
  • Loading a Symbol Module
  • Enumerating Symbol Modules
  • Enumerating Symbols
  • Retrieving Symbol Information by Name
  • Retrieving Symbol Information by Address
  • Retrieving Undecorated Symbol Names
  • Unloading a Symbol Module
  • Terminating the Symbol Handler


Initializing the Symbol Handler

The following code demonstrates how to initialize the symbol handler. The SymSetOptions function defers symbol loading until symbol information is requested. The code loads the symbols for each module in the specified process by passing a value of TRUE for the bInvade parameter of the SymInitialize function. (This function calls the SymLoadModule function for each module the process has mapped into its address space.)

If the specified process is not the process that called SymInitialize, the code passes a process identifier as the first parameter of SymInitialize.

Specifying NULL as the second parameter of SymInitialize indicates that the symbol handler should use the default search path to locate symbol files. For detailed information on how the symbol handler locates symbol files or how an application can specify a symbol search path, see Symbol Paths.

DWORD  error;
HANDLE hProcess;
DWORD  processId;

SymSetOptions(SYMOPT_UNDNAMES | SYMOPT_DEFERRED_LOADS);

hProcess = GetCurrentProcess();
// hProcess = (HANDLE)processId;

if (SymInitialize(hProcess, NULL, TRUE))
{
    // SymInitialize returned success
}
else
{
    // SymInitialize failed
    error = GetLastError();
    printf("SymInitialize returned error : %d\n", error);
}


Loading a Symbol Module

If an application does not call the SymInitialize function with the fInvadeProcess parameter set to TRUE, it must load symbols for a module when they are required. To load a symbol module on demand, the application can call the SymLoadModule function with a full path to a module name. When the module is loaded, the symbol handler will either load the symbols immediately or defer the load, depending on the options set using the SymSetOptions function.

The following code loads a symbol module.

char  szImageName[MAX_PATH+1];
DWORD dwBaseAddr;

if (SymLoadModule(hProcess, NULL, szImageName, NULL, dwBaseAddr, 0))
{
    // SymLoadModule returned success
}
else
{
    // SymLoadModule failed
    error = GetLastError();
    printf("SymLoadModule returned error : %d\n", error);
}

Note that szImageName can be a path to any executable module that has debugging information (.exe, .dll, .drv, .sys, .scr, .cpl, .com). Also, dwBaseAddr is the base address of the symbol module to be loaded. If this value is 0, the symbol handler will obtain the base address from the specified symbol module.


Enumerating Symbol Modules

The following code lists the modules that have been loaded by the SymLoadModule or SymInitialize function. The SymEnumerateModules function requires a callback function, which will be called once for each module loaded. In this example, EnumModules is an implementation of the callback function.

BOOL CALLBACK EnumModules(
    LPSTR ModuleName,
    ULONG BaseOfDll,
    PVOID UserContext )
{
    printf("%08X %s\n", BaseOfDll, ModuleName);
    return TRUE;
}

if (SymEnumerateModules(hProcess, EnumModules, NULL))
{
    // SymEnumerateModules returned success
}
else
{
    // SymEnumerateModules failed
    error = GetLastError();
    printf("SymEnumerateModules returned error : %d\n", error);
}


Enumerating Symbols

The following code displays the name, address, and size of each loaded symbol in the specified module. The SymEnumerateSymbols function requires a callback function, which will be called once for each module loaded. In this example, EnumSymbols is an implementation of the callback function.

BOOL CALLBACK EnumSymbols(LPSTR SymbolName,
    ULONG SymbolAddress,
    ULONG SymbolSize,
    PVOID UserContext)
{
    printf("%08X %4u %s\n", SymbolAddress, SymbolSize, SymbolName);
    return TRUE;
}

if (SymEnumerateSymbols(hProcess, BaseOfDll, EnumSymbols, NULL))
{
    // SymEnumerateSymbols returned success
}
else
{
    // SymEnumerateSymbols failed
    error = GetLastError();
    printf("SymEnumerateSymbols returned error : %d\n", error);
}


Retrieving Symbol Information by Name

The following code demonstrates how to call the SymGetSymFromName function. This function fills in an IMAGEHLP_SYMBOL structure. Because the name is variable in length, you must supply a buffer that is large enough to hold the name stored at the end of the IMAGEHLP_SYMBOL structure. Also, the MaxNameLength member must be set to the number of bytes reserved for the name. In this example, szSymbolName is a buffer that stores the name of the requested symbol.

BYTE szSymbolName[256];
BYTE buffer[256];
PIMAGEHLP_SYMBOL pSymbol = (PIMAGEHLP_SYMBOL)buffer;

lstrcpy(szSymbolName, "WinMain");
pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;

if (SymGetSymFromName(hProcess, szSymbolName, pSymbol))
{
    // SymGetSymFromName returned success
}
else
{
    // SymGetSymFromName failed
    error = GetLastError();
    printf("SymGetSymFromName returned error : %d\n", error);
}

If an application has a module or source file name as well as line number information, it can use SymGetLineFromName to retrieve a virtual code address. This function requires a pointer to an IMAGEHLP_LINE structure to receive the virtual code address. Note that the symbol handler can retrieve line number information only when SYMOPT_LOAD_LINES option is set using the SymSetOptions function. This option must be set before loading the module. The szModuleName parameter contains the source module name; it is optional and can be NULL. The szFileName parameter should contain the source file name, and dwLineNumber parameter should contain the line number for which the virtual address will be retrieved.

BYTE      szModuleName[MAX_PATH];
BYTE      szFileName[MAX_PATH];
DWORD dwLineNumber;
LONG     lDisplacement;
IMAGEHLP_LINE line;

SymSetOptions(SYMOPT_LOAD_LINES);

line.SizeOfStruct = sizeof(IMAGEHLP_LINE);
lstrcpy(szModuleName, "MyApp");
lstrcpy(szFileName, "main.c");
dwLineNumber = 248;

if (SymGetLineFromName(hProcess, szModuleName, szFileName,
    dwLineNumber, &lDisplacement, &line))
{
    // SymGetLineFromName returned success
}
else
{
    // SymGetLineFromName failed
    error = GetLastError();
    printf("SymGetLineFromName returned error : %d\n", error);
}


Retrieving Symbol Information by Address

The following code demonstrates how to call the SymGetSymFromAddr function. This function fills in an IMAGEHLP_SYMBOL structure. Because the name is variable in length, you must supply a buffer that is large enough to hold the name stored at the end of the IMAGEHLP_SYMBOL structure. Also, the MaxNameLength member must be set to the number of bytes reserved for the name. In this example, dwAddress is the address to be mapped to a symbol. The SymGetSymFromAddr function will store an offset to the beginning of the symbol to the address in dwDisplacement.

DWORD dwAddress;
DWORD dwDisplacement;
BYTE      buffer[256];
PIMAGEHLP_SYMBOL pSymbol = (PIMAGEHLP_SYMBOL)buffer;

pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;

if (SymGetSymFromAddr(hProcess, dwAddress, &dwDisplacement, pSymbol))
{
// SymGetSymFromAddr returned success
}
else
{
    // SymGetSymFromAddr failed
    error = GetLastError();
    printf("SymGetSymFromAddr returned error : %d\n", error);
}

To retrieve the source code line number for a specified address, an application can use SymGetLineFromAddr. This function requires a pointer to an IMAGEHLP_LINE structure to receive the source file name and line number corresponding to a specified code address. Note that the symbol handler can retrieve line number information only when SYMOPT_LOAD_LINES is set using the SymSetOptions function. This option must be set before loading the module. The dwAddress parameter contains the code address for which the source file name and line number will be located.

DWORD dwAddress;
DWORD dwDisplacement;
IMAGEHLP_LINE line;

SymSetOptions(SYMOPT_LOAD_LINES);

line.SizeOfStruct = sizeof(IMAGEHLP_LINE);

if (SymGetLineFromAddr(hProcess, dwAddress, &dwDisplacement, &line))
{
    // SymGetLineFromAddr returned success
}
else
{
    // SymGetLineFromAddr failed
    error = GetLastError();
    printf("SymGetLineFromAddr returned error : %d\n", error);
}


Retrieving Undecorated Symbol Names

The following code demonstrates how to retrieve an undecorated symbol name from an IMAGEHLP_SYMBOL structure. In this example, the pSymbol variable must be filled by the SymGetSymFromAddr or SymGetSymFromName function. The undecorated name is stored in szName.

char  szName[1024];
DWORD dwAddress;
DWORD dwDisplacement;
BYTE      buffer[256];
PIMAGEHLP_SYMBOL pSymbol = (PIMAGEHLP_SYMBOL)buffer;

if (SymUnDName(pSymbol, szName, sizeof(szName)))
{
    // SymUnDName returned success
    printf ("Symbol : %s\n", szName);
}
else
{
    // SymUnDName failed
    error = GetLastError();
    printf("SymUnDName returned error : %d\n", error);
}


Unloading a Symbol Module

The following code unloads a symbol module referred to by the BaseOfDll module address.

if (SymUnloadModule(hProcess, BaseOfDll)
{
    // SymUnloadModule returned success
}
else
{
    // SymUnloadModule failed
    error = GetLastError();
    printf("SymUnloadModule returned error : %d\n", error);
}


Terminating the Symbol Handler

The following code cleans up all memory associated with symbol handling for the specified process, hProcess.

if (SymCleanup(hProcess))
{
    // SymCleanup returned success
}
else
{
    // SymCleanup failed
    error = GetLastError();
    printf("SymCleanup returned error : %d\n", error);
}


DbgHelp Reference

The following elements are part of DbgHelp.

  • DbgHelp Functions
  • DbgHelp Structures
  • DbgHelp Enumerations


DbgHelp Functions

The following are the DbgHelp functions.

General

The following are general helper functions:

ImagehlpApiVersion
ImagehlpApiVersionEx
MakeSureDirectoryPathExists
SearchTreeForFile

Debugger

The debugging service functions are the functions most suited for use by a debugger or the debugging code in an application. These functions can be used in concert with the symbol handler functions for easier use.

EnumerateLoadedModules
EnumLoadedModulesProc
FindDebugFileProc
FindDebugInfoFile
FindDebugInfoFileEx
FindExecutableImage
FindExecutableImageEx
FindExeFileProc
FunctionTableAccessProc
GetModuleBaseProc
ReadProcessMemoryProc
StackWalk
TranslateAddressProc
UnDecorateSymbolName

Image Access

The image access functions access the data in an executable image. The functions provide high-level access to the base of images and very specific access to the most common parts of an image's data.

GetTimestampForLoadedLibrary
ImageDirectoryEntryToData
ImageDirectoryEntryToDataEx
ImageNtHeader
ImageRvaToSection
ImageRvaToVa

Symbol Handler

The symbol handler functions give applications easy and portable access to the symbolic debugging information of an image. These functions should be used exclusively to ensure access to symbolic information. This is necessary because these functions isolate the application from the symbol format.

SymbolRegisteredCallback
SymbolRegisteredFunctionEntryCallback
SymCleanup
SymEnumerateModules
SymEnumerateSymbols
SymEnumModulesCallback
SymEnumSymbolsCallback
SymFindFileInPath
SymFindFileInPathCallback
SymFunctionTableAccess
SymGetLineFromAddr
SymGetLineFromName
SymGetLineNext
SymGetLinePrev
SymGetModuleBase
SymGetModuleInfo
SymGetModuleInfoEx
SymGetOptions
SymGetSearchPath
SymGetSymbolInfo
SymGetSymFromAddr
SymGetSymFromName
SymGetSymNext
SymGetSymPrev
SymInitialize
SymLoadModule
SymMatchFileName
SymRegisterCallback
SymRegisterFunctionEntryCallback
SymSetOptions
SymSetSearchPath
SymTypeNameCallback
SymUnDName
SymUnloadModule

Symbol Server

The symbol server enables debuggers to automatically retrieve the correct symbol files without product names, releases, or build numbers.

SymbolServer
SymbolServerClose
SymbolServerGetOptions
SymbolServerSetOptions

User-mode Minidump Files

User-mode minidump files provide a way for applications to produce crashdump files that contain a useful subset of the entire process context. The following functions operate on these files or provide minidump information.

MiniDumpCallback
MiniDumpReadDumpStream
MiniDumpWriteDump


EnumerateLoadedModules

The EnumerateLoadedModules function enumerates the loaded modules for the specified process.

This function is implemented as a wrapper that calls EnumerateLoadedModules64. For more information, see New 64-bit Support.

BOOL EnumerateLoadedModules(
  HANDLE hProcess,
  PENUMLOADED_MODULES_CALLBACK EnumLoadedModulesCallback,
  PVOID UserContext
);

For EnumerateLoadedModules64, the parameter list is as follows.

BOOL EnumerateLoadedModules64(
  HANDLE hProcess,
  PENUMLOADED_MODULES_CALLBACK64 EnumLoadedModulesCallback,
  PVOID UserContext
);

Parameters

hProcess
[in] Handle to the process whose modules will be enumerated.
EnumLoadedModulesCallback
[in] Pointer to an application-defined callback function. For more information, see EnumLoadedModulesProc.
UserContext
[in] User-defined data. This value is passed to the callback function.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, EnumLoadedModulesProc


EnumLoadedModulesProc

The EnumLoadedModulesProc function is an application-defined callback function used with the EnumerateLoadedModules function.

The PENUMLOADED_MODULES_CALLBACK type defines a pointer to this callback function. EnumLoadedModulesProc is a placeholder for the application-defined function name.

BOOL CALLBACK EnumLoadedModulesProc(
  PSTR ModuleName,
  ULONG ModuleBase,
  ULONG ModuleSize,
  PVOID UserContext
);

The PENUMLOADED_MODULES_CALLBACK64 type defines a pointer to this callback function. EnumLoadedModulesProc64 is a placeholder for the application-defined function name.

BOOL CALLBACK EnumLoadedModulesProc64(
  PSTR ModuleName,
  DWORD64 ModuleBase,
  ULONG ModuleSize,
  PVOID UserContext
);

Parameters

ModuleName
[in] Pointer to the name of the enumerated module.
ModuleBase
[in] Specifies the module's base address.
ModuleSize
[in] Specifies the size of the module.
UserContext
[in] User-defined data. This value is passed from EnumerateLoadedModules.

Return Values

To continue enumeration, the callback function must return TRUE.

To stop enumeration, the callback function must return FALSE.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Functions, EnumerateLoadedModules


FindDebugFileProc

The FindDebugFileProc function is an application-defined callback function used with the FindDebugInfoFileEx function. It verifies whether the symbol file located by FindDebugInfoFileEx is the correct symbol file.

The PFIND_DEBUG_FILE_CALLBACK type defines a pointer to this callback function. FindDebugFileProc is a placeholder for the application-defined function name.

BOOL CALLBACK FindDebugFileProc(
  HANDLE FileHandle,
  PSTR FileName,
  PVOID CallerData
);

Parameters

FileHandle
[in] Handle to the symbol file.
FileName
[in] Pointer to a null-terminated string that specifies the name of the symbol file.
CallerData
[in] User-defined data. This parameter can be NULL.

Return Values

If the symbol file is valid, return TRUE. Otherwise, return FALSE.

Remarks

One way to verify the symbol file is to compare its timestamp to the timestamp in the image. To retrieve the timestamp of the image, use the GetTimestampForLoadedLibrary function. To retrieve the timestamp of the symbol file, use the SymGetModuleInfo function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Functions, FindDebugInfoFileEx, GetTimestampForLoadedLibrary, SymGetModuleInfo


FindDebugInfoFile

The FindDebugInfoFile function locates a debug (.dbg) file.

To provide a callback function to verify the symbol file located, use the FindDebugInfoFileEx function .

HANDLE FindDebugInfoFile(
  PSTR FileName,
  PSTR SymbolPath,
  PSTR DebugFilePath
);

Parameters

FileName
[in] Pointer to a null-terminated string that specifies the name of the .dbg file that is desired. You can use a partial path.
SymbolPath
[in] Pointer to a null-terminated string that specifies the path where symbol files are located. This can be multiple paths separated by semicolons. To retrieve the symbol path, use the SymGetSearchPath function.
DebugFilePath
[out] Receives the full path of the .dbg file that is found.

Return Values

If the function succeeds, the return value is an open handle to the .dbg file.

If the function fails, the return value is NULL. To retrieve extended error information, call GetLastError.

Remarks

The FindDebugInfoFile function is used to locate a .dbg file. This function is provided so the search can be conducted in several different directories through a single function call. The SymbolPath parameter can contain multiple paths, with each separated by a semicolon (;). When multiple paths are specified, the function searches each directory for the file. Subdirectories are not searched. When the file is located, the search stops. Thus, be sure to specify SymbolPath with the paths in the correct order.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, FindDebugInfoFileEx, SymGetSearchPath


FindDebugInfoFileEx

The FindDebugInfoFileEx function locates a debug (.dbg) file.

HANDLE FindDebugInfoFileEx(
  PSTR FileName,
  PSTR SymbolPath,
  PSTR DebugFilePath,
  PFIND_DEBUG_FILE_CALLBACK Callback,
  PVOID CallerData
);

Parameters

FileName
[in] Pointer to a null-terminated string that specifies the name of the .dbg file to locate. You can use a partial path.
SymbolPath
[in] Pointer to a null-terminated string that specifies the path where symbol files are located. This can be multiple paths separated by semicolons. To retrieve the symbol path, use the SymGetSearchPath function.
DebugFilePath
[out] Receives the full path of the .dbg file that is found.
Callback
[in] Pointer to an application-defined callback function that verifies whether the correct file was found or the function should continue its search. For more information, see FindDebugFileProc.

This parameter may be NULL.

CallerData
[in] User-defined data to pass to the callback function. This parameter may be NULL.

Return Values

If the function succeeds, the return value is an open handle to the .dbg file.

If the function fails, the return value is NULL. To retrieve extended error information, call GetLastError.

Remarks

The FindDebugInfoFileEx function is used to locate a .dbg file. This function is provided so the search can be conducted in several different directories through a single function call. The SymbolPath parameter can contain multiple paths, with each separated by a semicolon (;). When multiple paths are specified, the function searches each directory tree for the file. When the file is located, the search stops. Thus, be sure to specify SymbolPath with the paths in the correct order.

If the file name specified does not include a .dbg extension, FindDebugInfoFileEx searches for the file in the following sequence:

  1. <SymbolPath>\Symbols\<ext>\<filename>.dbg
  2. <SymbolPath>\Symbols\<ext>\<filename>.sym
  3. <SymbolPath>\<ext>\<filename>.dbg
  4. <SymbolPath>\<ext>\<filename>.sym
  5. <SymbolPath>\<filename>.dbg
  6. <SymbolPath>\<filename>.sym
  7. <FileNamePath>\<filename>.dbg
  8. <FileNamePath>\<filename>.sym

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, FindDebugFileProc, SymGetSearchPath


FindExecutableImage

The FindExecutableImage function locates an executable file.

To specify a callback function, use the FindExecutableImageEx function.

HANDLE FindExecutableImage(
  PSTR FileName,
  PSTR SymbolPath,
  PSTR ImageFilePath
);

Parameters

FileName
[in] Pointer to a null-terminated string that specifies the name of the symbol file to locate. You can use a partial path.
SymbolPath
[in] Pointer to a null-terminated string that specifies the path where symbol files are located. This can be multiple paths separated by semicolons. To retrieve the symbol path, use the SymGetSearchPath function.
ImageFilePath
[out] Receives the full path of the executable file that is found.

Return Values

If the function succeeds, the return value is an open handle to the executable file.

If the function fails, the return value is NULL. To retrieve extended error information, call GetLastError.

Remarks

The FindExecutableImage function is provided so executable files can be located in several different directories through a single function call. The SymbolPath parameter can contain multiple paths, with each separated by a semicolon (;). When multiple paths are specified, the function searches each directory tree for the executable file. When the file is located, the search stops. Thus, be sure to specify SymbolPath with the paths in the correct order.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, FindExecutableImageEx, SymGetSearchPath


FindExecutableImageEx

The FindExecutableImageEx function locates an executable file.

HANDLE FindExecutableImageEx(
  PSTR FileName,
  PSTR SymbolPath,
  PSTR ImageFilePath,
  PFIND_EXE_FILE_CALLBACK Callback,
  PVOID CallerData
);

Parameters

FileName
[in] Pointer to a null-terminated string that specifies the name of the symbol file to locate. You can use a partial path.
SymbolPath
[in] Pointer to a null-terminated string that specifies the path where symbol files are located. This string can contain multiple paths separated by semicolons. To retrieve the symbol path, use the SymGetSearchPath function.
ImageFilePath
[out] Receives the full path of the executable file that is found.
Callback
[in] Pointer to an application-defined callback function that verifies whether the correct executable file was found, or whether the function should continue its search. For more information, see FindExeFileProc.

This parameter can be NULL.

CallerData
[in] User-defined data to pass to the callback function. This parameter can be NULL.

Return Values

If the function succeeds, the return value is an open handle to the executable file.

If the function fails, the return value is NULL. To retrieve extended error information, call GetLastError.

Remarks

The FindExecutableImageEx function is provided so executable files can be found in several different directories by using a single function call. If the SymbolPath parameter containins multiple paths, the function searches each specified directory tree for the executable file. When the file is found, the search stops. Thus, be sure to specify SymbolPath with the paths in the correct order.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, FindExeFileProc, SymGetSearchPath


FindExeFileProc

The FindExeFileProc function is an application-defined callback function used with the FindExecutableImageEx function. It verifies whether the executable file found by FindExecutableImageEx is the correct executable file.

The PFIND_EXE_FILE_CALLBACK type defines a pointer to this callback function. FindExeFileProc is a placeholder for the application-defined function name.

BOOL CALLBACK FindExeFileProc(
  HANDLE FileHandle,
  PSTR FileName,
  PVOID CallerData
);

Parameters

FileHandle
[in] Handle to the executable file.
FileName
[in] Pointer to a null-terminated string that specifies the name of the executable file.
CallerData
[in] User-defined data. This parameter can be NULL.

Return Values

If the executable file is valid, return TRUE. Otherwise, return FALSE.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Functions, FindExecutableImageEx


FunctionTableAccessProc

The FunctionTableAccessProc function is an application-defined callback function used with the StackWalk function. It provides access to the run-time function table for the process.

The PFUNCTION_TABLE_ACCESS_ROUTINE type defines a pointer to this callback function. FunctionTableAccessProc is a placeholder for the application-defined function name.

PVOID CALLBACK FunctionTableAccessProc(
  HANDLE hProcess,
  DWORD AddrBase
);

The PFUNCTION_TABLE_ACCESS_ROUTINE64 type defines a pointer to this callback function. FunctionTableAccessProc64 is a placeholder for the application-defined function name.

PVOID CALLBACK FunctionTableAccessProc64(
  HANDLE hProcess,
  DWORD64 AddrBase
);

Parameters

hProcess
[in] Handle to the process for which the stack trace is generated.
AddrBase
[in] Address of the instruction for which you are searching.

Return Values

The function returns a pointer to the run-time function table. On an x86 computer, this is a pointer to an FPO_DATA structure. On an Alpha computer, this is a pointer to an IMAGE_FUNCTION_ENTRY structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Functions, FPO_DATA, IMAGE_FUNCTION_ENTRY, StackWalk


GetModuleBaseProc

The GetModuleBaseProc function is an application-defined callback function used with the StackWalk function. It is called when StackWalk needs a module base address for a given virtual address.

The PGET_MODULE_BASE_ROUTINE type defines a pointer to this callback function. GetModuleBaseProc is a placeholder for the application-defined function name.

DWORD CALLBACK GetModuleBaseProc(
  HANDLE hProcess,
  DWORD Address
);

The PGET_MODULE_BASE_ROUTINE64 type defines a pointer to this callback function. GetModuleBaseProc64 is a placeholder for the application-defined function name.

DWORD CALLBACK GetModuleBaseProc64(
  HANDLE hProcess,
  DWORD64 Address
);

Parameters

hProcess
[in] Handle to the process for which the stack trace is generated.
Address
[in] Address whose module image should be located.

Return Values

The function returns the base address of the module.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Functions, StackWalk


GetTimestampForLoadedLibrary

The GetTimestampForLoadedLibrary function returns the timestamp of a loaded image.

DWORD GetTimestampForLoadedLibrary(
  HMODULE ImageBase
);

Parameters

ImageBase
[in] Specifies the base address of an image that is mapped into memory by a call to the MapViewOfFile function.

Return Values

If the function succeeds, the return value is the timestamp from the image.

If the function fails, the return value is zero. To retrieve extended error information, call GetLastError.

Remarks

The timestamp for an image indicates the date and time that the image was created by the linker. The value is represented in the number of seconds elapsed since midnight (00:00:00), January 1, 1970, Universal Coordinated Time, according to the system clock. The timestamp can be printed using the C run-time (CRT) function ctime.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, MapViewOfFile


ImageDirectoryEntryToData

The ImageDirectoryEntryToData function obtains access to image-specific data.

This function has been superseded by the ImageDirectoryEntryToDataEx function. Use ImageDirectoryEntryToDataEx to retrieve the section header.

PVOID ImageDirectoryEntryToData(
  PVOID Base,
  BOOLEAN MappedAsImage,
  USHORT DirectoryEntry,
  PULONG Size
);

Parameters

Base
[in] Specifies the base address of the image.
MappedAsImage
[in] Specifies how the file is mapped. If this flag is TRUE, the file is mapped by the system as an image. If the flag is FALSE, the file is mapped as a data file by the MapViewOfFile function.
DirectoryEntry
[in] Specifies the index number of the desired directory entry. This parameter can be one of the following values.
Value | Meaning
IMAGE_DIRECTORY_ENTRY_EXPORT | Export directory
IMAGE_DIRECTORY_ENTRY_IMPORT | Import directory
IMAGE_DIRECTORY_ENTRY_RESOURCE | Resource directory
IMAGE_DIRECTORY_ENTRY_EXCEPTION | Exception directory
IMAGE_DIRECTORY_ENTRY_SECURITY | Security directory
IMAGE_DIRECTORY_ENTRY_BASERELOC | Base relocation table
IMAGE_DIRECTORY_ENTRY_DEBUG | Debug directory
IMAGE_DIRECTORY_ENTRY_ARCHITECTURE | Architecture-specific data
IMAGE_DIRECTORY_ENTRY_GLOBALPTR | Relative virtual address of global pointer
IMAGE_DIRECTORY_ENTRY_TLS | Thread local storage directory
IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG | Load configuration directory
IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT | Bound import directory
IMAGE_DIRECTORY_ENTRY_IAT | Import address table
IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT | Delay import table
IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR | COM descriptor table

Size
[out] Receives the size, in bytes, of the data for the directory entry.

Return Values

If the function succeeds, the return value is a pointer to the directory entry's data.

If the function fails, the return value is NULL. To retrieve extended error information, call GetLastError.

Remarks

The ImageDirectoryEntryToData function is used to obtain access to image-specific data.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, ImageDirectoryEntryToDataEx, MapViewOfFile


ImageDirectoryEntryToDataEx

The ImageDirectoryEntryToDataEx function locates a directory entry within the image header and returns the address of the data for the directory entry. This function returns the section header for the data located, if one exists.

PVOID ImageDirectoryEntryToDataEx(
  PVOID Base,
  BOOLEAN MappedAsImage,
  USHORT DirectoryEntry,
  PULONG Size,
  PIMAGE_SECTION_HEADER *FoundHeader
);

Parameters

Base
[in] Specifies the base address of the image or data file.
MappedAsImage
[in] Specifies how the file is mapped. If the flag is TRUE, the file is mapped by the system as an image. If this flag is FALSE, the file is mapped as a data file by the MapViewOfFile function.
DirectoryEntry
[in] Specifies the directory entry to locate. The value must be one of the following values.
Value | Meaning
IMAGE_DIRECTORY_ENTRY_EXPORT | Export directory
IMAGE_DIRECTORY_ENTRY_IMPORT | Import directory
IMAGE_DIRECTORY_ENTRY_RESOURCE | Resource directory
IMAGE_DIRECTORY_ENTRY_EXCEPTION | Exception directory
IMAGE_DIRECTORY_ENTRY_SECURITY | Security directory
IMAGE_DIRECTORY_ENTRY_BASERELOC | Base relocation table
IMAGE_DIRECTORY_ENTRY_DEBUG | Debug directory
IMAGE_DIRECTORY_ENTRY_ARCHITECTURE | Architecture-specific data
IMAGE_DIRECTORY_ENTRY_GLOBALPTR | Relative virtual address of global pointer
IMAGE_DIRECTORY_ENTRY_TLS | Thread local storage directory
IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG | Load configuration directory
IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT | Bound import directory
IMAGE_DIRECTORY_ENTRY_IAT | Import address table
IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT | Delay load import descriptors
IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR | COM run-time descriptor

Size
[out] Receives the size of the data for the directory entry that is located.
FoundHeader
[out] Receives the IMAGE_SECTION_HEADER structure for the data. If the section header does not exist, this parameter is NULL.

Return Values

If the function succeeds, the return value is a pointer to the data for the directory entry.

If the function fails, the return value is NULL. To retrieve extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, IMAGE_SECTION_HEADER, MapViewOfFile


ImagehlpApiVersion

The ImagehlpApiVersion function retrieves the information about the version of the library installed on the system.

LPAPI_VERSION ImagehlpApiVersion(VOID);

Parameters

This function has no parameters.

Return Values

The return value is a pointer to an API_VERSION structure.

Remarks

Use the information in the API_VERSION structure to determine whether the version of the library installed on the system is compatible with the version of the library used by the application. Although the library functions are backward compatible, functions introduced in one version are obviously not available in earlier versions.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, API_VERSION, ImagehlpApiVersionEx


ImagehlpApiVersionEx

The ImagehlpApiVersionEx function modifies the information about the version of the library used by the application.

LPAPI_VERSION ImagehlpApiVersionEx(
  LPAPI_VERSION AppVersion
);

Parameters

AppVersion
[in] Pointer to an API_VERSION structure that contains valid version information for your application.

Return Values

The return value is a pointer to an API_VERSION structure.

Remarks

Use the ImagehlpApiVersionEx function to indicate the version of the library with which the application was built. The library uses this information to ensure compatibility. For example, consider walking through kernel-mode callback stack frames (which exist in Windows NT 4.0, where User and GDI exist in kernel mode). If you call ImagehlpApiVersionEx to set the Revision member to version 4 or later, the StackWalk function will continue through a callback stack frame. Otherwise, if you set Revision to a version earlier than 4, StackWalk will stop at the kernel transition.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, API_VERSION, ImagehlpApiVersion


ImageNtHeader

The ImageNtHeader function locates the IMAGE_NT_HEADERS structure in a PE image and returns a pointer to the data.

PIMAGE_NT_HEADERS ImageNtHeader(
  PVOID ImageBase
);

Parameters

ImageBase
[in] Specifies the base address of an image that is mapped into memory by a call to the MapViewOfFile function.

Return Values

If the function succeeds, the return value is a pointer to an IMAGE_NT_HEADERS structure.

If the function fails, the return value is NULL. To retrieve extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, IMAGE_NT_HEADERS, MapViewOfFile


ImageRvaToSection

The ImageRvaToSection function locates a relative virtual address (RVA) within the image header of a file that is mapped as a file and returns a pointer to the section table entry for that virtual address.

PIMAGE_SECTION_HEADER ImageRvaToSection(
  PIMAGE_NT_HEADERS NtHeaders,
  PVOID Base,
  ULONG Rva
);

Parameters

NtHeaders
[in] Pointer to an IMAGE_NT_HEADERS structure. This structure can be obtained by calling the ImageNtHeader function.
Base
[in] Specifies the base address of an image that is mapped into memory through a call to MapViewOfFile.
Rva
[in] Specifies the relative virtual address to locate.

Return Values

If the function succeeds, the return value is a pointer to an IMAGE_SECTION_HEADER structure.

If the function fails, the return value is NULL. To retrieve extended error information, call GetLastError.

Remarks

The ImageRvaToSection function locates an RVA within the image header of a file that is mapped as a file and returns a pointer to the section table entry for that virtual address.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, IMAGE_NT_HEADERS, IMAGE_SECTION_HEADER, ImageNtHeader, MapViewOfFile


ImageRvaToVa

The ImageRvaToVa function locates a relative virtual address (RVA) within the image header of a file that is mapped as a file and returns the virtual address of the corresponding byte in the file.

PVOID ImageRvaToVa(
  PIMAGE_NT_HEADERS NtHeaders,
  PVOID Base,
  ULONG Rva,
  PIMAGE_SECTION_HEADER *LastRvaSection
);

Parameters

NtHeaders
[in] Pointer to an IMAGE_NT_HEADERS structure. This structure can be obtained by calling the ImageNtHeader function.
Base
[in] Specifies the base address of an image that is mapped into memory through a call to the MapViewOfFile function.
Rva
[in] Specifies the relative virtual address to locate.
LastRvaSection
[in/out] Pointer to an IMAGE_SECTION_HEADER structure that specifies the last RVA section. This is an optional parameter. When specified, it points to a variable that contains the last section value used for the specified image to translate an RVA to a VA.

Return Values

If the function succeeds, the return value is the virtual address in the mapped file.

If the function fails, the return value is NULL. To retrieve extended error information, call GetLastError.

Remarks

The ImageRvaToVa function locates an RVA within the image header of a file that is mapped as a file and returns the virtual address of the corresponding byte in the file.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, IMAGE_NT_HEADERS, IMAGE_SECTION_HEADER, ImageNtHeader, MapViewOfFile


MakeSureDirectoryPathExists

The MakeSureDirectoryPathExists function creates all the directories in the specified DirPath, beginning with the root.

BOOL MakeSureDirectoryPathExists(
  PCSTR DirPath
);

Parameters

DirPath
[in] Pointer to a null-terminated string that specifies a valid path name. If the final component of the path is a directory, not a file name, the string must end with a backslash (\) character.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

Each directory specified is created, if it does not already exist. If only some of the directories are created, the function will return FALSE.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions


MapDebugInformation

The MapDebugInformation function gains access to the debugging information for an image.

Note This function is provided only for backward compatibility. It does not return reliable information. New applications should use the SymGetModuleInfo and SymLoadModule functions. If you need the information provided by this function, the source code is available on the Platform SDK CD-ROM for you to adapt.

PIMAGE_DEBUG_INFORMATION MapDebugInformation(
  HANDLE FileHandle,
  PSTR FileName,
  PSTR SymbolPath,
  DWORD ImageBase
);

Parameters

FileHandle
[in] Handle to an open executable image or NULL.
FileName
[in] Pointer to a null-terminated string that specifies the name of an executable image file or NULL.
SymbolPath
[in] Pointer to a null-terminated string that specifies the path where symbol files are located. The path can be multiple paths separated by semicolons. To retrieve the symbol path, use the SymGetSearchPath function.
ImageBase
[in] Specifies the base address for the image or zero.

Return Values

If the function succeeds, the return value is a pointer to an IMAGE_DEBUG_INFORMATION structure.

If the function fails, the return value is NULL. To retrieve extended error information, call GetLastError.

Remarks

The MapDebugInformation function is used to gain access to an image's debugging information. The debugging information is extracted from the image or the symbol file and placed into the IMAGE_DEBUG_INFORMATION structure. This structure is allocated by the library and must be deallocated by using the UnmapDebugInformation function. The memory for the structure is not in the process's default heap, so attempts to free it with a memory deallocation routine will fail.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, IMAGE_DEBUG_INFORMATION, SymGetSearchPath, UnmapDebugInformation


MiniDumpCallback

[This is preliminary documentation and subject to change.]

The MiniDumpCallback function is an application-defined callback function used with MiniDumpWriteDump. It receives extended core dump information.

The MINIDUMP_CALLBACK_ROUTINE type defines a pointer to this callback function. MiniDumpCallback is a placeholder for the application-defined function name.

BOOL CALLBACK MiniDumpCallback (
  PVOID CallbackParam,
  CONST PMINIDUMP_CALLBACK_INPUT CallbackInput,
  PMINIDUMP_CALLBACK_OUTPUT CallbackOutput
);

Parameters

CallbackParam
[in] Application-defined parameter value.
CallbackInput
[in] Pointer to a MINIDUMP_CALLBACK_INPUT structure that specifies extended core dump information.
CallbackOutput
[out] Pointer to a MINIDUMP_CALLBACK_OUTPUT structure that receives application-defined information from the callback function.

Return Values

If the function succeeds, return TRUE; otherwise, return FALSE.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, MINIDUMP_CALLBACK_INFORMATION, MiniDumpWriteDump


MiniDumpReadDumpStream

[This is preliminary documentation and subject to change.]

The MiniDumpReadDumpStream function reads a stream from a user-mode minidump file.

BOOL MiniDumpReadDumpStream (
  PVOID BaseOfDump,
  ULONG StreamNumber,
  PMINIDUMP_DIRECTORY *Dir,
  PVOID *StreamPointer,
  ULONG *StreamSize
);

Parameters

BaseOfDump
[in] Pointer to the base of the mapped minidump file. The file should have been mapped into memory using the MapViewOfFile function.
StreamNumber
[in] Type of data to be read from the minidump file. This member can be one of the values in the MINIDUMP_STREAM_TYPE enumeration.
Dir
[out] Pointer to a MINIDUMP_DIRECTORY structure.
StreamPointer
[out] Pointer to the beginning of the minidump stream. The format of this stream depends on the value of StreamNumber. For more information, see MINIDUMP_STREAM_TYPE.
StreamSize
[out] Size, in bytes, of the stream pointed to by StreamPointer.

Return Values

If the function succeeds, the return value is TRUE; otherwise, the return value is FALSE.

Remarks

In this context, a data stream is a block of data written to a minidump file.

You can use this function on versions of Windows prior to Whistler without redistributing DbgHelp.dll. To do so, link with the static library MiniDump.lib, which is included in the Platform SDK.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, MINIDUMP_DIRECTORY, MINIDUMP_STREAM_TYPE, MiniDumpWriteDump


MiniDumpWriteDump

[This is preliminary documentation and subject to change.]

The MiniDumpWriteDump function writes user-mode minidump information to the specified file.

BOOL MiniDumpWriteDump (
  HANDLE hProcess,
  DWORD ProcessId,
  HANDLE hFile,
  MINIDUMP_TYPE DumpType,
  PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
  PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
  PMINIDUMP_CALLBACK_INFORMATION CallbackParam
);

Parameters

hProcess
[in] Handle to the process for which the information is to be generated. This handle must have read and query access.
ProcessId
[in] Identifier of the process for which the information is to be generated.
hFile
[in] Handle to the file in which the information is to be written.
DumpType
[in] Type of information to be generated. This parameter can be one of the values from the MINIDUMP_TYPE enumeration.
ExceptionParam
[in] Pointer to a MINIDUMP_EXCEPTION_INFORMATION structure describing the client exception that caused the minidump to be generated. If the value of this parameter is NULL, no exception information is included in the minidump file.
UserStreamParam
[in] Pointer to an array of MINIDUMP_USER_STREAM_INFORMATION structures. If the value of this parameter is NULL, no user-defined information is included in the minidump file.
CallbackParam
[in] Pointer to a MINIDUMP_CALLBACK_INFORMATION structure that specifies a callback routine which is to receive extended dump information. If the value of this parameter is NULL, no callbacks are performed.

Return Values

If the function succeeds, the return value is TRUE; otherwise, the return value is FALSE.

Remarks

The MiniDumpCallback function receives extended dump information from MiniDumpWriteDump. It also provides a way for the caller to determine the granularity of information written to the minidump file, as the callback function can filter the default information.

You can use this function on versions of Windows prior to Whistler without redistributing DbgHelp.dll. To do so, link with the static library MiniDump.lib, which is included in the Platform SDK.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, MINIDUMP_CALLBACK_INFORMATION, MINIDUMP_EXCEPTION_INFORMATION, MINIDUMP_USER_STREAM_INFORMATION, MiniDumpCallback, MiniDumpReadDumpStream


ReadProcessMemoryProc

The ReadProcessMemoryProc function is an application-defined callback function used with the StackWalk function. It is called when StackWalk needs to read memory from the address space of the process.

The PREAD_PROCESS_MEMORY_ROUTINE type defines a pointer to this callback function. ReadProcessMemoryProc is a placeholder for the application-defined function name.

BOOL CALLBACK ReadProcessMemoryProc(
  HANDLE hProcess,
  DWORD lpBaseAddress,
  PVOID lpBuffer,
  DWORD nSize,
  PDWORD lpNumberOfBytesRead
);

The PREAD_PROCESS_MEMORY_ROUTINE64 type defines a pointer to this callback function. ReadProcessMemoryProc64 is a placeholder for the application-defined function name.

BOOL CALLBACK ReadProcessMemoryProc64(
  HANDLE hProcess,
  DWORD64 lpBaseAddress,
  PVOID lpBuffer,
  DWORD nSize,
  LPDWORD lpNumberOfBytesRead
);

Parameters

hProcess
[in] Handle to the process for which the stack trace is generated.
lpBaseAddress
[in] Specifies the base address of the memory to be read.
lpBuffer
[in] Receives the memory to be read.
nSize
[in] Specifies the size, in bytes, of the memory to be read.
lpNumberOfBytesRead
[in] Receives the number of bytes actually read.

Return Values

If the function succeeds, the return value should be TRUE. If the function fails, the return value should be FALSE.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Functions, StackWalk


SearchTreeForFile

The SearchTreeForFile function searches a directory tree for a specified file.

BOOL SearchTreeForFile(
  PSTR RootPath,
  PSTR InputPathName,
  PSTR OutputPathBuffer
);

Parameters

RootPath
[in] Pointer to a null-terminated string that specifies the path where the function should begin searching for the file.
InputPathName
[in] Pointer to a null-terminated string that specifies the file for which the function will search. You can use a partial path.
OutputPathBuffer
[out] Pointer to a buffer that receives the full path to the file that is found. This string is not modified if the return value is FALSE.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The function searches for the file specified by the InputPathName parameter beginning at the path specified in the RootPath parameter. The maximum path depth that is allowed in the RootPath is 32 directories. When the function finds the file in the directory tree, it places the full path to the file in the buffer specified by the OutputPathBuffer parameter. The underlying file system specifies the order of the subdirectory search.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions


StackWalk

The StackWalk function provides a portable method for obtaining a stack trace.

This function is implemented as a wrapper that calls StackWalk64. For more information, see New 64-bit Support.

BOOL StackWalk(
  DWORD MachineType,
  HANDLE hProcess,
  HANDLE hThread,
  LPSTACKFRAME StackFrame,
  PVOID ContextRecord,
  PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
  PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
  PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
  PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
);

For StackWalk64, the parameter list is as follows.

BOOL StackWalk64(
  DWORD MachineType,
  HANDLE hProcess,
  HANDLE hThread,
  LPSTACKFRAME64 StackFrame,
  PVOID ContextRecord,
  PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
  PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
  PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
  PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress
);

Parameters

MachineType
[in] Specifies the architecture type of the computer for which the stack trace is generated. This parameter can be one of the following values.
Value | Meaning
IMAGE_FILE_MACHINE_I386 | Intel (32-bit)
IMAGE_FILE_MACHINE_IA64 | Whistler: Intel (64-bit)
IMAGE_FILE_MACHINE_AMD64 | Whistler: AMD (64-bit)
IMAGE_FILE_MACHINE_ALPHA | Windows NT 4.0 and earlier: DEC Alpha
IMAGE_FILE_MACHINE_POWERPC | Windows NT 4.0 and earlier: Power PC

hProcess
[in] Handle to the process for which the stack trace is generated. If the caller supplies a valid callback pointer for the ReadMemoryRoutine parameter, then this value does not have to be a valid process handle. It can be a token that is unique and consistently the same for all calls to the StackWalk function. If the symbol handler is used with StackWalk, use the same process handles for the calls to each function.
hThread
[in] Handle to the thread for which the stack trace is generated. If the caller supplies a valid callback pointer for the ReadMemoryRoutine parameter, then this value does not have to be a valid thread handle. It can be a token that is unique and consistently the same for all calls to the StackWalk function.
StackFrame
[in/out] Pointer to a STACKFRAME structure. This structure receives information for the next frame, if the function call succeeds.
ContextRecord
[in] Pointer to a CONTEXT structure. This parameter is required only when the MachineType parameter is not IMAGE_FILE_MACHINE_I386.
ReadMemoryRoutine
[in] Pointer to a callback routine that provides memory read services. When the StackWalk function needs to read memory from the process's address space, the ReadProcessMemoryProc callback is used. If NULL is passed, then the ReadProcessMemory function is used. In this case, the hProcess parameter must be a valid process handle.
FunctionTableAccessRoutine
[in] Pointer to a callback routine that provides access to the run-time function table for the process. For RISC computers, this function accesses the pdata table, while on X86 computers this function accesses the fpo table. This parameter is required because the StackWalk function does not have access to the process's run-time function table. For more information, see FunctionTableAccessProc.

The symbol handler provides functions that load and access the run-time table. If these functions are used, then SymFunctionTableAccess can be passed as a valid parameter.

GetModuleBaseRoutine
[in] Pointer to a callback routine that provides a module base for any given virtual address. This parameter is required. For more information, see GetModuleBaseProc.

The symbol handler provides functions that load and maintain module information. If these functions are used, then SymGetModuleBase can be passed as a valid parameter.

TranslateAddress
[in] Pointer to a callback routine that provides address translation for 16-bit addresses. For more information, see TranslateAddressProc.

Most callers of StackWalk can safely pass NULL for this parameter.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The StackWalk function provides a portable method for obtaining a stack trace. Using the StackWalk function is recommended over writing your own function because of all the complexities associated with stack walking on platforms. In addition, there are compiler options that cause the stack to appear differently, depending on how the module is compiled. By using this function, your application has a portable stack trace that continues to work as the compiler and operating system change.

The first call to this function will fail if the AddrPC and AddrFrame members of the STACKFRAME structure passed in the StackFrame parameter are not initialized.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, CONTEXT, FunctionTableAccessProc, GetModuleBaseProc, ReadProcessMemoryProc, STACKFRAME, TranslateAddressProc


SymbolRegisteredCallback

The SymbolRegisteredCallback function is an application-defined callback function used with the SymRegisterCallback function. It is called by the symbol handler.

The PSYMBOL_REGISTERED_CALLBACK type defines a pointer to this callback function. SymbolRegisteredCallback is a placeholder for the application-defined function name.

BOOL CALLBACK SymbolRegisteredCallback(
  HANDLE hProcess,
  ULONG ActionCode,
  PVOID CallbackData,
  PVOID UserContext
);

The PSYMBOL_REGISTERED_CALLBACK64 type defines a pointer to this callback function. SymbolRegisteredCallback64 is a placeholder for the application-defined function name.

BOOL CALLBACK SymbolRegisteredCallback64(
  HANDLE hProcess,
  ULONG ActionCode,
  ULONG64 CallbackData,
  ULONG64 UserContext
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
ActionCode
[in] Specifies the reason for the callback. The valid values are described in the following table.
Value | Meaning
CBA_DEFERRED_SYMBOL_LOAD_START | Deferred symbol load started. The CallbackData parameter is a pointer to a IMAGEHLP_DEFERRED_SYMBOL_LOAD structure.
CBA_DEFERRED_SYMBOL_LOAD_COMPLETE | Deferred symbol load completed. The CallbackData parameter is a pointer to a IMAGEHLP_DEFERRED_SYMBOL_LOAD structure.
CBA_DEFERRED_SYMBOL_LOAD_FAILURE | Deferred symbol load failure. The CallbackData parameter is a pointer to a IMAGEHLP_DEFERRED_SYMBOL_LOAD structure.
CBA_SYMBOLS_UNLOADED | Symbols unloaded. The CallbackData parameter is NULL.
CBA_DUPLICATE_SYMBOL | Duplicate symbol. The CallbackData parameter is a pointer to a IMAGEHLP_DUPLICATE_SYMBOL structure.
CBA_READ_MEMORY | Read loaded image. The CallbackData parameter is a pointer to a IMAGEHLP_CBA_READ_MEMORY structure.
CBA_DEBUG_INFO | Display verbose information. The CallbackData parameter is a pointer to a string.

CallbackData
[in] Specifies data for the operation. The format of this data depends on the value of the ActionCode parameter.
UserContext
[in] A user-defined value specified in SymRegisterCallback, or NULL. Typically, this parameter is used by an application to pass a pointer to a data structure that lets the callback function establish some context.

Return Values

Returning the value TRUE indicates success.

Returning the value FALSE indicates failure.

Remarks

The calling application gets called through the registered callback function as a result of another call to one of the symbol handler functions. The calling application must be prepared for the possible side effects that this can cause. If the application has only one callback function that is being used by multiple threads, then care may be necessary to synchronize some types of data access while in the context of the callback function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Functions, IMAGEHLP_CBA_READ_MEMORY, IMAGEHLP_DEFERRED_SYMBOL_LOAD, IMAGEHLP_DUPLICATE_SYMBOL, SymRegisterCallback


SymbolRegisteredFunctionEntryCallback

The SymbolRegisteredFunctionEntryCallback function is an application-defined callback function used with the SymRegisterFunctionEntryCallback function. It is called by the stack walking procedure.

The PSYMBOL_FUNCENTRY_CALLBACK type defines a pointer to this callback function. SymbolRegisteredFunctionEntryCallback is a placeholder for the application-defined function name.

PVOID CALLBACK SymbolRegisteredFunctionEntryCallback(
  HANDLE hProcess,
  DWORD AddrBase,
  PVOID UserContext
);

The PSYMBOL_FUNCENTRY_CALLBACK64 type defines a pointer to this callback function. SymbolRegisteredFunctionEntryCallback64 is a placeholder for the application-defined function name.

PVOID CALLBACK SymbolRegisteredFunctionEntryCallback64(
  HANDLE hProcess,
  ULONG64 AddrBase,
  ULONG64 UserContext
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the StackWalk function.
AddrBase
[in] Address of an instruction for which the callback function should return a function table entry.
UserContext
[in] A user-defined value specified in SymRegisterFunctionEntryCallback, or NULL. Typically, this parameter is used by an application to pass a pointer to a data structure that lets the callback function establish some context.

Return Values

Returning the value NULL indicates that no function table entry is available.

On success, return a pointer to an IMAGE_RUNTIME_FUNCTION_ENTRY structure.

Remarks

The structure must be returned in exactly the form it exists in the process being debugged. Some members may be pointers to other locations in the process address space. The ReadProcessMemoryProc callback function may be called to retrieve the information at these locations.

The calling application gets called through the registered callback function as a result of a call to the StackWalk function. The calling application must be prepared for the possible side effects that this can cause. If the application has only one callback function that is being used by multiple threads, then it may be necessary to synchronize some types of data access while in the context of the callback function.

This function is similar to the FunctionTableAccessProc callback function on Windows NT 4.0. The difference is that FunctionTableAccessProc returns an IMAGE_FUNCTION_ENTRY structure, while this function returns an IMAGE_RUNTIME_FUNCTION_ENTRY structure. Windows 2000 for Alpha computers supports enhancements to the Alpha calling standard which require the full IMAGE_RUNTIME_FUNCTION_ENTRY structure rather than the abbreviated IMAGE_FUNCTION_ENTRY structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Functions, SymRegisterFunctionEntryCallback


SymbolServer

The SymbolServer function is an entry point to the symbol server DLL. It is used to locate a symbol file. The PSYMBOLSERVERPROC type defines a pointer to this callback function. SymbolServer is a placeholder for the library-defined function name.

BOOL CALLBACK SymbolServer(
  LPCSTR params,
  LPCSTR filename,
  PVOID  id,
  DWORD  two,
  DWORD  three,
  LPSTR  path
);

Parameters

params
[in] Pointer to a string that specifies server-specific information. This information is used to identify which store to use for locating symbols. For more information, see Using the Symbol Server.
filename
[in] The name of the symbol file to be returned.
id
[in] The first of three identifying parameters (see Remarks).
two
[in] The second of three identifying parameters (see Remarks).
three
[in] The third of three identifying parameters (see Remarks).
path
[out] A buffer of _MAX_PATH bytes that receives the fully qualified path to the symbol file.

Return Values

If the server locates a valid symbol file, it returns TRUE; otherwise, it returns FALSE and GetLastError returns a value that indicates why the symbol file was not returned.

Remarks

The identifying parameters are filled in as follows.

  • If DbgHelp is looking for a .dbg file, the id parameter contains the TimeDateStamp of the original image as found in its PE header. Parameter two contains the SizeOfImage field, also extracted from the PE header. Parameter three is unused and set to zero.
  • If DbgHelp is looking for a .pdb file, the id parameter contains the PDB signature as found in the codeview debug directory of the original image. Parameter two contains the PDB age. Parameter three is unused and set to zero.
  • If DbgHelp is looking for any other type of image, such as an executable file, it is probably being called through the SymFindFileInPath function. In this case, the parameters are opaque to DbgHelp. However, if this function is being used to retrieve an executable file, it is expected that the parameters will be filled in as for a .dbg file, using TimeDateStamp and the image size as parameters.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.

See Also

Debug Help Library Overview, DbgHelp Functions, SymFindFileInPath


SymbolServerClose

The SymbolServerClose function is an entry point to the symbol server DLL. It is called every time the SymCleanup function is called. The PSYMBOLSERVERCLOSEPROC type defines a pointer to this callback function. SymbolServerGetOptions is a placeholder for the library-defined function name.

BOOL SymbolServerClose( );

Parameters

This function has no parameters.

Return Values

The server can return TRUE to indicate success, or return FALSE and call the SetLastError function to indicate an error condition.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.

See Also

Debug Help Library Overview, DbgHelp Functions


SymbolServerGetOptions

The SymbolServerGetOptions function is an entry point to the symbol server DLL. It is used to retrieve the symbol server options. The PSYMBOLSERVERGETOPTIONSPROC type defines a pointer to this callback function. SymbolServerGetOptions is a placeholder for the library-defined function name.

UINT_PTR CALLBACK SymbolServerGetOptions();

Parameters

This function has no parameters.

Return Values

The function returns the symbol server options that have been set. This parameter can be one of the following values.

Value | Meaning
SSRVOPT_CALLBACK | The data is a callback function.
SSRVOPT_DWORD | The data is a DWORD value.
SSRVOPT_DWORDPTR | The data is a DWORD_PTR value.
SSRVOPT_GUIDPTR | The data is a pointer to a GUID.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.

See Also

Debug Help Library Overview, DbgHelp Functions, SymbolServerSetOptions


SymbolServerSetOptions

The SymbolServerSetOptions function is an entry point to the symbol server DLL. It is used to set the symbol server options. The PSYMBOLSERVERSETOPTIONSPROC type defines a pointer to this callback function. SymbolServerSetOptions is a placeholder for the library-defined function name.

BOOL CALLBACK SymbolServerSetOptions(
  UINT_PTR options,
  ULONG64  data
);

Parameters

options
Specifies the options to be set. This parameter can be one of the following values.
Value | Meaning
SSRVOPT_CALLBACK | The data is a callback function.
SSRVOPT_DWORD | The data is a DWORD value.
SSRVOPT_DWORDPTR | The data is a DWORD_PTR value.
SSRVOPT_GUIDPTR | The data is a pointer to a GUID.

data
Server-specific data.

Return Values

The server can return TRUE to indicate success, or return FALSE and call the SetLastError function to indicate an error condition.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.

See Also

Debug Help Library Overview, DbgHelp Functions, SymbolServerGetOptions


SymCleanup

The SymCleanup function deallocates all resources associated with the process handle.

BOOL SymCleanup(
  HANDLE hProcess
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

This function frees all resources associated with the process handle. Failure to call this function causes memory and resource leaks in the calling application

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, SymInitialize


SymEnumerateModules

The SymEnumerateModules function enumerates all modules that have been loaded for the process by the SymLoadModule function.

This function is implemented as a wrapper that calls SymEnumerateModules64. For more information, see New 64-bit Support.

BOOL SymEnumerateModules(
  HANDLE hProcess,
  PSYM_ENUMMODULES_CALLBACK EnumModulesCallback,
  PVOID UserContext
);

For SymEnumerateModules64, the parameter list is as follows.

BOOL SymEnumerateModules64(
  HANDLE hProcess,
  PSYM_ENUMMODULES_CALLBACK64 EnumModulesCallback,
  PVOID UserContext
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
EnumModulesCallback
[in] Pointer to the enumeration callback function. This function is called once per module. For more information, see SymEnumModulesCallback.
UserContext
[in] A user-defined value or NULL. This value is simply passed to the callback function. Normally, this parameter is used by an application to pass a pointer to a data structure that lets the callback function establish some type of context.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The SymEnumerateModules function enumerates all modules that have been loaded for the process by SymLoadModule, even if the symbol loading is deferred. The enumeration callback function is called once for each module and is passed the module information.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, SymEnumModulesCallback, SymInitialize, SymLoadModule


SymEnumerateSymbols

The SymEnumerateSymbols function enumerates all the symbols for a specified module.

This function is implemented as a wrapper that calls SymEnumerateSymbols64. For more information, see New 64-bit Support.

BOOL SymEnumerateSymbols(
  HANDLE hProcess,
  DWORD BaseOfDll,
  PSYM_ENUMSYMBOLS_CALLBACK EnumSymbolsCallback,
  PVOID UserContext
);

For SymEnumerateSymbols64, the parameter list is as follows.

BOOL SymEnumerateSymbols64(
  HANDLE hProcess,
  DWORD64 BaseOfDll,
  PSYM_ENUMSYMBOLS_CALLBACK64 EnumSymbolsCallback,
  PVOID UserContext
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
BaseOfDll
[in] Specifies the base address of the module for which symbol enumeration is to take place.
EnumSymbolsCallback
[in] Pointer to the callback function that receives the symbol information. For more information, see SymEnumSymbolsCallback.
UserContext
[in] A user-defined value or NULL. This value is simply passed to the callback function. Normally, this parameter is used by an application to pass a pointer to a data structure that lets the callback function establish some type of context.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The SymEnumerateSymbols function enumerates all the symbols for a desired module. The module information is located by the BaseOfDll parameter. The EnumSymbolsCallback function is called once per symbol and is passed the information for each symbol.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, SymEnumSymbolsCallback, SymInitialize


SymEnumModulesCallback

The SymEnumModulesCallback function is an application-defined callback function used with the SymEnumerateModules function. It is called once for each enumerated module, and receives the module information.

The PSYM_ENUMMODULES_CALLBACK type defines a pointer to this callback function. SymEnumModulesCallback is a placeholder for the application-defined function name.

BOOL CALLBACK SymEnumModulesCallback(
  PSTR ModuleName,
  ULONG BaseOfDll,
  PVOID UserContext
);

The PSYM_ENUMMODULES_CALLBACK64 type defines a pointer to this callback function. SymEnumModulesCallback64 is a placeholder for the application-defined function name.

BOOL CALLBACK SymEnumModulesCallback64(
  PSTR ModuleName,
  DWORD64 BaseOfDll,
  PVOID UserContext
);

Parameters

ModuleName
[in] Pointer to a null-terminated string that specifies the name of the module.
BaseOfDll
[in] Specifies the base address where the module is loaded into memory.
UserContext
[in] A user-defined value specified in SymEnumerateModules, or NULL. Typically, this parameter is used by an application to pass a pointer to a data structure that lets the callback function establish some type of context.

Return Values

If the return value is TRUE, the enumeration will continue.

If the return value is FALSE, the enumeration will stop.

Remarks

The calling application is called once per module until all modules are enumerated, or until the enumeration callback function returns FALSE.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Functions, SymEnumerateModules


SymEnumSymbolsCallback

The SymEnumSymbolsCallback function is an application-defined callback function used with the SymEnumerateSymbols function. It is called once for each enumerated symbol, and receives the symbol information.

The PSYM_ENUMSYMBOLS_CALLBACK type defines a pointer to this callback function. SymEnumSymbolsCallback is a placeholder for the application-defined function name.

BOOL CALLBACK SymEnumSymbolsCallback(
  PTSTR  SymbolName,
  ULONG SymbolAddress,
  ULONG SymbolSize,
  PVOID UserContext
);

The PSYM_ENUMSYMBOLS_CALLBACK64 type defines a pointer to this callback function. SymEnumSymbolsCallback64 is a placeholder for the application-defined function name.

BOOL CALLBACK SymEnumSymbolsCallback64(
  PTSTR  SymbolName,
  DWORD64 SymbolAddress,
  ULONG SymbolSize,
  PVOID UserContext
);

Parameters

SymbolName
[in] Pointer to a null-terminated string that specifies the name of the symbol. The name can be undecorated if the SYMOPT_UNDNAME option is used with the SymSetOptions function.
SymbolAddress
[in] Specifies the virtual address for the beginning of the symbol.
SymbolSize
[in] Specifies the size of the symbol, in bytes. The size is calculated and is actually a best-guess value. In some cases, the value can be zero.
UserContext
[in] A user-defined value specified in SymEnumerateSymbols, or NULL. Typically, this parameter is used by an application to pass a pointer to a data structure that lets the callback function establish some type of context.

Return Values

If the function returns TRUE, the enumeration will continue.

If the function returns FALSE, the enumeration will stop.

Remarks

The calling application is called once per symbol until all the symbols are enumerated or until the enumeration callback function returns FALSE.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Functions, SymEnumerateSymbols


SymFindFileInPath

The SymFindFileInPath function is used to locate a symbol file.

BOOL SymFindFileInPath(
  HANDLE hprocess,
  LPSTR  SearchPath,
  LPSTR  FileName,
  PVOID  id,
  DWORD  two,
  DWORD  three,
  DWORD  flags,
  LPSTR  FilePath,
  PFINDFILEINPATHCALLBACK callback,
  PVOID context
);

Parameters

hprocess
[in] Handle to the process that was originally passed to the SymInitialize function.
SearchPath
[in] Pointer to a null-terminated string that specifies the path where symbol files are located. This can be multiple paths separated by semicolons. If this parameter is NULL, the function uses the symbol path set using the SymSetSearchPath function.
FileName
[in] Pointer to a null-terminated string that specifies the name of the file. You can use a partial path.
id
[in] The first of three identifying parameters (see Remarks).
two
[in] The second of three identifying parameters (see Remarks).
three
[in] The third of three identifying parameters (see Remarks).
flags
[in] Specifies the format of the id parameter. This parameter can be one of the following values.
Value | Meaning
SSRVOPT_DWORD | The id parameter is a DWORD.
SSRVOPT_DWORDPTR | The id parameter is a pointer to a DWORD.
SSRVOPT_GUIDPTR | The id parameter is a pointer to a GUID.

FilePath
[out] A buffer of _MAX_PATH bytes that receives the fully qualified path to the symbol file.
callback
[in] Pointer to a callback function. For more information, see SymFindFileInPathCallback.
context
[in] A user-defined value or NULL. This value is simply passed to the callback function. This parameter is typically used by an application to pass a pointer to a data structure that provides some context for the callback function.

Return Values

If the server locates a valid symbol file, it returns TRUE; otherwise, it returns FALSE and GetLastError returns a value that indicates why the symbol file was not returned.

Remarks

The identifying parameters are filled in as follows:

  • If DbgHelp is looking for a .pdb file, the id parameter specifies the PDB signature as found in the codeview debug directory of the original image. Parameter two specifies the PDB age. Parameter three is unused and set to zero.
  • If DbgHelp is looking for any other type of image, such as an executable file or .dbg file, the id parameter specifies the TimeDateStamp of the original image as found in its PE header. Parameter two specifies the SizeOfImage field, also extracted from the PE header. Parameter three is unused and set to zero.

Note In a preliminary version of the documentation, this function was known as FindFileInPath.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, SymFindFileInPathCallback, SymInitialize, SymSetSearchPath


SymFindFileInPathCallback

The SymFindFileInPathCallback function is an application-defined callback function used with the SymFindFileInPath function.

The PFINDFILEINPATHCALLBACK type defines a pointer to this callback function. SymFindFileInPathCallback is a placeholder for the application-defined function name.

BOOL SymFindFileInPathCallback(
  PSTR  fileName,
  PVOID context
);

Parameters

fileName
[in] Pointer to a null-terminated string that specifies the name of the file. This string can be a partial path.
context
[in] A user-defined value specified in SymFindFileInPath, or NULL. This parameter is typically used by an application to pass a pointer to a data structure that provides some context for the callback function.

Return Values

Return TRUE to indicate success.

Return FALSE to indicate failure.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.

See Also

Debug Help Library Overview, DbgHelp Functions, SymFindFileInPath


SymFunctionTableAccess

The SymFunctionTableAccess function retrieves the function table entry for the specified address.

This function is implemented as a wrapper that calls SymFunctionTableAccess64. For more information, see New 64-bit Support.

PVOID SymFunctionTableAccess(
  HANDLE hProcess,
  DWORD AddrBase
);

For SymFunctionTableAccess64, the parameter list is as follows.

PVOID SymFunctionTableAccess64(
  HANDLE hProcess,
  DWORD64 AddrBase
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
AddrBase
[in] Specifies the base address for which function table information is required.

Return Values

If the function succeeds, the return value is a pointer to the function table entry. The page in memory that contains the function table entry is marked as read-only. Any attempt to write to the returned pointer results in an access violation exception.

If the function fails, the return value is NULL. To retrieve extended error information, call GetLastError.

Remarks

The type of pointer returned is specific to the image from which symbols are loaded. If the image is from an Intel x86 computer, this is a pointer to an FPO_DATA structure. If the image is for any of the RISC platforms supported by Windows NT/Windows 2000, this is a pointer to an IMAGE_FUNCTION_ENTRY structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, FPO_DATA, IMAGE_FUNCTION_ENTRY, SymInitialize


SymGetLineFromAddr

The SymGetLineFromAddr function locates the source line for the specified address.

This function is implemented as a wrapper that calls SymGetLineFromAddr64. For more information, see New 64-bit Support.

BOOL SymGetLineFromAddr(
  HANDLE hProcess,
  DWORD dwAddr,
  PDWORD pdwDisplacement,
  PIMAGEHLP_LINE Line
);

For SymGetLineFromAddr64, the parameter list is as follows.

BOOL SymGetLineFromAddr64(
  HANDLE hProcess,
  DWORD64 dwAddr,
  PDWORD pdwDisplacement,
  PIMAGEHLP_LINE64 Line
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
dwAddr
[in] Specifies the address for which a line should be located. It is not necessary for the address to be on a line boundary. If the address appears after the beginning of a line and before the end of the line, the line is found.
pdwDisplacement
[out] The displacement from the beginning of the line, or zero.
Line
[out] Pointer to an IMAGEHLP_LINE structure.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The caller must allocate the Line buffer properly and fill in the required members of the IMAGEHLP_LINE structure before calling SymGetLineFromAddr.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, IMAGEHLP_LINE, SymGetLineFromName, SymInitialize


SymGetLineFromName

The SymGetLineFromName function locates a source line for the specified module, file name, and line number.

This function is implemented as a wrapper that calls SymGetLineFromName64. For more information, see New 64-bit Support.

BOOL SymGetLineFromName(
  HANDLE hProcess,
  PSTR ModuleName,
  PSTR FileName,
  DWORD dwLineNumber,
  PLONG lpDisplacement,
  PIMAGEHLP_LINE Line
);

For SymGetLineFromName64, the parameter list is as follows.

BOOL SymGetLineFromName64(
  HANDLE hProcess,
  PSTR ModuleName,
  PSTR FileName,
  DWORD dwLineNumber,
  PLONG lpDisplacement,
  PIMAGEHLP_LINE64 Line
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
ModuleName
[in] Pointer to a null-terminated string that specifies the name of the module in which a line is to be located.
FileName
[in] Pointer to a null-terminated string that specifies the name of the file in which a line is to be located.
dwLineNumber
[in] Specifies the line number to be located.
lpDisplacement
[out] The displacement from the beginning of the line, or zero.
Line
[in/out] Pointer to an IMAGEHLP_LINE structure.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The caller must allocate the Line buffer properly and fill in the required members of the IMAGEHLP_LINE structure before calling SymGetLineFromName.

Before calling this function, ensure that the symbols are initialized correctly by first calling SymInitialize, SymSetOptions, and SymLoadModule.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, IMAGEHLP_LINE, SymGetLineFromAddr, SymInitialize


SymGetLineNext

The SymGetLineNext function retrieves the line information for the next source line.

This function is implemented as a wrapper that calls SymGetLineNext64. For more information, see New 64-bit Support.

BOOL SymGetLineNext(
  HANDLE hProcess,
  PIMAGEHLP_LINE Line
);

For SymGetLineNext64, the parameter list is as follows.

BOOL SymGetLineNext64(
  HANDLE hProcess,
  PIMAGEHLP_LINE64 Line
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
Line
[in/out] Pointer to an IMAGEHLP_LINE structure that contains the line information.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The SymGetLineNext function requires that the IMAGEHLP_LINE structure have valid data, presumably obtained from a call to the SymGetLineFromAddr or SymGetLineFromName function. This structure receives the line information for the next line in sequence.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, IMAGEHLP_LINE, SymGetLineFromAddr, SymGetLineFromName, SymGetLinePrev, SymInitialize


SymGetLinePrev

The SymGetLinePrev function retrieves the line information for the previous source line.

This function is implemented as a wrapper that calls SymGetLinePrev64. For more information, see New 64-bit Support.

BOOL SymGetLinePrev(
  HANDLE hProcess,
  PIMAGEHLP_LINE Line
);

For SymGetLinePrev64, the parameter list is as follows.

BOOL SymGetLinePrev64(
  HANDLE hProcess,
  PIMAGEHLP_LINE64 Line
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
Line
[in/out] Pointer to an IMAGEHLP_LINE structure.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The SymGetLinePrev function requires that the IMAGEHLP_LINE structure have valid data, presumably obtained from a call to the SymGetLineFromAddr or SymGetLineFromName function. This structure is filled with the line information for the previous line in sequence.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, IMAGEHLP_LINE, SymGetLineFromAddr, SymGetLineFromName, SymGetLineNext, SymInitialize


SymGetModuleBase

The SymGetModuleBase function retrieves the base address of the module that contains the specified address.

This function is implemented as a wrapper that calls SymGetModuleBase64. For more information, see New 64-bit Support.

DWORD SymGetModuleBase(
  HANDLE hProcess,
  DWORD dwAddr
);

For SymGetModuleBase64, the parameter list is as follows.

DWORD64 SymGetModuleBase64(
  HANDLE hProcess,
  DWORD64 dwAddr
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
dwAddr
[in] Specifies the valid virtual address that is contained in one of the modules loaded by the SymLoadModule function.

Return Values

If the function succeeds, the return value is a nonzero virtual address. The value is the base address of the module containing the address specified by the dwAddr parameter.

If the function fails, the return value is zero. To retrieve extended error information, call GetLastError.

Remarks

The module table is searched for a module that contains dwAddr. The module is located based on the load address and size of each module.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, SymInitialize, SymLoadModule


SymGetModuleInfo

The SymGetModuleInfo function retrieves the module information of the specified module.

This function is implemented as a wrapper that calls SymGetModuleInfo64. For more information, see New 64-bit Support.

BOOL SymGetModuleInfo(
  HANDLE hProcess,
  DWORD dwAddr,
  PIMAGEHLP_MODULE ModuleInfo
);

For SymGetModuleInfo64, the parameter list is as follows.

BOOL SymGetModuleInfo64(
  HANDLE hProcess,
  DWORD64 dwAddr,
  PIMAGEHLP_MODULE64 ModuleInfo
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
dwAddr
[in] Specifies the valid, virtual address that is contained in one of the modules loaded by the SymLoadModule function
ModuleInfo
[out] Pointer to an IMAGEHLP_MODULE structure. The SizeOfStruct member must be set to the size of the IMAGEHLP_MODULE structure. An invalid value will result in an error.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The module table is searched for a module that contains the dwAddr. The module is located based on the load address and size of each module. If a valid module is found, the ModuleInfo parameter is filled with the information about the module.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, IMAGEHLP_MODULE, SymGetModuleInfoEx, SymInitialize, SymLoadModule


SymGetModuleInfoEx

The SymGetModuleInfoEx function retrieves advanced module information for the specified module. This function is intended for use by Windows 2000 debuggers.

This function is implemented as a wrapper that calls SymGetModuleInfoEx64. For more information, see New 64-bit Support.

BOOL SymGetModuleInfoEx(
  HANDLE hProcess,
  DWORD dwAddr,
  IMAGEHLP_TYPES TypeIn,
  PBYTE DataIn,
  IMAGEHLP_TYPES TypeOut,
  PULONG SizeOut,
  PBYTE DataOut
);

For SymGetModuleInfoEx64, the parameter list is as follows.

BOOL SymGetModuleInfoEx64(
  HANDLE hProcess,
  DWORD64 dwAddr,
  IMAGEHLP_TYPES TypeIn,
  PBYTE DataIn,
  IMAGEHLP_TYPES TypeOut,
  PULONG SizeOut,
  PBYTE DataOut
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
dwAddr
[in] Specifies the valid, virtual address that is contained in one of the modules loaded by the SymLoadModule function.
TypeIn
[in] Specifies the input type. This parameter can be one of the following values.
Value | Meaning
IMAGEHLP_TYPEID_IMAGEHLP_SYMBOL | The DataIn parameter is a pointer to an IMAGEHLP_SYMBOL structure.
IMAGEHLP_TYPEID_IMAGEHLP_SYMBOL64 | The DataIn parameter is a pointer to an IMAGEHLP_SYMBOL64 structure.
IMAGEHLP_TYPEID_INDEX | The DataIn parameter is a pointer to a type index.
IMAGEHLP_TYPEID_NAME | The DataIn parameter is a pointer to a string that specifies the symbol name.

DataIn
[in] Pointer to a buffer that specifies the input data.
TypeOut
[in] Specifies the output type. This parameter can be one of the following values.
Value | Meaning
IMAGEHLP_TYPEID_INDEX | The function takes the symbol name in DataIn and returns its type index in DataOut.
IMAGEHLP_TYPEID_MODULE_TYPE_INFO | The function takes the type index from DataIn and returns a MODULE_TYPE_INFO structure.
IMAGEHLP_TYPEID_TYPE_ENUM_INFO | The function takes the partial symbol name in DataIn and enumerates all symbols that begin with the same characters. The DataOut parameter is a pointer to a TYPE_ENUM_INFO structure. Each time the function finds a match, it calls the SymTypeNameCallback function specified in the structure.

SizeOut
[in] Specifies the size, in bytes, of the DataOut buffer.
DataOut
[in,out] Pointer to a buffer that receives the data.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, MODULE_TYPE_INFO, SymInitialize, SymLoadModule, TYPE_ENUM_INFO


SymGetOptions

The SymGetOptions function retrieves the current options mask.

DWORD SymGetOptions(VOID);

Parameters

This function has no parameters.

Return Values

The SymGetOptions function always returns the current options mask. Zero is a valid value and indicates that all options are turned off. The options values are masks that are combined using the OR operator to form a valid options value. The valid mask values are as follows.

Value | Meaning
SYMOPT_CASE_INSENSITIVE | All symbol searches are insensitive to case.
SYMOPT_UNDNAME | All symbols are presented in undecorated form.
SYMOPT_DEFERRED_LOADS | Symbols are not loaded until a reference is made requiring the symbols be loaded. This is the fastest, most efficient way to use the symbol handler.
SYMOPT_NO_CPP | All C++ decorated symbols containing the symbol separator "::" are replaced by "__". This option exists for debuggers that cannot handle parsing real C++ symbol names.
SYMOPT_LOAD_LINES | Loads line number information.

Remarks

The options value can be changed several times while the library is in use by an application. The option change affects all future calls to the symbol handler.

To set the current options mask, use the SymSetOptions function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions


SymGetSearchPath

The SymGetSearchPath function retrieves the symbol search path for the specified process.

BOOL SymGetSearchPath(
  HANDLE hProcess,
  PSTR SearchPath,
  DWORD SearchPathLength
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
SearchPath
[out] Pointer to the buffer that receives the symbol search path.
SearchPathLength
[in] Specifies the length of the SearchPath buffer, in bytes.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The SymGetSearchPath function copies the symbol search path for the specified process into the SearchPath buffer. If the function fails, the contents of the buffer are undefined.

To specify a symbol search path for the process, use the SymSetSearchPath function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, SymInitialize, SymSetSearchPath


SymGetSymbolInfo

The SymGetSymbolInfo function retrieves advanced symbol information for a specified symbol. This function is intended for use by Windows 2000 debuggers.

This function is implemented as a wrapper that calls SymGetSymbolInfo64. For more information, see New 64-bit Support.

BOOL SymGetSymbolInfo(
  HANDLE hProcess,
  DWORD Address,
  IMAGEHLP_TYPES TypeIn,
  PBYTE DataIn,
  IMAGEHLP_TYPES TypeOut,
  PULONG SizeOut,
  PBYTE DataOut
);

For SymGetSymbolInfo64, the parameter list is as follows.

BOOL SymGetSymbolInfo64(
  HANDLE hProcess,
  DWORD64 Address,
  IMAGEHLP_TYPES TypeIn,
  PBYTE DataIn,
  IMAGEHLP_TYPES TypeOut,
  PULONG SizeOut,
  PBYTE DataOut
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
Address
[in] Specifies the address for which a symbol should be found. The address does not need to be on a symbol boundary. If the address comes after the beginning of a symbol and before the end of the symbol (the beginning of the symbol plus the symbol size), the symbol is found.
TypeIn
[in] Specifies the input type. This parameter can be one of the following values.
Value | Meaning
IMAGEHLP_TYPEID_IMAGEHLP_SYMBOL | The DataIn parameter is a pointer to an IMAGEHLP_SYMBOL structure.
IMAGEHLP_TYPEID_IMAGEHLP_SYMBOL64 | The DataIn parameter is a pointer to an IMAGEHLP_SYMBOL64 structure.
IMAGEHLP_TYPEID_NAME | The DataIn parameter is a pointer to a string that specifies the symbol name.

DataIn
[in] Pointer to a buffer that specifies the input data. The data type of the buffer is determined by the value of the TypeIn parameter.
TypeOut
[in] Specifies the output type. This parameter can be one of the following values.
Value | Meaning
IMAGEHLP_TYPEID_INDEX | The function takes the symbol name in DataIn and returns its type index in DataOut.
IMAGEHLP_TYPEID_TYPE_ENUM_INFO | The function takes the partial symbol name in DataIn and enumerates all symbols that begin with the same characters. The DataOut parameter is a pointer to a TYPE_ENUM_INFO structure. Each time the function finds a match, it calls the SymTypeNameCallback function specified in the structure.

SizeOut
[in] Specifies the size, in bytes, of the DataOut buffer.
DataOut
[in/out] Pointer to a buffer that receives the data. The data type of the buffer is determined by the value of the TypeOut parameter.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions


SymGetSymFromAddr

The SymGetSymFromAddr function locates the symbol for the specified address.

This function is implemented as a wrapper that calls SymGetSymFromAddr64. For more information, see New 64-bit Support.

BOOL SymGetSymFromAddr(
  HANDLE hProcess,
  DWORD Address,
  PDWORD Displacement,
  PIMAGEHLP_SYMBOL Symbol
);

For SymGetSymFromAddr64, the parameter list is as follows.

BOOL SymGetSymFromAddr64(
  HANDLE hProcess,
  DWORD64 Address,
  PDWORD64 Displacement,
  PIMAGEHLP_SYMBOL64 Symbol
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
Address
[in] Specifies the address for which a symbol should be located. The address does not have to be on a symbol boundary. If the address comes after the beginning of a symbol and before the end of the symbol (the beginning of the symbol plus the symbol size), the symbol is found.
Displacement
[out] The displacement from the beginning of the symbol, or zero.
Symbol
[out] Pointer to an IMAGEHLP_SYMBOL structure.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The SymGetSymFromAddr function locates the symbol for a specified address. The modules are searched for the one the address belongs to. When the module is found, its symbol table is searched for a match. When the symbol is found, the symbol information is copied into the Symbol buffer provided by the caller. The caller must allocate the Symbol buffer properly and fill in the required parameters in the IMAGEHLP_SYMBOL structure before calling SymGetSymFromAddr.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, IMAGEHLP_SYMBOL, SymInitialize


SymGetSymFromName

The SymGetSymFromName function locates a symbol for the specified name.

This function is implemented as a wrapper that calls SymGetSymFromName64. For more information, see New 64-bit Support.

BOOL SymGetSymFromName(
  HANDLE hProcess,
  PSTR Name,
  PIMAGEHLP_SYMBOL Symbol
);

For SymGetSymFromName64, the parameter list is as follows.

BOOL SymGetSymFromName64(
  HANDLE hProcess,
  PSTR Name,
  PIMAGEHLP_SYMBOL64 Symbol
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
Name
[in] Pointer to a null-terminated string that specifies the symbol name for which a symbol is to be located.
Symbol
[out] Pointer to an IMAGEHLP_SYMBOL structure.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The SymGetSymFromName function is used to locate a symbol for a specified name. The name can contain a module prefix that isolates the symbol search to a single module's symbol table.

The module prefix is in the form of "module!". The "!" character is the delimiter between the module name and the symbol name. If there is no module prefix, then the search is performed on each module's symbol table in a linear manner, beginning with the first module that is loaded.

Using the module prefix is preferable for two reasons. First, the symbol search occurs much faster. Second, when deferred symbol loading is turned on, the search causes symbols to be loaded for each module that is searched. When the symbol is found, the symbol information is copied into the Symbol buffer provided by the caller. The caller must allocate the Symbol buffer properly and fill in the required parameters in the IMAGEHLP_SYMBOL structure before calling SymGetSymFromName.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, IMAGEHLP_SYMBOL, SymInitialize


SymGetSymNext

The SymGetSymNext function retrieves the symbol information of the next symbol.

This function is implemented as a wrapper that calls SymGetSymNext64. For more information, see New 64-bit Support.

BOOL SymGetSymNext(
  HANDLE hProcess,
  PIMAGEHLP_SYMBOL Symbol
);

For SymGetSymNext64, the parameter list is as follows.

BOOL SymGetSymNext64(
  HANDLE hProcess,
  PIMAGEHLP_SYMBOL64 Symbol
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
Symbol
[in/out] Pointer to an IMAGEHLP_SYMBOL structure.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The SymGetSymNext function requires that the IMAGEHLP_SYMBOL structure have valid data, presumably obtained from a call to the SymGetSymFromAddr or SymGetSymFromName function. This structure is filled with the symbol information for the next symbol in sequence by virtual address.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, IMAGEHLP_SYMBOL, SymGetSymFromAddr, SymGetSymFromName, SymGetSymPrev, SymInitialize


SymGetSymPrev

The SymGetSymPrev function retrieves the symbol information of the previous symbol.

This function is implemented as a wrapper that calls SymGetSymPrev64. For more information, see New 64-bit Support.

BOOL SymGetSymPrev(
  HANDLE hProcess,
  PIMAGEHLP_SYMBOL Symbol
);

For SymGetSymNext64, the parameter list is as follows.

BOOL SymGetSymPrev64(
  HANDLE hProcess,
  PIMAGEHLP_SYMBOL64 Symbol
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
Symbol
[in/out] Pointer to an IMAGEHLP_SYMBOL structure.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The SymGetSymPrev function requires the IMAGEHLP_SYMBOL structure to have valid data, presumably obtained from a call to the SymGetSymFromAddr or SymGetSymFromName function. This structure is filled in with the symbol information for the previous symbol in sequence by virtual address.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, IMAGEHLP_SYMBOL, SymGetSymFromAddr, SymGetSymFromName, SymGetSymNext, SymInitialize


SymInitialize

The SymInitialize function initializes the symbol handler for a process.

BOOL SymInitialize(
  HANDLE hProcess,
  PSTR UserSearchPath,
  BOOL fInvadeProcess
);

Parameters

hProcess
[in] Handle to the process for which symbols are to be maintained. If the application is a debugger, use the process handle for the object being debugged, otherwise use the GetCurrentProcess function to obtain the process handle.

Windows 95/98/Me: Use the process identifier, not the process handle.

UserSearchPath
[in] Pointer to a null-terminated string that specifies a path, or series of paths separated by a semicolon (;), that is used to search for symbol files. If a value of NULL is used, then the library attempts to form a symbol path from the following sources:
  • The current working directory of the application
  • The _NT_SYMBOL_PATH environment variable
  • The _NT_ALTERNATE_SYMBOL_PATH environment variable
fInvadeProcess
[in] If this value is TRUE, enumerates the loaded modules for the process and effectively calls the SymLoadModule function for each module.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The SymInitialize function is used to initialize the symbol handler for a process. In the context of the symbol handler, a process is a convenient object to use when collecting symbol information. Usually, symbol handlers are used by debuggers and other tools that need to load symbols for a process being debugged.

The process handle passed to SymInitialize can be any unique value, except in the case when fInvadeProcess is TRUE. The value passed to SymInitialize must be the same value passed to all other symbol handler functions. It is the process handle that the functions use to identify the caller and locate the correct symbol information. You must call the SymCleanup function to deallocate all resources associated with the process for which symbols are loaded.

The search for symbols files is performed recursively for all paths specified in the UserSearchPath parameter. Therefore, if you specify the root directory in a search, the whole drive is searched, which can take significant time. Note that the directory that contains the executable file for the process is not automatically part of the search path. To include this directory in the search path, call the GetModuleFileNameEx function, then add the path returned to UserSearchPath.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, GetModuleFileNameEx, SymLoadModule


SymLoadModule

The SymLoadModule function loads the symbol table.

This function is implemented as a wrapper that calls SymLoadModule64. For more information, see New 64-bit Support.

DWORD SymLoadModule(
  HANDLE hProcess,
  HANDLE hFile,
  PSTR ImageName,
  PSTR ModuleName,
  DWORD BaseOfDll,
  DWORD SizeOfDll
);

For SymLoadModule64, the parameter list is as follows.

DWORD64 SymLoadModule64(
  HANDLE hProcess,
  HANDLE hFile,
  PSTR ImageName,
  PSTR ModuleName,
  DWORD64 BaseOfDll,
  DWORD SizeOfDll
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
hFile
[in] Handle to the file for the executable image. This argument is used mostly by debuggers, where the debugger passes the file handle obtained from a debugging event. A value of NULL indicates that hFile is not used.
ImageName
[in] Pointer to a null-terminated string that specifies the name of the executable image. This name can contain a partial path, a full path, or no path at all. If the file cannot be located by the name provided, the symbol search path is used.
ModuleName
[in] Pointer to a null-terminated string that specifies a shortcut name for the module. If the pointer value is NULL, the library creates a name using the base name of the symbol file.
BaseOfDll
[in] Specifies the load address of the module. If the value is zero, the library obtains the load address from the symbol file. The load address contained in the symbol file is not necessarily the actual load address. Debuggers and other applications having an actual load address should use the real load address when calling this function.
SizeOfDll
[in] Specifies the size of the module. If the value is zero, the library obtains the size from the symbol file. The size contained in the symbol file is not necessarily the actual size. Debuggers and other applications having an actual size should use the real size when calling this function.

Return Values

If the function succeeds, the return value is the base address of the loaded module.

If the function fails, the return value is zero. To retrieve extended error information, call GetLastError.

Remarks

The symbol handler creates an entry for the module and if the deferred symbol loading option is turned off, an attempt is made to load the symbols. If deferred symbol loading is enabled, the module is marked as deferred and the symbols are not loaded until a reference is made to a symbol in the module.

To unload the symbol table, use the SymUnloadModule function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, SymInitialize, SymUnloadModule


SymMatchFileName

The SymMatchFileName function compares a string to a file name and path.

BOOL SymMatchFileName(
  PSTR FileName,
  PSTR Match,
  PSTR *FileNameStop,
  PSTR *MatchStop
);

Parameters

FileName
[in] Pointer to the file name to compare to the Match parameter.
Match
[in] Pointer to the string to compare to the FileName parameter.
FileNameStop
[out] Receives a pointer to the location in FileName where matching stopped. For a complete match, this value can be one character before FileName. This value can also be NULL.
MatchStop
[out] Receives a pointer to the location in Match where matching stopped. For a complete match, this value may be one character before Match. This value may be NULL.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

Because the match string can be a suffix of the complete file name, this function can be used to match a plain file name to a fully qualified file name.

Matching begins from the end of both strings and proceeds backward. Matching is case-insensitive and equates a backslash ('\') with a forward slash ('/').

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions


SymRegisterCallback

The SymRegisterCallback function lets an application register a callback function for use by the symbol handler.

This function is implemented as a wrapper that calls SymRegisterCallback64. For more information, see New 64-bit Support.

BOOL SymRegisterCallback(
  HANDLE hProcess,
  PSYMBOL_REGISTERED_CALLBACK CallbackFunction,
  PVOID UserContext
);

For SymRegisterCallback64, the parameter list is as follows.

BOOL SymRegisterCallback64(
  HANDLE hProcess,
  PSYMBOL_REGISTERED_CALLBACK64 CallbackFunction,
  ULONG64 UserContext
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
CallbackFunction
[in] Pointer to a callback function. For more information, see SymbolRegisteredCallback.
UserContext
[in] A user-defined value or NULL. This value is simply passed to the callback function. Normally, this parameter is used by an application to pass a pointer to a data structure that lets the callback function establish some context.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The SymRegisterCallback function lets an application register a callback function for use by the symbol handler. The symbol handler calls the registered callback function when there is status or progress information for the application.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, SymbolRegisteredCallback, SymInitialize


SymRegisterFunctionEntryCallback

The SymRegisterFunctionEntryCallback function lets an application register a callback function for use by the stack walking procedure on Alpha computers.

This function is implemented as a wrapper that calls SymRegisterFunctionEntryCallback64. For more information, see New 64-bit Support.

BOOL SymRegisterFunctionEntryCallback(
  HANDLE hProcess,
  PSYMBOL_FUNCENTRY_CALLBACK CallbackFunction,
  PVOID UserContext
);

For SymRegisterFunctionEntryCallback64, the parameter list is as follows.

BOOL SymRegisterFunctionEntryCallback64(
  HANDLE hProcess,
  PSYMBOL_FUNCENTRY_CALLBACK64 CallbackFunction,
  ULONG64 UserContext
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the StackWalk function.
CallbackFunction
[in] Pointer to a callback function. For more information, see SymbolRegisteredFunctionEntryCallback.
UserContext
[in] A user-defined value or NULL. This value is simply passed to the callback function. Normally, this parameter is used by an application to pass a pointer to a data structure that lets the callback function establish some context.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The SymRegisterFunctionEntryCallback function lets an application register a callback function for use by the stack walking procedure. The stack walking procedure calls the registered callback function when it is unable to locate a function table entry for an address. In most cases, the stack walking procedure locates the function table entries in the function table of the image containing the address. However, in situations where the function table entries are not in the image, this callback allows the debugger to provide the function table entry from another source. For example, run-time generated code on Alpha computers can define dynamic function tables to support exception handling and stack tracing.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, SymbolRegisteredFunctionEntryCallback, StackWalk


SymSetOptions

The SymSetOptions function sets the options mask.

DWORD SymSetOptions(
  DWORD SymOptions
);

Parameters

SymOptions
[in] Specifies the new options value. Zero is a valid value and indicates that all options are turned off. The options values are masks that are combined using the OR operator to form a valid options value. The following are valid mask values.
Value | Meaning
SYMOPT_CASE_INSENSITIVE | All symbol searches are insensitive to case.
SYMOPT_UNDNAME | All symbols are presented in undecorated form.
SYMOPT_DEFERRED_LOADS | Symbols are not loaded until a reference is made requiring the symbols be loaded. This is the fastest, most efficient way to use the symbol handler.
SYMOPT_NO_CPP | All C++ decorated symbols containing the symbol separator "::" are replaced by "__". This option exists for debuggers that cannot handle parsing real C++ symbol names.
SYMOPT_LOAD_LINES | Loads line number information.

Return Values

The function returns the current options mask.

Remarks

The options value can be changed any number of times while the library is in use by an application. The option change affects all future calls to the symbol handler.

To get the current options mask, call the SymGetOptions function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, SymGetOptions


SymSetSearchPath

The SymSetSearchPath function sets the search path for the specified process.

BOOL SymSetSearchPath(
  HANDLE hProcess,
  PSTR SearchPath
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
SearchPath
[in] Specifies the symbol search path. The string can contain multiple paths separated by semicolons.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The symbol search path can be changed any number of times while the library is in use by an application. The change affects all future calls to the symbol handler.

To get the current search path, call the SymGetSearchPath function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, SymGetSearchPath, SymInitialize


SymTypeNameCallback

The SymTypeNameCallback function is an application-defined callback function used with the SymGetModuleInfoEx function.

The PSYMBOL_TYPE_NAME_CALLBACK type defines a pointer to this callback function. SymTypeNameCallback is a placeholder for the application-defined function name.

BOOL CALLBACK SymTypeNameCallback(
  PSTR MatchedName,
  ULONG typeIndex,
  PVOID CallerData
);

Parameters

MatchedName
[in] The symbol name that was matched to the partial symbol name.
typeIndex
[in] The type index.
CallerData
[in] User-defined data.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Functions, SymGetModuleInfoEx


SymUnDName

The SymUnDName function undecorates a decorated symbol.

This function is implemented as a wrapper that calls SymUnDName64. For more information, see New 64-bit Support.

BOOL SymUnDName(
  PIMAGEHLP_SYMBOL Symbol,
  PSTR UnDecName,
  DWORD UnDecNameLength
);

For SymUnDName64, the parameter list is as follows.

BOOL SymUnDName64(
  PIMAGEHLP_SYMBOL64 Symbol,
  PSTR UnDecName,
  DWORD UnDecNameLength
);

Parameters

Symbol
[in] Specifies the symbol to be undecorated.
UnDecName
[out] Specifies the buffer that receives the undecorated symbol name.
UnDecNameLength
[in] Specifies the length of the UnDecName buffer, in bytes.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The UnDecName buffer contains the undecorated symbol name. However, if the buffer is too small, the name is truncated to UnDecNameLength length.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions


SymUnloadModule

The SymUnloadModule function unloads the symbol table.

This function is implemented as a wrapper that calls SymUnloadModule64. For more information, see New 64-bit Support.

BOOL SymUnloadModule(
  HANDLE hProcess,
  DWORD BaseOfDll
);

For SymUnloadModule64, the parameter list is as follows.

BOOL SymUnloadModule64(
  HANDLE hProcess,
  DWORD64 BaseOfDll
);

Parameters

hProcess
[in] Handle to the process that was originally passed to the SymInitialize function.
BaseOfDll
[in] Specifies the base address of the module that is unloaded.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, SymInitialize


TranslateAddressProc

The TranslateAddressProc function is an application-defined callback function used with the StackWalk function. It provides address translation for 16-bit addresses.

The PTRANSLATE_ADDRESS_ROUTINE type defines a pointer to this callback function. TranslateAddressProc is a placeholder for the application-defined function name.

DWORD CALLBACK TranslateAddressProc(
  HANDLE hProcess,
  HANDLE hThread,
  LPADDRESS lpaddr
);

The PTRANSLATE_ADDRESS_ROUTINE64 type defines a pointer to this callback function. TranslateAddressProc64 is a placeholder for the application-defined function name.

DWORD64 CALLBACK TranslateAddressProc64(
  HANDLE hProcess,
  HANDLE hThread,
  LPADDRESS64 lpaddr
);

Parameters

hProcess
[in] Handle to the process for which the stack trace is generated.
hThread
[in] Handle to the thread for which the stack trace is generated.
lpaddr
[in] Address to be translated.

Return Values

The function returns the translated address.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Functions, StackWalk


UnDecorateSymbolName

The UnDecorateSymbolName function undecorates decorated C++ symbol names.

DWORD UnDecorateSymbolName(
  PCSTR DecoratedName,
  PSTR UnDecoratedName,
  DWORD UndecoratedLength,
  DWORD Flags
);

Parameters

DecoratedName
[in] Pointer to a null-terminated string that specifies a decorated C++ symbol name. This name can be identified by the first character of the name, which is always a question mark (?).
UnDecoratedName
[in] Pointer to a null-terminated string that specifies the buffer that receives the undecorated name.
UndecoratedLength
[in] Specifies the length of the UnDecoratedName buffer, in bytes.
Flags
[in] Specifies how the decorated name is undecorated. This parameter can be zero or any combination of the following values.
Value | Description
UNDNAME_COMPLETE | Enable full undecoration.
UNDNAME_NO_LEADING_UNDERSCORES | Remove leading underscores from Microsoft keywords.
UNDNAME_NO_MS_KEYWORDS | Disable expansion of Microsoft keywords.
UNDNAME_NO_FUNCTION_RETURNS | Disable expansion of return types for primary declarations.
UNDNAME_NO_ALLOCATION_MODEL | Disable expansion of the declaration model.
UNDNAME_NO_ALLOCATION_LANGUAGE | Disable expansion of the declaration language specifier.
UNDNAME_NO_MS_THISTYPE | Disable expansion of Microsoft keywords on the this type for primary declaration.
UNDNAME_NO_CV_THISTYPE | Disable expansion of CodeView modifiers on the this type for primary declaration.
UNDNAME_NO_THISTYPE | Disable all modifiers on the this type.
UNDNAME_NO_ACCESS_SPECIFIERS | Disable expansion of access specifiers for members.
UNDNAME_NO_THROW_SIGNATURES | Disable expansion of throw-signatures for functions and pointers to functions.
UNDNAME_NO_MEMBER_TYPE | Disable expansion of the static or virtual attribute of members.
UNDNAME_NO_RETURN_UDT_MODEL | Disable expansion of Microsoft model for user-defined type returns.
UNDNAME_32_BIT_DECODE | Undecorate 32-bit decorated names.
UNDNAME_NAME_ONLY | Crack only the name for primary declaration. Returns [scope::]name. Does expand template parameters.
UNDNAME_NO_ARGUMENTS | Do not undecorate function arguments.
UNDNAME_NO_SPECIAL_SYMS | Do not undecorate special names, such as vtable, vcall, vector, metatype, and so on.

Return Values

If the function succeeds, the return value is the number of characters in the UnDecoratedName buffer, not including the NULL terminator.

If the function fails, the return value is zero. To retrieve extended error information, call GetLastError.

Remarks

If the function fails and returns zero, the content of the UnDecoratedName buffer is undetermined.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions


UnmapDebugInformation

The UnmapDebugInformation function deallocates the memory and resources allocated by a call to the MapDebugInformation function.

Note This function is provided only for backward compatibility. New applications should use the SymUnloadModule function.

BOOL UnmapDebugInformation(
  PIMAGE_DEBUG_INFORMATION DebugInfo
);

Parameters

DebugInfo
[in] Pointer to an IMAGE_DEBUG_INFORMATION structure that is returned from a call to MapDebugInformation.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The UnmapDebugInformation function is the counterpart to the MapDebugInformation function and must be used to deallocate the memory and resources allocated by a call to the MapDebugInformation function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.
Library: Use Dbghelp.lib.

See Also

Debug Help Library Overview, DbgHelp Functions, IMAGE_DEBUG_INFORMATION, MapDebugInformation


DbgHelp Structures

The following are the DbgHelp structures.

ADDRESS
API_VERSION
IMAGE_DEBUG_INFORMATION
IMAGEHLP_CBA_READ_MEMORY
IMAGEHLP_DEFERRED_SYMBOL_LOAD
IMAGEHLP_DUPLICATE_SYMBOL
IMAGEHLP_LINE
IMAGEHLP_MODULE
IMAGEHLP_SYMBOL
KDHELP
LOADED_IMAGE
MINIDUMP_CALLBACK_INFORMATION
MINIDUMP_CALLBACK_INPUT
MINIDUMP_CALLBACK_OUTPUT
MINIDUMP_DIRECTORY
MINIDUMP_EXCEPTION
MINIDUMP_EXCEPTION_INFORMATION
MINIDUMP_EXCEPTION_STREAM
MINIDUMP_HANDLE_DATA_STREAM
MINIDUMP_HANDLE_DESCRIPTOR
MINIDUMP_HEADER
MINIDUMP_LOCATION_DESCRIPTOR
MINIDUMP_MEMORY_DESCRIPTOR
MINIDUMP_MEMORY_LIST
MINIDUMP_MODULE
MINIDUMP_MODULE_CALLBACK
MINIDUMP_MODULE_LIST
MINIDUMP_STRING
MINIDUMP_SYSTEM_INFO
MINIDUMP_THREAD
MINIDUMP_THREAD_CALLBACK
MINIDUMP_THREAD_EX
MINIDUMP_THREAD_EX_CALLBACK
MINIDUMP_THREAD_EX_LIST
MINIDUMP_THREAD_LIST
MINIDUMP_USER_STREAM
MINIDUMP_USER_STREAM_INFORMATION
MODULE_TYPE_INFO
STACKFRAME
TYPE_ENUM_INFO


ADDRESS

The ADDRESS structure represents an address. It is used in the STACKFRAME structure.

This structure is declared for both 32- and 64-bit Windows. For more information, see New 64-bit Support.

typedef struct _tagADDRESS {
  DWORD        Offset;
  WORD         Segment;
  ADDRESS_MODE Mode;
} ADDRESS, *LPADDRESS;

The ADDRESS64 structure is defined as follows.

typedef struct _tagADDRESS64 {
  DWORD64      Offset;
  WORD         Segment;
  ADDRESS_MODE Mode;
} ADDRESS64, *LPADDRESS64;

Members

Offset
An offset into the segment, or a 32-bit virtual address. The interpretation of this value depends on the value contained in the Mode member.
Segment
Segment number. This value is used only for 16-bit addressing.
Mode
Addressing mode. This member can be one of the following values.
Value | Meaning
AddrMode1616 | 16:16 addressing. To support this addressing mode, you must supply a TranslateAddressProc callback function.
AddrMode1632 | 16:32 addressing. To support this addressing mode, you must supply a TranslateAddressProc callback function.
AddrModeReal | Real-mode addressing. To support this addressing mode, you must supply a TranslateAddressProc callback function.
AddrModeFlat | Flat addressing. This is the only addressing mode supported by the library.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures


API_VERSION

The API_VERSION structure contains the library version.

typedef struct API_VERSION {
  USHORT MajorVersion;
  USHORT MinorVersion;
  USHORT Revision;
  USHORT Reserved;
} API_VERSION, *LPAPI_VERSION;

Members

MajorVersion
Major version number.
MinorVersion
Minor version number.
Revision
Revision number.
Reserved
Reserved for use by the operating system.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, ImagehlpApiVersion, ImagehlpApiVersionEx


IMAGE_DEBUG_INFORMATION

The IMAGE_DEBUG_INFORMATION structure contains debugging information.

Note This structure is used by the MapDebugInformation and UnmapDebugInformation functions, which are provided only for backward compatibility.

typedef struct _IMAGE_DEBUG_INFORMATION {
  LIST_ENTRY List;
  DWORD Size;
  PVOID MappedBase;
  USHORT Machine;
  USHORT Characteristics;
  DWORD CheckSum;
  DWORD ImageBase;
  DWORD SizeOfImage;
  DWORD NumberOfSections;
  PIMAGE_SECTION_HEADER Sections;
  DWORD ExportedNamesSize;
  PSTR ExportedNames;
  DWORD NumberOfFunctionTableEntries;
  PIMAGE_FUNCTION_ENTRY FunctionTableEntries;
  DWORD LowestFunctionStartingAddress;
  DWORD HighestFunctionEndingAddress;
  DWORD NumberOfFpoTableEntries;
  PFPO_DATA FpoTableEntries;
  DWORD SizeOfCoffSymbols;
  PIMAGE_COFF_SYMBOLS_HEADER CoffSymbols;
  DWORD SizeOfCodeViewSymbols;
  PVOID CodeViewSymbols;
  PSTR ImageFilePath;
  PSTR ImageFileName;
  PSTR ReservedDebugFilePath;
  DWORD ReservedTimeDateStamp;
  BOOL ReservedRomImage;
  PIMAGE_DEBUG_DIRECTORY ReservedDebugDirectory;
  DWORD ReservedNumberOfDebugDirectories;
  DWORD ReservedOriginalFunctionTableBaseAddress;
  DWORD Reserved[2];
} IMAGE_DEBUG_INFORMATION, *PIMAGE_DEBUG_INFORMATION;

Members

List
Linked list pointers.
Size
Size of the memory allocated for the IMAGE_DEBUG_INFORMATION structure and all debugging information, in bytes.
MappedBase
Base address of the image.
Machine
Computer type. This member can be one of the following values.
Value | Meaning
IMAGE_FILE_MACHINE_I386 | Intel (32-bit)
IMAGE_FILE_MACHINE_IA64 | Intel (64-bit)
IMAGE_FILE_MACHINE_ALPHA | DEC Alpha
IMAGE_FILE_MACHINE_POWERPC | Power PC

Characteristics
Characteristics of the image. This member can be one of the following values.
Value | Meaning
IMAGE_FILE_RELOCS_STRIPPED | Relocation information is stripped from the file.
IMAGE_FILE_EXECUTABLE_IMAGE | The file is executable (there are no unresolved external references).
IMAGE_FILE_LINE_NUMS_STRIPPED | Line numbers are stripped from the file.
IMAGE_FILE_LOCAL_SYMS_STRIPPED | Local symbols are stripped from file.
IMAGE_FILE_AGGRESIVE_WS_TRIM | Aggressively trim the working set.
IMAGE_FILE_LARGE_ADDRESS_AWARE | The application can handle addresses larger than 2 GB.
IMAGE_FILE_BYTES_REVERSED_LO | Bytes of the word are reversed.
IMAGE_FILE_32BIT_MACHINE | Computer supports 32-bit words.
IMAGE_FILE_DEBUG_STRIPPED | Debugging information is stored separately in a .dbg file.
IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP | If the image is on removable media, copy and run from the swap file.
IMAGE_FILE_NET_RUN_FROM_SWAP | If the image is on the network, copy and run from the swap file.
IMAGE_FILE_SYSTEM | System file.
IMAGE_FILE_DLL | DLL file.
IMAGE_FILE_UP_SYSTEM_ONLY | File should be run only on a uniprocessor computer.
IMAGE_FILE_BYTES_REVERSED_HI | Bytes of the word are reversed.

CheckSum
Checksum of the image.
ImageBase
Requested base address of the image.
SizeOfImage
Size of the image, in bytes.
NumberOfSections
Number of COFF section headers.
Sections
Pointer to the first COFF section header. For more information, see IMAGE_SECTION_HEADER.
ExportedNamesSize
Size of the ExportedNames member, in bytes.
ExportedNames
Pointer to a series of null-terminated strings that name all the functions exported from the image.
NumberOfFunctionTableEntries
Number of entries contained in the FunctionTableEntries member.
FunctionTableEntries
Pointer to the first function table entry. For more information, see IMAGE_FUNCTION_ENTRY.
LowestFunctionStartingAddress
Lowest function table starting address.
HighestFunctionEndingAddress
Highest function table ending address.
NumberOfFpoTableEntries
Number of entries contained in the FpoTableEntries member.
FpoTableEntries
Pointer to the first FPO entry. For more information, see FPO_DATA.
SizeOfCoffSymbols
Size of the COFF symbol table, in bytes.
CoffSymbols
Pointer to the COFF symbol table.
SizeOfCodeViewSymbols
Size of the CodeView symbol table, in bytes.
CodeViewSymbols
Pointer to the beginning of the CodeView symbol table.
ImageFilePath
Relative path to the image file name.
ImageFileName
Image file name.
ReservedDebugFilePath
Full path to the symbol file.
ReservedTimeDateStamp
Timestamp of the image. This represents the date and time the image was created by the linker.
ReservedRomImage
This value is TRUE if the image is a ROM image.
ReservedDebugDirectory
Pointer to the first debug directory. For more information, see IMAGE_DEBUG_DIRECTORY.
ReservedNumberOfDebugDirectories
Number of entries contained in the DebugDirectory member.
ReservedOriginalFunctionTableBaseAddress
Original function table base address.
Reserved
Reserved for use by the operating system.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, FPO_DATA, IMAGE_COFF_SYMBOLS_HEADER, IMAGE_DEBUG_DIRECTORY, IMAGE_FUNCTION_ENTRY, IMAGE_SECTION_HEADER, MapDebugInformation, UnmapDebugInformation


IMAGEHLP_CBA_READ_MEMORY

The IMAGEHLP_CBA_READ_MEMORY structure contains information about a memory read operation.

typedef struct _IMAGEHLP_CBA_READ_MEMORY {
  DWORD64   addr;
  PVOID     buf;
  DWORD     bytes;
  DWORD    *bytesread;
} IMAGEHLP_CBA_READ_MEMORY, *PIMAGEHLP_CBA_READ_MEMORY;

Members

addr
Address to be read.
buf
Pointer to a buffer that receives the memory read.
bytes
Number of bytes to read.
bytesread
Pointer to a variable that receives the number of bytes read.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, SymbolRegisteredCallback


IMAGEHLP_DEFERRED_SYMBOL_LOAD

The IMAGEHLP_DEFERRED_SYMBOL_LOAD structure contains information about a deferred symbol load.

This structure is declared for both 32- and 64-bit Windows. For more information, see New 64-bit Support.

typedef struct _IMAGEHLP_DEFERRED_SYMBOL_LOAD {
  DWORD   SizeOfStruct;
  DWORD   BaseOfImage;
  DWORD   CheckSum;
  DWORD   TimeDateStamp;
  CHAR    FileName[MAX_PATH];
  BOOLEAN Reparse;
} IMAGEHLP_DEFERRED_SYMBOL_LOAD, *PIMAGEHLP_DEFERRED_SYMBOL_LOAD;

The IMAGEHLP_DUPLICATE_SYMBOL64 structure is defined as follows.

typedef struct _IMAGEHLP_DEFERRED_SYMBOL_LOAD64 {
  DWORD   SizeOfStruct;
  DWORD64 BaseOfImage;
  DWORD   CheckSum;
  DWORD   TimeDateStamp;
  CHAR    FileName[MAX_PATH];
  BOOLEAN Reparse;
} IMAGEHLP_DEFERRED_SYMBOL_LOAD64, *PIMAGEHLP_DEFERRED_SYMBOL_LOAD64;

Members

SizeOfStruct
Size of the structure, in bytes. The caller must set this member to sizeof(IMAGEHLP_DEFERRED_SYMBOL_LOAD).
BaseOfImage
Base virtual address where the image is loaded.
CheckSum
Computed checksum of the image. This value can be zero.
TimeDateStamp
Date and timestamp value. The value is represented in the number of seconds elapsed since midnight (00:00:00), January 1, 1970, Universal Coordinated Time, according to the system clock. The timestamp can be printed using the C run-time (CRT) function ctime.
FileName
Image name. The name may or may not contain a full path.
Reparse
Windows 2000 or later: Specifies whether the operation should be performed again.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, SymbolRegisteredCallback


IMAGEHLP_DUPLICATE_SYMBOL

The IMAGEHLP_DUPLICATE_SYMBOL structure contains duplicate symbol information.

This structure is declared for both 32- and 64-bit Windows. For more information, see New 64-bit Support.

typedef struct _IMAGEHLP_DUPLICATE_SYMBOL {
  DWORD            SizeOfStruct;
  DWORD            NumberOfDups;
  PIMAGEHLP_SYMBOL Symbol;
  DWORD            SelectedSymbol;
} IMAGEHLP_DUPLICATE_SYMBOL, *PIMAGEHLP_DUPLICATE_SYMBOL;

The IMAGEHLP_DUPLICATE_SYMBOL64 structure is defined as follows.

typedef struct _IMAGEHLP_DUPLICATE_SYMBOL64 {
  DWORD              SizeOfStruct;
  DWORD              NumberOfDups;
  PIMAGEHLP_SYMBOL64 Symbol;
  DWORD              SelectedSymbol;
} IMAGEHLP_DUPLICATE_SYMBOL64, *PIMAGEHLP_DUPLICATE_SYMBOL64;

Members

SizeOfStruct
Size of the structure, in bytes. The caller must set this member to sizeof(IMAGEHLP_DUPLICATE_SYMBOL).
NumberOfDups
Number of duplicate symbols.
Symbol
Pointer to an array of symbols (IMAGEHLP_SYMBOL structures). The number of entries in the array is specified by the NumberOfDups member.
SelectedSymbol
Index into the symbol array for the selected symbol.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, IMAGEHLP_SYMBOL, SymbolRegisteredCallback


IMAGEHLP_LINE

The IMAGEHLP_LINE structure represents a source file line.

This structure is declared for both 32- and 64-bit Windows. For more information, see New 64-bit Support.

typedef struct _IMAGEHLP_LINE {
  DWORD SizeOfStruct;
  PVOID Key;
  DWORD LineNumber;
  PCHAR FileName;
  DWORD Address;
} IMAGEHLP_LINE, *PIMAGEHLP_LINE;

The IMAGEHLP_MODULE64 structure is defined as follows.

typedef struct _IMAGEHLP_LINE64 {
  DWORD   SizeOfStruct;
  PVOID   Key;
  DWORD   LineNumber;
  PCHAR   FileName;
  DWORD64 Address;
} IMAGEHLP_LINE64, *PIMAGEHLP_LINE64;

Members

SizeOfStruct
Sze of the structure, in bytes. The caller must set this member to sizeof(IMAGEHLP_LINE).
Key
Reserved for use by the operating system.
LineNumber
Line number in the file.
FileName
Name of the file. The name contains the full path.
Address
Address of the first instruction in the line.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, SymGetLineFromAddr, SymGetLineFromName, SymGetLineNext, SymGetLinePrev


IMAGEHLP_MODULE

The IMAGEHLP_MODULE structure contains module information.

This structure is declared for both 32- and 64-bit Windows. For more information, see New 64-bit Support.

typedef struct _IMAGEHLP_MODULE {
  DWORD    SizeOfStruct;
  DWORD    BaseOfImage;
  DWORD    ImageSize;
  DWORD    TimeDateStamp;
  DWORD    CheckSum;
  DWORD    NumSyms;
  SYM_TYPE SymType;
  TCHAR    ModuleName[32];
  TCHAR    ImageName[256];
  TCHAR    LoadedImageName[256];
} IMAGEHLP_MODULE, *PIMAGEHLP_MODULE;

The IMAGEHLP_MODULE64 structure is defined as follows.

typedef struct _IMAGEHLP_MODULE64 {
  DWORD    SizeOfStruct;
  DWORD64  BaseOfImage;
  DWORD    ImageSize;
  DWORD    TimeDateStamp;
  DWORD    CheckSum;
  DWORD    NumSyms;
  SYM_TYPE SymType;
  TCHAR    ModuleName[32];
  TCHAR    ImageName[256];
  TCHAR    LoadedImageName[256];
} IMAGEHLP_MODULE64, *PIMAGEHLP_MODULE64;

Members

SizeOfStruct
Size of the structure, in bytes. The caller must set this member to sizeof(IMAGEHLP_MODULE).
BaseOfImage
Base virtual address where the image is loaded.
ImageSize
Size of the image, in bytes.
TimeDateStamp
Date and timestamp value. The value is represented in the number of seconds elapsed since midnight (00:00:00), January 1, 1970, Universal Coordinated Time, according to the system clock. The timestamp can be printed using the C run-time (CRT) function ctime.
CheckSum
Checksum of the image. This value can be zero.
NumSyms
Number of symbols in the symbol table.
SymType
Type of symbols that are loaded. This member can be one of the following values.
Value | Meaning
SymNone | No symbols are loaded.
SymCoff | COFF symbols.
SymCv | CodeView symbols.
SymPdb | .pdb file
SymExport | Symbols generated from a DLL's export table.
SymDeferred | The library has not yet attempted to load symbols.
SymSym | .SYM file

ModuleName
Module name.
ImageName
Image name. The name may or may not contain a full path.
LoadedImageName
Full path and file name from which symbols were loaded.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, SymGetModuleInfo


IMAGEHLP_SYMBOL

The IMAGEHLP_SYMBOL structure contains symbol information.

This structure is declared for both 32- and 64-bit Windows. For more information, see New 64-bit Support.

typedef struct _IMAGEHLP_SYMBOL {
  DWORD SizeOfStruct;
  DWORD Address;
  DWORD Size;
  DWORD Flags;
  DWORD MaxNameLength;
  CHAR  Name[1];
} IMAGEHLP_SYMBOL, *PIMAGEHLP_SYMBOL;

The IMAGEHLP_SYMBOL64 structure is defined as follows.

typedef struct _IMAGEHLP_SYMBOL64 {
  DWORD   SizeOfStruct;
  DWORD64 Address;
  DWORD   Size;
  DWORD   Flags;
  DWORD   MaxNameLength;
  CHAR    Name[1];
} IMAGEHLP_SYMBOL64, *PIMAGEHLP_SYMBOL64;

Members

SizeOfStruct
Size of the structure, in bytes. The caller must set this member to sizeof(IMAGEHLP_SYMBOL).
Address
Virtual address for the symbol.
Size
Size of the symbol, in bytes. This value is a best guess and can be zero.
Flags
Reserved for use by the operating system.
MaxNameLength
The caller must set this value to the maximum length of the string that the Name member can contain. Because symbol names can vary in length, this data structure is allocated by the caller. This member is used so the library knows how much memory is available for use by the symbol name.
Name
Null-terminated string specifying either the decorated or undecorated symbol name. If the buffer is not large enough for the complete name, it is truncated to MaxNameLength characters.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, SymGetSymFromAddr, SymGetSymFromName


KDHELP

The KDHELP structure is included in the STACKFRAME structure, and is used to trace through user-mode callbacks in a thread's kernel stack. This structure is used by kernel debuggers.

This structure is declared for both 32- and 64-bit Windows. For more information, see New 64-bit Support.

typedef struct _KDHELP {
  DWORD Thread;
  DWORD ThCallbackStack;
  DWORD NextCallback;
  DWORD FramePointer;
  DWORD KiCallUserMode;
  DWORD KeUserCallbackDispatcher;
  DWORD SystemRangeStart;
  DWORD ThCallbackBStore;
  DWORD Reserved[8];
} KDHELP, *PKDHELP;

The KDHELP64 structure is defined as follows.

typedef struct _KDHELP64 {
  DWORD64 Thread;
  DWORD   ThCallbackStack;
  DWORD   ThCallbackBStore;
  DWORD   NextCallback;
  DWORD   FramePointer;
  DWORD64 KiCallUserMode;
  DWORD64 KeUserCallbackDispatcher;
  DWORD64 SystemRangeStart;
  DWORD64 Reserved[8];
} KDHELP64, *PKDHELP64;

Members

Thread
Address of the kernel thread object, as provided in the WAIT_STATE_CHANGE packet.
ThCallbackStack
Offset in the thread object to the pointer to the current callback frame in the kernel stack.
NextCallback
Address of the next callback frame.
FramePointer
Address of the saved frame pointer, if applicable.
KiCallUserMode
Address of the kernel function that calls out to user mode.
KeUserCallbackDispatcher
Address of the user-mode dispatcher function.
SystemRangeStart
Lowest kernel-mode address.
ThCallbackBStore
Offset in the thread object to a pointer to the current callback backing store frame in the kernel stack.
Reserved
Reserved for use by the operating system.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures


LOADED_IMAGE

The LOADED_IMAGE structure contains information about the loaded image.

typedef struct _LOADED_IMAGE {
  PSTR ModuleName;
  HANDLE hFile;
  PUCHAR MappedAddress;
#ifdef _IMAGEHLP64
  PIMAGE_NT_HEADERS64 FileHeader;
#else
  PIMAGE_NT_HEADERS32 FileHeader;
#endif
  PIMAGE_SECTION_HEADER LastRvaSection;
  ULONG NumberOfSections;
  PIMAGE_SECTION_HEADER Sections;
  ULONG Characteristics;
  BOOLEAN fSystemImage;
  BOOLEAN fDOSImage;
  LIST_ENTRY Links;
  ULONG SizeOfImage;
} LOADED_IMAGE, *PLOADED_IMAGE;

Members

ModuleName
Null-terminated string that specifies the file name of the mapped file.
hFile
Handle to the mapped file.
MappedAddress
Base address of the mapped file.
FileHeader
Pointer to an IMAGE_NT_HEADERS structure.
LastRvaSection
Pointer to an IMAGE_SECTION_HEADER structure.
NumberOfSections
Number of COFF section headers.
Sections
Pointer to an IMAGE_SECTION_HEADER structure.
Characteristics
Image characteristics value. This member can be one of the following values.
Value | Meaning
IMAGE_FILE_RELOCS_STRIPPED | Relocation information is stripped from the file.
IMAGE_FILE_EXECUTABLE_IMAGE | The file is executable (there are no unresolved external references).
IMAGE_FILE_LINE_NUMS_STRIPPED | Line numbers are stripped from the file.
IMAGE_FILE_LOCAL_SYMS_STRIPPED | Local symbols are stripped from file.
IMAGE_FILE_AGGRESIVE_WS_TRIM | Aggressively trim the working set.
IMAGE_FILE_LARGE_ADDRESS_AWARE | The application can handle addresses larger than 2 GB.
IMAGE_FILE_BYTES_REVERSED_LO | Bytes of word are reversed.
IMAGE_FILE_32BIT_MACHINE | Computer supports 32-bit words.
IMAGE_FILE_DEBUG_STRIPPED | Debugging information is stored separately in a .dbg file.
IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP | If the image is on removable media, copy and run from the swap file.
IMAGE_FILE_NET_RUN_FROM_SWAP | If the image is on the network, copy and run from the swap file.
IMAGE_FILE_SYSTEM | System file.
IMAGE_FILE_DLL | DLL file.
IMAGE_FILE_UP_SYSTEM_ONLY | File should be run only on a uniprocessor computer.
IMAGE_FILE_BYTES_REVERSED_HI | Bytes of the word are reversed.

fSystemImage
This value is TRUE if the image is a kernel mode executable image.
fDOSImage
This value is TRUE if the image is a 16-bit executable image.
Links
List of loaded images.
SizeOfImage
Size of the image, in bytes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, IMAGE_NT_HEADERS, IMAGE_SECTION_HEADER, ImageLoad, MapAndLoad


MINIDUMP_CALLBACK_INFORMATION

[This is preliminary documentation and subject to change.]

The MINIDUMP_CALLBACK_INFORMATION structure contains a pointer to an optional callback function that can be used by the MiniDumpWriteDump function.

typedef struct _MINIDUMP_CALLBACK_INFORMATION {
  MINIDUMP_CALLBACK_ROUTINE CallbackRoutine;
  PVOID CallbackParam;
} MINIDUMP_CALLBACK_INFORMATION, *PMINIDUMP_CALLBACK_INFORMATION;

Members

CallbackRoutine
Pointer to the MiniDumpCallback callback function.
CallbackParam
Application-defined data for CallbackRoutine.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MiniDumpCallback, MiniDumpWriteDump


MINIDUMP_CALLBACK_INPUT

[This is preliminary documentation and subject to change.]

The MINIDUMP_CALLBACK_INPUT structure contains information used by the MiniDumpCallback function.

typedef struct _MINIDUMP_CALLBACK_INPUT {
  ULONG ProcessId;
  HANDLE ProcessHandle;
  ULONG CallbackType;
  union {
     MINIDUMP_THREAD_CALLBACK Thread;
     MINIDUMP_THREAD_EX_CALLBACK ThreadEx;
     MINIDUMP_MODULE_CALLBACK Module;
  };
} MINIDUMP_CALLBACK_INPUT, *PMINIDUMP_CALLBACK_INPUT;

Members

ProcessId
Identifier of the process that contains callback function.
ProcessHandle
Handle to the process that contains the callback function.
CallbackType
Type of callback function. This member can be one of the values in the MINIDUMP_CALLBACK_TYPE enumeration.
Thread
If CallbackType is ThreadCallback, the union is a MINIDUMP_THREAD_CALLBACK structure.
ThreadEx
If CallbackType is ThreadExCallback, the union is a MINIDUMP_THREAD_EX_CALLBACK structure.
Module
If CallbackType is ModuleCallback, the union is a MINIDUMP_MODULE_CALLBACK structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_CALLBACK_TYPE, MINIDUMP_MODULE_CALLBACK, MINIDUMP_THREAD_CALLBACK, MINIDUMP_THREAD_EX_CALLBACK, MiniDumpCallback


MINIDUMP_CALLBACK_OUTPUT

[This is preliminary documentation and subject to change.]

The MINIDUMP_CALLBACK_OUTPUT structure contains information returned from the MiniDumpCallback function.

typedef struct _MINIDUMP_CALLBACK_OUTPUT {
  union {
    ULONG ModuleWriteFlags;
    ULONG ThreadWriteFlags;
  };
} MINIDUMP_CALLBACK_OUTPUT, *PMINIDUMP_CALLBACK_OUTPUT;

Members

ModuleWriteFlags
Module write operation flags. This member can be one or more of the values in the MODULE_WRITE_FLAGS enumeration.
ThreadWriteFlags
Thread write operation flags. This member can be one or more of the values in the THREAD_WRITE_FLAGS enumeration.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MiniDumpCallback, MODULE_WRITE_FLAGS, THREAD_WRITE_FLAGS


MINIDUMP_DIRECTORY

[This is preliminary documentation and subject to change.]

The MINIDUMP_DIRECTORY structure contains information needed to access a specific data stream in a minidump file.

typedef struct _MINIDUMP_DIRECTORY {
  ULONG32 StreamType;
  MINIDUMP_LOCATION_DESCRIPTOR Location;
} MINIDUMP_DIRECTORY, *PMINIDUMP_DIRECTORY;

Members

StreamType
Type of data stream. This member can be one of the values in the MINIDUMP_STREAM_TYPE enumeration.
Location
A MINIDUMP_LOCATION_DESCRIPTOR structure that specifies the location of the data stream.

Remarks

In this context, a data stream is a block of data within a minidump file.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MiniDumpReadDumpStream, MINIDUMP_LOCATION_DESCRIPTOR, MINIDUMP_STREAM_TYPE


MINIDUMP_EXCEPTION

[This is preliminary documentation and subject to change.]

The MINIDUMP_EXCEPTION structure describes an exception.

typedef struct _MINIDUMP_EXCEPTION  {
    ULONG32 ExceptionCode;
    ULONG32 ExceptionFlags;
    ULONG64 ExceptionRecord;
    ULONG64 ExceptionAddress;
    ULONG32 NumberParameters;
    ULONG32 __unusedAlignment;
    ULONG64 ExceptionInformation [EXCEPTION_MAXIMUM_PARAMETERS];
} MINIDUMP_EXCEPTION, *PMINIDUMP_EXCEPTION;

Members

ExceptionCode
Reason the exception occurred. This is the code generated by a hardware exception, or the code specified in the RaiseException function for a software-generated exception. Following are the exception codes likely to occur due to common programming errors.
Value | Meaning
EXCEPTION_ACCESS_VIOLATION | The thread tried to read from or write to a virtual address for which it does not have the appropriate access.
EXCEPTION_ARRAY_BOUNDS_EXCEEDED | The thread tried to access an array element that is out of bounds and the underlying hardware supports bounds checking.
EXCEPTION_BREAKPOINT | A breakpoint was encountered.
EXCEPTION_DATATYPE_MISALIGNMENT | The thread tried to read or write data that is misaligned on hardware that does not provide alignment. For example, 16-bit values must be aligned on 2-byte boundaries; 32-bit values on 4-byte boundaries, and so on.
EXCEPTION_FLT_DENORMAL_OPERAND | One of the operands in a floating-point operation is denormal. A denormal value is one that is too small to represent as a standard floating-point value.
EXCEPTION_FLT_DIVIDE_BY_ZERO | The thread tried to divide a floating-point value by a floating-point divisor of zero.
EXCEPTION_FLT_INEXACT_RESULT | The result of a floating-point operation cannot be represented exactly as a decimal fraction.
EXCEPTION_FLT_INVALID_OPERATION | This exception represents any floating-point exception not included in this list.
EXCEPTION_FLT_OVERFLOW | The exponent of a floating-point operation is greater than the magnitude allowed by the corresponding type.
EXCEPTION_FLT_STACK_CHECK | The stack overflowed or underflowed as the result of a floating-point operation.
EXCEPTION_FLT_UNDERFLOW | The exponent of a floating-point operation is less than the magnitude allowed by the corresponding type.
EXCEPTION_ILLEGAL_INSTRUCTION | The thread tried to execute an invalid instruction.
EXCEPTION_IN_PAGE_ERROR | The thread tried to access a page that was not present, and the system was unable to load the page. For example, this exception might occur if a network connection is lost while running a program over the network.
EXCEPTION_INT_DIVIDE_BY_ZERO | The thread tried to divide an integer value by an integer divisor of zero.
EXCEPTION_INT_OVERFLOW | The result of an integer operation caused a carry out of the most significant bit of the result.
EXCEPTION_INVALID_DISPOSITION | An exception handler returned an invalid disposition to the exception dispatcher. Programmers using a high-level language such as C should never encounter this exception.
EXCEPTION_NONCONTINUABLE_EXCEPTION | The thread tried to continue execution after a noncontinuable exception occurred.
EXCEPTION_PRIV_INSTRUCTION | The thread tried to execute an instruction whose operation is not allowed in the current machine mode.
EXCEPTION_SINGLE_STEP | A trace trap or other single-instruction mechanism signaled that one instruction has been executed.
EXCEPTION_STACK_OVERFLOW | The thread used up its stack.

Another exception code is likely to occur when debugging console processes. It does not arise because of a programming error. The DBG_CONTROL_C exception code occurs when CTRL+C is input to a console process that handles CTRL+C signals and is being debugged. This exception code is not meant to be handled by applications. It is raised only for the benefit of the debugger, and is raised only when a debugger is attached to the console process.

ExceptionFlags
This member can be either zero, indicating a continuable exception, or EXCEPTION_NONCONTINUABLE, indicating a noncontinuable exception. Any attempt to continue execution after a noncontinuable exception causes the EXCEPTION_NONCONTINUABLE_EXCEPTION exception.
ExceptionRecord
Pointer to an associated MINIDUMP_EXCEPTION structure. Exception records can be chained together to provide additional information when nested exceptions occur.
ExceptionAddress
Address where the exception occurred.
NumberParameters
Number of parameters associated with the exception. This is the number of defined elements in the ExceptionInformation array.
ExceptionInformation
An array of additional 32-bit arguments that describe the exception. The RaiseException function can specify this array of arguments. For most exception codes, the array elements are undefined. For the following exception code, the array elements are defined as follows.
Exception code Array contents
EXCEPTION_ACCESS_VIOLATION The first element of the array contains a read/write flag that indicates the type of operation that caused the access violation. If this value is zero, the thread attempted to read the inaccessible data. If this value is 1, the thread attempted to write to an inaccessible address.

The second array element specifies the virtual address of the inaccessible data.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_EXCEPTION_STREAM, RaiseException


MINIDUMP_EXCEPTION_INFORMATION

[This is preliminary documentation and subject to change.]

The MINIDUMP_EXCEPTION_INFORMATION structure contains exception information written to the minidump file by the MiniDumpWriteDump function.

typedef struct _MINIDUMP_EXCEPTION_INFORMATION {
  DWORD ThreadId;
  PEXCEPTION_POINTERS ExceptionPointers;
  BOOL ClientPointers;
} MINIDUMP_EXCEPTION_INFORMATION, *PMINIDUMP_EXCEPTION_INFORMATION;

Members

ThreadId
Identifier of the thread throwing the exception.
ExceptionPointers
Pointer to an EXCEPTION_POINTERS structure specifying a computer-independent description of the exception and the processor context at the time of the exception.
ClientPointers
Memory location to which the value of ExceptionPointers refers. If this member is TRUE, the exception pointer is located in the address space of the client, or the process that crashed. If this member is FALSE, the exception pointer is located in the address space of the calling program.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, EXCEPTION_POINTERS, MiniDumpWriteDump


MINIDUMP_EXCEPTION_STREAM

[This is preliminary documentation and subject to change.]

The MINIDUMP_EXCEPTION_STREAM structure describes an exception information stream.

typedef struct MINIDUMP_EXCEPTION_STREAM {
    ULONG32 ThreadId;
    ULONG32  __alignment;
    MINIDUMP_EXCEPTION ExceptionRecord;
    MINIDUMP_LOCATION_DESCRIPTOR ThreadContext;
} MINIDUMP_EXCEPTION_STREAM, *PMINIDUMP_EXCEPTION_STREAM;

Members

ThreadId
Identifier of the thread that caused the exception.
ExceptionRecord
A MINIDUMP_EXCEPTION structure.
ThreadContext
A MINIDUMP_LOCATION_DESCRIPTOR structure.

Remarks

In this context, a data stream is a set of data in a minidump file.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_EXCEPTION, MINIDUMP_LOCATION_DESCRIPTOR


MINIDUMP_HANDLE_DATA_STREAM

[This is preliminary documentation and subject to change.]

The MINIDUMP_HANDLE_DATA_STREAM structure is the header for a handle data stream.

typedef struct _MINIDUMP_HANDLE_DATA_STREAM {
    ULONG SizeOfHeader;
    ULONG SizeOfDescriptor;
    ULONG NumberOfDescriptors;
    ULONG Reserved;
} MINIDUMP_HANDLE_DATA_STREAM, *PMINIDUMP_HANDLE_DATA_STREAM;

Members

SizeOfHeader
Size of the header information for the stream, in bytes. This value is sizeof(MINIDUMP_HANDLE_DATA_STREAM).
SizeOfDescriptor
Size of a descriptor in the stream, in bytes. This value is sizeof(MINIDUMP_HANDLE_DESCRIPTOR).
NumberOfDescriptors
Number of descriptors in the stream.
Reserved
Reserved for future use; must be zero.

Remarks

In this context, a data stream is a set of data in a minidump file.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_HANDLE_DESCRIPTOR


MINIDUMP_HANDLE_DESCRIPTOR

[This is preliminary documentation and subject to change.]

The MINIDUMP_HANDLE_DESCRIPTOR structure describes the state of an individual system handle at the time the minidump was written.

typedef struct _MINIDUMP_HANDLE_DESCRIPTOR {
    ULONG64 Handle;
    RVA TypeNameRva;
    RVA ObjectNameRva;
    ULONG Attributes;
    ULONG GrantedAccess;
    ULONG HandleCount;
    ULONG PointerCount;
} MINIDUMP_HANDLE_DESCRIPTOR, *PMINIDUMP_HANDLE_DESCRIPTOR;

Members

Handle
Operating system handle value.
TypeNameRva
An RVA to a MINIDUMP_STRING structure that specifies the object type of the handle. This member can be zero.
ObjectNameRva
An RVA to a MINIDUMP_STRING structure that specifies the object name of the handle. This member can be zero.
Attributes
The meaning of this member depends on the handle type and the operating system.
GrantedAccess
The meaning of this member depends on the handle type and the operating system.
HandleCount
The meaning of this member depends on the handle type and the operating system.
PointerCount
The meaning of this member depends on the handle type and the operating system.

Remarks

The first descriptor in the handle data stream appears after the header, MINIDUMP_HANDLE_DATA_STREAM.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_HANDLE_DATA_STREAM, MINIDUMP_STRING


MINIDUMP_HEADER

[This is preliminary documentation and subject to change.]

The MINIDUMP_HEADER structure contains header information for the minidump file.

typedef struct _MINIDUMP_HEADER {
    ULONG32 Signature;
    ULONG32 Version;
    ULONG32 NumberOfStreams;
    RVA StreamDirectoryRva;
    ULONG32 CheckSum;
    union {
        ULONG32 Reserved;
        ULONG32 TimeDateStamp;
    };
    ULONG64 Flags;
} MINIDUMP_HEADER, *PMINIDUMP_HEADER;

Members

Signature
Set to MINIDUMP_SIGNATURE.
Version
Version of the minidump format. The low-order word is MINIDUMP_VERSION. The high-order word is an internal value that is implementation specific.
NumberOfStreams
Number of streams in the minidump directory.
StreamDirectoryRva
Base RVA of the minidump directory. This is an array of MINIDUMP_DIRECTORY structures.
CheckSum
Checksum for the minidump file. This member can be zero.
TimeDateStamp
Time and date, in time_t format.
Flags
Which MINIDUMP_TYPE values were used.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_DIRECTORY, MINIDUMP_TYPE


MINIDUMP_LOCATION_DESCRIPTOR

[This is preliminary documentation and subject to change.]

The MINIDUMP_LOCATION_DESCRIPTOR structure contains information describing the location of a data stream within a minidump file.

This structure is uses 32-bit locations for RVAs in the first 4GB and 64-bit locations are used for larger RVAs.

typedef struct _MINIDUMP_LOCATION_DESCRIPTOR {
  ULONG32 DataSize;
  RVA Rva;
} MINIDUMP_LOCATION_DESCRIPTOR;

The MINIDUMP_LOCATION_DESCRIPTOR64 structure is defined as follows.

typedef struct _MINIDUMP_LOCATION_DESCRIPTOR64 {
  ULONG64 DataSize;
  RVA64 Rva;
} MINIDUMP_LOCATION_DESCRIPTOR64;

Members

DataSize
Size of the data stream, in bytes.
Rva
Relative virtual address (RVA) of the data. This is the byte offset of the data stream from the beginning of the minidump file.

Remarks

In this context, a data stream refers to a block of data within a minidump file.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_DIRECTORY, MINIDUMP_EXCEPTION_STREAM, MINIDUMP_MEMORY_DESCRIPTOR, MINIDUMP_MODULE


MINIDUMP_MEMORY_DESCRIPTOR

[This is preliminary documentation and subject to change.]

The MINIDUMP_MEMORY_DESCRIPTOR structure describes a range of memory.

typedef struct _MINIDUMP_MEMORY_DESCRIPTOR {
    ULONG64 StartOfMemoryRange;
    MINIDUMP_LOCATION_DESCRIPTOR Memory;
} MINIDUMP_MEMORY_DESCRIPTOR, *PMINIDUMP_MEMORY_DESCRIPTOR;

The MINIDUMP_MEMORY_DESCRIPTOR64 structure is defined as follows. It is used for full-memory minidumps.

typedef struct _MINIDUMP_MEMORY_DESCRIPTOR64 {
    ULONG64 StartOfMemoryRange;
    ULONG64 DataSize;
} MINIDUMP_MEMORY_DESCRIPTOR64, *PMINIDUMP_MEMORY_DESCRIPTOR64;

Members

StartOfMemoryRange
Start of the memory range.
Memory
A MINIDUMP_LOCATION_DESCRIPTOR structure.
DataSize
Size of the data block, in bytes.

Remarks

MINIDUMP_MEMORY_DESCRIPTOR64 is used for full-memory minidumps where all of the raw memory is laid out sequentially at the end of the dump. There is no need for individual relative virtual addresses (RVAs), because the RVA is the base RVA plus the sum of the preceding data blocks.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_LOCATION_DESCRIPTOR


MINIDUMP_MEMORY_LIST

[This is preliminary documentation and subject to change.]

The MINIDUMP_MEMORY_LIST structure contains a list of memory ranges.

typedef struct _MINIDUMP_MEMORY_LIST {
    ULONG32 NumberOfMemoryRanges;
    MINIDUMP_MEMORY_DESCRIPTOR MemoryRanges [0];
} MINIDUMP_MEMORY_LIST, *PMINIDUMP_MEMORY_LIST;

The MINIDUMP_MEMORY64_LIST structure is defined as follows. It is used for full-memory minidumps.

typedef struct _MINIDUMP_MEMORY64_LIST {
    ULONG64 NumberOfMemoryRanges;
    RVA64 BaseRva;
    MINIDUMP_MEMORY_DESCRIPTOR64 MemoryRanges [0];
} MINIDUMP_MEMORY64_LIST, *PMINIDUMP_MEMORY64_LIST;

Members

NumberOfMemoryRanges
Number of structures in the MemoryRanges array.
BaseRva
Overall base RVA for the memory list. To locate the data for a particular descriptor, start at BaseRva and increment by the size of a descriptor until you reach the descriptor.
MemoryRanges
An array of MINIDUMP_MEMORY_DESCRIPTOR structures.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_MEMORY_DESCRIPTOR


MINIDUMP_MODULE

[This is preliminary documentation and subject to change.]

The MINIDUMP_MODULE structure contains information for a specific module.

typedef struct _MINIDUMP_MODULE {
    ULONG64 BaseOfImage;
    ULONG32 SizeOfImage;
    ULONG32 CheckSum;
    ULONG32 TimeDateStamp;
    RVA ModuleNameRva;
    VS_FIXEDFILEINFO VersionInfo;
    MINIDUMP_LOCATION_DESCRIPTOR CvRecord;
    MINIDUMP_LOCATION_DESCRIPTOR MiscRecord;
    ULONG64 Reserved0;
    ULONG64 Reserved1;
} MINIDUMP_MODULE, *PMINIDUMP_MODULE;

Members

BaseOfImage
Base address of the module executable image in memory.
SizeOfImage
Size of the module executable image in memory, in bytes.
CheckSum
Checksum value of the module executable image.
TimeDateStamp
Timestamp value of the module executable image.
ModuleNameRva
An RVA to a MINIDUMP_STRING structure that specifies the name of the module.
VersionInfo
A VS_FIXEDFILEINFO structure that specifies the version of the module.
CvRecord
Pointer to a string containing the CodeView record of the module.
MiscRecord
Pointer to a string that specifies the miscellaneous record of the module.
Reserved0
Reserved for future use.
Reserved1
Reserved for future use.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_STRING, VS_FIXEDFILEINFO


MINIDUMP_MODULE_CALLBACK

[This is preliminary documentation and subject to change.]

The MINIDUMP_MODULE_CALLBACK structure contains module information for the MiniDumpCallback function.

typedef struct _MINIDUMP_MODULE_CALLBACK {
  PWCHAR FullPath;
  ULONG64 BaseOfImage;
  ULONG SizeOfImage;
  ULONG CheckSum;
  ULONG TimeDateStamp;
  VS_FIXEDFILEINFO VersionInfo;
  PVOID CvRecord;
  ULONG SizeOfCvRecord;
  PVOID MiscRecord;
  ULONG SizeOfMiscRecord;
} MINIDUMP_MODULE_CALLBACK, *PMINIDUMP_MODULE_CALLBACK;

Members

FullPath
Pointer to a string that specifies the fully qualified path of the module executable.
BaseOfImage
Base address of the module executable image in memory.
SizeOfImage
Size of the module executable image in memory, in bytes.
CheckSum
Checksum value of the module executable image.
TimeDateStamp
Timestamp value of the module executable image.
VersionInfo
A VS_FIXEDFILEINFO structure that specifies the version of the module.
CvRecord
Pointer to a string containing the CodeView record of the module.
SizeOfCvRecord
Size of the Codeview record of the module in the CvRecord member, in bytes.
MiscRecord
Pointer to a string that specifies the miscellaneous record of the module.
SizeOfMiscRecord
Size of the miscellaneous record of the module in the MiscRecord member, in bytes.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_CALLBACK_INPUT, MiniDumpCallback, VS_FIXEDFILEINFO


MINIDUMP_MODULE_LIST

[This is preliminary documentation and subject to change.]

The MINIDUMP_MODULE_LIST structure contains a list of modules.

typedef struct _MINIDUMP_MODULE_LIST {
    ULONG32 NumberOfModules;
    MINIDUMP_MODULE Modules[0];
} MINIDUMP_MODULE_LIST, *PMINIDUMP_MODULE_LIST;

Members

NumberOfModules
Number of structures in the Modules array.
Modules
An array of MINIDUMP_MODULE structures.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_MODULE


MINIDUMP_STRING

[This is preliminary documentation and subject to change.]

The MINIDUMP_STRING structure describes a string.

typedef struct _MINIDUMP_STRING {
    ULONG32 Length;
    WCHAR   Buffer [0];
} MINIDUMP_STRING, *PMINIDUMP_STRING;

Members

Length
Size of the Buffer string, in bytes.
Buffer
Pointer to a variably sized buffer that contains the string.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_HANDLE_DESCRIPTOR, MINIDUMP_MODULE


MINIDUMP_SYSTEM_INFO

[This is preliminary documentation and subject to change.]

The MINIDUMP_SYSTEM_INFO structure contains processor and operating system information.

typedef struct _MINIDUMP_SYSTEM_INFO {
    UINT16 ProcessorArchitecture;
    UINT16 ProcessorLevel;
    UINT16 ProcessorRevision;
    UINT16 Reserved0;
    ULONG32 MajorVersion;
    ULONG32 MinorVersion;
    ULONG32 BuildNumber;
    ULONG32 PlatformId;
    RVA CSDVersionRva;
    ULONG32 Reserved1;
    union _CPU_INFORMATION {
        struct {
            // CPUID Subfunction 0, EAX (VendorId[0]),
            // EBX (VendorId[1]) and ECX (VendorId[2]).

            ULONG32 VendorId[3];

            // CPUID Subfunction 1, register EAX

            ULONG32 VersionInformation;

            // CPUID Subfunction 1, register EDX

            ULONG32 FeatureInformation;

            // CPUID, Subfunction 80000001, register EBX.
            // Supported only if VendorId is "AuthenticAMD".

            ULONG32 AMDExtendedCpuFeatures;
        } X86CpuInfo;

        struct {
            ULONG64 ProcessorFeatures[2];
        } OtherCpuInfo;

    } Cpu;
} MINIDUMP_SYSTEM_INFO, *PMINIDUMP_SYSTEM_INFO;

Members

ProcessorArchitecture
Specifies the system's processor architecture. This member can be one of the following values:

PROCESSOR_ARCHITECTURE_UNKNOWN
PROCESSOR_ARCHITECTURE_INTEL
Whistler 64-bit: PROCESSOR_ARCHITECTURE_IA64
Whistler 64-bit: PROCESSOR_ARCHITECTURE_AMD64

ProcessorLevel
Specifies the system's architecture-dependent processor level.

If ProcessorArchitecture is PROCESSOR_ARCHITECTURE_INTEL, ProcessorLevel can be one of the following values.
Value | Meaning
3 | Intel 80386
4 | Intel 80486
5 | Intel Pentium
6 | Intel Pentium Pro or Pentium II

If ProcessorArchitecture is PROCESSOR_ARCHITECTURE_IA64, ProcessorLevel is set to 1.

ProcessorRevision
Specifies an architecture-dependent processor revision.
Processor Value
Intel 80386 or 80486 A value of the form xxyz.

If xx is equal to 0xFF, y - 0xA is the model number, and z is the stepping identifier. For example, an Intel 80486-D0 system returns 0xFFD0.

If xx is not equal to 0xFF, xx + 'A' is the stepping letter and yz is the minor stepping.

Intel Pentium, Cyrix, or NextGen 586 A value of the form xxyy, where xx is the model number and yy is the stepping. Display this value of 0x0201 as follows:

Model xx, Stepping yy

Reserved0
Reserved for future use. Must be zero.
MajorVersion
Identifies the major version number of the operating system as follows.
Operating system | Value
Windows 95 | 4
Windows 98 | 4
Windows Me | 4
Windows NT 3.51 | 3
Windows NT 4.0 | 4
Windows 2000 | 5
Whistler | 5

MinorVersion
Identifies the minor version number of the operating system as follows.
Operating system | Value
Windows 95 | 0
Windows 98 | 10
Windows Me | 90
Windows NT 3.51 | 51
Windows NT 4.0 | 0
Windows 2000 | 0
Whistler | 1

BuildNumber
Windows NT/2000: Identifies the build number of the operating system.

Windows 95/98: Identifies the build number of the operating system in the low-order word. The high-order word contains the major and minor version numbers.

PlatformId
Identifies the operating system platform. This member can be one of the following values.
Value | Platform
VER_PLATFORM_WIN32s | Win32s on Windows 3.1.
VER_PLATFORM_WIN32_WINDOWS | Windows 95, Windows 98, or Windows Me.
VER_PLATFORM_WIN32_NT | Windows NT 3.51, Windows NT 4.0, Windows 2000, or Whistler.

CSDVersionRva
Windows NT/2000, Whistler: Contains a null-terminated string, such as "Service Pack 3", that indicates the latest Service Pack installed on the system. If no Service Pack has been installed, the string is empty.

Windows 95/98/Me: Contains a null-terminated string that indicates additional version information. For example, " C" indicates Windows 95 OSR2 and " A" indicates Windows 98 SE.

Reserved1
Reserved for future use.
X86CpuInfo
CPU information obtained from the CPUID instruction. This structure is supported only for x86 computers.
OtherCpuInfo
CPU information obtained from the IsProcessorFeaturePresent function. This structure is supported only for non-x86 computers.
Cpu
A structure that contains CPU information. See the syntax for X86CpuInfo and OtherCpuInfo for details.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, IsProcessorFeaturePresent


MINIDUMP_THREAD

[This is preliminary documentation and subject to change.]

The MINIDUMP_THREAD structure contains information for a specific thread.

typedef struct _MINIDUMP_THREAD {
    ULONG32 ThreadId;
    ULONG32 SuspendCount;
    ULONG32 PriorityClass;
    ULONG32 Priority;
    ULONG64 Teb;
    MINIDUMP_MEMORY_DESCRIPTOR Stack;
    MINIDUMP_LOCATION_DESCRIPTOR ThreadContext;
} MINIDUMP_THREAD, *PMINIDUMP_THREAD;

Members

ThreadId
Identifier of the thread.
SuspendCount
Suspend count for the thread. If the suspend count is greater than zero, the thread is suspended; otherwise, the thread is not suspended. The maximum value is MAXIMUM_SUSPEND_COUNT.
PriorityClass
Priority class of the thread. See Scheduling Priorities.
Priority
Priority level of the thread.
Teb
Thread environment block.
Stack
A MINIDUMP_MEMORY_DESCRIPTOR structure.
ThreadContext
A MINIDUMP_LOCATION_DESCRIPTOR structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_LOCATION_DESCRIPTOR, MINIDUMP_MEMORY_DESCRIPTOR


MINIDUMP_THREAD_CALLBACK

[This is preliminary documentation and subject to change.]

The MINIDUMP_THREAD_CALLBACK structure contains thread information for the MiniDumpCallback function.

typedef struct _MINIDUMP_THREAD_CALLBACK {
  ULONG ThreadId;
  HANDLE ThreadHandle;
  CONTEXT Context;
  ULONG SizeOfContext;
  ULONG64 StackBase;
  ULONG64 StackEnd;
} MINIDUMP_THREAD_CALLBACK, *PMINIDUMP_THREAD_CALLBACK;

Members

ThreadId
Identifier of the thread.
ThreadHandle
Handle to the thread
Context
Processor-specific data returned in a CONTEXT structure.
SizeOfContext
Size of the returned processor-specific data in the Context member, in bytes.
StackBase
Base address of the thread stack.
StackEnd
Ending address of the thread stack.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_CALLBACK_INPUT, MiniDumpCallback, CONTEXT


MINIDUMP_THREAD_EX

[This is preliminary documentation and subject to change.]

The MINIDUMP_THREAD_EX structure contains extended information for a specific thread.

typedef struct _MINIDUMP_THREAD_EX {
    ULONG32 ThreadId;
    ULONG32 SuspendCount;
    ULONG32 PriorityClass;
    ULONG32 Priority;
    ULONG64 Teb;
    MINIDUMP_MEMORY_DESCRIPTOR Stack;
    MINIDUMP_LOCATION_DESCRIPTOR ThreadContext;
    MINIDUMP_MEMORY_DESCRIPTOR BackingStore;
} MINIDUMP_THREAD_EX, *PMINIDUMP_THREAD_EX;

Members

ThreadId
Identifier of the thread.
SuspendCount
Suspend count for the thread. If the suspend count is greater than zero, the thread is suspended; otherwise, the thread is not suspended. The maximum value is MAXIMUM_SUSPEND_COUNT.
PriorityClass
Priority class of the thread. See Scheduling Priorities.
Priority
Priority level of the thread.
Teb
Thread environment block.
Stack
A MINIDUMP_MEMORY_DESCRIPTOR structure.
ThreadContext
A MINIDUMP_LOCATION_DESCRIPTOR structure.
BackingStore
Backing store for the thread. This value applies only to architectures that use backing store memory in addition to a stack, such as the IA-64.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_LOCATION_DESCRIPTOR, MINIDUMP_MEMORY_DESCRIPTOR


MINIDUMP_THREAD_EX_CALLBACK

[This is preliminary documentation and subject to change.]

The MINIDUMP_THREAD_EX_CALLBACK structure contains extended thread information for the MiniDumpCallback function.

typedef struct _MINIDUMP_THREAD_EX_CALLBACK {
    ULONG ThreadId;
    HANDLE ThreadHandle;
    CONTEXT Context;
    ULONG SizeOfContext;
    ULONG64 StackBase;
    ULONG64 StackEnd;
    ULONG64 BackingStoreBase;
    ULONG64 BackingStoreEnd;
} MINIDUMP_THREAD_EX_CALLBACK, *PMINIDUMP_THREAD_EX_CALLBACK;

Members

ThreadId
Identifier of the thread.
ThreadHandle
Handle to the thread
Context
Processor-specific data returned in a CONTEXT structure.
SizeOfContext
Size of the returned processor-specific data in the Context member, in bytes.
StackBase
Base address of the thread stack.
StackEnd
Ending address of the thread stack.
BackingStoreBase
Base address of the thread backing store. This value applies only to architectures that use backing store memory in addition to a stack, such as the IA-64.
BackingStoreEnd
Ending address of the thread backing store. This value applies only to architectures that use backing store memory in addition to a stack, such as the IA-64.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_CALLBACK_INPUT, MiniDumpCallback, CONTEXT


MINIDUMP_THREAD_EX_LIST

[This is preliminary documentation and subject to change.]

The MINIDUMP_THREAD_EX_LIST structure contains a list of threads.

typedef struct _MINIDUMP_THREAD_EX_LIST {
    ULONG32 NumberOfThreads;
    MINIDUMP_THREAD_EX Threads [0];
} MINIDUMP_THREAD_EX_LIST, *PMINIDUMP_THREAD_EX_LIST;

Members

NumberOfThreads
Number of structures in the Threads array.
Threads
An array of MINIDUMP_THREAD_EX structures.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_THREAD_EX


MINIDUMP_THREAD_LIST

[This is preliminary documentation and subject to change.]

The MINIDUMP_THREAD_LIST structure contains a list of threads.

typedef struct _MINIDUMP_THREAD_LIST {
    ULONG32 NumberOfThreads;
    MINIDUMP_THREAD Threads [0];
} MINIDUMP_THREAD_LIST, *PMINIDUMP_THREAD_LIST;

Members

NumberOfThreads
Number of structures in the Threads array.
Threads
An array of MINIDUMP_THREAD structures.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_THREAD


MINIDUMP_USER_STREAM

[This is preliminary documentation and subject to change.]

The MINIDUMP_USER_STREAM structure contains user-defined information stored in a data stream.

typedef struct _MINIDUMP_USER_STREAM {
  ULONG32 Type;
  ULONG BufferSize;
  PVOID Buffer;
} MINIDUMP_USER_STREAM, *PMINIDUMP_USER_STREAM;

Members

Type
Type of data stream. For more information, see MINIDUMP_STREAM_TYPE.
BufferSize
Size of the user-defined data stream buffer, in bytes.
Buffer
Pointer to a buffer that contains the user-defined data stream.

Remarks

In this context, a data stream refers to a block of data within a minidump file.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_STREAM_TYPE, MINIDUMP_USER_STREAM_INFORMATION, MiniDumpCallback


MINIDUMP_USER_STREAM_INFORMATION

[This is preliminary documentation and subject to change.]

The MINIDUMP_USER_STREAM_INFORMATION structure contains a list of user data streams used by the MiniDumpWriteDump function.

typedef struct _MINIDUMP_USER_STREAM_INFORMATION {
  ULONG UserStreamCount;
  PMINIDUMP_USER_STREAM UserStreamArray;
} MINIDUMP_USER_STREAM_INFORMATION, *PMINIDUMP_USER_STREAM_INFORMATION;

Members

UserStreamCount
Number of user streams.
UserStreamArray
An array of MINIDUMP_USER_STREAM structures.

Remarks

In this context, a data stream refers to a block of data within a minidump file.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, MINIDUMP_USER_STREAM, MiniDumpWriteDump


MODULE_TYPE_INFO

The MODULE_TYPE_INFO structure contains advanced module information. This structure is intended for use by Windows debuggers.

typedef struct _MODULE_TYPE_INFO {
  USHORT      dataLength;
  USHORT      leaf;
  BYTE        data[1];
} MODULE_TYPE_INFO, *PMODULE_TYPE_INFO;

Members

dataLength
Length of the structure, in bytes.
leaf
Data type of the data member.
data
Pointer to the data buffer.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, SymGetModuleInfoEx


STACKFRAME

The STACKFRAME structure represents a stack frame.

This structure is declared for both 32- and 64-bit Windows. For more information, see New 64-bit Support.

typedef struct _tagSTACKFRAME {
  ADDRESS AddrPC;
  ADDRESS AddrReturn;
  ADDRESS AddrFrame;
  ADDRESS AddrStack;
  PVOID   FuncTableEntry;
  DWORD   Params[4];
  BOOL    Far;
  BOOL    Virtual;
  DWORD   Reserved[3];
  KDHELP  KdHelp;
  ADDRESS AddrBStore;
} STACKFRAME, *LPSTACKFRAME;

The STACKFRAME64 structure is defined as follows.

typedef struct _tagSTACKFRAME64 {
  ADDRESS64 AddrPC;
  ADDRESS64 AddrReturn;
  ADDRESS64 AddrFrame;
  ADDRESS64 AddrStack;
  ADDRESS64 AddrBStore;
  PVOID     FuncTableEntry;
  DWORD64   Params[4];
  BOOL      Far;
  BOOL      Virtual;
  DWORD64   Reserved[3];
  KDHELP64  KdHelp;
} STACKFRAME64, *LPSTACKFRAME64;

Members

AddrPC
An ADDRESS structure that specifies the program counter (EIP).
AddrReturn
An ADDRESS structure that specifies the return address.
AddrFrame
An ADDRESS structure that specifies the frame pointer (ESP).

On Alpha computers, there is no frame register, so the Offset member is not used and should be zero. However, the Offset member is used when walking a kernel stack which terminates in an exception frame. This is a special case.

AddrStack
An ADDRESS structure that specifies the stack pointer (ESP).
FuncTableEntry
On x86 computers, this member is an FPO_DATA structure. On Alpha computers, this member is an IMAGE_FUNCTION_ENTRY structure. If there is no function table entry, this member is NULL.
Params
Possible arguments to the function.
Far
This member is TRUE if this is a WOW far call.
Virtual
This member is TRUE if this is a virtual frame.
Reserved
Used internally by the StackWalk function.
KdHelp
A KDHELP structure that specifies helper data for walking kernel callback frames.
AddrBStore
An ADDRESS structure that specifies the backing store.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, ADDRESS, FPO_DATA, IMAGE_FUNCTION_ENTRY, KDHELP, StackWalk


TYPE_ENUM_INFO

The TYPE_ENUM_INFO structure is used in enumerating advanced symbol information. This structure is intended for use by Windows debuggers.

typedef struct _TYPE_ENUM_INFO {
  PVOID CallerData;
  PSYMBOL_TYPE_NAME_CALLBACK CallbackRoutine;
} TYPE_ENUM_INFO, *PTYPE_ENUM_INFO;

Members

CallerData
User-defined data.
CallbackRoutine
Pointer to a SymTypeNameCallback function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Version: Requires DbgHelp.dll version 5.0.2195.1.
Header: Declared in Dbghelp.h.

See Also

Debug Help Library Overview, DbgHelp Structures, SymGetSymbolInfo, SymTypeNameCallback


DbgHelp Enumerations

The following are the DbgHelp enumerations.

MINIDUMP_CALLBACK_TYPE
MINIDUMP_STREAM_TYPE
MINIDUMP_TYPE
MODULE_WRITE_FLAGS
THREAD_WRITE_FLAGS


MINIDUMP_CALLBACK_TYPE

[This is preliminary documentation and subject to change.]

The MINIDUMP_CALLBACK_TYPE enumeration values identify the type of information returned by the MiniDumpCallback function.

typedef enum _MINIDUMP_CALLBACK_TYPE {
  ModuleCallback,
  ThreadCallback,
  ThreadExCallback
} MINIDUMP_CALLBACK_TYPE;

Member

ModuleCallback
The callback function returns module information.
ThreadCallback
The callback function returns thread information.
ThreadExCallback
The callback function returns extended thread information.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.

See Also

Debug Help Library Overview, DbgHelp Enumerations, MINIDUMP_CALLBACK_INPUT, MiniDumpCallback


MINIDUMP_STREAM_TYPE

[This is preliminary documentation and subject to change.]

The MINIDUMP_STREAM_TYPE enumeration values identify the type of a data stream.

typedef enum _MINIDUMP_STREAM_TYPE {
  UnusedStream                = 0,
  ReservedStream0             = 1,
  ReservedStream1             = 2,
  ThreadListStream            = 3,
  ModuleListStream            = 4,
  MemoryListStream            = 5,
  ExceptionStream             = 6,
  SystemInfoStream            = 7,
  ThreadExListStream          = 8,
  Memory64ListStream          = 9,
  CommentStreamA              = 10,
  CommentStreamW              = 11,
  HandleDataStream            = 12,
  LastReservedStream          = 0xffff
} MINIDUMP_STREAM_TYPE;

Members

UnusedStream
Reserved. Do not use this enumeration value.
ReservedStream0
Reserved. Do not use this enumeration value.
ReservedStream1
Reserved. Do not use this enumeration value.
ThreadListStream
The stream contains thread information. For more information, see MINIDUMP_THREAD_LIST.
ModuleListStream
The stream contains module information. For more information, see MINIDUMP_MODULE_LIST.
MemoryListStream
The stream contains memory allocation information. For more information, see MINIDUMP_MEMORY_LIST.
ExceptionStream
The stream contains exception information. For more information, see MINIDUMP_EXCEPTION_STREAM.
SystemInfoStream
The stream contains general system information. For more information, see MINIDUMP_SYSTEM_INFO.
ThreadExListStream
The stream contains extended thread information. For more information, see MINIDUMP_THREAD_EX_LIST.
Memory64ListStream
The stream contains memory allocation information. For more information, see MINIDUMP_MEMORY64_LIST.
CommentStreamA
The stream contains an ANSI string used for documentation purposes.
CommentStreamW
The stream contains a Unicode string used for documentation purposes.
HandleDataStream
The stream contains high-level information about the active operating system handles. For more information, see MINIDUMP_HANDLE_DATA_STREAM.
LastReservedStream
Any value greater than this value will not be used by the system and can be used to represent application-defined data streams. For more information, see MINIDUMP_USER_STREAM.

Remarks

In this context, a data stream is a set of data in a minidump file.

The StreamType member of the MINIDUMP_DIRECTORY structure can be one of these types. Additional types may be added in the future, so if a program reading the minidump header encounters a stream type it does not recognize, it should ignore the stream altogether.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.

See Also

Debug Help Library Overview, DbgHelp Enumerations, MINIDUMP_DIRECTORY, MINIDUMP_EXCEPTION_STREAM, MINIDUMP_HANDLE_DATA_STREAM, MINIDUMP_MEMORY_LIST, MINIDUMP_MODULE_LIST, MINIDUMP_SYSTEM_INFO, MINIDUMP_THREAD_EX_LIST, MINIDUMP_THREAD_LIST, MINIDUMP_USER_STREAM


MINIDUMP_TYPE

[This is preliminary documentation and subject to change.]

The MINIDUMP_TYPE enumeration values identify the type of information that will be written to the minidump file by the MiniDumpWriteDump function.

typedef enum _MINIDUMP_TYPE {
  MiniDumpNormal,
  MiniDumpWithDataSegs,
  MiniDumpWithFullMemory,
  MiniDumpWithHandleData
} MINIDUMP_TYPE;

Members

MiniDumpNormal
Include just the information necessary to capture stack traces for all existing threads in a process.
MiniDumpWithDataSegs
Include the data sections from all loaded modules. This results in the inclusion of global variables, which can make the dump file significantly larger.
MiniDumpWithFullMemory
Include all accessible memory in the process. The raw memory data is included at the end, so that the initial structures can be mapped directly without the raw memory information. This option can result in a very large file.
MiniDumpWithHandleData
Windows NT/2000 or later: Include high-level information about the operating system handles that are active when the dump is made.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.

See Also

Debug Help Library Overview, DbgHelp Enumerations, MiniDumpWriteDump


MODULE_WRITE_FLAGS

[This is preliminary documentation and subject to change.]

The MODULE_WRITE_FLAGS enumeration values identify the type of module information that will be written to the minidump file by the MiniDumpWriteDump function.

typedef enum _MODULE_WRITE_FLAGS {
  ModuleWriteModule       = 0x0001,
  ModuleWriteDataSeg      = 0x0002,
  ModuleWriteMiscRecord   = 0x0004
} MODULE_WRITE_FLAGS;

Members

ModuleWriteModule
Only module information will be written to the minidump file.
ModuleWriteDataSeg
Module and data segment information will be written to the minidump file.
ModuleWriteMiscRecord
Module, data segment, and miscellaneous record information will be written to the minidump file.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.

See Also

Debug Help Library Overview, DbgHelp Enumerations, MINIDUMP_CALLBACK_OUTPUT, MiniDumpWriteDump


THREAD_WRITE_FLAGS

[This is preliminary documentation and subject to change.]

The THREAD_WRITE_FLAGS enumeration values identify the type of thread information that will be written to the minidump file by the MiniDumpWriteDump function.

typedef enum _THREAD_WRITE_FLAGS {
  ThreadWriteThread            = 0x0001,
  ThreadWriteStack             = 0x0002,
  ThreadWriteContext           = 0x0004
  ThreadWriteBackingStore      = 0x0008,
  ThreadWriteInstructionWindow = 0x0010
} THREAD_WRITE_FLAGS;

Members

ThreadWriteThread
Only basic thread information will be written to the minidump file.
ThreadWriteStack
Basic thread and thread stack information will be written to the minidump file.
ThreadWriteContext
The entire thread context will be written to the minidump file.
ThreadWriteBackingStore
The backing store memory of every thread will be written to the minidump file. This value applies only to architectures that use backing store memory in addition to a stack, such as the IA-64.
ThreadWriteInstructionWindow
A small amount of memory surrounding each thread's instruction pointer will be written to the minidump file. This allows instructions near a thread's instruction pointer to be disassembled even if an executable image matching the module cannot be found.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Version: Requires Whistler DbgHelp.dll.
Header: Declared in DbgHelp.h.

See Also

Debug Help Library Overview, DbgHelp Enumerations, MINIDUMP_CALLBACK_OUTPUT, MiniDumpWriteDump


Error Handling

Well-written applications include error-handling code that allows them to recover gracefully from unexpected errors. When an error occurs, the application may need to request user intervention, or it may be able to recover on its own. In extreme cases, the application may log the user off or shut down the system.

  • About Error Handling
  • Using Error Handling
  • Error Handling Reference

For information about exception handling, see Structured Exception Handling.


About Error Handling

The error handling functions enable you to receive and display error information for your application. For more information, see the following topics:

  • Process Error Mode
  • Last Error Code
  • Notifying the User
  • Message Tables
  • Fatal Application Exit

For information on writing error messages, see Error Message Guidelines.


Process Error Mode

Each process has an associated error mode that indicates to the system how the application is going to respond to serious errors. Serious errors include disk failure, drive-not-ready errors, data misalignment, and unhandled exceptions. An application can let the system display a message box informing the user that an error has occurred, or it can handle the errors. To handle these errors without user intervention, use the SetErrorMode function. After calling SetErrorMode and specifying appropriate flags, the system will not display the corresponding error message boxes.


Last-Error Code

When an error occurs, most functions in the Win32 API return an error code, usually zero, NULL, or –1. Many functions also set an internal error code called the last-error code. When a function succeeds, the last-error code is not reset. The error code is maintained separately for each running thread; an error in one thread does not overwrite the last-error code in another thread. An application can retrieve the last-error code by using the GetLastError function; the error code may tell more about what actually occurred to make the function fail.

The SetLastError function sets the error code for the current thread. The SetLastErrorEx function also allows the caller to set an error type indicating the severity of the error. These functions are intended primarily for dynamic-link libraries (DLL), so they can emulate the behavior of the Win32 API.

The system defines a set of error codes that can be set as last-error codes or be returned by these functions. Error codes are 32-bit values (bit 31 is the most significant bit). Bit 29 is reserved for application-defined error codes; no system error code has this bit set. If you define error codes for your application, set this bit to indicate that the error code has been defined by an application and to ensure that the error codes do not conflict with any system-defined error codes. For more information, see Error Codes.


Notifying the User

To notify the user that some kind of error has occurred, many applications simply produce a sound by using the Beep or MessageBeep function or flash the window by using the FlashWindow or FlashWindowEx function. An application can also use these functions to call attention to an error and then display a message box or an error message containing details about the error.


Message Tables

Message tables are special string resources used when displaying error messages. They are declared in a resource file using the MESSAGETABLE resource-definition statement. To access the message strings, use the FormatMessage function.

The system provides a message table for the Win32 error codes. To retrieve the string that corresponds to the error code, call FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag.

To provide a message table for your application, follow the instructions in About Message Text Files. To retrieve strings from your message table, call FormatMessage with the FORMAT_MESSAGE_FROM_HMODULE flag.


Fatal Application Exit

The FatalAppExit function displays a message box and terminates the application when the user closes the message box. This function should only be used as a last resort, because it may not free the memory or files owned by the application.


Error Message Guidelines

The guidelines presented here are intended to help you write clearer and more useful error messages.

In particular, these guidelines address three common problems:

  • Users often misunderstand popup errors.
  • Administrators cannot easily understand event log messages.
  • Technical support receives many calls as a result of confusing error messages.

This overview contains the following topics:

  • Basic Guidelines
  • Searchable Messages
  • Style Considerations
  • Message Length
  • Dialog Box and Popup Message Guidelines


Basic Guidelines

  • Do not anthropomorphize. Do not imply that programs or hardware can think or feel. The following table shows an example.
Correct | Incorrect
Node [node name] cannot use Windows protocols. | Node [node name] does not speak any of our protocols.

  • Avoid the word "Bad." Try to find a more descriptive term to tell the user what is wrong. For example, avoid messages such as the following:
    bad link          // Avoid!
bad size          // Avoid!
bad argument      // Avoid!
bad address       // Avoid!
bad CRC           // Avoid!
  • Use full sentences. For example, use "Binding is too long." instead of "Binding too long."
  • Take indexing into account. To create error messages suitable for a global audience, use clear language and complete sentences. If you index each error message, make them easy to look up. (1) Avoid starting a message with an article (the, a, or an). (2) Never put a placeholder variable, such as %1 or %2 at the beginning of a message, because these are very difficult for a user to look up in an index. If you plan to index the error message just as it appears to the user, write the message so that a word that is in the index is at the beginning and the placeholder is embedded in the message. The following table shows some examples.
Correct | Incorrect
Log file %1 is full. | %1 log file is full.
Listen failed in %1. | %1: Listen failed.
Computer name %1 is a domain controller of domain %2. | %1 is a domain controller of domain %2.


Searchable Messages

Place words that are both in the index and relevant to the central meaning at the beginning of the message string. The following table shows some examples.

Correct | Incorrect
Recycle Bin cannot store some of the items you are about to delete. | Some of the items you are about to delete cannot be stored in the Recycle Bin.
Endpoint was not found. | No endpoint was found.
Move you specified requires moving text cards. | That move requires moving text cards.
Computer name as entered is not valid. | The computer name you typed is invalid. Or Invalid computer name.
Chat application cannot start. | The application cannot start in Chat component.


Style Considerations

Users almost always prefer simple sentences that use simple present or past tense and active voice. The following table shows some examples.

Correct | Incorrect
Registry Editor cannot create the subkey. | Could not create the subkey.
Setup cannot start Program Manager. | Setup was unable to activate Program Manager.
Floppy disk sector ID field does not match floppy disk controller track address. | Mismatch between the floppy disk sector ID field and the floppy disk controller track address.
CHKDSK encountered an error during... | An error was encountered during...
Cannot find %1. | Could not find %1.
Modem does not respond. | Modem not responding.

However, using active voice and simple constructions is less important than making your message searchable. Use passive voice and more complex constructions if necessary to place search-relevant words at the beginning of the message. The following table shows some examples.

Correct | Incorrect
Log file size cannot be adjusted. | Cannot adjust the size of the log file. Or Was unable to adjust the size of the log file.
Printing of %1 cannot resume. | Cannot resume printing %1. Or Could not resume printing %1.


Message Length

Wordiness or verbosity of messages should depend on the component. Consider the following guidelines on message length:

  • Strings from components that have the potential to destroy an installation or cause the system to crash should include more explanation and user guidance. For example, Setup and STOP messages can contain more text.
  • Strings from components that are displayed often to less technical users (as opposed to administrators or technical support) can also be longer. For example, Print Manager and IIS messages can be longer.
  • Strings that display mostly to technical users should be shorter. Explanation and user action fields in the Messages Help file can go into more detail for these users. For example, WINS and TCP/IP messages should be brief and to the point.


Dialog Box and Popup Message Guidelines

Users are often confused by messages that appear as dialog boxes or popup messages. When these appear on the screen and do not close until the user clicks the OK or Cancel button, users often feel they have "broken" something on the computer and are not sure what to do next.

When writing this type of message, consider the following:

  • Does the message give the user a clear, non-technical explanation of the problem?
  • Does the message include steps or a clear explanation of how to prevent the problem from occurring again?
  • If a long explanation is needed, point the user to a help file topic to search for more information.
  • If it is a critical problem, be sure to use the event log and write out the error.


Using Error Handling

  • Notifying the user of errors
  • Retrieving the last-error code


Notifying the User of Errors

The following example flashes a window and plays the system exclamation sound.

FlashWindow(hwnd, TRUE); // invert the title bar
Sleep(500);              // wait a bit
FlashWindow(hwnd, TRUE); // invert again

// Play the system exclamation sound.

MessageBeep(MB_ICONEXCLAMATION);


Retrieving the Last-Error Code

When many system functions fail, they set the last-error code (check the documentation for the function). If your application needs more details about an error, it can retrieve the last-error code.

The following example shows an error-handling function.

void error(LPSTR lpszFunction)
{
    CHAR szBuf[80];
    DWORD dw = GetLastError();

    sprintf(szBuf, "%s failed: GetLastError returned %u\n",
        lpszFunction, dw);

    MessageBox(NULL, szBuf, "Error", MB_OK);
    ExitProcess(dw);
}


Error Handling Reference

The following elements are used with error handling.

  • Error Handling Functions
  • Error Handling Structures


Error Handling Functions

The following functions are used with error handling.

Function | Description
Beep | Generates simple tones on the speaker.
FatalAppExit | Displays a message box and terminates the application when the message box is closed.
FlashWindow | Flashes the specified window one time.
FlashWindowEx | Flashes the specified window.
FormatMessage | Formats a message string.
GetLastError | Retrieves the calling thread's last-error code value.
MessageBeep | Plays a waveform sound.
SetErrorMode | Controls whether the system will handle the specified types of serious errors, or whether the process will handle them.
SetLastError | Sets the last-error code for the calling thread.
SetLastErrorEx | Sets the last-error code for the calling thread.


Beep

The Beep function generates simple tones on the speaker. The function is synchronous; it does not return control to its caller until the sound finishes.

BOOL Beep(
  DWORD dwFreq,      // sound frequency
  DWORD dwDuration   // sound duration
);

Parameters

dwFreq
Windows NT/2000 or later: [in] Specifies the frequency, in hertz, of the sound. This parameter must be in the range 37 through 32,767 (0x25 through 0x7FFF).
dwDuration
Windows NT/2000 or later: [in] Specifies the duration, in milliseconds, of the sound.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Windows 95/98/Me: The Beep function ignores the dwFreq and dwDuration parameters. On computers with a sound card, the function plays the default sound event. On computers without a sound card, the function plays the standard system beep.

For example, see Registering a Control Handler Function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Error Handling Overview, Error Handling Functions, MessageBeep


FatalAppExit

The FatalAppExit function displays a message box and terminates the application when the message box is closed. If the system is running with a kernel debugger, the message box gives the user the opportunity to terminate the application or to cancel the message box and return to the application that called FatalAppExit.

VOID FatalAppExit(
  UINT uAction,          // reserved
  LPCTSTR lpMessageText  // display string
);

Parameters

uAction
Reserved; must be zero.
lpMessageText
[in] Pointer to a null-terminated string that is displayed in the message box. The message is displayed on a single line. To accommodate low-resolution screens, the string should be no more than 35 characters in length.

Return Values

This function does not return a value.

Remarks

An application calls FatalAppExit only when it is not capable of terminating any other way. FatalAppExit may not always free an application's memory or close its files, and it may cause a general failure of the system. An application that encounters an unexpected error should terminate by freeing all its memory and returning from its main message loop.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Error Handling Overview, Error Handling Functions, FatalExit


FlashWindow

The FlashWindow function flashes the specified window one time. It does not change the active state of the window.

To flash the window a specified number of times, use the FlashWindowEx function.

BOOL FlashWindow(
  HWND hWnd,     // handle to window
  BOOL bInvert   // flash status
);

Parameters

hWnd
[in] Handle to the window to be flashed. The window can be either open or minimized.
bInvert
[in] Specifies whether the window is to be flashed or returned to its original state. The window is flashed from one state to the other if this parameter is TRUE. If it is FALSE, the window is returned to its original state (either active or inactive). When an application is minimized, if this parameter is TRUE, the taskbar window button flashes active/inactive. If it is FALSE, the taskbar window button flashes inactive, meaning that it does not change colors. It flashes, as if it were being redraw, but it does not provide the visual invert clue to the user.

Return Values

The return value specifies the window's state before the call to the FlashWindow function. If the window caption was drawn as active before the call, the return value is nonzero. Otherwise, the return value is zero.

Remarks

Flashing a window means changing the appearance of its caption bar as if the window were changing from inactive to active status, or vice versa. (An inactive caption bar changes to an active caption bar; an active caption bar changes to an inactive caption bar.)

Typically, a window is flashed to inform the user that the window requires attention but that it does not currently have the keyboard focus.

The FlashWindow function flashes the window only once; for repeated flashing, the application should create a system timer.

For example, see Notifying the User of Errors.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Error Handling Overview, Error Handling Functions


FlashWindowEx

The FlashWindowEx function flashes the specified window. It does not change the active state of the window.

BOOL FlashWindowEx(
  PFLASHWINFO pfwi  // flash status information
);

Parameters

pfwi
[in] Pointer to the FLASHWINFO structure.

Return Values

The return value specifies the window's state before the call to the FlashWindowEx function. If the window caption was drawn as active before the call, the return value is nonzero. Otherwise, the return value is zero.

Remarks

Typically, you flash a window to inform the user that the window requires attention but does not currently have the keyboard focus. When a window flashes, it appears to change from inactive to active status. An inactive caption bar changes to an active caption bar; an active caption bar changes to an inactive caption bar.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Error Handling Overview, Error Handling Functions, FLASHWINFO


FormatMessage

The FormatMessage function formats a message string. The function requires a message definition as input. The message definition can come from a buffer passed into the function. It can come from a message table resource in an already-loaded module. Or the caller can ask the function to search the system's message table resource(s) for the message definition. The function finds the message definition in a message table resource based on a message identifier and a language identifier. The function copies the formatted message text to an output buffer, processing any embedded insert sequences if requested.

DWORD FormatMessage(
  DWORD dwFlags,      // source and processing options
  LPCVOID lpSource,   // message source
  DWORD dwMessageId,  // message identifier
  DWORD dwLanguageId, // language identifier
  LPTSTR lpBuffer,    // message buffer
  DWORD nSize,        // maximum size of message buffer
  va_list *Arguments  // array of message inserts
);

Parameters

dwFlags
[in] Specifies aspects of the formatting process and how to interpret the lpSource parameter. The low-order byte of dwFlags specifies how the function handles line breaks in the output buffer. The low-order byte can also specify the maximum width of a formatted output line.

You can specify a combination of the following values.
Value | Meaning
FORMAT_MESSAGE_ALLOCATE_BUFFER | Specifies that the lpBuffer parameter is a pointer to a PVOID pointer, and that the nSize parameter specifies the minimum number of TCHARs to allocate for an output message buffer. The function allocates a buffer large enough to hold the formatted message, and places a pointer to the allocated buffer at the address specified by lpBuffer. The caller should use the LocalFree function to free the buffer when it is no longer needed.
FORMAT_MESSAGE_IGNORE_INSERTS | Specifies that insert sequences in the message definition are to be ignored and passed through to the output buffer unchanged. This flag is useful for fetching a message for later formatting. If this flag is set, the Arguments parameter is ignored.
FORMAT_MESSAGE_FROM_STRING | Specifies that lpSource is a pointer to a null-terminated message definition. The message definition may contain insert sequences, just as the message text in a message table resource may. Cannot be used with FORMAT_MESSAGE_FROM_HMODULE or FORMAT_MESSAGE_FROM_SYSTEM.
FORMAT_MESSAGE_FROM_HMODULE | Specifies that lpSource is a module handle containing the message-table resource(s) to search. If this lpSource handle is NULL, the current process's application image file will be searched. Cannot be used with FORMAT_MESSAGE_FROM_STRING.
FORMAT_MESSAGE_FROM_SYSTEM Specifies that the function should search the system message-table resource(s) for the requested message. If this flag is specified with FORMAT_MESSAGE_FROM_HMODULE, the function searches the system message table if the message is not found in the module specified by lpSource. Cannot be used with FORMAT_MESSAGE_FROM_STRING.

If this flag is specified, an application can pass the result of the GetLastError function to retrieve the message text for a system-defined error.
FORMAT_MESSAGE_ARGUMENT_ARRAY | Specifies that the Arguments parameter is not a va_list structure, but instead is just a pointer to an array of values that represent the arguments.

The low-order byte of dwFlags can specify the maximum width of a formatted output line. Use the FORMAT_MESSAGE_MAX_WIDTH_MASK constant and bitwise Boolean operations to set and retrieve this maximum width value.

The following table shows how FormatMessage interprets the value of the low-order byte.
Value | Meaning
0 | There are no output line width restrictions. The function stores line breaks that are in the message definition text into the output buffer.
A nonzero value other than FORMAT_MESSAGE_MAX_WIDTH_MASK | The nonzero value is the maximum number of characters in an output line. The function ignores regular line breaks in the message definition text. The function never splits a string delimited by white space across a line break. The function stores hard-coded line breaks in the message definition text into the output buffer. Hard-coded line breaks are coded with the %n escape sequence.
FORMAT_MESSAGE_MAX_WIDTH_MASK | The function ignores regular line breaks in the message definition text. The function stores hard-coded line breaks in the message definition text into the output buffer. The function generates no new line breaks.

lpSource
[in] Specifies the location of the message definition. The type of this parameter depends upon the settings in the dwFlags parameter.
dwFlags Setting | Parameter Type
FORMAT_MESSAGE_FROM_HMODULE | Handle to the module that contains the message table to search.
FORMAT_MESSAGE_FROM_STRING | Pointer to a string that consists of unformatted message text. It will be scanned for inserts and formatted accordingly.

If neither of these flags is set in dwFlags, then lpSource is ignored.

dwMessageId
[in] Specifies the message identifier for the requested message. This parameter is ignored if dwFlags includes FORMAT_MESSAGE_FROM_STRING.
dwLanguageId
[in] Specifies the language identifier for the requested message. This parameter is ignored if dwFlags includes FORMAT_MESSAGE_FROM_STRING.

If you pass a specific LANGID in this parameter, FormatMessage will return a message for that LANGID only. If the function cannot find a message for that LANGID, it returns ERROR_RESOURCE_LANG_NOT_FOUND. If you pass in zero, FormatMessage looks for a message for LANGIDs in the following order:

  1. Language neutral
  2. Thread LANGID, based on the thread's locale value
  3. User default LANGID, based on the user's default locale value
  4. System default LANGID, based on the system default locale value
  5. US English

If FormatMessage doesn't find a message for any of the preceding LANGIDs, it returns any language message string that is present. If that fails, it returns ERROR_RESOURCE_LANG_NOT_FOUND.

lpBuffer
[out] Pointer to a buffer for the formatted (and null-terminated) message. If dwFlags includes FORMAT_MESSAGE_ALLOCATE_BUFFER, the function allocates a buffer using the LocalAlloc function, and places the pointer to the buffer at the address specified in lpBuffer.
nSize
[in] If the FORMAT_MESSAGE_ALLOCATE_BUFFER flag is not set, this parameter specifies the maximum number of TCHARs that can be stored in the output buffer. If FORMAT_MESSAGE_ALLOCATE_BUFFER is set, this parameter specifies the minimum number of TCHARs to allocate for an output buffer. For ANSI text, this is the number of bytes; for Unicode text, this is the number of characters.
Arguments
[in] Pointer to an array of values that are used as insert values in the formatted message. A %1 in the format string indicates the first value in the Arguments array; a %2 indicates the second argument; and so on.

The interpretation of each value depends on the formatting information associated with the insert in the message definition. The default is to treat each value as a pointer to a null-terminated string.

By default, the Arguments parameter is of type va_list*, which is a language- and implementation-specific data type for describing a variable number of arguments. If you do not have a pointer of type va_list*, then specify the FORMAT_MESSAGE_ARGUMENT_ARRAY flag and pass a pointer to an array of values; those values are input to the message formatted as the insert values. Each insert must have a corresponding element in the array.

Windows 95/98/Me: No single insertion string may exceed 1023 characters in length.

Return Values

If the function succeeds, the return value is the number of TCHARs stored in the output buffer, excluding the terminating null character.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The FormatMessage function can be used to obtain error message strings for the system error codes returned by GetLastError, as shown in the following sample code.

LPVOID lpMsgBuf;
FormatMessage(
    FORMAT_MESSAGE_ALLOCATE_BUFFER |
    FORMAT_MESSAGE_FROM_SYSTEM |
    FORMAT_MESSAGE_IGNORE_INSERTS,
    NULL,
    GetLastError(),
    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
    (LPTSTR) &lpMsgBuf,
    0,
    NULL
);
// Process any inserts in lpMsgBuf.
// ...
// Display the string.
MessageBox( NULL, (LPCTSTR)lpMsgBuf, "Error", MB_OK | MB_ICONINFORMATION );
// Free the buffer.
LocalFree( lpMsgBuf );

Within the message text, several escape sequences are supported for dynamically formatting the message. These escape sequences and their meanings are shown in the following table. All escape sequences start with the percent character (%).

Escape Sequence | Meaning
%0 | Terminates a message text line without a trailing newline character. This escape sequence can be used to build up long lines or to terminate the message itself without a trailing newline character. It is useful for prompt messages.
%n!printf format string! | Identifies an insert. The value of n can be in the range 1 through 99. The printf format string (which must be bracketed by exclamation marks) is optional and defaults to !s! if not specified.
 | The printf format string can contain the * specifier for either the precision or the width component. If * is specified for one component, the FormatMessage function uses insert %n+1; it uses %n+2 if * is specified for both components.
 | Floating-point printf format specifiers — e, E, f, and g — are not supported. The workaround is to to use the sprintf function to format the floating-point number into a temporary buffer, then use that buffer as the insert string.

Any other nondigit character following a percent character is formatted in the output message without the percent character. Following are some examples:

Format string | Resulting output
%% | A single percent sign in the formatted message text.
%n | A hard line break when the format string occurs at the end of a line. This format string is useful when FormatMessage is supplying regular line breaks so the message fits in a certain width.
%space | A space in the formatted message text. This format string can be used to ensure the appropriate number of trailing spaces in a message text line.
%. | A single period in the formatted message text. This format string can be used to include a single period at the beginning of a line without terminating the message text definition.
%! | A single exclamation point in the formatted message text. This format string can be used to include an exclamation point immediately after an insert without its being mistaken for the beginning of a printf format string.

For example, see Looking Up Text for Error Code Numbers.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Error Handling Overview, Error Handling Functions, MESSAGETABLE Resource, Message Compiler


GetLastError

The GetLastError function retrieves the calling thread's last-error code value. The last-error code is maintained on a per-thread basis. Multiple threads do not overwrite each other's last-error code.

DWORD GetLastError(VOID);

Parameters

This function has no parameters.

Return Values

The return value is the calling thread's last-error code value. Functions set this value by calling the SetLastError function. The Return Value section of each reference page notes the conditions under which the function sets the last-error code.

Windows 95/98/Me: Win32 functions that are actually implemented in 16-bit code do not set the last-error code. You should ignore the last-error code when you call these functions. They include window management functions, GDI functions, and Multimedia functions.

Remarks

To obtain an error string for system error codes, use the FormatMessage function. For a complete list of error codes, see Win32 Error Codes.

You should call the GetLastError function immediately when a function's return value indicates that such a call will return useful data. That is because some functions call SetLastError(0) when they succeed, wiping out the error code set by the most recently failed function.

Most functions in the Win32 API that set the thread's last error code value set it when they fail; a few functions set it when they succeed. Function failure is typically indicated by a return value error code such as zero, NULL, or –1. Some functions call SetLastError under conditions of success; those cases are noted in each function's reference page.

Error codes are 32-bit values (bit 31 is the most significant bit). Bit 29 is reserved for application-defined error codes; no system error code has this bit set. If you are defining an error code for your application, set this bit to one. That indicates that the error code has been defined by an application, and ensures that your error code does not conflict with any error codes defined by the system.

MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.

For example, see Retrieving the Last-Error Code.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Error Handling Overview, Error Handling Functions, FormatMessage, SetLastError, SetLastErrorEx


MessageBeep

The MessageBeep function plays a waveform sound. The waveform sound for each sound type is identified by an entry in the registry.

BOOL MessageBeep(
  UINT uType   // sound type
);

Parameters

uType
[in] Specifies the sound type, as identified by an entry in the registry. This parameter can be one of the following values.
Value | Sound
-1 | Standard beep using the computer speaker
MB_ICONASTERISK | SystemAsterisk
MB_ICONEXCLAMATION | SystemExclamation
MB_ICONHAND | SystemHand
MB_ICONQUESTION | SystemQuestion
MB_OK | SystemDefault

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

After queuing the sound, the MessageBeep function returns control to the calling function and plays the sound asynchronously.

If it cannot play the specified alert sound, MessageBeep attempts to play the system default sound. If it cannot play the system default sound, the function produces a standard beep sound through the computer speaker.

The user can disable the warning beep by using the Sound control panel application.

For example, see Notifying the User of Errors.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Error Handling Overview, Error Handling Functions, FlashWindow, MessageBox


SetErrorMode

The SetErrorMode function controls whether the system will handle the specified types of serious errors, or whether the process will handle them.

UINT SetErrorMode(
  UINT uMode   // process error mode
);

Parameters

uMode
[in] Specifies the process error mode. This parameter can be one or more of the following values.
Value | Action
0 | Use the system default, which is to display all error dialog boxes.
SEM_FAILCRITICALERRORS | The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process.
SEM_NOALIGNMENTFAULTEXCEPT Itanium or RISC: The system automatically fixes memory alignment faults and makes them invisible to the application. It does this for the calling process and any descendant processes.

This value has no effect on x86 processors.

Whistler: After this value is set for a process, subsequent attempts to clear the value are ignored.
SEM_NOGPFAULTERRORBOX | The system does not display the general-protection-fault message box. This flag should only be set by debugging applications that handle general protection (GP) faults themselves with an exception handler.
SEM_NOOPENFILEERRORBOX | The system does not display a message box when it fails to find a file. Instead, the error is returned to the calling process.

Return Values

The return value is the previous state of the error-mode bit flags.

Remarks

Each process has an associated error mode that indicates to the system how the application is going to respond to serious errors. A child process inherits the error mode of its parent process.

Itanium: An application must explicitly call SetErrorMode with SEM_NOALIGNMENTFAULTEXCEPT to have the system automatically fix alignment faults. The default setting is for the system to make alignment faults visible to an application

x86: The system does not make alignment faults visible to an application. Therefore, specifying SEM_NOALIGNMENTFAULTEXCEPT is not an error, but the system is free to silently ignore the request. This means that code sequences such as the following are not always valid on x86 computers:

    SetErrorMode(SEM_NOALIGNMENTFAULTEXCEPT);
    fuOldErrorMode = SetErrorMode(0);
    ASSERT(fuOldErrorMode == SEM_NOALIGNMENTFAULTEXCEPT);

RISC: Misaligned memory references cause an alignment fault exception. To control whether the system automatically fixes such alignment faults or makes them visible to an application, use SEM_NOALIGNMENTFAULTEXCEPT.

MIPS: An application must explicitly call SetErrorMode with SEM_NOALIGNMENTFAULTEXCEPT to have the system automatically fix alignment faults. The default setting is for the system to make alignment faults visible to an application.

Alpha: To control the alignment fault behavior, set the EnableAlignmentFaultExceptions value in the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager registry key as follows.

Value | Meaning
0 | Automatically fix alignment faults. This is the default.
1 | Make alignment faults visible to the application. You must call SetErrorMode with SEM_NOALIGNMENTFAULTEXCEPT to have the system automatically fix alignment faults.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Error Handling Overview, Error Handling Functions


SetLastError

The SetLastError function sets the last-error code for the calling thread.

VOID SetLastError(
  DWORD dwErrCode   // per-thread error code
);

Parameters

dwErrCode
[in] Specifies the last-error code for the thread.

Return Values

This function does not return a value.

Remarks

Error codes are 32-bit values (bit 31 is the most significant bit). Bit 29 is reserved for application-defined error codes; no system error code has this bit set. If you are defining an error code for your application, set this bit to indicate that the error code has been defined by your application and to ensure that your error code does not conflict with any system-defined error codes.

This function is intended primarily for dynamic-link libraries (DLL). Calling this function after an error occurs lets the DLL emulate the behavior of the Win32 API.

Most Win32 functions call SetLastError when they fail. Function failure is typically indicated by a return value error code such as zero, NULL, or –1. Some functions call SetLastError under conditions of success; those cases are noted in each function's reference topic.

Applications can retrieve the value saved by this function by using the GetLastError function. The use of GetLastError is optional; an application can call it to find out the specific reason for a function failure.

The last-error code is kept in thread local storage so that multiple threads do not overwrite each other's values.

For example, see Displaying the User for an Event.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Error Handling Overview, Error Handling Functions, GetLastError, SetLastErrorEx


SetLastErrorEx

The SetLastErrorEx function sets the last-error code.

Currently, this function is identical to the SetLastError function. The second parameter is ignored.

VOID SetLastErrorEx(
  DWORD dwErrCode,  // per-thread error code
  DWORD dwType      // error type
);

Parameters

dwErrCode
[in] Specifies the last-error code for the thread.
dwType
This parameter is ignored.

Return Values

This function does not return a value.

Remarks

Error codes are 32-bit values (bit 31 is the most significant bit). Bit 29 is reserved for application-defined error codes; no Win32 API error code has this bit set. If you are defining an error code for your application, set this bit to indicate that the error code has been defined by the application and to ensure that your error code does not conflict with any system-defined error codes.

This function is intended primarily for dynamic-link libraries (DLL). Calling this function after an error occurs allows the DLL to emulate the behavior of the Win32 API.

Most Win32 functions call SetLastError when they fail. Function failure is typically indicated by a return value error code such as zero, NULL, or –1. Some functions call SetLastError under conditions of success; those cases are noted in each function's reference topic.

Applications can retrieve the value saved by this function by using the GetLastError function.

The last-error code is kept in thread local storage so that multiple threads do not overwrite each other's values.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Error Handling Overview, Error Handling Functions, GetLastError


Error Handling Structures

The following structure is used with error handling.

FLASHWINFO


FLASHWINFO

The FLASHWINFO structure contains the flash status for a window and the number of times the system should flash the window.

typedef struct {
  UINT  cbSize;
  HWND  hwnd;
  DWORD dwFlags;
  UINT  uCount;
  DWORD dwTimeout;
} FLASHWINFO, *PFLASHWINFO;

Members

cbSize
Specifies the size, in bytes, of the structure.
hwnd
Handle to the window to be flashed. The window can be either opened or minimized.
dwFlags
Specifies the flash status. This parameter can be one or more of the following values.
Value | Meaning
FLASHW_STOP | Stop flashing. The system restores the window to its original state.
FLASHW_CAPTION | Flash the window caption.
FLASHW_TRAY | Flash the taskbar button.
FLASHW_ALL | Flash both the window caption and taskbar button. This is equivalent to setting the FLASHW_CAPTION | FLASHW_TRAY flags.
FLASHW_TIMER | Flash continuously, until the FLASHW_STOP flag is set.
FLASHW_TIMERNOFG | Flash continuously until the window comes to the foreground.

uCount
Specifies the number of times to flash the window.
dwTimeout
Specifies the rate, in milliseconds, at which the window will be flashed. If dwTimeout is zero, the function uses the default cursor blink rate.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Error Handling Overview, Error Handling Structures, FlashWindowEx


Event Logging

Many applications record errors and events in various proprietary error logs. These proprietary error logs have different formats and display different user interfaces. Moreover, you cannot merge the data to provide a complete report. Therefore, you need to check a variety of sources to diagnose problems. Event logging in Microsoft® Windows NT®/Windows® 2000 provides a standard, centralized way for applications (and the operating system) to record important software and hardware events. The event-logging service stores events from various sources in a single collection called an event log. Windows NT/Windows 2000 also supplies Event Viewer for viewing the logs, and a programming interface for examining the logs.

  • About Event Logging
  • Using Event Logging
  • Event Logging Reference


About Event Logging

When an error occurs, the system administrator or support technicians must determine what caused the error, attempt to recover any lost data, and prevent the error from recurring. It is helpful if applications, the operating system, and other system services record important events such as low-memory conditions or excessive attempts to access a disk. Then the system administrator can use the event log to help determine what conditions caused the error and the context in which it occurred. By periodically viewing the event log, the system administrator may be able to identify problems (such as a failing hard drive) before they cause damage.

This overview contains the following topics, which discuss the programming interface for writing to and examining event logs:

  • Event types
  • Logging guidelines
  • Event logging elements
  • Event logging operations
  • Event logging model
  • Event logging security


Event Types

There are five types of events that can be logged. All event classifications have well-defined common data and can optionally include event-specific data. The application indicates the event type when it reports an event. Each event must be of a single type. The Event Viewer uses this type to determine which icon to display in the list view of the log.

The following table describes the event types used in event logging.

Event type | Description
Information | Information events indicate infrequent but significant successful operations. For example, when Microsoft® SQL Server™ successfully loads, it may be appropriate to log an information event stating that "SQL Server has started." Note that while this is appropriate behavior for major server services, it is generally inappropriate for a desktop application (Microsoft® Excel, for example) to log an event each time it starts.
Warning | Warning events indicate problems that are not immediately significant, but that may indicate conditions that could cause future problems. Resource consumption is a good candidate for a warning event. For example, an application can log a warning event if disk space is low. If an application can recover from an event without loss of functionality or data, it can generally classify the event as a warning event.
Error | Error events indicate significant problems that the user should know about. Error events usually indicate a loss of functionality or data. For example, if a service cannot be loaded as the system boots, it can log an error event.
Success audit | Success audit events are security events that occur when an audited access attempt is successful. For example, a successful logon attempt is a success audit event.
Failure audit | Failure audit events are security events that occur when an audited access attempt fails. For example, a failed attempt to open a file is a failure audit event.

Selected activities of users on can be tracked by auditing security events and then placing entries in a computer's security log. To determine the types of security events that will be logged for the computer, use User Manager. For more information, look up "auditing" in the online help provided with User Manager.


Logging Guidelines

Event logs store records of significant events on behalf of Windows NT/Windows 2000 and applications running on Windows NT/Windows 2000. Because the logging functions are general purpose, you must decide what information is appropriate to log. Generally, you should log only information that could be useful in diagnosing a hardware or software problem. Event logging is not intended to be used as a tracing tool.

Choosing Events to Log

The following are examples of cases in which event logging can be helpful:

  • Resource problems. If an application gets into a low-memory situation (caused by a code bug or inadequate memory) that degrades performance, logging a warning event when memory allocation fails might provide a clue about what went wrong.
  • Hardware problems. If a device driver encounters a disk controller time-out, a power failure in a parallel port, or a data error from a network or serial card, logging information about these events can help the system administrator diagnose hardware problems. The device driver logs the error.
  • Bad sectors. If a disk driver encounters a bad sector, it may be able to read from or write to the sector after retrying the operation, but the sector will go bad eventually. Therefore, if the disk driver can proceed, it should log a warning; otherwise, it should log an error event. If a file system driver finds a large number of bad sectors, fixes them, and logs warning events, logging information of this type might indicate that the disk is about to fail.
  • Information events. A server application (such as a database server) records a user logging on, opening a database, or starting a file transfer. The server can also log error events it encounters (cannot access file, host process disconnected, and so on), a corruption in the database, or whether a file transfer was successful.

Writing Messages

Remember that your audience is administrators and users who are trying to troubleshoot the problem. A message should contain all information needed to interpret what caused the problem and what to do to correct the problem. Avoid writing a cryptic message like the following:

A driver packet received from the I/O subsystem was invalid.
The data is the packet.

A better message would indicate that the driver in question is functioning properly, but is logging incorrectly formatted packets. It would go on to say that a Unicode version of the driver is needed to correct the problem. For more information, see Error Message Guidelines.

Do not use tabs or commas in the message text. Event logfiles can be saved as comma or tab separated text files. Many organizations import these files into databases and the extra formatting characters require manual manipulation.

When using UNC names, or other links which contain spaces, enclose the name in angle brackets. For example, <\\sharename\servername>.

Windows 2000 or later: You can write a URL to the end of the message that points the user to related help material. The URL must be a full-qualified DNS host name. For example, you could append the following text to your messages:

For additional information on this message, please visit our support site at http://www.microsoft.com/Support/ProdRedirect/ContentSearch.asp.

The page should be an ASP page that redirects the user to the exact content that relates to the messages. It must parse additional parameters that are passed when the URL is clicked to determine where to redirect the user.

From the arguments passed to the ReportEvent function:

  • Event source
  • Event ID
  • Event category

From the message DLL header for the event source:

  • Company name
  • Product name
  • Product version
  • File version

Reducing Overhead

Event logging consumes resources such as disk space and processor time. The amount of disk space that an event log requires and the overhead for an application that logs events depend on how much information you choose to log. This is why it is important to log only essential information. It is also good to place event logging calls in an error path in the code rather than in the main code path, which would reduce performance.

The amount of disk space required per event log record includes the members of the EVENTLOGRECORD structure. This is a variable length structure; strings and binary data are stored following the structure.


Event Logging Elements

The following are the major elements used in event logging:

  • Logfiles
  • Event sources
  • Event categories
  • Event identifiers
  • Message files
  • Event data


Logfiles

The event-logging service uses the information stored in the EventLog registry key. The EventLog key (shown in the following example) contains several subkeys, called logfiles. Logfile registry information is used to locate resources that the event logging service needs when an application writes to and reads from the event log. The default logfiles are Application, Security, and System. The structure is as follows:

HKEY_LOCAL_MACHINE
SYSTEM
CurrentControlSet
Services
EventLog
Application
Security
System

Applications and services use the Application logfile. Device drivers use the System logfile. The system will generate success and failure audit events in the Security log when auditing is turned on. For more information about auditing security events, see the documentation for User Manager.


Event Sources

Each logfile can contain subkeys called event sources. The event source is the name of the software that logs the event. It is often the name of the application, or the name of a subcomponent of the application, if the application is large. Applications and services should add their names to the Application logfile. Device drivers should add their names to the System logfile. The structure is as follows:

HKEY_LOCAL_MACHINE
SYSTEM
CurrentControlSet
Services
EventLog
Application
AppName
Security
System
DriverName

The application provides its name when it opens the event log using the RegisterEventSource function. You cannot use a source name that has already been used as a logfile name. In addition, source names cannot be hierarchical (that is, you cannot use the backslash character [\]).

Each event source contains information specific to the software that will be logging the events, such as the message files, as shown in the following table.

Registry Value | Description
CategoryCount | Specifies the number of event categories supported. This value has the type REG_DWORD.
CategoryMessageFile | Specifies the path for the category message file. A category message file contains language-dependent strings that describe the categories. This value has the type REG_EXPAND_SZ.
DisplayNameFile | Windows 2000 or later: Specifies the file that stores the localized name of the event log. The name stored in the specified file appears as the log name in Event Viewer. If this entry does not appear in the registry for an event log, Event Viewer displays the name of the registry subkey as the log name. This value has the type REG_EXPAND_SZ.
DisplayNameID | Windows 2000 or later: Specifies the message identification number of the log name string. This number indicates the message in which the localized display name appears. The message is stored in the file specified by the DisplayNameFile value. This value has the type REG_DWORD.
EventMessageFile | Specifies the path for the event message file. You can list multiple files, separated by semicolons. An event message file contains language-dependent strings that describe the events. This value has the type REG_EXPAND_SZ.
ParameterMessageFile | Specifies the path for the parameter message file. A parameter message file contains language-independent strings that are to be inserted into the event description strings. This value has the type REG_EXPAND_SZ.
TypesSupported | Specifies a bitmask of supported types. This value has the type REG_DWORD. It can be one or more of the following values: EVENTLOG_ERROR_TYPE EVENTLOG_WARNING_TYPE EVENTLOG_INFORMATION_TYPE EVENTLOG_AUDIT_SUCCESS EVENTLOG_AUDIT_FAILURE

When an application uses the RegisterEventSource or OpenEventLog function to get a handle to an event log, the event-logging service searches for the specified event source in the registry. For example, the Application logfile might contain event sources for Microsoft SQL Server and Microsoft Excel. If an application uses RegisterEventSource or OpenEventLog with a source name of Application, SQL, or Excel, the event-logging service returns a handle to the Application logfile.

An application can use the Application event log without adding a new event source to the registry. If the application calls RegisterEventSource, passing a source name that cannot be found in the registry, the event-logging service uses the Application logfile by default. However, because there are no message files, the Event Viewer cannot map any event identifiers or event categories to a description string, and will display an error. For this reason, you should add a unique event source to the registry for your application and specify a message file.


Event Categories

Categories help you organize events so Event Viewer can filter them. Each event source can define its own numbered categories and the text strings to which they are mapped. The categories must be numbered consecutively beginning with the number 1. For example, the security system uses the following categories:

  • Logon/logoff
  • File system access
  • Privileged actions
  • Change in security policy


Event Identifiers

Event identifiers uniquely identify a particular event. Each event source can define its own numbered events and the description strings to which they are mapped. Event viewers can present these strings to the user. They should help the user understand what went wrong and suggest what actions to take. Direct the description at users solving their own problems, not at administrators or support technicians. Make the description clear and concise and avoid culture-specific phrases.

The following sections discuss these description strings, and the insertion strings that serve as placeholders in the description strings.

Description Strings

The description strings in the event message file are indexed by event identifier, enabling Event Viewer to display event-specific text for any event based on the event identifier. All descriptions are localized and language dependent. The description strings may contain insertion string placeholders, of the form %n, where %1 indicates the first insertion string, and so on. For example, the following is a sample entry in the .MC file:

MessageId=0x4
Severity=Error
Facility=System
SymbolicName=MSG_CMD_DELETE
Language=English
File %1 contains %2, which is in error.

In this case, the buffer returned by ReadEventLog contains insertion strings. The NumStrings member of the EVENTLOGRECORD structure indicates the number of insertion strings. The StringOffset member of the EVENTLOGRECORD structure indicates the location of the first insertion string in the buffer.

The description string can also contain placeholders for parameter strings from the parameter message file. The placeholders are of the form %%n, where %%1 is replaced by the parameter string with the identifier of 1, and so on. In this case, the event viewer uses LoadLibraryEx and FormatMessage to retrieve the insertion string from the file indicated by the source's ParameterMessageFile registry value.

Insertion Strings

Insertion strings are optional language-independent strings used to fill in values for placeholders in description strings. Because the strings are not localized, it is critical that these placeholders be used only to represent language-independent strings such as numeric values, file names, user names, and so on. The string length must not exceed 32 kilobytes – 1 characters.

It is not acceptable to use several strings to create a larger description. The insertion string should be treated as data, not text. For example, the following example is not recommended:

LPSTR pszString1 = "successfully";
LPSTR pszString2 = "not";
LPSTR pszDescription = "The user was %1 added to the database.";

It is not acceptable to use pszString1 and pszString2 to form the strings "The user was successfully added to the database." and "The user was not added to the database." There are three reasons this substitution is not effective:

  • The strings "successfully" and "not" should be localized.
  • Even if the description strings are obtained from language-dependent message files, this is done when the event is logged, not when it is viewed. When the event is viewed, the language may be wrong.
  • Such substitutions of adverbs and adjectives will not work in many other languages. The preceding example should use two separate events, each with its own description string.

In the following example, it is appropriate to use either pszString1 or pszString2 for the insertion string in pszDescription.

LPSTR pszString1 = "c:\\testapp1.c";
LPSTR pszString2 = "c:\\testapp2.c";
LPSTR pszDescription = "Access denied. Attempted to open the file %1."


Message Files

Each event sources should register message files that contain description strings for each event identifier, event category, and parameter. Register these files in the EventMessageFile, CategoryMessageFile, and ParameterMessageFile registry values for the event source. You can create one message file that contains descriptions for the event identifiers, categories, and parameters, or create three separate message files. Several applications can share the same message file.

You should typically create message files as resource-only DLLs. They are smaller and faster than ordinary DLLs. Use the following procedure to create these DLLs.

To create a message file

  1. Create an .MC file to define the message resource table. For more information, see Message Compiler.
  2. Use the message compiler to create .RC and .BIN files from the .MC file. Use the following command:
    mc filename.mc.
  3. Use the resource compiler to create a .RES file. Use the following command:
    rc -r -fo filename.res filename.rc.
  4. Use the linker to create a .DLL file. Use the following command line:
    link -dll -noentry -out:filename.dll filename.res.

To make it easier for the application to use your message file, create a header file that lists each event. For example, suppose you have defined the following message in your .MC file:

MessageId=0x4
Severity=Error
Facility=System
SymbolicName=MSG_CMD_DELETE
Language=English
File %1 contains %2, which is in error.

Your header file should contain the following code:

//
// MessageId: MSG_CMD_DELETE
// MessageText:
//  File %1 contains %2, which is in error.
//
#define MSG_CMD_DELETE                     ((DWORD)0xC0000004L)

Now the event-viewing application can use the following procedure to gain access to the description strings in the message file.

To obtain description strings

  1. Use the RegOpenKey function to open the event source.
  2. Use the RegQueryValueEx function to obtain the EventMessageFile value for the event source, which is the name of the event message DLL.
  3. Use the LoadLibraryEx function to load the event message DLL.
  4. Use the FormatMessage function to obtain the description from the DLL and add the insertion strings.


Event Data

Each event can have event-specific data associated with it. The Event Viewer does not interpret this data; it displays extra data only in a combined hexadecimal and text format. Use event-specific data sparingly, including it only if you are sure it will be useful to someone debugging the problem. For example, many network-related events include network control blocks (NCBs) as event-specific data.

When you use event-specific data, the last part of its description string should provide a note about the information provided as event-specific data. For example, the network software could provide a note such as: "(The NCB is the event data)." As a convention, use parentheses around such remarks, as indicated in this example.

You can also use event-specific data to store information the application can process independently of the Event Viewer. For example, you could write a viewer specifically for your events, or write a program that scans the logfile and makes reports that include information from the event-specific data.


Event Logging Operations

The OpenEventLog, OpenBackupEventLog, RegisterEventSource, DeregisterEventSource, and CloseEventLog functions open and close event log handles. Accessing the object through its handle provides an object-oriented model for the event-logging functions, as well as some performance gain when requesting multiple operations on the logs.

The following table shows the operations that can be performed on an open event log, and the corresponding function for each operation.

Operation | Function
Backup | BackupEventLog
Clear | ClearEventLog
Monitor | NotifyChangeEventLog
Query | GetOldestEventLogRecord, GetNumberOfEventLogRecords
Read | ReadEventLog
Write | ReportEvent

The OpenEventLog and ReportEvent functions take an optional server name as a parameter so the operations can be performed on the remote server. Use OpenEventLog for reading or performing administrative operations (backup, clear, monitor, and query) on the log, and use RegisterEventSource for writing to the log.

Each call to an event logging function is an atomic operation. When you read from the event log, only whole event records are returned. When you write to the event log, each event record is guaranteed to be written sequentially as a complete record in the log. The following list describes how the event-logging service handles special conditions:

  • The event-logging service receives a read operation and a write operation at the same time. If the read position is at the end of the file, either the read operation fails with an "end-of-file" status (if the write operation has not been completed), or it returns the new record (if the write operation has been completed).
  • The event-logging service completes a clear operation before receiving a read operation. The read operation fails with "end-of-file" status.
  • The event-logging service completes a clear operation before receiving a write operation. The clear operation truncates the log, then the write operation adds the new record at the beginning of the log.


Event Logging Model

The following sections describe the processes that form the event-logging model:

  • Writing to the Event Log
  • Reading from the Event Log
  • Viewing the Event Log


Writing to the Event Log

When an application calls the ReportEvent function to write an entry to the log, the system passes the parameters to the event-logging service. The event-logging service uses the information to write an EVENTLOGRECORD structure to the event log. The following diagram illustrates this process.


Reading from the Event Log

An event viewer application uses the OpenEventLog function to open the event log for an event source. The event viewer can then use the ReadEventLog function to read event records from the log. ReadEventLog returns a buffer containing an EVENTLOGRECORD structure and additional information that describes a logged event. The following diagram illustrates this process.


Viewing the Event Log

When the user starts Event Viewer to view the event log entries, it calls the ReadEventLog function to obtain the EVENTLOGRECORD structures. The Event Viewer uses the event source and event identifier to get message text for each event from the registered message file (indicated by the EventMessageFile registry value for the source). The Event Viewer uses the LoadLibraryEx function to load the message file. The Event Viewer then uses the FormatMessage function to retrieve the description string from the loaded module.

The following illustration shows how the Windows 2000 Event Viewer presents this information.

If the user double-clicks on an event log entry, Event Viewer displays more information, as shown in the following illustration.


Event Logging Security

Access to the event logs is determined by the account under which the application is running. The LocalSystem account is a special account that service applications can use. The Administrator account consists of the administrators for the system. The Server Operator account (ServerOp) consists of the administrators of the domain server. The World account includes all users on all systems.

The following table shows which accounts are granted read, write, and clear access to each log.

Log | Account | Access |  |
Application | LocalSystem | Read | Write | Clear
 | Administrator | Read | Write | Clear
 | ServerOp | Read | Write | Clear
 | World | Read | Write |
Security | LocalSystem | Read | Write | Clear
 | Administrator | Read |  | Clear
 | World |  |  |
System | LocalSystem | Read | Write | Clear
 | Administrator | Read | Write | Clear
 | ServerOp | Read |  | Clear
 | World | Read |  |

In addition, users can read and clear the Security log if they have been granted one of the following:

  • The "manage auditing and security log" user right. Use the User Manager. Click the Policies menu, then click User Rights.
  • The SE_AUDIT_NAME privilege. For more information, see Windows NT Privileges.

The following table shows which types of access are required for the event logging functions.

Function | Access Required
OpenEventLog | Read
OpenBackupEventLog | Read
RegisterEventSource | Write
ClearEventLog | Clear

As an example, OpenEventLog requires read access. A member of the ServerOp account can call OpenEventLog for the Application event log and the System event log, because ServerOp has read access for both of these logs. However, a member of the ServerOp account cannot call OpenEventLog for the Security log, because it does not have read access for this log.

Access to the Application event log is restricted. To grant access to the members of the Guests account, change the following registry entry from 1 (the default) to 0:

HKEY_LOCAL_MACHINE
SYSTEM
CurrentControlSet
Services
EventLog
Application
RestrictGuestAccess


Using Event Logging

You can use the Registry Editor (REGEDT32.EXE) to view the event log registry keys, and you can use the Event Viewer to view the event logs. To create event log entries, use the event logging functions as shown in the following topics:

  • Adding a source to the registry
  • Reporting an event
  • Querying the event log
  • Reading the event log
  • Displaying the user for an event
  • Displaying the local time for an event


Adding a Source to the Registry

You can use the default Application event log without adding an event source to the registry. However, Event Viewer will not be able to map your event identifier codes to message strings unless you register your event source and provide a message file.

You can add a new source name to the registry by opening a new registry subkey under the Application key using the RegCreateKey function, and adding registry values to the new subkey using the RegSetValueEx function. The following example opens a new source name called SamplApp and adds a message-file name and a bitmask of supported types.

void AddEventSource()
{
    HKEY hk;
    DWORD dwData;
    UCHAR szBuf[80];

    // Add your source name as a subkey under the Application
    // key in the EventLog registry key.

    if (RegCreateKey(HKEY_LOCAL_MACHINE,
            "SYSTEM\\CurrentControlSet\\Services\
            \\EventLog\\Application\\SamplApp", &hk))
        ErrorExit("Could not create the registry key.");

    // Set the name of the message file.

    strcpy(szBuf, "%SystemRoot%\\System\\SamplApp.dll");

    // Add the name to the EventMessageFile subkey.

    if (RegSetValueEx(hk,             // subkey handle
            "EventMessageFile",       // value name
            0,                        // must be zero
            REG_EXPAND_SZ,            // value type
            (LPBYTE) szBuf,           // pointer to value data
            strlen(szBuf) + 1))       // length of value data
        ErrorExit("Could not set the event message file.");

    // Set the supported event types in the TypesSupported subkey.

    dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE |
        EVENTLOG_INFORMATION_TYPE;

    if (RegSetValueEx(hk,      // subkey handle
            "TypesSupported",  // value name
            0,                 // must be zero
            REG_DWORD,         // value type
            (LPBYTE) &dwData,  // pointer to value data
            sizeof(DWORD)))    // length of value data
        ErrorExit("Could not set the supported types.");

    RegCloseKey(hk);
}


Reporting an Event

After you have added a source name to the registry, use the RegisterEventSource function to get a handle to the Application event log. The following example obtains the handle and then adds an event to the log using the ReportEvent function.

void MyReportEvent(LPSTR szMsg)
{
    HANDLE h;

    h = RegisterEventSource(NULL,  // uses local computer
             "SamplApp");          // source name
    if (h == NULL)
        ErrorExit("Could not register the event source.");

    if (!ReportEvent(h,           // event log handle
            EVENTLOG_ERROR_TYPE,  // event type
            0,                    // category zero
            MSG_ERR_EXIST,        // event identifier
            NULL,                 // no user security identifier
            1,                    // one substitution string
            0,                    // no data
            (LPTSTR *) szMsg,     // pointer to string array
            NULL))                // pointer to data
        ErrorExit("Could not report the event.");

    DeregisterEventSource(h);
}

Recall that your header file contains the event identifiers. For this example, the following event identifier was used:

//
// MessageId: MSG_ERR_EXIST
// MessageText:
//  File %1 does not exist.
//
#define MSG_ERR_EXIST                         ((DWORD)0xC0000004L)


Querying the Event Log

If you want to find out how many event records are in the event log, use the GetNumberOfEventLogRecords function. The following example displays the number of event records in the Application event log and the System event log. It opens the logs using the OpenEventLog function and obtains the number of records using GetNumberOfEventLogRecords.

void DisplayEventCount()
{
    HANDLE h;
    DWORD cRecords;

    // Open the System log.

    h = OpenEventLog(NULL,  // uses local computer
             "System");     // source name
    if (h == NULL)
        ErrorExit("Could not open the System event log.");

    // Get the number of records in the System event log.

    if (!GetNumberOfEventLogRecords(h, &cRecords))
        ErrorExit("Could not get the number of records.");

    printf("There are %d records in the System event log.\n",
        cRecords);

    CloseEventLog(h);

    // Open the Application log.

    h = OpenEventLog(NULL,    // uses local computer
             "Application");  // source name
    if (h == NULL)
        ErrorExit("Could not open the Application event log.");

    // Get the number of records in the Application event log.

    if (!GetNumberOfEventLogRecords(h, &cRecords))
        ErrorExit("Could not get number of records.");

    printf("There are %d records in the Application event log.\n",
        cRecords);

    CloseEventLog(h);
}


Reading the Event Log

The following example reads all the records in the Application logfile and displays the event identifier, event type, and event source for each event log entry.

void DisplayEntries( )
{
    HANDLE h;
    EVENTLOGRECORD *pevlr;
    BYTE bBuffer[BUFFER_SIZE];
    DWORD dwRead, dwNeeded, cRecords, dwThisRecord = 0;

    // Open the Application event log.

    h = OpenEventLog( NULL,             // use local computer
             "Application");   // source name
    if (h == NULL)
        ErrorExit("Could not open the Application event log.");

    pevlr = (EVENTLOGRECORD *) &bBuffer;

    // Opening the event log positions the file pointer for this
    // handle at the beginning of the log. Read the records
    // sequentially until there are no more.

    while (ReadEventLog(h,                // event log handle
                EVENTLOG_FORWARDS_READ |  // reads forward
                EVENTLOG_SEQUENTIAL_READ, // sequential read
                0,            // ignored for sequential reads
                pevlr,        // pointer to buffer
                BUFFER_SIZE,  // size of buffer
                &dwRead,      // number of bytes read
                &dwNeeded))   // bytes in next record
    {
        while (dwRead > 0)
        {
            // Print the event identifier, type, and source name.
            // The source name is just past the end of the
            // formal structure.

            printf("%02d  Event ID: 0x%08X ",
                dwThisRecord++, pevlr->EventID);
            printf("EventType: %d Source: %s\n",
                pevlr->EventType, (LPSTR) ((LPBYTE) pevlr +
                sizeof(EVENTLOGRECORD)));

            dwRead -= pevlr->Length;
            pevlr = (EVENTLOGRECORD *)
                ((LPBYTE) pevlr + pevlr->Length);
        }

        pevlr = (EVENTLOGRECORD *) &bBuffer;
    }

    CloseEventLog(h);
}


Displaying the User For the Event

Platform SDK: Debugging and Error Handling

Displaying the User for an Event

The following example retrieves the name of the user for an event. The function parameters are a pointer to the EVENTLOGRECORD structure, a pointer to a buffer to receive the user name, and a pointer to the size of the allocated buffer. If the function succeeds, it returns TRUE; otherwise, it returns FALSE. To get extended error information, call GetLastError.

BOOL
GetEventUserName(EVENTLOGRECORD *pelr, LPSTR pszUser, LPDWORD pcbUser)
{
    PSID lpSid;
    char szName[256];
    char szDomain[256];
    SID_NAME_USE snu;
    DWORD dwLen;
    DWORD cbName = 256;
    DWORD cbDomain = 256;

    // Point to the SID.
    lpSid = (PSID)((LPBYTE) pelr + pelr->UserSidOffset);

    if (LookupAccountSid(NULL, lpSid, szName, &cbName, szDomain,
         &cbDomain, &snu))
    {
        // Determine whether the buffer is large enough.
        dwLen = lstrlen(lpszUser) + 1;

        if (dwLen > *lpcbUser)
        {
            SetLastError( ERROR_INSUFFICIENT_BUFFER );
            *lpcbUser = dwLen;
            return FALSE;
        }

        // Return the user's name.
        lstrcpy( lpszUser, szName );

    }
    else
    {
        // Use the error status from LookupAccountSid.
        return FALSE;
   }

    SetLastError(0);
    return TRUE;
}


Displaying the Local Time For the Event

Platform SDK: Debugging and Error Handling

Displaying the Local Time for an Event

The following example displays the time information for an event. The function parameter is a pointer to the EVENTLOGRECORD structure. The function has no return value.

void PrintTimeGenerated(EVENTLOGRECORD *pevlr)
{
    FILETIME FileTime, LocalFileTime;
    SYSTEMTIME SysTime;
    __int64 lgTemp;
    __int64 SecsTo1970 = 116444736000000000;

    lgTemp = Int32x32To64(pevlr->TimeGenerated,10000000) + SecsTo1970;

    FileTime.dwLowDateTime = (DWORD) lgTemp;
    FileTime.dwHighDateTime = (DWORD)(lgTemp >> 32);

    FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
    FileTimeToSystemTime(&LocalFileTime, &SysTime);

    printf("Time Generated: %02d/%02d/%02d   %02d:%02d:%02d\n",
        SysTime.wMonth,
        SysTime.wDay,
        SysTime.wYear,
        SysTime.wHour,
        SysTime.wMinute,
        SysTime.wSecond);
}


Event Logging Reference

The following elements are used with event logging:

  • Event Logging Functions
  • Event Logging Structures


Event Logging Functions

The following functions are used with event logging.

Function | Description
BackupEventLog | Saves the specified event log to a backup file.
ClearEventLog | Clears the specified event log, and optionally saves the current copy of the logfile to a backup file.
CloseEventLog | Closes a read handle to the specified event log.
DeregisterEventSource | Closes a write handle to the specified event log.
GetEventLogInformation | Retrieves information about the specified event log.
GetNumberOfEventLogRecords | Retrieves the number of records in the specified event log.
GetOldestEventLogRecord | Retrieves the absolute record number of the oldest record in the specified event log.
NotifyChangeEventLog | Enables an application to receive notification when an event is written to the specified event logfile.
OpenBackupEventLog | Opens a handle to a backup event log.
OpenEventLog | Opens a handle to an event log.
ReadEventLog | Reads a whole number of entries from the specified event log.
RegisterEventSource | Retrieves a registered handle to an event log.
ReportEvent | Writes an entry at the end of the specified event log.


BackupEventLog

The BackupEventLog function saves the specified event log to a backup file. The function does not clear the event log.

BOOL BackupEventLog(
  HANDLE hEventLog,          // handle to event log
  LPCTSTR lpBackupFileName   // name of backup file
);

Parameters

hEventLog
[in] Handle to the open event log. This handle is returned by the OpenEventLog or OpenBackupEventLog function.
lpBackupFileName
[in] Pointer to a null-terminated string that names the backup file.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The backup file cannot be written to a remote server because this function is implemented by a service running in the LocalSystem account, which does not have credentials on the remote machine. However, it is possible to write the file to a remote machine using a null session.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Event Logging Overview, Event Logging Functions, OpenBackupEventLog, OpenEventLog


ClearEventLog

The ClearEventLog function clears the specified event log, and optionally saves the current copy of the logfile to a backup file.

BOOL ClearEventLog(
  HANDLE hEventLog,          // handle to event log
  LPCTSTR lpBackupFileName   // name of backup file
);

Parameters

hEventLog
[in] Handle to the event log to be cleared. This handle is returned by the OpenEventLog function.
lpBackupFileName
[in] Pointer to the null-terminated string specifying the name of a file in which a current copy of the event logfile will be placed. If this file already exists, the function fails.

If the lpBackupFileName parameter is NULL, the current event logfile is not backed up.

Return Values

If the function succeeds, the return value is nonzero. The specified event log has been backed up (if lpBackupFileName is not NULL) and then cleared.

If the function fails, the return value is zero. To get extended error information, call GetLastError. The ClearEventLog function fails if the event log is empty or a file already exists with the same name as lpBackupFileName.

Remarks

After this function returns, any handles that reference the cleared event log cannot be used to read the log.

The ClearEventLog function is used to optionally back up an existing logfile of the module represented by hEventLog. The function backs up the logfile to another file, and then clears the existing logfile. The caller must have write permission for the path specified, and must also have permission to clear the current logfile.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Event Logging Overview, Event Logging Functions, OpenEventLog


CloseEventLog

The CloseEventLog function closes a read handle to the specified event log.

BOOL CloseEventLog(
  HANDLE hEventLog   // handle to event log
);

Parameters

hEventLog
[in/out] Handle to the event log to be closed. This handle is returned by the OpenEventLog or OpenBackupEventLog function.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

For example, see Reading the Event Log.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Advapi32.lib.

See Also

Event Logging Overview, Event Logging Functions, OpenEventLog


DeregisterEventSource

The DeregisterEventSource function closes a write handle to the specified event log.

BOOL DeregisterEventSource(
  HANDLE hEventLog   // handle to event log
);

Parameters

hEventLog
[in/out] Handle to the event log. This handle is returned by the RegisterEventSource function.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

For example, see Reporting an Event.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Advapi32.lib.

See Also

Event Logging Overview, Event Logging Functions, RegisterEventSource


GetEventLogInformation

The GetEventLogInformation function retrieves information about the specified event log.

BOOL GetEventLogInformation(
  HANDLE  hEventLog,      // handle to event log
  DWORD   dwInfoLevel,    // information to retrieve
  LPVOID  lpBuffer,       // buffer for read data
  DWORD   cbBufSize,      // size of buffer in bytes
  LPDWORD pcbBytesNeeded  // number of bytes needed
);

Parameters

hEventLog
[in] Handle to the event log. This handle is returned by the OpenEventLog or RegisterEventSource function.
dwInfoLevel
[in] Specifies the event log information to be returned. Use EVENTLOG_FULL_INFO to find out if the specified log is full. The lpBuffer parameter is a pointer to an EVENTLOG_FULL_INFORMATION structure.

Currently, no other information levels are defined.

lpBuffer
[out] Pointer to a buffer for the event log information. The format of this data depends on the value of the dwInfoLevel parameter.
cbBufSize
[in] Specifies the size, in bytes, of the buffer.
pcbBytesNeeded
[out] Pointer to a variable that receives the number of bytes required for the requested information, regardless of whether the function succeeds. This parameter can not be NULL.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Advapi32.lib.

See Also

Event Logging Overview, Event Logging Functions, EVENTLOG_FULL_INFORMATION OpenEventLog, RegisterEventSource


GetNumberOfEventLogRecords

The GetNumberOfEventLogRecords function retrieves the number of records in the specified event log.

BOOL GetNumberOfEventLogRecords(
  HANDLE hEventLog,        // handle to event log
  PDWORD NumberOfRecords   // buffer for number of records
);

Parameters

hEventLog
[in] Handle to the open event log. This handle is returned by the OpenEventLog or OpenBackupEventLog function.
NumberOfRecords
[out] Pointer to the buffer that receives the number of records in the specified event log.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

For example, see Querying the Event Log.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Advapi32.lib.

See Also

Event Logging Overview, Event Logging Functions, GetOldestEventLogRecord, OpenBackupEventLog, OpenEventLog


GetOldestEventLogRecord

The GetOldestEventLogRecord function retrieves the absolute record number of the oldest record in the specified event log.

BOOL GetOldestEventLogRecord(
  HANDLE hEventLog,     // handle to event log
  PDWORD OldestRecord   // buffer for number of records
);

Parameters

hEventLog
[in] Handle to the open event log. This handle is returned by the OpenEventLog or OpenBackupEventLog function.
OldestRecord
[out] Pointer to the buffer that receives the absolute record number of the oldest record in the specified event log.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Advapi32.lib.

See Also

Event Logging Overview, Event Logging Functions, GetNumberOfEventLogRecords, OpenBackupEventLog, OpenEventLog


NotifyChangeEventLog

The NotifyChangeEventLog function enables an application to receive notification when an event is written to the specified event logfile. When the event is written to the event logfile, the specified event object is set to the signaled state.

BOOL NotifyChangeEventLog(
  HANDLE hEventLog,  // handle to event log
  HANDLE hEvent      // handle to event object
);

Parameters

hEventLog
[in] Handle to an event logfile. This handle is returned by the OpenEventLog or OpenBackupEventLog function.
hEvent
[in] Handle to a manual-reset event object. Use the CreateEvent function to create the event object.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The NotifyChangeEventLog function does not work with remote handles. If the hEventLog parameter is the handle to an event log on a remote computer, NotifiyChangeEventLog returns zero, and GetLastError returns ERROR_INVALID_HANDLE.

When an event is written to the logfile specified by hEventLog, the system uses the PulseEvent function to set the event specified by the hEvent parameter to the signaled state. If the thread is not waiting on the event when the system calls PulseEvent, the thread will not receive the notification. Therefore, you should create a separate thread to wait for notifications.

Note that the system calls PulseEvent no more than once every five seconds. Therefore, even if more than one event log change occurs within a five-second interval, you will only receive one notification.

The system will continue to notify you of changes until you close the handle to the event log. To close the event log, use the CloseEventLog or DeregisterEventSource function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Advapi32.lib.

See Also

Event Logging Overview, Event Logging Functions, CloseEventLog, CreateEvent, DeregisterEventSource, OpenBackupEventLog, OpenEventLog


OpenBackupEventLog

The OpenBackupEventLog function opens a handle to a backup event log. This handle can be used with the BackupEventLog function.

HANDLE OpenBackupEventLog(
  LPCTSTR lpUNCServerName,  // backup file server name
  LPCTSTR lpFileName        // backup file name
);

Parameters

lpUNCServerName
[in] Pointer to a null-terminated string that specifies the Universal Naming Convention (UNC) name of the server on which this operation is to be performed. If this parameter is NULL, the operation is performed on the local computer.
lpFileName
[in] Pointer to a null-terminated string that specifies the name of the backup file.

Return Values

If the function succeeds, the return value is a handle to the backup event log.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The backup file cannot be written to a remote server because this function is implemented by a service running in the LocalSystem account, which does not have credentials on the remote machine. However, it is possible to write the file to a remote machine using a null session.

If the backup filename specifies a remote server, lpUNCServerName must be NULL.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Event Logging Overview, Event Logging Functions, BackupEventLog


OpenEventLog

The OpenEventLog function opens a handle to an event log.

HANDLE OpenEventLog(
  LPCTSTR lpUNCServerName,  // server name
  LPCTSTR lpSourceName      // file name
);

Parameters

lpUNCServerName
[in] Pointer to a null-terminated string that specifies the Universal Naming Convention (UNC) name of the server on which the event log is to be opened. If this parameter is NULL, the operation is performed on the local computer.
lpSourceName
[in] Pointer to a null-terminated string that specifies the name of the logfile that the returned handle will reference. This can be the Application, Security, or System logfile, or a custom registered logfile. If a custom registered logfile name cannot be found, the event logging service opens the Application logfile, however, there will be no associated message or category string file.

Return Values

If the function succeeds, the return value is the handle to an event log.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

To close the handle to the event log, use the CloseEventLog function.

For example, see Reading the Event Log.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Event Logging Overview, Event Logging Functions, ClearEventLog, CloseEventLog, GetNumberOfEventLogRecords, GetOldestEventLogRecord, ReadEventLog, ReportEvent


ReadEventLog

The ReadEventLog function reads a whole number of entries from the specified event log. The function can be used to read log entries in chronological or reverse chronological order.

BOOL ReadEventLog(
  HANDLE hEventLog,                // handle to event log
  DWORD dwReadFlags,               // how to read log
  DWORD dwRecordOffset,            // offset of first record
  LPVOID lpBuffer,                 // buffer for read data
  DWORD nNumberOfBytesToRead,      // bytes to read
  DWORD *pnBytesRead,              // number of bytes read
  DWORD *pnMinNumberOfBytesNeeded  // bytes required
);

Parameters

hEventLog
[in] Handle to the event log to read. This handle is returned by the OpenEventLog function.
dwReadFlags
[in] Specifies how the read operation is to proceed. This parameter must include one of the following values.
Value Meaning
EVENTLOG_SEEK_READ The read operation proceeds from the record specified by the dwRecordOffset parameter.

This flag cannot be used with EVENTLOG_SEQUENTIAL_READ.
EVENTLOG_SEQUENTIAL_READ The read operation proceeds sequentially from the last call to the ReadEventLog function using this handle.

This flag cannot be used with EVENTLOG_SEEK_READ.

If the buffer is large enough, more than one record can be read at the specified seek position; you must specify one of the following flags to indicate the direction for successive read operations.
Value Meaning
EVENTLOG_FORWARDS_READ The log is read in chronological order.

This flag cannot be used with EVENTLOG_BACKWARDS_READ.
EVENTLOG_BACKWARDS_READ The log is read in reverse chronological order.

This flag cannot be used with EVENTLOG_FORWARDS_READ.

dwRecordOffset
[in] Specifies the log-entry record number at which the read operation should start. This parameter is ignored unless dwReadFlags includes the EVENTLOG_SEEK_READ flag.
lpBuffer
[out] Pointer to a buffer for the data read from the event log. This parameter cannot be NULL, even if the nNumberOfBytesToRead parameter is zero.

The buffer will be filled with an EVENTLOGRECORD structure.

nNumberOfBytesToRead
[in] Specifies the size, in bytes, of the buffer. This function will read as many whole log entries as will fit in the buffer; the function will not return partial entries, even if there is room in the buffer.
pnBytesRead
[out] Pointer to a variable that receives the number of bytes read by the function.
pnMinNumberOfBytesNeeded
[out] Pointer to a variable that receives the number of bytes required for the next log entry. This count is valid only if ReadEventLog returns zero and GetLastError returns ERROR_INSUFFICIENT_BUFFER.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

When this function returns successfully, the read position in the error log is adjusted by the number of records read. Only a whole number of event log records will be returned.

Note The configured filename for this source may also be the configured filename for other sources (several sources can exist as subkeys under a single logfile). Therefore, this function may return events that were logged by more than one source.

For example, see Reading the Event Log.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Event Logging Overview, Event Logging Functions, ClearEventLog, CloseEventLog, EVENTLOGRECORD, OpenEventLog, ReportEvent


RegisterEventSource

The RegisterEventSource function retrieves a registered handle to an event log.

HANDLE RegisterEventSource(
  LPCTSTR lpUNCServerName,  // server name
  LPCTSTR lpSourceName      // source name
);

Parameters

lpUNCServerName
[in] Pointer to a null-terminated string that specifies the Universal Naming Convention (UNC) name of the server on which this operation is to be performed. If this parameter is NULL, the operation is performed on the local computer.
lpSourceName
[in] Pointer to a null-terminated string that specifies the name of the source referenced by the returned handle. The source name must be a subkey of a logfile entry under the EventLog key in the registry. For example, WinApp is a valid source name if the registry has the following key:

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Event
Log\Application\WinApp

For more information, see Event Sources.

Return Values

If the function succeeds, the return value is a handle that can be used with the ReportEvent function.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

If the source name cannot be found, the event logging service uses the Application logfile; it does not create a new source. Events are reported for the source, however, there are no message and category message files specified for looking up descriptions of the event identifiers for the source.

To close the handle to the event log, use the DeregisterEventSource function.

For example, see Reporting an Event.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Event Logging Overview, Event Logging Functions, DeregisterEventSource, ReportEvent


ReportEvent

The ReportEvent function writes an entry at the end of the specified event log.

BOOL ReportEvent(
  HANDLE hEventLog,    // handle to event log
  WORD wType,          // event type
  WORD wCategory,      // event category
  DWORD dwEventID,     // event identifier
  PSID lpUserSid,      // user security identifier
  WORD wNumStrings,    // number of strings to merge
  DWORD dwDataSize,    // size of binary data
  LPCTSTR *lpStrings,  // array of strings to merge
  LPVOID lpRawData     // binary data buffer
);

Parameters

hEventLog
[in] Handle to the event log. This handle is returned by the RegisterEventSource function.
wType
[in] Specifies the type of event being logged. This parameter can be one of the following values.
Value | Meaning
EVENTLOG_SUCCESS | Success event
EVENTLOG_ERROR_TYPE | Error event
EVENTLOG_WARNING_TYPE | Warning event
EVENTLOG_INFORMATION_TYPE | Information event
EVENTLOG_AUDIT_SUCCESS | Success audit event
EVENTLOG_AUDIT_FAILURE | Failure audit event

For more information about event types, see Event Types.

wCategory
[in] Specifies the event category. This is source-specific information; the category can have any value.
dwEventID
[in] Specifies the event. The event identifier specifies the message that goes with this event as an entry in the message file associated with the event source.
lpUserSid
[in] Pointer to the current user's security identifier. This parameter can be NULL if the security identifier is not required.
wNumStrings
[in] Specifies the number of strings in the array pointed to by the lpStrings parameter. A value of zero indicates that no strings are present.
dwDataSize
[in] Specifies the number of bytes of event-specific raw (binary) data to write to the log. If this parameter is zero, no event-specific data is present.
lpStrings
[in] Pointer to a buffer containing an array of null-terminated strings that are merged into the message from the message file before Event Viewer displays the string to the user. This parameter must be a valid pointer (or NULL), even if wNumStrings is zero. Each string has a limit of 32K characters.
lpRawData
[in] Pointer to the buffer containing the binary data. This parameter must be a valid pointer (or NULL), even if the dwDataSize parameter is zero.

Return Values

If the function succeeds, the return value is nonzero, indicating that the entry was written to the log.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

This function is used to log an event. The entry is written to the end of the configured logfile for the source identified by the hEventLog parameter. The ReportEvent function adds the time, the entry's length, and the offsets before storing the entry in the log. To enable the function to add the username, you must supply the user's SID in the lpUserSid parameter.

For example, see Reporting an Event.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Event Logging Overview, Event Logging Functions, ClearEventLog, CloseEventLog, OpenEventLog, ReadEventLog, RegisterEventSource


Event Logging Structures

The following structures are used with event logging.

EVENTLOG_FULL_INFORMATION
EVENTLOGRECORD


EVENTLOG_FULL_INFORMATION

The EVENTLOG_FULL_INFORMATION structure indicates whether the event log is full.

typedef struct _EVENTLOG_FULL_INFORMATION {
  DWORD    dwFull;
} EVENTLOG_FULL_INFORMATION, *LPEVENTLOG_FULL_INFORMATION;

Members

dwFull
Indicates whether the event log is full. If the log is full, this member is TRUE. Otherwise, it is FALSE.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.

See Also

Event Logging Overview, Event Logging Structures, GetEventLogInformation


EVENTLOGRECORD

The EVENTLOGRECORD structure contains information about an event record returned by the ReadEventLog function.

typedef struct _EVENTLOGRECORD {
  DWORD  Length;
  DWORD  Reserved;
  DWORD  RecordNumber;
  DWORD  TimeGenerated;
  DWORD  TimeWritten;
  DWORD  EventID;
  WORD   EventType;
  WORD   NumStrings;
  WORD   EventCategory;
  WORD   ReservedFlags;
  DWORD  ClosingRecordNumber;
  DWORD  StringOffset;
  DWORD  UserSidLength;
  DWORD  UserSidOffset;
  DWORD  DataLength;
  DWORD  DataOffset;
  //
  // Then follow:
  //
  // TCHAR SourceName[]
  // TCHAR Computername[]
  // SID   UserSid
  // TCHAR Strings[]
  // BYTE  Data[]
  // CHAR  Pad[]
  // DWORD Length;
  //
} EVENTLOGRECORD, *PEVENTLOGRECORD;

Members

Length
Specifies the length, in bytes, of this event record. Note that this value is stored at both ends of the entry to ease moving forward or backward through the log. The length includes any pad bytes inserted at the end of the record for DWORD alignment.
Reserved
Reserved.
RecordNumber
Contains a record number that can be used with the EVENTLOG_SEEK_READ flag passed in a call to the ReadEventLog function to begin reading at a specified record.
TimeGenerated
The time at which this entry was submitted. This time is measured in the number of seconds elapsed since 00:00:00 January 1, 1970, Universal Coordinated Time.
TimeWritten
Specifies the time at which this entry was received by the service to be written to the logfile. This time is measured in the number of seconds elapsed since 00:00:00 January 1, 1970, Universal Coordinated Time.
EventID
Specifies the event. This is specific to the source that generated the event log entry, and is used, together with SourceName, to identify a message in a message file that is presented to the user while viewing the log.
EventType
Specifies the type of event. This member can be one of the following values.
Value | Meaning
EVENTLOG_ERROR_TYPE | Error event
EVENTLOG_WARNING_TYPE | Warning event
EVENTLOG_INFORMATION_TYPE | Information event
EVENTLOG_AUDIT_SUCCESS | Success Audit event
EVENTLOG_AUDIT_FAILURE | Failure Audit event

For more information, see Event Types.

NumStrings
Specifies the number of strings present in the log (at the position indicated by StringOffset). These strings are merged into the message before it is displayed to the user.
EventCategory
Specifies a subcategory for this event. This subcategory is source specific.
ReservedFlags
Reserved.
ClosingRecordNumber
Reserved.
StringOffset
Specifies the offset of the strings within this event log entry.
UserSidLength
Specifies the length, in bytes, of the UserSid member. This value can be zero if no security identifier was provided.
UserSidOffset
Specifies the offset of the security identifier (SID) within this event record. To obtain the user name for this SID, use the LookupAccountSid function.
DataLength
Specifies the length, in bytes, of the event-specific data (at the position indicated by DataOffset).
DataOffset
Specifies the offset of the event-specific information within this event record. This information could be something specific (a disk driver might log the number of retries, for example), followed by binary information specific to the event being logged and to the source that generated the entry.
SourceName
Contains the variable-length null-terminated string specifying the name of the source (application, service, driver, subsystem) that generated the entry. This is the name used to retrieve from the registry the name of the file containing the message strings for this source. It is used, together with the event identifier, to get the message string that describes this event.
Computername
Contains the variable-length null-terminated string specifying the name of the computer that generated this event. There may also be some pad bytes after this field to ensure that the UserSid is aligned on a DWORD boundary.
UserSid
Specifies the security identifier of the active user at the time this event was logged. This member may be empty if the UserSidLength member is zero.

Remarks

The defined members are followed by the replacement strings for the message identified by the event identifier, the binary information, some pad bytes to make sure the full entry is on a DWORD boundary, and finally the length of the log entry again. Because the strings and the binary information can be of any length, no structure members are defined to reference them.

The event identifier together with SourceName and a language identifier identify a message string that describes the event in more detail. The strings are used as replacement strings and are merged into the message string to make a complete message. The message strings are contained in a message file specified in the source entry in the registry. To obtain the appropriate message string from the message file, load the message file with the LoadLibrary function and use the FormatMessage function.

The binary information is information that is specific to the event. It could be the contents of the processor registers when a device driver got an error, a dump of an invalid packet that was received from the network, a dump of all the structures in a program (when the data area was detected to be corrupt), and so on. This information should be useful to the writer of the device driver or the application in tracking down bugs or unauthorized breaks into the application.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winnt.h; include Windows.h.

See Also

Event Logging Overview, Event Logging Structures, LookupAccountSid, ReadEventLog


Event Tracing

Purpose

Developers can use event tracing to define, record, and track system activities, called events. Event tracing is extremely flexible and may be put to a variety of uses; however, its primary function is as a highly customizable tool for tracking system resources. This technology has been integrated into the Windows 2000 operating system in a way that allows maximum flexibility while using minimal system resources.

Where Applicable

Event tracing provides a mechanism for managing data that is useful to performance monitors, capacity planning tools, and other applications that analyze information relating to system resource utilization.

About Event Tracing

General information about event tracing.

Event Tracing API Reference

Documentation of event tracing structures and functions.

Feedback

Make error reports and feature requests directly to Microsoft.


About Event Tracing

Developers can use event tracing to define, record, and track system activities, called events. An event is any discrete activity that is of interest. Familiar events include low-level operating system activities, such as page faults and disk I/O. The software being developed will, in large part, determine what constitutes an event and how the Event Tracer is used in practice. As an example, when a server services a client's request, page faults and disk I/O may occur. From the viewpoint of the server software developer, the event may be defined to encompass anything that occurs while servicing the client's request, and may or may not include page faults and disk I/O.

The Event Tracer provides a way to track the resources that have been used while performing the activity that defines an event. Like an event, the definition of a resource is determined by the software context. Well-known resources include processors and I/O devices. For a server software developer, a context-dependent resource would be the number of connections that the server can maintain simultaneously.

The following topics discuss event tracing in Microsoft® Windows® 2000.

  • Event Tracer
  • Event Tracing with WMI
  • Access to Event Tracing
  • Globally Unique Identifiers and Event Tracing


Event Tracer

The Event Tracer is part of the Windows 2000 operating system kernel, and is responsible for implementing event tracing. The following topics describe the Event Tracer:

  • Event Traces and Event Trace Classes
  • Organizing Event Traces
  • Event Tracing Sessions
  • Event Tracer API


Event Traces and Event Trace Classes

While an event is a discrete activity that may or may not occur, an event trace is a collection of information about a specific event occurrence. All event traces contain context-independent information, such as the time the event occurred. Event traces may also contain context-dependent information, called event trace data, which is determined by the kind of event that occurred. Using client/server software as an example, one kind of event may include the activity that occurs when a client's request is serviced. There may also be a client authentication event which includes the activity that occurs when a client connects to the server. The event trace data for a service request would typically be different from the event trace data related to a connection attempt.

Each event trace must specify which kind of event has occurred. To accomplish this, event traces are divided into event trace classes. Each event trace class models an application-defined event and specifies the format of the event trace data contained in its traces. In other words, traces that belong to the same event trace class represent different occurrences of an event and contain the same event trace data. For example, traces generated each time a server receives a client's service request would belong to the same event trace class. The event trace data for each service request trace would contain the same fields (to hold the details specific to each service request). For additional information on event trace classes, see Event Tracing with WMI.


Organizing Event Traces

The Event Tracer allows events to be divided into subevents using event types and event trace instances. A subevent is an event that is also part of a larger event. Event types are useful for dividing an event into subevents that occur in a predictable order. The Event Tracer provides a set of predefined event types, and supports custom event types. When tracing an event that is organized into subevents, event types identify the processing stage the event has reached, and the meaning of the event trace data. For example, consider tracing a complex calculation event as a series of subevents. The first event trace has the "Start" event type, and its event trace data contains the initial values for the calculation. As each intermediate calculation completes, an event trace with the "Checkpoint" type is generated to record the intermediate results. When the calculation is finished, an "End" type event trace is generated with trace data containing the final results. For each of these subevent traces, the event trace data layout is defined by the event trace class, and the event trace data values are interpreted based on the event type in each trace. For an example that demonstrates using event types, see Tracing Events.

A transaction is a group of related activities, usually tracked for cost accounting purposes. A transaction typically involves multiple events executing in one or more threads. The events traced as work is done for a transaction are called event trace instances. They are used to calculate the resources consumed while completing a transaction. The Event Tracer API provides a function to create a unique transaction identifier to include in the data recorded for event trace instances generated by a transaction. The Event Tracer also supports parent/child relationships between event trace instances; the data recorded for an event trace instance may include identification information for a previously generated parent event. For an example that uses event trace instances, see Tracing Event Instances.


Event Tracing Sessions

Event traces are recorded by event tracing sessions, which are part of the Event Tracer and can be customized. The Event Tracer supports a maximum of 32 event tracing sessions executing simultaneously. Some of these sessions are reserved for special purposes; the remaining sessions are available for general use and fully customizable. For more information, see Reserved Event Tracing Sessions.

Each event tracing session maintains a set of buffers, called its buffer pool, where it temporarily stores event traces. The purpose of buffering is to minimize the resources used in forwarding event traces to their destination. To eliminate several buffer-related performance issues, buffers are allocated from non-paged memory, and at least two buffers are used for recording events and forwarding traces. In addition, on multiprocessor systems, each processor is allocated a separate active buffer to eliminate contention.

An event tracing session's buffers can be configured when the session is started, and can be changed during processing. Developers can specify the buffer size, the maximum and minimum number of buffers in the pool, the rate at which buffers will be flushed, and an amount of time to wait before freeing unused buffers. If the chosen configuration cannot support the throughput necessary for all event traces to be recorded, the event tracing session discards event traces. Each session keeps a record of the number of traces discarded.

When a session starts, it is given a set of property values which include the buffer-related values noted previously, and the delivery mode that the session will use. Event traces can be delivered in real-time or written to a log file stored on disk. If a log file is selected, the maximum size and log file configuration can be specified. Currently, the Event Tracer supports two log file configurations: sequential and circular. If the log file is sequential, event traces will be written to the file until it reaches the maximum size; any additional event traces will be discarded. If the log file is circular, event traces will be written until the maximum file size is reached and then the event traces at the beginning of the file will be replaced with incoming traces.


Reserved Event Tracing Sessions

Each system can support a maximum of 32 event tracing sessions, or loggers. Two of these are reserved for special purpose logging:

  • Global Logger
  • NT Kernel Logger

These sessions provide access to events that cannot be traced by regular event tracing sessions.

In Whistler, a third session has been reserved for internal use, leaving 29 sessions available for applications.

Global Logger

As part of the operating system kernel, the Event Tracer is loaded during the system boot process; however, the portion of the Event Tracer API responsible for starting event tracing sessions is not accessible until after the boot process is complete. This limitation, combined with the fact that traces must be sent to an executing event tracing session, poses an obstacle to tracing events that may occur before the system is fully operational, mainly device driver events. The solution to this problem is the Global Logger, a special event tracing session which can be configured and started using the system registry. When the appropriate registry entries are present, the Global Logger event tracing session is started early in the boot process, enabling device drivers to record event traces before the system is fully operational. After starting, the Global Logger behaves like a regular event tracing session.

Because the Event Tracer is optimized to have a minimal effect on system performance, it can also be used as a low-impact debugger, useful for troubleshooting timing-related problems in device drivers. For additional information on event tracing and device drivers, consult the documentation shipped with the Windows NT/2000 Device Driver Kit.

NT Kernel Logger

Most operating system events, also called kernel events, cannot be predicted or trapped by an application, even though these events may be an important part of the activity that defines an application event. The purpose of the NT Kernel Logger session is to record traces for a predefined set of kernel events. These traces are automatically generated by the operating system, and are the only event traces recorded by the NT Kernel Logger.

Starting and stopping the NT Kernel Logger, defining the set of operating system events to trace, and obtaining event traces are under the control of the software developer.


Private Logger

Collecting the data that is normally included in event traces requires transitions from user mode to kernel mode. Processes that do not require trace information from the system kernel can eliminate the overhead associated with kernel mode transitions by using a private logger to record traces. A private logger is a user-mode event tracing session, which runs in the same process as its event trace provider.

Private loggers, although less expensive, do have some limitations:

  • A private logger can only record traces for the threads of the process it is executing in; no other process may send traces to it.
  • There can be only one private logger per process.
  • Private loggers cannot be used with real-time event tracing.
  • Traces generated by a private logger do not include execution time for kernel mode versus user-mode instructions, or thread level detail of CPU time used.


Event Tracer API

The Event Tracer application programming interface (API) is a set of functions that developers can use to access and control all aspects of event tracing. Using the Event Tracer API, developers can manage event tracing sessions, generate event traces, and receive event traces. The Event Tracer API is divided into sections based on the functionality implemented:

  • Event Trace Controller
  • Event Trace Provider
  • Event Trace Consumer

Note Although the Event Tracer API is divided according to functionality, there is no restriction on how the roles are implemented by a software application. All may be filled by a single executable file or dynamic-link library, or the responsibilities of each role may be divided among different software elements.

Event Trace Controller

Event trace controllers start and stop event tracing sessions, manage buffer resources, and obtain execution statistics for sessions. Session statistics include the number of buffers used, the number of buffers delivered, the number of events and buffers lost, and the size and location of the log file, if applicable.

Event Trace Provider

The event trace provider section of the Event Tracer API is where event trace providers and classes are registered with the Event Tracer, and event traces and event trace instances are generated.

After registering to generate traces for one or more classes of events, an event trace provider can be enabled or disabled for an event tracing session. It is left to the provider to define its interpretation of being enabled or disabled. In general, if a provider has been enabled, it will generate event traces for the session to record, and while it is disabled, it will not.

Event Trace Consumer

Software that functions as an event trace consumer can select one or more event tracing sessions as the source of its event traces. Consumers can receive event traces stored in log files, or from sessions that deliver event traces in real-time. When processing event traces, a consumer can specify starting and ending times, and only events that occur in the specified time frame will be delivered to the consumer. A consumer can request events from multiple event tracing sessions simultaneously, and the Event Tracer will put the events into chronological order before delivering them to the consumer.

An event trace consumer can use three different types of event delivery:

  • Generic event delivery
  • Event class delivery
  • Buffer notification

Generic event delivery occurs every time an event trace is sent to the event trace consumer. Event class delivery occurs whenever a trace belonging to a specific event trace class is sent to the consumer. Event class delivery is independent of generic event delivery; either or both may be used by a consumer. The third type of delivery is buffer notification, which occurs once for each buffer of traces sent to the consumer. Using buffer notification, the consumer receives summary information about the set of traces in the buffer that has just been processed.


Event Tracing with WMI

Without WMI, event trace providers and consumers must devise a method for sharing information about event trace classes. To make event trace class descriptions publicly available, developers can describe a provider's event trace classes in Managed Object Format (MOF) syntax. If a MOF description file is specified during provider registration, the Event Tracer will add the event trace class descriptions to the Common Information Model (CIM) repository where consumers may access them. The following diagram illustrates this.

The MOF compiler and access to the CIM repository are available through the Windows Management Instrumentation (WMI) API.

In the CIM repository, under the root\wmi namespace, event traces and the event trace providers that generate them are described by classes derived from the EventTrace abstract class. An event trace provider class inherits a qualifier from EventTrace which is used to store its control GUID. Traces generated by a specific provider are described by event trace classes derived from the provider's class. Each event trace class is named for the underlying event that has occurred and also inherits a qualifier, where its trace GUID is stored.


Access to Event Tracing

By default, event tracing does not require any special access privileges. Event trace controllers, providers, and consumers have full access to event tracing sessions, and the traces that they record. Using the appropriate registry entries, access to event tracing sessions and traces can be restricted. For more information, see Restricting Access to Event Tracing Sessions.


Globally Unique Identifiers and Event Tracing

Globally unique identifiers are used by the Event Tracer to uniquely identify several event tracing elements. A globally unique identifier (GUID) is a 16-byte integer value that is guaranteed to be unique. The Platform SDK includes uuidgen, a utility that can be used to generate GUIDs, also known as universally unique identifiers (UUIDS). Uuidgen.exe is located in the \Bin subdirectory of the Platform SDK installation directory.

The following items are examples of how GUIDs are used in event tracing:

  • Event tracing sessions may be assigned a GUID (logger instance GUID)
  • Each event trace provider must be assigned its own GUID (control GUID)
  • Each event trace class must be assigned a GUID (trace GUID)

For more information on uuidgen, see Generating Interface UUIDs in the Remote Procedure Call (RPC) section of the Platform SDK.


Using Event Tracing

The following topics describe how to use the Event Tracer API.

Topic | Description
Controlling Event Tracing Sessions | Managing event tracing sessions.
Providing Event Traces | Defining the contents of event traces, registering an event trace provider, and generating traces.
Consuming Event Traces | Accessing event traces and implementing functions used for delivering traces to a consumer.
Using the NT Kernel Logger | Starting this special purpose event-tracing session, specifying which operating system events to trace, and accessing traces recorded by the NT Kernel Logger.
Using the Global Logger | Specifying the registry settings that start the Global Logger session.
Support Functions | Example implementations for support functions used in the examples. These support functions are included for completeness; they are neither required by nor part of the Event Tracer or its API.

The Event Tracer API functions, structures, and constants are defined in the files Evntrace.h, Wmistr.h, and Initguid.h, which ship with the Platform SDK. The GUIDs reserved for the NT Kernel Logger and the Global Logger are defined in Wmiguid.h, which ships with the Microsoft® Windows NT® Device Driver Kit. These elements are described in detail in Event Tracing API Reference.

Samples for Event Tracing are located in the Platform SDK installation directory under \Samples\Winbase\EventTrace.


Controlling Event Tracing Sessions

The event trace controller section of the Event Tracer API is responsible for managing event tracing sessions. The responsibilities of a controller include specifying buffer resources and event trace delivery methods when starting sessions. Controllers also manage stopping, updating, and querying event tracing sessions and may enable and disable event trace providers.

The following topics demonstrate event trace controller functionality:

  • Configuring an EVENT_TRACE_PROPERTIES Structure
  • Setting Buffer Properties
  • Starting an Event Tracing Session
  • Stopping an Event Tracing Session
  • Querying Event Tracing Sessions
  • Updating an Event Tracing Session
  • Enabling an Event Trace Provider


Configuring an EVENT_TRACE_PROPERTIES Structure

The EVENT_TRACE_PROPERTIES structure is a required argument to the event trace controller functions. It is used to set and retrieve values for the properties of an event tracing session.

The Event Tracer requires that an EVENT_TRACE_PROPERTIES structure be allocated from a single block in memory. Space allocated for strings must be adjacent to the other members of the structure, and pointers to those strings must be specified as offsets from the start of the structure's allocated memory. The following function allocates and initializes an EVENT_TRACE_PROPERTIES structure.

PEVENT_TRACE_PROPERTIES AllocSessionProperties()
{
  PEVENT_TRACE_PROPERTIES Properties;
  ULONG SizeNeeded;

  // Calculate the size needed to store the properties,
  // a LogFileName string, and LoggerName string.

  SizeNeeded = sizeof(EVENT_TRACE_PROPERTIES) +
  (2 * MAX_STRLEN * sizeof(WCHAR));
  Properties = (PEVENT_TRACE_PROPERTIES) LocalAlloc(LPTR,SizeNeeded);

  if (Properties == NULL)
  {
    SetLastError(ERROR_OUTOFMEMORY);
    return NULL;
  }
  // Set the location for the event tracing session name.
  // LoggerNameOffset is a relative address.
  Properties->LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES);

  // Set the log file name location.
  // LogFileNameOffset is a relative address.
  Properties->LogFileNameOffset = sizeof(EVENT_TRACE_PROPERTIES) +
    (MAX_STRLEN * sizeof(WCHAR));

  // Store the total number of bytes pointed to by Properties.
  Properties->Wnode.BufferSize = SizeNeeded;

  // The WNODE_HEADER is being used for Event Tracer-related information.
  Properties->Wnode.Flags = WNODE_FLAG_TRACED_GUID;

  return Properties;
}

This function returns the newly allocated and initialized structure, and is used in the examples given for Starting an Event Tracing Session, Stopping an Event Tracing Session, Querying Event Tracing Sessions, and Updating an Event Tracing Session.

MAX_STRLEN represents an application-defined string length limit.


Setting Buffer Properties

Event tracing sessions buffer traces as they are received from event trace providers. When a buffer is full, the session can flush it either by writing the traces to a log file or delivering them to event trace consumers in real time. If the session's buffers are filled faster than they can be flushed, new buffers are allocated and added to the session's buffer pool, up to the maximum number specified. Beyond this limit, the session discards incoming event traces until a buffer becomes available.

Event trace controllers can limit the resources a session allocates for its buffer pool by setting values in the appropriate members of an EVENT_TRACE_PROPERTIES structure, before passing the structure into the StartTrace, ControlTrace, or UpdateTrace functions. Set the members to zero to use the default values.

Use the QueryTrace function to determine the resources allocated and used by an executing session.

Determining Buffer Property Values

There is no straightforward way to determine the correct size or number of buffers for an event tracing session. Instead, these values should be determined empirically, by examining the number of events lost during test runs.

To determine the number of events lost by a session, examine the EventsLost member of an EVENT_TRACE_PROPERTIES structure, after calling the QueryTrace function.

Setting the Number of Buffers to Allocate

To set the minimum number of buffers to allocate, specify a value for the MinimumBuffers member of an EVENT_TRACE_PROPERTIES structure. On uniprocessor systems, the default minimum number of buffers allocated by each event tracing session is 2. On multiprocessor systems, the minimum number of buffers allocated by each session is equal to the number of processors plus 1. Allocating a separate buffer for each processor eliminates contention for a buffer among concurrently executing threads.

To set the maximum number of buffers to allocate, specify a value for the MaximumBuffers member of EVENT_TRACE_PROPERTIES.

To determine the number of buffers allocated by a session, examine the NumberOfBuffers member of EVENT_TRACE_PROPERTIES, after calling the QueryTrace function.

Setting the Buffer Size

To set the size of each buffer, specify a value for the Buffersize member of an EVENT_TRACE_PROPERTIES structure. Event tracing sessions use a multiple of the system-defined memory page size as the default buffer size. Use the GetSystemInfo function to determine the page size of the computer.

If an application expects a relatively low event rate, the buffer size should be set to the memory page size. If the event rate is expected to be relatively high, the application should specify a larger buffer size, and should increase the maximum number of buffers. The buffer size affects the rate at which buffers fill and must be flushed. Although a small buffer size requires less memory, it increases the rate at which buffers must be flushed. This is particularly important when the event traces are being written to a log file because writing to disk is a relatively slow operation.

Controlling Buffer Flushing

To set the time delay before buffers get scheduled to be flushed, specify a value for the FlushTimer member of an EVENT_TRACE_PROPERTIES structure.

Freeing Unused Buffers

Unused buffers are those that have not been accessed in the number of minutes specified by the AgeLimit member of an EVENT_TRACE_PROPERTIES structure. By default, unused buffers are removed from the buffer pool and freed after 15 minutes.

For information on obtaining current settings for buffer properties, see Querying Event Tracing Sessions.

For information on changing buffer settings, see Updating an Event Tracing Session.


Starting an Event Tracing Session

An event tracing session is started by calling the StartTrace function, which requires a pointer to a session handle, the name of the session, and an initialized EVENT_TRACE_PROPERTIES structure. The session name is case-sensitive, and duplicate session names are allowed. For the implementation of the AllocSessionProperties function which allocates and initializes EVENT_TRACE_PROPERTIES, see Configuring an EVENT_TRACE_PROPERTIES Structure.

The following example specifies a log file and settings for the session buffer resources, and starts the event tracing session. The log file name must not be in use by any other event tracing session.

#define MY_EVENT_TRACING_SESSION_NAME L"My Example Session"
#define MY_EVENT_TRACING_LOGFILE_NAME L"C:\\dev\\eventlog.etl"

TRACEHANDLE StartMySession()
{
  ULONG ret;
  PEVENT_TRACE_PROPERTIES Properties;
  TRACEHANDLE SessionHandle;

  Properties = AllocSessionProperties();
  if (Properties == NULL)
  {
    return((TRACEHANDLE) INVALID_HANDLE_VALUE);
  }
  // Deliver traces to a circular log file.
  Properties->LogFileMode |= EVENT_TRACE_FILE_MODE_CIRCULAR;

  // Circular log files should have a maximum size.
  Properties->MaximumFileSize = 20;

  // Store the name of the log file.
  wcscpy ((LPWSTR) ((char *)Properties +
    Properties->LogFileNameOffset), MY_EVENT_TRACING_LOGFILE_NAME);

  // Choose some buffer settings.
  Properties->BufferSize = 4;
  Properties->MinimumBuffers = 3;
  Properties->MaximumBuffers = 6;

  // Start the session.
  ret = StartTrace (&SessionHandle,
    MY_EVENT_TRACING_SESSION_NAME,
    Properties);

  LocalFree(Properties);

  if (ret!= ERROR_SUCCESS)
  {
    wprintf(L"StartTrace failed: %d\n", ret);
    SessionHandle = (TRACEHANDLE) INVALID_HANDLE_VALUE;
  }
  return SessionHandle;
}

If StartTrace is successful, SessionHandle contains the address of the session handle, and the LoggerNameOffset member of Properties contains the name of the session.


Stopping an Event Tracing Session

To stop an event tracing session, call the StopTrace function. The StopTrace function requires a valid event tracing session handle (obtained from an earlier call to the StartTrace function), or the name of a previously started session.

The StopTrace function requires an allocated and initialized EVENT_TRACE_PROPERTIES structure, which is used to return the final properties of the stopped session. For the implementation of the AllocSessionProperties function, which allocates and initializes EVENT_TRACE_PROPERTIES, see Configuring an EVENT_TRACE_PROPERTIES Structure.

The following example demonstrates stopping an event tracing session using a previously obtained session handle.

ULONG StopMySession(TRACEHANDLE MyHandle)
{
  ULONG ret;
  PEVENT_TRACE_PROPERTIES Properties;

  Properties = AllocSessionProperties();
  if (Properties == NULL)
  {
    return(ERROR_OUTOFMEMORY);
  }
  ret = StopTrace (MyHandle, NULL, Properties);
  if (ret == ERROR_SUCCESS)
  {
    wprintf(L"\n\n Stopped................\n");
    PrintSession(Properties);
  }
  LocalFree(Properties);
  return ret;
}

If StopTrace is successful, Properties is updated to reflect the final properties and run statistics for the event tracing session. The support function PrintSession is neither part of, nor required by the Event Tracer API. In this example, it is used to print the final information for the event tracing session.

Note If a session name is given for the second argument to StopTrace, the session handle must be set to NULL. Duplicate session names are allowed; the oldest session with the specified name is stopped.

An event tracing session can also be stopped using the ControlTrace function.


Querying Event Tracing Sessions

To retrieve information about multiple event-tracing sessions, call the QueryAllTraces function. The information returned by this function includes allocated resources and run statistics.

The first parameter for the QueryAllTraces function is an array of pointers to the EVENT_TRACE_PROPERTIES structures which holds the information about each session, and the second parameter is the number of elements in the array. The third parameter is used to return the number of event tracing sessions that are currently executing. This value may be less than or more than the number of elements in the array.

The following example demonstrates the use of QueryAllTraces.

#define MAX_SESSIONS 32

int QueryAll()
{
  ULONG ret;
  PEVENT_TRACE_PROPERTIES pSessions[MAX_SESSIONS];
  int numSessions = 0;
  int i;
  int SomeSessions = 4;

  // Allocate a Properties structure for each session.

  for (i= 0; i < SomeSessions; i++ )
  {
    pSessions[i] = AllocSessionProperties();
  }
  // Query all sessions - properties will be returned
  // for up to "SomeSessions" number of sessions.
  ret = QueryAllTraces(pSessions,
    (ULONG) SomeSessions,
    &numSessions);

  if (ret != ERROR_SUCCESS)
  {
    // Were there more sessions than space was allocated for?
    if (ret == ERROR_MORE_DATA)
    {
      wprintf(L"\n\nQueryAllTraces: %d of %d sessions\n",
        SomeSessions,
        numSessions);
      // Set the number of sessions to print.
      numSessions = SomeSessions;
    }
    else // A real error was returned.
    {
      wprintf(L"\n\nError querying all traces: %d\n",ret);
      numSessions = 0;
    }
  }
  else // Query was successful.
  {
    wprintf(L"\n\nQueryAllTraces retrieved %lu sessions\n",
      numSessions);
  }

  for (i=0; i< numSessions; i++)
  {
    PrintSession(pSessions[i]);
    wprintf(L"\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n");
  }
  // Free the memory allocated by AllocSessionProperties.
  for (i = 0; i< SomeSessions; i++)
  {
    LocalFree(pSessions[i]);
  }
  return numSessions;
}

If the call is successful, the EVENT_TRACE_PROPERTIES structures are updated to reflect the property values and run statistics for the event tracing sessions. For the implementation of the AllocSessionProperties function, which allocates and initializes EVENT_TRACE_PROPERTIES, see Configuring an EVENT_TRACE_PROPERTIES Structure.

The support function PrintSession, used in this example to print the information returned for each event tracing session, is neither part of, nor required by the Event Tracer API.

Use the QueryTrace or ControlTrace functions to retrieve information for a single event tracing session.


Updating an Event Tracing Session

Use the UpdateTrace function to update the properties of an event tracing session. The session is selected by passing either a session handle obtained from an earlier call to StartTrace, or a session name. The properties of the event tracing session are updated using the values specified in the EVENT_TRACE_PROPERTIES structure passed into the function call.

The following example shows how to update the event tracing session using the session name.

#define MY_EVENT_TRACING_SESSION_NAME L"My Example Session"

ULONG UpdateMySession(void)
{
  ULONG ret;
  PEVENT_TRACE_PROPERTIES Properties;

  Properties = AllocSessionProperties();
  if (Properties == NULL)
  {
     return(ERROR_OUTOFMEMORY);
  }
  // Turn on real-time delivery and increase the
  // maximum number of buffers.
  Properties->LogFileMode = EVENT_TRACE_REAL_TIME_MODE;
  Properties->MaximumBuffers =  17;

  ret = UpdateTrace ((TRACEHANDLE)NULL,
    MY_EVENT_TRACING_SESSION_NAME,
    Properties);

  if (ret == ERROR_SUCCESS)
  {
    wprintf(L"\n\n Updating...................\n");
    PrintSession(Properties);
  }
  LocalFree(Properties);
  return ret;
}

If the call is successful, the EVENT_TRACE_PROPERTIES structure is updated to reflect the property values and run statistics for the event tracing session. For the implementation of the AllocSessionProperties function, which allocates and initializes EVENT_TRACE_PROPERTIES, see Configuring an EVENT_TRACE_PROPERTIES Structure.

The support function PrintSession, used in this example to print the information returned for the updated event tracing session, is neither part of nor required by the Event Tracer API.

Note If a session name is given for the second argument to UpdateTrace, the session handle should be set to NULL. Duplicate session names are allowed; the oldest session with the specified name is updated.

Event tracing sessions may also be updated using the ControlTrace function.


Enabling an Event Trace Provider

After an event trace provider is registered to trace events, it may be notified to enable or disable tracing for a specific event tracing session. An event trace controller sends enable/disable notification to a provider using the EnableTrace function, which requires the provider's GUID and the handle of the session for which the provider is being enabled/disabled.

Before EnableTrace may be called for a provider, the provider must have previously registered using the RegisterTraceGuids function. During registration, the provider specifies the address of a callback function to handle enable/disable notifications. This callback function, ControlCallback, gets called whenever the provider's GUID is specified as the ControlGuid argument to EnableTrace, indicating that the provider is being enabled or disabled for a particular event tracing session.

The following example shows how to enable an event trace provider using a previously obtained session handle.

ULONG EnableProvider(TRACEHANDLE SessionHandle)
{
  ULONG ret;

  ret = EnableTrace (
    (ULONG)TRUE,    // True = Enable; FALSE = Disable.
    0,              // Flag - Use any way you care to.
    0,              // Level - Use any way you care to.
    &ControlGuid,   // The provider to enable.
    SessionHandle); // Session for which the provider is enabled.
  return ret;
}

To disable a provider, call the EnableTrace function as shown above, except specify FALSE as the first argument.

For information on implementing the callback function, see Implementing a ControlCallback Function.

For information on registering an event trace provider, see Registering to Provide Events.

For information on obtaining a session handle, see Starting an Event Tracing Session.


Providing Event Traces

The event trace provider section of the Event Tracer API is responsible for registering events, optionally describing events to WMI, implementing enable/disable functionality, and generating traces. The following topics cover each of these areas in detail:

  • Registering to Provide Events
  • Implementing a ControlCallback Function
  • Tracing Events
  • Tracing Event Instances
  • Storing Event Trace Information Using WMI


Registering to Provide Events

The RegisterTraceGuids function registers an event trace provider and associates the trace GUIDs of the event trace classes with the registered provider's control GUID.

This example demonstrates how to register an event trace provider and its event trace classes using RegisterTraceGuids. The GUIDs used in this example were obtained using the Uuidgen.exe program distributed with the Platform SDK. The DEFINE_GUID macro is defined in the Guiddef.h header file, shipped with the Platform SDK.

After obtaining a GUID, use the DEFINE_GUID macro to assign it a name. TransactionGuid is the name given to the trace GUID used in these examples:

DEFINE_GUID (
  TransactionGuid,
  0xf4dc272d,
  0x88dd,
  0x4472,
  0xa3, 0xb1, 0xcb, 0x6d, 0xa4, 0x86, 0xf0, 0xbe
  );

ControlGuid is the name given to the control GUID assigned to the example event trace provider.

DEFINE_GUID (
  ControlGuid,
  0xee0a7545,
  0x2fcb,
  0x47fe,
  0xb0, 0xb5, 0x86, 0x62, 0x5b, 0xc5, 0x64, 0xfe
);

Trace GUIDs are passed to the RegisterTraceGuids function using an array of TRACE_GUID_REGISTRATION structures. The trace GUID is stored in the Guid member of the structure and, if the function call is successful, a handle to the registered event trace class is returned in the RegHandle member.

The following statement declares and initializes the TRACE_GUID_REGISTRATION structure array used in this example.

TRACE_GUID_REGISTRATION TraceGuidReg[] =
{
  {
    (LPGUID) &TransactionGuid,
    NULL
  }
};

The following example shows how to register an event trace provider that generates traces for a single event trace class.

ULONG ProviderRegisterTraces()
{
  ULONG ret;

  ret = RegisterTraceGuids (
    (WMIDPREQUEST)ControlCallback, // Enable/disable function.
    NULL,                          // RequestContext parameter
    (LPGUID)&ControlGuid,          // Provider GUID
    1,                             // TraceGuidReg array size
    TraceGuidReg,                  // Array of TraceGuidReg structures
    NULL,                          // Optional WMI - MOFImagePath
    NULL,                          // Optional WMI - MOFResourceName
    &RegistrationHandle);          // Handle required to unregister.

  return ret;
}

In the above example, only one TRACE_GUID_REGISTRATION structure is passed to RegisterTraceGuids. In other words, only one class of event traces is generated by this provider.

The MofImagePath parameter specifies the path of the DLL or executable program that contains the resource named by the MofResourceName parameter. The MofResourceName parameter identifies the string resource containing the name of the binary MOF file that describes the event trace classes. These arguments can be set to NULL when the event trace provider and consumer use some other mechanism to share information about the event trace classes used by the provider. For more information on creating binary MOF files, see Storing Event Trace Information Using WMI.

If the registration is successful, RegistrationHandle contains a handle which must be supplied to the UnregisterTraceGuids function. Every registered provider must be unregistered using this function:

UnregisterTraceGuids(RegistrationHandle);

For information on how to implement the enable/disable function pointed to by a ControlCallback function, see Implementing a ControlCallback Function.


Implementing a ControlCallback Function

The ControlCallback function implementation is automatically called by the EnableTrace function to enable or disable an event trace provider. The ControlCallback function is specified as an argument to the RegisterTraceGuids function, used to register an event trace provider.

The following example demonstrates a typical ControlCallback function implementation.

ULONG WINAPI ControlCallback(
    WMIDPREQUESTCODE RequestCode,
    PVOID Context,
    ULONG *InOutBufferSize,
    PVOID Buffer
    )
{
  ULONG ret;
  TRACEHANDLE LoggerHandle;
  ULONG EnableFlags;
  UCHAR EnableLevel;

  ret = ERROR_SUCCESS;

  switch (RequestCode)
  {
    case WMI_ENABLE_EVENTS:  //Enable Provider.
        {
            TraceOnFlag = TRUE;
            LoggerHandle = GetTraceLoggerHandle(Buffer);
            EnableLevel = GetTraceEnableLevel(LoggerHandle);
            EnableFlags = GetTraceEnableFlags(LoggerHandle);
            wprintf(L"Tracing enabled for Level %u\nFlags %lu\n",
              EnableLevel, EnableFlags);
            break;
        }
        case WMI_DISABLE_EVENTS:  //Disable Provider.
        {
            TraceOnFlag = FALSE;
            break;
        }
        default:
        {
            ret = ERROR_INVALID_PARAMETER;
            break;
        }
    }
    return ret;
}

This ControlCallback function implementation sets a global variable TraceOnFlag, which is used to turn tracing on or off within the event trace provider. This flag is referenced in the Tracing Events example.

The ControlCallback function is called by the EnableTrace function, and can retrieve the session handle, EnableFlag, and EnableLevel values passed as arguments to EnableTrace. The EnableFlag and EnableLevel parameters may be used to encode application-defined information such as an event nesting level. For additional information, see GetTraceEnableFlags, GetTraceEnableLevel, and GetTraceLoggerHandle.


Tracing Events

After an event trace provider has been registered and enabled, it can generate traces by calling the TraceEvent function. Providers must use an EVENT_TRACE_HEADER structure to pass required information to TraceEvent. Most providers also append event-specific information to the EVENT_TRACE_HEADER.

Because events are defined by the software application, the provider developer decides when to generate event traces and what event-specific information is included in a trace. In the example that follows, the event is defined as the set of calculations that compute the average value for a group of random numbers. The event consists of three steps:

  1. Pick a random number (Count).
  2. Generate Count random numbers, and sum them.
  3. Compute the average value of the Count random numbers (Average).

Traces for this event contain two event-specific data values: Count and Average. The following structures are used to hold the event trace header and event-specific data:

typedef struct _myUserData {
  ULONG Count;
  ULONG Average;
} *PMYUSER_DATA, MYUSER_DATA;

typedef struct _myEvent {
  EVENT_TRACE_HEADER Header;
  MYUSER_DATA MyData;
} *PMYEVENT_TRACE, MYEVENT_TRACE;

A pointer to a MYEVENT_TRACE structure is passed to the TraceEvent function. Prior to calling TraceEvent, the event-specific data must be stored in MyData, and the required Header members must contain the following information:

  • The Size member must hold the total number of bytes to be recorded for the trace, including the EVENT_TRACE_HEADER structure.
  • Either the Guid member must contain the trace GUID assigned to the class that describes this trace, or the GuidPtr member must contain a pointer to the trace GUID. The trace GUID must have been registered previously using the RegisterTraceGuids function.
  • The Flags member must contain the WNODE_FLAG_TRACED_GUID flag. If the trace GUID is specified using the GuidPtr member, also add the WNODE_FLAG_USE_GUID_PTR flag.
ULONG ProvideEvents(TRACEHANDLE SessionHandle)
{
  int count;
  int total = 0;
  int i;
  ULONG ret;
  MYEVENT_TRACE EventTrace;

  // Size must include the header plus
  // context-specific information.
  EventTrace.Header.Size = sizeof(MYEVENT_TRACE);

  // Header.Guid must be set to a GUID that is
  // registered to this provider.
  EventTrace.Header.Guid = TransactionGuid;

  EventTrace.Header.Flags = WNODE_FLAG_TRACED_GUID;
  // Optionally set an event type in each trace to
  // break each event into subevents.
  //
  // The event begins with a "Start" type event trace,
  // followed by the calculations,
  // followed by an "End" type event trace.

  // START EVENT: How many calculations to
  // compute the average value for a set of random numbers?
  count = Random(100);

  // Set up "Start" event trace:
  EventTrace.Header.Class.Type =  EVENT_TRACE_TYPE_START;
  // Count tells how many calculations to do.
  EventTrace.MyData.Count = count;
  // Average is unused in "Start" type traces.
  EventTrace.MyData.Average = 0;

  // Send the "Start" event trace.
  TraceEvent(SessionHandle,(PEVENT_TRACE_HEADER) &EventTrace);

  // Do the calculations.
  for (i = 0; i< count; i++) {
    // The random function generates a "random" number.
    total += Random(10);

    // The Random function uses the current time.
    // Since nothing time-consuming occurs
    // in these events, sleep away some time.

    Sleep (100);
  }
  // Set up "End" event trace:
  EventTrace.Header.Class.Type =  EVENT_TRACE_TYPE_END;
  // Count tells how many random numbers were generated.
  EventTrace.MyData.Count = count;
  // Compute and store the average random number value.
  total /= count;
  EventTrace.MyData.Average = total;
  // Finished the example event.

  // Send the "End" event trace.
  ret = TraceEvent(SessionHandle,(PEVENT_TRACE_HEADER) &EventTrace);

  return ret;
}


Tracing Event Instances

As an alternative to tracing an event as a set of sequentially processed activities, you can use the TraceEventInstance function to track an event as it passes through multiple stages executing in one or more threads.

Note To use this functionality, the event trace provider must have registered previously (using the RegisterTraceGuids function), and the TRACE_GUID_REGISTRATION structures populated during registration must be available.

To follow a transaction as it progresses through a system, a transaction identifier must be obtained by calling the CreateTraceInstanceId function as follows:

EVENT_INSTANCE_INFO myInfo;
CreateTraceInstanceId (TraceGuidReg[0].RegHandle,&myInfo);

This function generates a unique transaction identifier, and maps it to a registered trace GUID handle. The handles for registered trace GUIDs are available in the RegHandle members of TRACE_GUID_REGISTRATION structures, after calling the RegisterTraceGuids function. The transaction identifier is placed in the InstanceId member of an EVENT_INSTANCE_INFO structure that you pass to the CreateTraceInstanceId function.

For information on registering a provider and obtaining a registered trace GUID handle, see Registering to Provide Events.

The following structure is used to hold the event trace instance data.

typedef struct _myEventInstance {
  EVENT_INSTANCE_HEADER Header;
  MYUSER_DATA MyData;
} *PMYEVENT_INSTANCE_TRACE, MYEVENT_INSTANCE_TRACE;

Use the TraceEventInstance function to generate traces of events that occur while completing a particular transaction.

  MYEVENT_INSTANCE_TRACE EventTrace;

  EventTrace.Header.Size = sizeof(MYEVENT_INSTANCE_TRACE);
  EventTrace.Header.Flags = WNODE_FLAG_TRACED_GUID;
  // Copy any event-specific data...
  // Generate the trace.

  TraceEventInstance (
    SessionHandle,
    (PEVENT_INSTANCE_HEADER) &EventTrace,
    &myInfo, // Populated by CreateTraceInstanceId.
    NULL);   // Optional Parent Event Instance Info.

The EVENT_INSTANCE_HEADER structure that is passed to the TraceEventInstance function is similar to the EVENT_TRACE_HEADER structure (see Tracing Events), except that it contains additional information relating to instances, and does not contain a Guid member.

Event instances can be used to establish a hierarchical relationship between events. The TraceEventInstance function accepts instance-specific information from two event instances. The pInstInfo parameter points to the EVENT_INSTANCE_INFO structure of the event instance, and the pParentInstInfo parameter points to the EVENT_INSTANCE_INFO structure of a parent event instance. The definition of a "parent" event instance is application-defined; the parent can be any instance that has already been generated.

The EVENT_INSTANCE_INFO structure from the parent's traced event instance can be saved and used as the parent in any trace generated later. The myInfo argument passed into this example function is the InstInfo structure from the previous example.

CreateChildInstance(EVENT_INSTANCE_INFO myInfo)
{
  EVENT_INSTANCE_INFO childInstInfo;

  // When the child event occurs:

  // RegHandle is the registered trace GUID handle for
  // the child event's class.
  CreateTraceInstanceID(RegHandle, &childInstInfo)
  // Copy child event information to EventTrace...

  TraceEventInstance (
    SessionHandle,
    (PEVENT_INSTANCE_HEADER) &EventTrace,
    &childInstInfo, // Populated by CreateTraceInstanceId.
    &myInfo);       // Parent event instance information.
}


Storing Event Trace Information Using WMI

The Event Tracer does not limit or control the ways that event trace providers and consumers share information about event trace classes, but does give providers the option of making event trace class descriptions publicly available using Windows Management Instrumentation (WMI).

To store event trace class descriptions in WMI

  1. Describe the event trace classes using Managed Object Format (MOF) syntax.
  2. Compile the MOF descriptions using the MOF compiler Mofcomp.exe, distributed with the Platform SDK.
  3. Specify the name of the compiled description file as a string resource.

During registration, the event trace provider specifies the name of the resource and the executable program or DLL that contains it. The MOF descriptions of the event trace classes are stored in the Common Information Model (CIM) repository, where they can be retrieved by event trace consumers.

For more information, see these topics:

  • Registering to Provide Events
  • Event Tracing with WMI
  • Providing Information to WMI


Consuming Event Traces

Event trace consumers access and process traces supplied by one or more providers. Event trace consumer functionality is demonstrated in the following sections:

  • Opening a Set of Event Traces
  • Implementing Generic Event Delivery
  • Implementing Buffer Notification
  • Implementing Event Class Delivery
  • Setting the EventClassCallback Function
  • Processing Traces


Opening a Set of Event Traces

Before traces can be delivered to a consumer, each set of event traces must be opened using the OpenTrace function. This function takes an initialized EVENT_TRACE_LOGFILE structure and returns a handle to the opened set of event traces.

To open a set of traces for real-time access, store the name of the executing event tracing session in the LoggerName member of the EVENT_TRACE_LOGFILE structure. To open a set of traces stored on disk, store the name of the file in the LogFileName member.

Use the EventCallBack member to specify the name of the function that will handle generic event delivery. This function is called once for each trace that is delivered to the consumer.

Use the BufferCallBack member to specify the name of the function that will handle buffer notification. This function is called once after each buffer of traces is delivered.

The following example demonstrates opening a set of event traces stored in a log file on disk.

#define MY_EVENT_TRACING_LOGFILE_NAME L"C:\\dev\\eventlog.etl"

TRACEHANDLE OpenTraceLogFile ()
{
  EVENT_TRACE_LOGFILE EventTraceLog;
  TRACEHANDLE LogHandle;

  // To open traces in a log file,
  // you don't need to specify a session name.
  EventTraceLog.LoggerName = NULL;

  // Store the name of the log file.
  EventTraceLog.LogFileName =
    (LPWSTR) LocalAlloc(LPTR,MAX_STRLEN);

  if (EventTraceLog.LogFileName == NULL)
    return (TRACEHANDLE) INVALID_HANDLE_VALUE;

  wcscpy(EventTraceLog.LogFileName,
    MY_EVENT_TRACING_LOGFILE_NAME);

  // Set the function that will be called
  // after each buffer is processed.
  EventTraceLog.BufferCallback =
    (PEVENT_TRACE_BUFFER_CALLBACK) (BufferReadCallback);

  // Set the function that will be called
  // for every event trace that is processed.
  EventTraceLog.EventCallback =
    (PEVENT_CALLBACK) (GenericEventCallback);

  // Open the event trace log file.
  LogHandle =  OpenTrace (&EventTraceLog);

  LocalFree(EventTraceLog.LogFileName);
  return LogHandle;
}

For more information, see Implementing Generic Event Delivery and Implementing Buffer Notification.


Implementing Generic Event Delivery

An event trace consumer handles generic event delivery by implementing a callback function, called an EventCallback function. This function is automatically called each time a trace is delivered to the consumer. The trace information is provided to an EventCallback function implementation through an EVENT_TRACE structure argument.

The following example shows an implementation for an EventCallback function.

VOID WINAPI GenericEventCallback(PEVENT_TRACE etrace)
{
  // Do any processing that should occur
  // for every event trace.

  // TotalEvents is a global variable.
  TotalEvents +=1;
  return;
}

The address of the EventCallback function implementation is set in the EventCallback member of an EVENT_TRACE_LOGFILE structure, before the structure is passed to the OpenTrace function. For more information, see Opening a Set of Event Traces.


Implementing Buffer Notification

An event trace consumer handles buffer notification by implementing a callback function, called the BufferCallback function. The BufferCallback function implementation is called after each buffer of event traces has been delivered to the consumer for processing. Information about the buffer contents is provided to the callback function through an EVENT_TRACE_LOGFILE structure.

The following example shows an implementation for a BufferCallback function.

ULONG WINAPI BufferReadCallback(PEVENT_TRACE_LOGFILE logFile)
{
  // Count the number of buffers received.
  TotalBuffers +=1;

  wprintf(L"\nBuffer #%lu Size: %lu (filled: %lu) Lost events: %lu\n",
    TotalBuffers,
    logFile->BufferSize,
    logFile->Filled,
    logFile->EventsLost);

  // Return TRUE if you want more traces delivered.
  // Return FALSE to stop event traces from being delivered.

  return (ULONG) TRUE;
}

The value returned by the BufferCallback function implementation determines whether the consumer continues to receive traces. Returning FALSE from this function terminates event trace processing.

The address of the BufferCallback function implementation is set in the BufferCallback member of an EVENT_TRACE_LOGFILE structure, before the structure is passed to the OpenTrace function. For more information, see Opening a Set of Event Traces.


Implementing Event Class Delivery

Using event class delivery, an event trace consumer implements a function, called an EventClassCallback function, that is called each time a trace belonging to a specific event trace class is delivered. The trace information is provided to the EventClassCallback function through an EVENT_TRACE structure.

The following example shows an implementation for an EventClassCallback function. This example processes the traces generated by the example provided in Tracing Events.

typedef struct _myUserData {
  ULONG Count;
  ULONG Average;
} *PMYUSER_DATA, MYUSER_DATA;

VOID WINAPI EventClassCallback(PEVENT_TRACE etrace)
{
  EVENT_TRACE_HEADER header = etrace->Header;
  PMYUSER_DATA pData = (PMYUSER_DATA) etrace->MofData;
  WCHAR buf[MAX_STRLEN];

  TotalMyEvents +=1;

  switch (header.Class.Type)
{
    case EVENT_TRACE_TYPE_START:
      wcscpy(buf,L"START");
      break;
    case EVENT_TRACE_TYPE_END:
      wcscpy(buf,L"END");
      break;
    default:
      wcscpy(buf,L"UNKNOWN");
      break;
  }
  wprintf(L"\nEvent #%lu -> %ws Event <- Count: %hu Avg: %hu\n",
    TotalMyEvents,
    buf,
    pData->Count,
    pData->Average);
  return;
}

Event class delivery functions are specified using the SetTraceCallback function. For more information, see Setting the EventClassCallback Function.


Setting the EventClassCallback Function

Event trace consumers may require the ability to process traces based on the event trace class that describes the trace. The traces belonging to each event trace class can be delivered through class-specific callback functions, called EventClassCallback functions, implemented by the consumer. This process is known as event class delivery, and it requires associations between EventClassCallback functions and the event trace classes that they process. To make these associations, use the SetTraceCallback function as follows:

  // Set the callback functions for each event trace class GUID.
  ret  = SetTraceCallback(
    &TransactionGuid,
    (PEVENT_CALLBACK) (EventClassCallback)
    );

The SetTraceCallback function associates an EventClassCallback function with the GUID of the event trace class that requires special processing. During event trace processing, if an event trace identified by this GUID is found, the associated function is called.

For an example implementation of the event class delivery callback function, see Implementing Event Class Delivery.

To disassociate the event class delivery callback function from the event trace class, call the RemoveTraceCallback, function:

RemoveTraceCallback(&TransactionGuid);


Processing Traces

After obtaining handles to one or more sets of event traces and optionally specifying event class delivery functions, an event trace consumer can process traces by calling the ProcessTrace function. This function requires an array of handles obtained from previous calls to OpenTrace.

The sets of event traces are combined, sorted into approximate chronological order, and then delivered to the consumer one at a time. The traces can be filtered to include only those that fall into a specific time frame using the ProcessTrace function's StartTime and EndTime parameters.

The following example demonstrates using ProcessTrace.

int ConsumeLogEvents()
{
  TRACEHANDLE HandleArray[1];
  ULONG ret;
  TRACEHANDLE LogHandle;

  // Open the event trace logfile.
  LogHandle = OpenTraceLogFile ();

  if (LogHandle == (TRACEHANDLE)INVALID_HANDLE_VALUE)
    return(ERROR_INVALID_HANDLE);

  // Set the callback functions for
  // the event's trace GUID.
  ret = SetTraceCallback(&TransactionGuid,
    (PEVENT_CALLBACK) (EventClassCallback));

  if (ret != ERROR_SUCCESS)
  {
    CloseTrace(LogHandle);
    return ret;
  }
  // Store the handle in the array of handles
  // passed to ProcessTrace.
  HandleArray[0] = LogHandle;

  // Process the event traces.
  ret = ProcessTrace(HandleArray,1,NULL,NULL);

  if (ret != ERROR_SUCCESS)
  {
    // Everything is okay only if ProcessTrace was canceled
    // using the BufferCallback function.
    if (ret != ERROR_CANCELLED)
       wprintf(L"ProcessTrace failed: %d\n", ret);
  }
  // Close the trace logfile.
  CloseTrace(LogHandle);
  return ret;
}

For the implementation of the OpenTraceLogFile example function, see Opening a Set of Event Traces.

For an example implementation of the EventClassCallback function, see Implementing Event Class Delivery.


Using the NT Kernel Logger

Certain kernel events are traced by the operating system, and can be made available to consumers using the NT Kernel Logger session. The following topics provide information on using the NT Kernel Logger event tracing session.

  • Starting the NT Kernel Logger Session describes how to specify the operating system events to trace, and how the traces are delivered.
  • Consuming Traces from the NT Kernel Logger describes obtaining access to operating system event traces.


Starting the NT Kernel Logger Session

The NT Kernel Logger session is started using the StartTrace function. To start this reserved event tracing session, allocate and initialize an EVENT_TRACE_PROPERTIES structure, and specify the GUID that identifies the NT Kernel Logger. You must also specify the events to be traced by the operating system, and how those traces are to be delivered.

The following example demonstrates starting the NT Kernel Logger session.

ULONG StartKernelSession()
{
  ULONG ret;
  PEVENT_TRACE_PROPERTIES Properties;
  TRACEHANDLE tHandle;

  Properties = (PEVENT_TRACE_PROPERTIES) AllocSessionProperties();
  if (!Properties)
    return ERROR_OUTOFMEMORY;

  // Use real-time trace delivery for this example.
  Properties->LogFileMode = EVENT_TRACE_REAL_TIME_MODE;

  // We want the NT Kernel Logger session.
  Properties->Wnode.Guid = SystemTraceControlGuid;

  // Indicate which kernel mode events the
  // operating system should trace.
  Properties->EnableFlags |= (
    EVENT_TRACE_FLAG_MEMORY_PAGE_FAULTS |
    EVENT_TRACE_FLAG_MEMORY_HARD_FAULTS |
    EVENT_TRACE_FLAG_DISK_IO |
    EVENT_TRACE_FLAG_DISK_FILE_IO);

  // The second argument to
  // StartTrace must not be null.
  ret = StartTrace(&tHandle,L"kernel",Properties);

  // Free memory allocated for properties.
  LocalFree(Properties);
  return ret;
}

For the implementation of the AllocSessionProperties function which allocates and initializes EVENT_TRACE_PROPERTIES, see Configuring an EVENT_TRACE_PROPERTIES Structure.

Specify the operating system events to trace by combining predefined flags in the EnableFlag member of the EVENT_TRACE_PROPERTIES structure. The following flags are allowed.

EnableFlag value | Kernel event description
EVENT_TRACE_FLAG_DISK_FILE_IO | Requests disk I/O
EVENT_TRACE_FLAG_DISK_IO | Physical disk I/O
EVENT_TRACE_FLAG_IMAGE_LOAD | Image load
EVENT_TRACE_FLAG_MEMORY_HARD_FAULTS | Hard page faults
EVENT_TRACE_FLAG_MEMORY_PAGE_FAULTS | All page faults
EVENT_TRACE_FLAG_NETWORK_TCPIP | TCP/IP, UDP send and receive operations
EVENT_TRACE_FLAG_PROCESS | Process creation and termination
EVENT_TRACE_FLAG_REGISTRY | Registry searches and updates
EVENT_TRACE_FLAG_THREAD | Thread creation and termination


Consuming Traces from the NT Kernel Logger

The following example demonstrates obtaining access to the NT Kernel Logger session's traces, and specifying callback functions to be used for trace delivery and buffer notification. This example uses event class delivery for traces belonging to the Disk I/O and Page Fault kernel event trace classes.

#define NT_KERNEL_LOGGER L"NT Kernel Logger"
#define MAX_STRLEN 512

TRACEHANDLE OpenKernelSession()
{
  EVENT_TRACE_LOGFILE EventTraceLog;
  TRACEHANDLE LogHandle;

  ULONG ret;

  // Prepare to consume real-time events
  // from the NT Kernel Logger session.

  EventTraceLog.LogFileName= NULL;

  // Alloc room to hold the session name
  EventTraceLog.LoggerName = (LPWSTR) LocalAlloc(LPTR,MAX_STRLEN * sizeof(WCHAR));

  if (EventTraceLog.LoggerName  == NULL)
    return (TRACEHANDLE) INVALID_HANDLE_VALUE;

  // Copy the session name and delivery mode.
  wcscpy(EventTraceLog.LoggerName,NT_KERNEL_LOGGER);
  EventTraceLog.LogFileMode = EVENT_TRACE_REAL_TIME_MODE;

  // Set the function that will be called
  // after each buffer is processed.
  EventTraceLog.BufferCallback =
    (PEVENT_TRACE_BUFFER_CALLBACK) (KernelBufferCallback);

  // Set the function that will be called
  // for every event trace that is processed.
  EventTraceLog.EventCallback =
    (PEVENT_CALLBACK) (KernelGenericEventCallback);

  // Set the event class delivery functions
  // for I/O and page faults.
  SetTraceCallback(&PageFaultGuid,
    (PEVENT_CALLBACK) (PageFaultCallback));

  SetTraceCallback(&DiskIoGuid,
    (PEVENT_CALLBACK) (IOCallback));

  // Open the set of event traces and get a handle to it.
  LogHandle = OpenTrace (&EventTraceLog);

  if (LogHandle == (TRACEHANDLE) INVALID_HANDLE_VALUE)
  {
    wprintf(L"Error opening kernel session %d\n", ret);
  }
  return LogHandle;
}

After obtaining a handle to the traces, use the ProcessTrace function to process them. For more information, see Processing Traces.

For a complete list of the GUIDs and event types reserved for the NT Kernel Logger session, see NT Kernel Logger Constants.


Using the Global Logger

The Global Logger event tracing session records traces of events that occur before a system is fully operational, such as those generated by device drivers. Because the Global Logger must be available early in the operating system boot process, it is started using the system registry.

The following information describes the registry settings used to start the Global Logger session.

To start the Global Logger

If it is not present in the registry, add a GlobalLogger key to:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\WMI

The supported values for the GlobalLogger key are shown in the following table.

Value | Type | Description
Start | REG_DWORD | 0 = Off 1 = On.
BufferSize | REG_DWORD | Size of each buffer, in KB.
MinimumBuffers | REG_DWORD | Minimum number of buffers to allocate at startup.
MaximumBuffers | REG_DWORD | Maximum number of buffers that are allocated.
FlushTimer | REG_DWORD | Time delay before dirty buffers are scheduled to be flushed, in seconds.
FileName | REG_SZ | Fully-qualified path of the log file. Make sure the directory already exists.

The Start key value is the only value required to start the Global Logger; all other values have default settings that are used if the value is not present in the registry.

Note If FileName is not specified, event traces are written to %SystemRoot%\System32\LogFiles\WMI\trace.log. The path to this file must exist.

After the registry has been modified and the system restarted, the Global Logger event tracing session starts automatically and is used like any other session with one exception: the Global Logger session handle may be referenced using the constant handle WMI_GLOBAL_LOGGER_ID. This constant may be used as an argument to any Event Tracer API function that accepts a session handle. In functions that accept a session name, the Global Logger can be specified using the session name "GlobalLogger".


Restricting Access to Event Tracing Sessions

By default, the Event Tracer does not require special privileges; however, developers have the option to add security by restricting access to event tracing sessions. Before you can set permissions for an event tracing session, it must be assigned a Globally Unique Identifier (GUID). The session's GUID and a security descriptor with the required access permissions are stored in the system registry. If the GUID specified for an event tracing session is not in the registry, all permissions are granted.

Note Access to the Global Logger event tracing session cannot be restricted.

The following information describes the steps a developer must follow to restrict access to an event tracing session.

To restrict access to an event tracing session

  1. Obtain a GUID for the event tracing session. See Globally Unique Identifiers and Event Tracing for more information. This step is not necessary to restrict access to the NT Kernel Logger session.
  2. Locate the registry key:

    HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\WMI\Security.

  3. If the GUID is not already a value under this key, add it to the system registry. Specify the GUID as the name of the registry value, REG_BINARY as the data type, and a security descriptor as the value data. The Event Tracer uses the security descriptor to determine the access permissions for an event tracing session. For additional information on security descriptors see Access Control.

The following security permissions may be set.

Permission | Description
TRACELOG_ACCESS_KERNEL_LOGGER | Requester has permission to access the NT Kernel Logger session. Checked during QueryTrace, StartTrace, StopTrace, and UpdateTrace.
TRACELOG_ACCESS_REALTIME | Requester has permission to process real-time traces from an event tracing session. Checked during ProcessTrace.
TRACELOG_CREATE_INPROC | Requester has permission to start a private logger. Checked during StartTrace.
TRACELOG_CREATE_ONDISK | Session can write traces to a log file. Checked during StartTrace, UpdateTrace.
TRACELOG_CREATE_REALTIME | Session can record traces in real-time. Checked during StartTrace and UpdateTrace
TRACELOG_GUID_ENABLE | Session can be enabled / disabled. Checked during StartTrace, StopTrace, and UpdateTrace.

When you start the event tracing session, specify the session GUID using the Wnode.Guid member of the EVENT_TRACE_PROPERTIES structure that is used to access the session, as illustrated in the following example.

// {E29ADB0A-AA90-4724-8647-2076637971FE}
DEFINE_GUID(
  SecureSessionGuid,
  0xe29adb0a,
  0xaa90,
  0x4724,
  0x86, 0x47,
  0x20, 0x76, 0x63, 0x79, 0x71, 0xfe
);

#define MY_EVENT_TRACING_SESSION_NAME L"My Example Session"
#define MY_EVENT_TRACING_LOGFILE_NAME L"C:\\dev\\eventlog.etl"

TRACEHANDLE StartSecureSession()
{
  ULONG ret;
  PEVENT_TRACE_PROPERTIES Properties;
  TRACEHANDLE SessionHandle;

  Properties = AllocSessionProperties();

  if (Properties == NULL)
  {
    return((TRACEHANDLE) INVALID_HANDLE_VALUE);
  }
  // Deliver traces to a circular log file.

  Properties->LogFileMode |= EVENT_TRACE_FILE_MODE_CIRCULAR;
  Properties->MaximumFileSize = 20;

  // Store the name of the log file.

  wcscpy ((LPWSTR) ((char *)Properties + Properties->LogFileNameOffset),
    MY_EVENT_TRACING_LOGFILE_NAME);
  // Specify the GUID for the session.
  Properties->Wnode.Guid = SecureSessionGuid;
  // Start the session.

  ret = StartTrace (
    &SessionHandle,
    MY_EVENT_TRACING_SESSION_NAME,
    Properties);

  LocalFree(Properties);
  if (ret != ERROR_SUCCESS)
  {
    wprintf(L"StartTrace failed: %d\n", ret);
    SessionHandle = (TRACEHANDLE) INVALID_HANDLE_VALUE;
  }
  return SessionHandle;
}

Refer to Configuring an EVENT_TRACE_PROPERTIES Structure for the implementation of the AllocSessionProperties function which allocates and initializes an EVENT_TRACE_PROPERTIES structure. Refer to Starting an Event Tracing Session for additional information about using the StartTrace function.


Support Functions

The following functions are included only for completeness. These functions are neither required by nor a part of the Event Tracer or its API.

  • PrintSession
  • GetFileMode

PrintSession

The PrintSession function generates a command-line display of a session's current properties settings.

VOID PrintSession(PEVENT_TRACE_PROPERTIES session)
{
  WCHAR modeString[20];

  GetFileMode(session->LogFileMode,&modeString[0]);

  wprintf(L"\n%ws       [Filemode %ws-%ws]\n\n",
    (WCHAR *) ((char*)session + session->LoggerNameOffset),
    modeString,
    (WCHAR *) ((char*)session + session->LogFileNameOffset));

  wprintf(L"              Buffer Settings & Statistics\n");
  wprintf(L"--------------------------------------------------------\n");
  wprintf(L"(KB)                           Buffers   (Secs)   (Mins)\n");
  wprintf(L"Size  | Min |  Max  |  Free  | Written  | Flush    Age\n");

  wprintf(L"%-5lu %5lu     %-5lu  %-2lu  %8lu  %8lu %8d\n\n",
    session->BufferSize,
    session->MinimumBuffers,
    session->MaximumBuffers,
    session->FreeBuffers,
    session->BuffersWritten,
    session->FlushTimer,
    session->AgeLimit);

  wprintf(L"Allocated Buffers: %lu Thread: %d Handle: %lu\n",
    session->NumberOfBuffers,
    session->LoggerThreadId,
    session->Wnode.HistoricalContext);

  wprintf(L"LOST EVENTS:%15lu\n",
    session->EventsLost);

  wprintf(L"LOST LOG BUFFERS:%10lu\n",
    session->LogBuffersLost);

  wprintf(L"LOST REAL TIME BUFFERS:%4lu\n",
    session->RealTimeBuffersLost);
}

The PrintSession function is used by the examples in Controlling Event-Tracing Sessions.

GetFileMode

The GetFileMode function generates a string that lists the delivery methods used by a session. This function is called by PrintSession.

LPCWSTR GetFileMode(ULONG mode, LPWSTR mString)
{
  wcscpy(mString,L"-");

  if (mode & EVENT_TRACE_FILE_MODE_NONE)
    wcscat(mString,L"N");
  if (mode & EVENT_TRACE_FILE_MODE_SEQUENTIAL)
    wcscat(mString,L"S");
  if (mode & EVENT_TRACE_FILE_MODE_CIRCULAR)
    wcscat(mString,L"C");
  if (mode & EVENT_TRACE_REAL_TIME_MODE)
    wcscat(mString,L"R");
  if (mode & EVENT_TRACE_DELAY_OPEN_FILE_MODE)
    wcscat(mString,L"D");
  if (mode & EVENT_TRACE_BUFFERING_MODE)
    wcscat(mString,L"B");
  if (mode & EVENT_TRACE_PRIVATE_LOGGER_MODE)
    wcscat(mString,L"P");
  if (mode & EVENT_TRACE_ADD_HEADER_MODE)
    wcscat(mString,L"A");

  return mString;
}


Event Tracing API Reference

The following sections describe the elements that are used with event tracing:

  • Event Tracing Functions
  • Event Tracing Structures
  • Event Tracing Constants


Event Tracing Functions

The following table is a list of event tracing functions by category.

Category | Description
Event Trace Controller Functions | Manage event tracing sessions.
Event Trace Provider Functions | Create event traces.
Event Trace Consumer Functions | Obtain event traces.

For information about callback functions that handle application-specific processing, see Event Tracing Function Prototypes.

Event Trace Controller Functions

The event trace controller functions are used to manage event tracing sessions.

Function | Description
ControlTrace | Queries, updates, or stops a session.
EnableTrace | Enables/disables an event trace provider.
EnumerateTraceGuids | Retrieves information about registered event trace providers.
FlushTrace | Gives immediate access to buffered traces awaiting delivery.
QueryAllTraces | Retrieves property settings and execution statistics for sessions.
QueryTrace | Retrieves property settings and execution statistics for a session. This function has been superseded by the ControlTrace function.
StartTrace | Starts a session.
StopTrace | Stops a session. This function has been superseded by the ControlTrace function.
UpdateTrace | Changes a session's properties. This function has been superseded by the ControlTrace function.

Event Trace Provider Functions

The event trace provider functions are used to create event traces.

Function | Description
CreateTraceInstanceId | Creates an identifier for a group of related traces.
GetTraceEnableFlags | Retrieves the flags set by the EnableTrace function.
GetTraceEnableLevel | Retrieves the level set by the EnableTrace function.
GetTraceLoggerHandle | Retrieves the event tracing session handle passed into the EnableTrace function.
RegisterTraceGuids | Registers a provider and its event trace classes.
TraceEvent | Generates event traces.
TraceEventInstance | Generates traces for related events.
TraceMessage and TraceMessageVa | Generates trace messages.
UnregisterTraceGuids | Unregisters a provider and its event trace classes.

Event Trace Consumer Functions

The event trace consumer functions are used to obtain traces.

Function | Description
CloseTrace | Closes a set of traces.
OpenTrace | Opens a set of traces.
ProcessTrace | Delivers traces to a consumer.
RemoveTraceCallback | Stops an EventClassCallback function from processing an event trace class.
SetTraceCallback | Specifies an EventClassCallback function to process an event trace class.


CloseTrace

The CloseTrace function closes a set of traces opened by the OpenTrace function.

ULONG CloseTrace(
  TRACEHANDLE TraceHandle
);

Parameters

TraceHandle
[in] Handle to the set of event traces to close, obtained from an earlier call to the OpenTrace function.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a non-zero error code. The following table lists common errors and their causes.

Error code | Meaning
ERROR_INVALID_HANDLE | One of the following is true: TraceHandle is null. TraceHandle is equal to INVALID_HANDLE_VALUE.

Remarks

The CloseTrace function should be called after calling OpenTrace to open a set of traces, and ProcessTrace to retrieve the traces.

For an example that uses CloseTrace, see Processing Traces.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

OpenTrace, Processing Traces, ProcessTrace


ControlTrace

The ControlTrace function queries, updates, or stops an event tracing session.

ULONG ControlTrace(
  TRACEHANDLE TraceHandle,
  LPCTSTR InstanceName,
  PEVENT_TRACE_PROPERTIES Properties,
  ULONG ControlCode
);

Parameters

TraceHandle
[in] Handle to an event tracing session. Either TraceHandle or InstanceName is required.
InstanceName
[in] Name of an event tracing session. Either TraceHandle or InstanceName is required.
Properties
[in, out] Pointer to an EVENT_TRACE_PROPERTIES structure.

When ControlCode specifies EVENT_TRACE_CONTROL_UPDATE, on input the members of Properties must specify the new values for properties that should be updated. On output, Properties contains the properties and execution statistics for the event tracing session.

ControlCode
[in] Specifies the requested control function. This parameter must be one of the following values.
Value | Description
EVENT_TRACE_CONTROL_FLUSH | Flushes the session's active buffers. Available in Whistler only.
EVENT_TRACE_CONTROL_QUERY | Retrieves session properties and execution statistics.
EVENT_TRACE_CONTROL_STOP | Stops the session.
EVENT_TRACE_CONTROL_UPDATE | Updates the session properties.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a non-zero error code. The following table lists common errors and their causes.

Error code | Meaning
ERROR_BAD_LENGTH | The Wnode.BufferSize member of Properties specifies an incorrect size.
ERROR_INVALID_PARAMETER | One of the following is true: Properties is null. The LogfileNameOffset member of Properties is invalid. The LoggerNameOffset member of Properties is invalid. InstanceName and TraceHandle are null.

Remarks

The value specified for the TraceHandle parameter can be obtained using the QueryTrace, QueryAllTraces, or StartTrace functions.

To access the NT Kernel Logger, the Wnode.Guid member of Properties must specify the SystemTraceControlGuid GUID.

This function assumes that the EVENT_TRACE_PROPERTIES structure has been properly initialized, as demonstrated in Configuring an EVENT_TRACE_PROPERTIES Structure.

This function supersedes the QueryTrace, StopTrace, and UpdateTrace functions.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

Configuring an EVENT_TRACE_PROPERTIES Structure, EVENT_TRACE_PROPERTIES, QueryTrace, StopTrace, UpdateTrace, WNODE_HEADER


CreateTraceInstanceId

The CreateTraceInstanceId function generates a unique transaction identifier, and maps it to a trace GUID registration handle.

ULONG CreateTraceInstanceId(
  HANDLE RegHandle,
  PEVENT_INSTANCE_INFO pInstInfo
);

Parameters

RegHandle
[in] Handle to a registered event trace class. This handle is obtained from an earlier call to the RegisterTraceGuids function and is stored in the RegHandle member of the structure pointed to by pInstInfo.
pInstInfo
[out] Pointer to an EVENT_INSTANCE_INFO structure. The transaction identifier is returned in the InstanceId member of this structure.

Return Values

If the function is successful, the return value is ERROR_SUCCESS.

If the function fails, the return value is a non-zero error code. The following table lists common errors and their causes.

Error code | Meaning
ERROR_INVALID_PARAMETER | One of the following is true: RegHandle is null. pInstInfo is null.

Remarks

The handles for registered trace GUIDs are available in the RegHandle members of TRACE_GUID_REGISTRATION structures which are populated by calling the RegisterTraceGuids function.

Use CreateTraceInstanceId to obtain a unique transaction identifier and then call the TraceEventInstance function to generate traces of events that occur while completing the transaction.

For an example that uses CreateTraceInstanceId, see Tracing Event Instances.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

EVENT_INSTANCE_INFO, RegisterTraceGuids, TraceEventInstance, TRACE_GUID_REGISTRATION, Tracing Event Instances


EnableTrace

The EnableTrace function enables or disables event tracing by an event trace provider, for an event tracing session.

ULONG EnableTrace(
  ULONG Enable,
  ULONG EnableFlag,
  ULONG EnableLevel,
  LPCGUID ControlGuid,
  TRACEHANDLE TraceHandle
);

Parameters

Enable
[in] Specify TRUE to enable tracing or FALSE to disable tracing.
EnableFlag
[in] User-defined value. 0x01000000 through 0xff000000 are reserved values and should not be used.
EnableLevel
[in] User-defined value ranging from 0 to 255. See Remarks for more information.
ControlGuid
[in] GUID of a registered event trace provider that is to be enabled or disabled for the session specified by the TraceHandle parameter.
TraceHandle
[in] Handle to the event tracing session for which the provider is being enabled or disabled. See Remarks for more information.

Return Values

If the function is successful, the return value is ERROR_SUCCESS.

If the function is unsuccessful, the return value is a non-zero error code. The following table lists common errors and their causes.

Error code | Meaning
ERROR_INVALID_PARAMETER | One of the following is true: ControlGuid is null. EnableLevel is greater than 255. TraceHandle is null.

Remarks

The EnableTrace function calls a ControlCallback function implementation. The address of this callback function is specified when the provider registers by calling the RegisterTraceGuids function.

The ControlCallback function implementation may call the GetTraceEnableFlags, GetTraceEnableLevel, and GetTraceLoggerHandle functions to obtain the values specified for the EnableFlag, EnableLevel, and TraceHandle parameters, respectively.

The value specified for the TraceHandle parameter can be obtained using the QueryTrace, ControlTrace, QueryAllTraces, or StartTrace functions.

In Windows 2000 if the EnableTrace function is called with the Control GUID of a provider that is enabled, EnableTrace returns an error. To avoid this error the provider must first be disabled. As of Whistler, you do not have to disable an enabled provider before applying new flags and level settings.

For an example that uses EnableTrace, see Enabling an Event Trace Provider.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

ControlCallback, ControlTrace, Enabling an Event Trace Provider, GetTraceEnableFlags, GetTraceEnableLevel, GetTraceLoggerHandle, QueryAllTraces, QueryTrace, RegisterTraceGuids, StartTrace


EnumerateTraceGuids

[This is preliminary documentation and subject to change.]

The EnumerateTraceGuids function retrieves information about event providers registered on a system.

ULONG EnumerateTraceGuids (
  PTRACE_GUID_PROPERTIES *GuidPropertiesArray,
  ULONG PropertyArrayCount,
  PULONG GuidCount
);

Parameters

GuidPropertiesArray
[in, out] Address of an array of pointers to TRACE_GUID_PROPERTIES structures.
PropertyArrayCount
[in] The number of elements in the array specified by the GuidPropertiesArray parameter.
GuidCount
[out] Pointer to a ULONG that receives the count of providers for which information is available.

Return Values

If GuidPropertiesArray has enough space allocated to return information for all of the registered providers and no error has occurred, the return value is ERROR_SUCCESS. The GuidCount parameter contains the total number of entries returned.

If GuidPropertiesArray does not have sufficient space allocated, the return value is ERROR_MORE_DATA. The GuidCount parameter contains the total number of entries required.

For any other error, the return value is an NTSTATUS code indicating the error.

Remarks

For information on registering event trace providers, see RegisterTraceGuids.

Requirements

Windows NT/2000 or later: Requires Whistler.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

RegisterTraceGuids


FlushTrace

[This is preliminary documentation and subject to change.]

The FlushTrace function causes an event tracing session to immediately deliver event traces held in active buffers. Normally, an event tracing session does not deliver event traces until an active buffer is full.

ULONG FlushTrace(
  TRACEHANDLE TraceHandle,
  LPTSTR InstanceName,
  PEVENT_TRACE_PROPERTIES Properties
);

Parameters

TraceHandle
[in] Handle to the event tracing session whose buffers will be flushed. If InstanceName is specified, TraceHandle must be NULL.
InstanceName
[in] The name of the event tracing session whose buffers will be flushed. If TraceHandle is specified, InstanceName must be NULL.
Properties
[in, out] Pointer to an EVENT_TRACE_PROPERTIES structure that receives the properties of the event tracing session. The values returned in Properties reflect the state of the session after the flush.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a non-zero error code. The following table lists a common error and its causes.

Error code | Meaning
ERROR_INVALID_PARAMETER | One of the following is true: Properties is null. InstanceName and TraceHandle are both null.

Remarks

The FlushTrace function does not disable event trace buffering. The active buffers are flushed once, and then buffering resumes.

Requirements

Windows NT/2000 or later: Requires Whistler.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.


GetTraceEnableFlags

The GetTraceEnableFlags function obtains the value specified for the EnableFlag parameter of the EnableTrace function.

The GetTraceEnableFlags function is called from an event trace provider's ControlCallback function implementation.

ULONG GetTraceEnableFlags(
  TRACEHANDLE TraceHandle
);

Parameters

TraceHandle
[in] Handle to an event tracing session, obtained by calling the GetTraceLoggerHandle function.

Return Values

If the function is successful, the value specified for the EnableFlag parameter of the EnableTrace function is returned.

A return value of 0 may indicate an error. To get extended error information, call the GetLastError function.

Remarks

A ControlCallback function is implemented by an event trace provider, and specified using the RegisterTraceGuids function.

For an example that uses GetTraceEnableFlags, see Implementing a ControlCallback Function.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

ControlCallback, EnableTrace, GetTraceLoggerHandle, GetLastError, Implementing a ControlCallback Function, RegisterTraceGuids


GetTraceEnableLevel

The GetTraceEnableLevel function obtains the value specified for the EnableLevel parameter of the EnableTrace function.

The GetTraceEnableLevel function is called from an event trace provider's ControlCallback function implementation.

UCHAR GetTraceEnableLevel(
  TRACEHANDLE TraceHandle
);

Parameters

TraceHandle
[in] Handle to an event tracing session, obtained by calling the GetTraceLoggerHandle function.

Return Values

If the function is successful, the value specified for the EnableLevel parameter of the EnableTrace function is returned.

A return value of 0 may indicate an error. To get extended error information, call GetLastError.

Remarks

A ControlCallback function is implemented by an event trace provider, and specified using the RegisterTraceGuids function.

For an example that uses GetTraceEnableLevel, see Implementing a ControlCallback Function.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

ControlCallback, EnableTrace, GetLastError, GetTraceLoggerHandle, Implementing a ControlCallback Function, RegisterTraceGuids


GetTraceLoggerHandle

The GetTraceLoggerHandle function obtains the value specified for the TraceHandle parameter of the EnableTrace function.

The GetTraceLoggerHandle function is called from an event trace provider's ControlCallback function implementation.

TRACEHANDLE GetTraceLoggerHandle(
  PVOID Buffer
);

Parameters

Buffer
[in] Pointer to a WNODE_HEADER structure. See Remarks for more information.

Return Values

If the function succeeds, the event tracing session handle specified as an argument to the EnableTrace function is returned.

If the function fails, INVALID_HANDLE_VALUE is returned. To get extended error information, call the GetLastError function.

Remarks

The GetTraceLoggerHandle function returns valid information when called from a ControlCallback function implementation. The Buffer parameter value from the ControlCallback function implementation should be passed to the Buffer parameter of GetTraceLoggerHandle.

The TRACEHANDLE returned by GetTraceLoggerHandle should be used as the value of the TraceHandle parameter for the GetTraceEnableFlags and GetTraceEnableLevel functions.

A ControlCallback function is specified using the RegisterTraceGuids function.

For an example that uses GetTraceLoggerHandle, see Implementing a ControlCallback Function.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

ControlCallback, EnableTrace, GetLastError, GetTraceEnableFlags, GetTraceEnableLevel, Implementing a ControlCallback Function, RegisterTraceGuids


OpenTrace

The OpenTrace function provides an event trace consumer with access to the set of traces recorded by an event tracing session.

TRACEHANDLE OpenTrace(
  PEVENT_TRACE_LOGFILE Logfile
);

Parameters

Logfile
[in, out] Pointer to an EVENT_TRACE_LOGFILE structure. On input, the members of the structures should be initialized as follows.
Member | Initial value
LogfileName | Name of a disk file that contains the set of traces. Null, if LoggerName is specified.
LoggerName | Name of a session that is recording traces for real-time consumption. Null, if LogfileName is specified.
BufferCallback | Function to call after each buffer of traces is processed.
EventCallback | Function to call to process each trace.

Return Values

If the function succeeds, it returns a handle to the set of traces.

If the function fails, it returns INVALID_HANDLE_VALUE. To get extended error information, use the GetLastError function. The following table lists common errors and their causes.

Error code | Meaning
ERROR_INVALID_PARAMETER | The Logfile parameter is null.

Remarks

The OpenTrace function must be called prior to calling the ProcessTrace function.

To access traces from a currently executing event tracing session in real time, specify the session name using the LoggerName member of the EVENT_TRACE_LOGFILE structure. To access traces stored in a log file on disk, specify the name of the file using the LogFileName member.

A set of traces opened using OpenTrace must be closed by calling the CloseTrace function.

For an example that uses OpenTrace, see Opening a Set of Event Traces.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

CloseTrace, EVENT_TRACE_LOGFILE, Opening a Set of Event Traces, ProcessTrace


ProcessTrace

The ProcessTrace function filters, sorts, and delivers traces from one or more event tracing sessions to event trace consumers.

Traces are delivered using BufferCallback, EventCallback, and EventClassCallback callback functions implemented by the consumer.

ULONG ProcessTrace(
  PTRACEHANDLE HandleArray,
  ULONG HandleCount,
  LPFILETIME StartTime,
  LPFILETIME EndTime
);

Parameters

HandleArray
[in] Pointer to an array of handles obtained from earlier calls to the OpenTrace function.
HandleCount
[in] Number of elements in HandleArray.
StartTime
[in] Pointer to an optional FILETIME structure that specifies the earliest time the delivered traces occur. Traces recorded prior to StartTime are not delivered.
EndTime
[in] Pointer to an optional FILETIME structure that specifies the latest time the delivered traces occur. Traces recorded after EndTime are not delivered.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a non-zero error code. The following table lists common errors and their causes.

Error code | Meaning
ERROR_BAD_LENGTH | HandleCount is invalid.
ERROR_INVALID_HANDLE | An element of HandleArray is not a valid event tracing session handle.
ERROR_INVALID_TIME | EndTime is less than StartTime.
ERROR_INVALID_PARAMETER | HandleArray is null.
ERROR_NOACESS | An exception occurred in one of the callback functions used to deliver the traces.

Remarks

The BufferCallback and EventCallback function implementations are specified using the OpenTrace function, which must be called prior to calling ProcessTrace. The EventClassCallback function implementations are optionally specified using the SetTraceCallback function.

The ProcessTrace function sorts the traces chronologically and delivers all traces generated between StartTime and EndTime, unless the BufferCallback function implementation returns FALSE to cancel trace delivery.

For an example that uses ProcessTrace, see Processing Traces.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

BufferCallback, EventCallback, EventClassCallback, OpenTrace, Processing Traces, SetTraceCallback


QueryAllTraces

The QueryAllTraces function retrieves the total number of event tracing sessions executing on a system, and the properties and execution statistics for one or more sessions.

ULONG QueryAllTraces(
  PEVENT_TRACE_PROPERTIES *PropertyArray,
  ULONG PropertyArrayCount,
  PULONG LoggerCount
);

Parameters

PropertyArray
[out] Pointer to an array of EVENT_TRACE_PROPERTIES structures that receive properties and execution statistics for event tracing sessions.
PropertyArrayCount
[in] Number of EVENT_TRACE_PROPERTIES structures in the array pointed to by PropertyArray. The value specified for the PropertyArrayCount parameter should not be greater than 32, the maximum number of event tracing sessions supported by Windows 2000.
LoggerCount
[out] Pointer to a ULONG variable that receives the number of executing event tracing sessions. If the number of structures in PropertyArray is smaller than LoggerCount, information for some sessions is not returned.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a non-zero error code. The following table lists common errors and their causes.

Error code | Meaning
ERROR_INVALID_PARAMETER | One of the following is true: PropertyArrayCount is 0 or greater than 32. PropertyArray is null.
ERROR_MORE_DATA | PropertyArray is not large enough to receive information for all executing sessions.

Remarks

When PropertyArray is not large enough to receive information for all executing sessions, information is returned in the available EVENT_TRACE_PROPERTIES structures, and ERROR_MORE_DATA is the return value.

This function assumes that the EVENT_TRACE_PROPERTIES structures have been properly initialized, as demonstrated in Configuring an EVENT_TRACE_PROPERTIES Structure.

To retrieve information for a single session, use the QueryTrace or ControlTrace functions.

For an example that uses QueryAllTraces, see Querying Event Tracing Sessions.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

Configuring an EVENT_TRACE_PROPERTIES Structure, ControlTrace, EVENT_TRACE_PROPERTIES, Querying Event Tracing Sessions, QueryTrace


QueryTrace

The QueryTrace function retrieves properties and execution statistics for an executing event tracing session.

This function has been superseded by the ControlTrace function.

ULONG QueryTrace(
  TRACEHANDLE TraceHandle,
  LPTSTR InstanceName,
  PEVENT_TRACE_PROPERTIES Properties
);

Parameters

TraceHandle
[in] Handle to the event tracing session. Either TraceHandle or InstanceName is required.
InstanceName
[in] Name of the event tracing session. Either TraceHandle or InstanceName is required.
Properties
[in, out] Pointer to an EVENT_TRACE_PROPERTIES structure.

On input, the structure should be properly configured and initialized. See Remarks for additional information. On output, the structure members receive property settings and execution statistics for the event tracing session.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a non-zero error code. The following table lists common errors and their causes.

Error code | Meaning
ERROR_BAD_LENGTH | The Wnode.BufferSize member of Properties specifies an incorrect size.
ERROR_INVALID_PARAMETER | One of the following is true: Properties is null. The LogfileNameOffset member of Properties is invalid. The LoggerNameOffset member of Properties is invalid. InstanceName and TraceHandle are null.

Remarks

Either InstanceName or TraceHandle must be supplied. The TraceHandle parameter value may be obtained from the StartTrace or QueryAllTraces functions. The value specified by the InstanceName parameter is initially specified using the StartTrace function, and may be obtained by calling the QueryAllTraces function.

This function assumes that the EVENT_TRACE_PROPERTIES structure has been properly initialized, as demonstrated in Configuring an EVENT_TRACE_PROPERTIES Structure.

To access the NT Kernel Logger, the Wnode.Guid member of Properties must be set to SystemTraceControlGuid, and any non-null string can be specified for InstanceName.

This function has been superseded by the ControlTrace function.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

Configuring an EVENT_TRACE_PROPERTIES Structure, ControlTrace, EVENT_TRACE_PROPERTIES, StartTrace, QueryAllTraces


RegisterTraceGuids

The RegisterTraceGuids function registers an event trace provider and the event trace classes that it uses to generate traces. This function also specifies the function used to enable and disable tracing for the provider.

The RegisterTraceGuids function provides the option of storing Managed Object Format (MOF) descriptions of event trace classes in the Windows Management Instrumentation (WMI) Common Information Model (CIM) repository.

ULONG RegisterTraceGuids(
  WMIDPREQUEST RequestAddress,
  PVOID RequestContext,
  LPCGUID ControlGuid,
  ULONG GuidCount,
  PTRACE_GUID_REGISTRATION TraceGuidReg,
  LPCTSTR MofImagePath,
  LPCTSTR MofResourceName,
  PTRACEHANDLE RegistrationHandle
);

Parameters

RequestAddress
[in] Callback function that receives notification when the registered provider specified by ControlGuid is enabled or disabled for an event tracing session. This function must conform to the ControlCallback prototype.
RequestContext
[in] Pointer to an optional user-defined context that is passed into the function specified by RequestAddress.
ControlGuid
[in] GUID of the registering provider.
GuidCount
[in] Number of elements in the TraceGuidReg array.
TraceGuidReg
[in, out] Pointer to the first element of an array containing GuidCount TRACE_GUID_REGISTRATION structures.

On input, the Guid member of each structure contains the GUID assigned to an event traced by the registering provider. On output, the RegHandle member receives a handle to the event's trace GUID registration.

MofImagePath
[in] String that specifies the path of the DLL or executable program that contains the resource specified by MofResourceName.
MofResourceName
[in] String resource that names the binary MOF file containing descriptions of the traces generated by the registered provider.
RegistrationHandle
[out] Pointer to the provider's registration handle, eventually passed to the UnregisterTraceGuids function.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a non-zero error code. The following table lists common errors and their causes.

Error code | Meaning
ERROR_INVALID_PARAMETER | One of the following is true: RequestAddress is null. ControlGuid is null. TraceGuidReg is null. RegistrationHandle is null. GuidCount is less than or equal to zero.

Remarks

The function specified by the RequestAddress parameter is called by the EnableTrace function to enable or disable event tracing by the provider for a given session.

If using WMI to store description of event traces, the classes associated with trace GUIDs (stored in the Guid member of the TRACE_GUID_REGISTRATION structures) must derive from the class associated with the provider, and the provider's class must derive from the EventTrace abstract class.

When RegisterTraceGuids is successful, a valid handle is received by RegistrationHandle. This handle is required by the UnregisterTraceGuids function to unregister the provider.

After a successful call to RegisterTraceGuids, each RegHandle member in the TRACE_GUID_REGISTRATION structures receives a handle to a trace GUID registration. This handle is required to trace a set of events that make up a discrete transaction, using the TraceEventInstance and CreateTraceInstanceId functions.

If the provider's ControlGuid has been previously registered and enabled, subsequent registrations that reference the same ControlGuid are automatically enabled.

For an example that uses RegisterTraceGuids, see Registering to Provide Events.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

ControlCallback, CreateTraceInstanceId, EnableTrace, Registering to Provide Events, TRACE_GUID_REGISTRATION, TraceEventInstance, UnregisterTraceGuids


RemoveTraceCallback

The RemoveTraceCallback function disassociates an EventClassCallback function implementation from an event trace class.

The EventClassCallback function implementation must have been associated previously using the SetTraceCallback function.

ULONG RemoveTraceCallback(
  LPCGUID pGuid
);

Parameters

pGuid
[in] Pointer to the GUID of an event trace class.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a non-zero error code. The following table lists common errors and their causes.

Error code | Meaning
ERROR_INVALID_PARAMETER | The pGuid parameter is null.
ERROR_WMI_GUID_NOT_FOUND | There is no EventClassCallback function associated with the class identified by pGuid.

Remarks

An EventClassCallback function implementation is called by the ProcessTrace function to deliver any traces containing the GUID specified by pGuid.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

EventClassCallback, ProcessTrace, SetTraceCallback


SetTraceCallback

The SetTraceCallback function associates an EventClassCallback function implementation with an event trace class.

ULONG SetTraceCallback(
  LPCGUID pGuid,
  PEVENT_CALLBACK EventCallback
);

Parameters

pGuid
[in] Pointer to the GUID of an event trace class.
EventCallback
[in] An EventClassCallback function implementation used to deliver traces belonging to the class specified by pGuid.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a non-zero error code. The following table lists common errors and their causes.

Error code | Meaning
ERROR_INVALID_PARAMETER | One of the following is true: pGuid is null. EventCallback is null.

Remarks

An EventClassCallback function implementation is called by the ProcessTrace function to deliver any traces containing the GUID specified by pGuid.

Remove the association between the callback function and the GUID, using the RemoveTraceCallback function.

For an example that uses SetTraceCallback, see Setting the EventClassCallback Function.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

EventClassCallback, ProcessTrace, RemoveTraceCallback, Setting the EventClassCallback Function


StartTrace

The StartTrace function starts an event tracing session.

ULONG StartTrace(
  PTRACEHANDLE TraceHandle,
  LPTSTR InstanceName,
  PEVENT_TRACE_PROPERTIES Properties
);

Parameters

TraceHandle
[out] Receives a handle to the started event tracing session.
InstanceName
[in] Name of the event tracing session.
Properties
[in, out] Pointer to an EVENT_TRACE_PROPERTIES structure. On input, the LogfileMode member of this structure should contain one or more of the following flags.
Flag | Value
EVENT_TRACE_FILE_MODE_APPEND

(Whistler only)

 Append to an existing sequential log file. This value may not be used with real time event trace delivery (EVENT_TRACE_REAL_TIME_MODE), or with circular log files (EVENT_TRACE_FILE_MODE_CIRCULAR).
EVENT_TRACE_FILE_MODE_CIRCULAR | Store traces in a disk file, replacing older traces with new traces.
EVENT_TRACE_FILE_MODE_NONE | Do not store traces.
EVENT_TRACE_FILE_MODE_SEQUENTIAL | Store traces in a disk file, until file size limit is reached.
EVENT_TRACE_PRIVATE_LOGGER_MODE | A private logger is being used. This value cannot be specified if EVENT_TRACE_REAL_TIME_MODE is specified. See Remarks.
EVENT_TRACE_REAL_TIME_MODE | Deliver traces to consumers in real time. This value cannot be specified if EVENT_TRACE_PRIVATE_LOGGER_MODE is specified.
EVENT_TRACE_USE_GLOBAL_SEQUENCE

(Whistler only)

 Use sequence numbers that are unique across event tracing sessions. See TraceMessage for usage details.
EVENT_TRACE_USE_LOCAL_SEQUENCE

(Whistler only)

 Use sequence numbers that are unique only for an individual event tracing session. See TraceMessage for usage details.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a non-zero error code. The following table lists common errors and their causes.

Error code | Meaning
ERROR_BAD_LENGTH | One of the following is true: The Wnode.BufferSize member of Properties specifies an incorrect size. Properties does not have sufficient space allocated to hold a copy of InstanceName.
ERROR_INVALID_PARAMETER | One of the following is true: Properties is null. TraceHandle is null. The LogfileNameOffset member of Properties is invalid. The LoggerNameOffset member of Properties is invalid. Properties.LogfileMode specified values for real-time delivery and private logger mode.
ERROR_ALREADY_EXISTS | Properties.Wnode.Guid specified the GUID for the NT Kernel Logger, and it has already been started.
ERROR_INVALID_PATHNAME | One of the following is true: A session is already using the file name specified by Properties.LogfileName. EVENT_TRACE_REAL_TIME_MODE is not specified in Properties.LogfileMode, but no file name is specified in Properties.LogfileName.

Remarks

To stop an executing event tracing session, use the StopTrace or ControlTrace functions.

This function assumes that the EVENT_TRACE_PROPERTIES structure has been properly initialized, as demonstrated in Configuring an EVENT_TRACE_PROPERTIES Structure.

When starting a private logger the EVENT_TRACE_PROPERTIES Wnode member structure's Guid member (Wnode.Guid) must contain the private logger's control GUID.

For an example that uses StartTrace, see Starting an Event Tracing Session.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

Configuring an EVENT_TRACE_PROPERTIES Structure, ControlTrace, EVENT_TRACE_PROPERTIES, Starting an Event Tracing Session, StopTrace


StopTrace

The StopTrace function stops an event tracing session previously started using the StartTrace function.

This function has been superseded by the ControlTrace function.

ULONG StopTrace(
  TRACEHANDLE TraceHandle,
  LPTSTR InstanceName,
  PEVENT_TRACE_PROPERTIES Properties
);

Parameters

TraceHandle
[in] Handle to the event tracing session to stop. Either TraceHandle or InstanceName is required.
InstanceName
[in] Name of the event tracing session to stop. Either TraceHandle or InstanceName is required.
Properties
[out] Pointer to an EVENT_TRACE_PROPERTIES structure that receives the final properties and execution statistics for the session.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a non-zero error code. The following table lists common errors and their causes.

Error code | Meaning
ERROR_BAD_LENGTH | The Wnode.BufferSize member of Properties specifies an incorrect size.
ERROR_INVALID_PARAMETER | One of the following is true: Properties is null. The LogfileNameOffset member of Properties is invalid. The LoggerNameOffset member of Properties is invalid. InstanceName and TraceHandle are null.

Remarks

Either InstanceName or TraceHandle must be supplied.

To access the NT Kernel Logger, the Wnode.Guid member of Properties must specify the SystemTraceControlGuid GUID.

This function assumes that the EVENT_TRACE_PROPERTIES structure has been properly initialized, as demonstrated in Configuring an EVENT_TRACE_PROPERTIES Structure.

This function has been superseded by the ControlTrace function.

For an example using StopTrace, see Stopping an Event Tracing Session.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

Configuring an EVENT_TRACE_PROPERTIES Structure, ControlTrace, EVENT_TRACE_PROPERTIES, StartTrace, Stopping an Event Tracing Session


TraceEvent

The TraceEvent function sends an event trace to an event tracing session to be written to a log file or forwarded to event trace consumers in real time.

ULONG TraceEvent(
  TRACEHANDLE TraceHandle,
  PEVENT_TRACE_HEADER EventTrace
);

Parameters

TraceHandle
[in] Handle to the event tracing session that should record the trace.
EventTrace
[in] Pointer to an EVENT_TRACE_HEADER structure, optionally appended with event-specific data. The members of the EVENT_TRACE_HEADER section of EventTrace must be initialized as follows.
Member | Initial value
Size | Total number of bytes to be recorded for the trace, including the EVENT_TRACE_HEADER structure. For more information, see the Remarks section.
Guid Trace GUID assigned to the class that describes the trace. The GuidPtr member may be used instead.

The trace GUID must have been registered previously using the RegisterTraceGuids function.

GuidPtr Pointer to the trace GUID assigned to the class that describes the trace. The Guid member may be used instead.

The trace GUID must have been registered previously using the RegisterTraceGuids function.

Flags WNODE_FLAG_TRACED_GUID flag.

If the trace GUID is specified using the GuidPtr member, also add the WNODE_FLAG_USE_GUID_PTR flag.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a non-zero error code. The following table lists common errors and their causes.

Error code | Meaning
ERROR_INVALID_FLAG_NUMBER | The Flags member of the EVENT_TRACE_HEADER section of EventTrace is incorrect.
ERROR_INVALID_HANDLE | TraceHandle specified the NT Kernel Logger session handle.
ERROR_OUTOFMEMORY | There was insufficient memory to complete the function call. The causes for this error code are described in the following Remarks section.
ERROR_INVALID_PARAMETER | One of the following is true: TraceHandle is null. EventTrace is null. The Size member of the EVENT_TRACE_HEADER section of EventTrace is incorrect.

Remarks

Before tracing events, the event trace provider must have previously registered by calling the RegisterTraceGuids function. The TRACE_GUID_REGISTRATION structures passed into the registration must have included a entry for the trace GUID referenced in this event trace.

The event trace provider must be enabled. To enable a provider, call the EnableTrace function.

Data from a single trace cannot span multiple buffers. An event trace is limited to the size of the event tracing session's buffer minus 72 bytes. The 72 bytes are used to hold buffer header information.

The ERROR_OUTOFMEMORY error code is returned if either of the following conditions is true:

  • The trace has been discarded because the buffer pool has reached its maximum size and there is no buffer available to receive the trace. For possible solutions, see Setting Buffer Properties.
  • The trace has been discarded because, although the buffer pool has not reached maximum size, there is insufficient available memory to allocate an additional buffer and there is no buffer available to receive the trace. If you are logging to a private logger, make additional paged memory available. If logging to one of the 32 system loggers, make additional non-paged memory available.

To trace a set of related events, use the TraceEventInstance function.

For an example that uses TraceEvent, see Tracing Events.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

EnableTrace, EVENT_TRACE_HEADER, RegisterTraceGuids, TraceEventInstance, TRACE_GUID_REGISTRATION, Tracing Events


TraceEventInstance

The TraceEventInstance function records the events associated with a transaction as it progresses through multiple stages of execution. This function may also be used to track hierarchical relationships between related events.

Transactions and the event instances they generate are identified by unique transaction identifiers, obtained by calling the CreateTraceInstanceId function.

ULONG TraceEventInstance(
  TRACEHANDLE TraceHandle,
  PEVENT_INSTANCE_HEADER EventTrace,
  PEVENT_INSTANCE_INFO pInstInfo,
  PEVENT_INSTANCE_INFO pParentInstInfo
);

Parameters

TraceHandle
[in] Handle to the event tracing session that records the event instance.
EventTrace
[in] Pointer to an EVENT_INSTANCE_HEADER structure, optionally appended with event-specific data. The required members of the EVENT_INSTANCE_HEADER section of EventTrace must be initialized as follows.
Member | Initial value
Size | Total number of bytes to be recorded for the trace, including the EVENT_INSTANCE_HEADER structure.
Flags | WNODE_FLAG_TRACED_GUID flag.

pInstInfo
[in] Pointer to an EVENT_INSTANCE_INFO structure initialized for this event. This structure is populated by a previous call to the CreateTraceInstanceId function using the trace GUID registration handle for this trace's event trace class.
pParentInstInfo
[in] Pointer to an optional EVENT_INSTANCE_INFO structure initialized for a parent event. This structure is populated by a previous call to the CreateTraceInstanceId function, using the trace GUID registration handle for the parent event.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a non-zero error code. The following table lists common errors and their causes.

Error code | Meaning
ERROR_INVALID_FLAGS | The Flags member of the EVENT_INSTANCE_HEADER section of EventTrace does not contain WNODE_FLAG_TRACED_GUID.
ERROR_OUTOFMEMORY | There was insufficient memory to complete the function call. The causes for this error code are described in the following Remarks section.
ERROR_INVALID_PARAMETER | One of the following is true: EventTrace is null. pInstInfo is null. The members of pInstInfo are null. TraceHandle is null. The Size member of the EVENT_INSTANCE_HEADER section of EventTrace is incorrect.

Remarks

Before tracing event instances, the event trace provider must have registered by calling the RegisterTraceGuids function, and the TRACE_GUID_REGISTRATION structures populated during registration must be available. The RegHandle members of these structures contain the trace GUID registration handles required by the CreateTraceInstanceId function to obtain a unique transaction identifier.

The ERROR_OUTOFMEMORY error code is returned if either of the following conditions is true:

  • The trace has been discarded because the buffer pool has reached its maximum size and there is no buffer available to receive the trace. For possible solutions, see Setting Buffer Properties.
  • The trace has been discarded because, although the buffer pool has not reached maximum size, there is insufficient available memory to allocate an additional buffer and there is no buffer available to receive the trace. If you are logging to a private logger, make additional paged memory available. If logging to one of the 32 system loggers, make additional non-paged memory available.

For an example of generating related sets of event traces using CreateTraceInstanceId and TraceEventInstance, see Tracing Event Instances.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

CreateTraceInstanceId, EVENT_INSTANCE_HEADER, EVENT_INSTANCE_INFO, RegisterTraceGuids, TRACE_GUID_REGISTRATION, Tracing Event Instances


TraceMessage

[This is preliminary documentation and subject to change.]

The TraceMessage function is used to include informational messages in event tracing session output.

This function consumes fewer resources than the TraceEvent and TraceEventInstance functions.

ULONG TraceMessage (
  TRACEHANDLE LoggerHandle,
  ULONG MessageFlags,
  LPGUID MessageGuid,
  USHORT MessageNumber,
  …
);

Parameters

LoggerHandle
[in] Handle to an event tracing session.
MessageFlags
[in] Values that control the information generated as part of the trace message.

The following table lists the valid values for the MessageFlags parameter.
Flag | Description
TRACE_MESSAGE_SEQUENCE | Include a sequence number in the message. For more information, see the Remarks section.
TRACE_MESSAGE_GUID | The MessageGuid parameter specifies a GUID. Always specify this flag.
TRACE_MESSAGE_TIMESTAMP | Include a time stamp in the message.
TRACE_MESSAGE_PERFORMANCE_TIMESTAMP | Time stamp is the performance counter (not the system clock). This flag is valid only if TRACE_MESSAGE_TIMESTAMP is also specified.
TRACE_MESSAGE_SYSTEMINFO | Include the thread identifier (TID) and process identifier (PID) in the message.

MessageGuid
[in ] The GUID associated with the class of the current message.
MessageNumber
[in] A number that uniquely identifies each occurrence of the message. You must define the value specified for this parameter; the value should be meaningful to the application.
…
A list of variable arguments to be appended to the message. The list must be composed of pairs of arguments, as described in the following table.
Data Type | Description
PVOID | Pointer to the argument data.
ULONG | The size of the argument data, in bytes.

The list must be terminated by an argument pair consisting of a pointer to NULL and zero.

The caller must ensure that the sum of the sizes of the arguments + 72 does not exceed the size of the event tracing session's buffer.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a non-zero error code. The following table lists common errors and their causes.

Error code | Meaning
ERROR_INVALID_HANDLE | TraceHandle is null. TraceHandle specified the NT Kernel Logger session handle.
ERROR_OUTOFMEMORY | There was insufficient memory to complete the function call. The causes for this error code are described in the following Remarks section.
ERROR_INVALID_PARAMETER | MessageFlags contains an invalid value.

Remarks

If you need to access message tracing functionality from a wrapper function, call the TraceMessageVa version of this function.

To include a sequence number in the message, specify the TRACE_MESSAGE_SEQUENCE flag in the MessageFlags parameter and enable message sequence numbering for the event tracing session indicated by the LoggerHandle parameter.

You can enable message sequence numbering for an event tracing session when starting the session or by updating the session properties. To start a new event tracing session, call the StartTrace function or alter the properties of an existing event tracing session by calling the UpdateTrace function. Specify one of the following flags in the LogFileMode member of the EVENT_TRACE_PROPERTIES structure required by these functions.

LogFileMode flag | Description
EVENT_TRACE_USE_GLOBAL_SEQUENCE | Use sequence numbers that are unique across event tracing sessions.
EVENT_TRACE_USE_LOCAL_SEQUENCE | Use sequence numbers that are unique only for an individual event tracing session.

The ERROR_OUTOFMEMORY error code is returned if either of the following conditions is true:

  • The trace message has been discarded because the buffer pool has reached its maximum size and there is no buffer available to receive the trace. For possible solutions, see Setting Buffer Properties.
  • The trace message has been discarded because, although the buffer pool has not reached maximum size, there is insufficient available memory to allocate an additional buffer and there is no buffer available to receive the trace. If you are logging to a private logger, make additional paged memory available. If logging to one of the 32 system loggers, make additional non-paged memory available.

Requirements

Windows NT/2000 or later: Requires Whistler.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

StartTrace, TraceEvent, TraceEventInstance, TraceMessageVa, UpdateTrace


TraceMessageVa

[This is preliminary documentation and subject to change.]

The TraceMessageVa function is used to include informational messages in event tracing session output.

This function consumes fewer resources than the TraceEvent and TraceEventInstance functions.

ULONG TraceMessageVa (
  TRACEHANDLE LoggerHandle,
  ULONG MessageFlags,
  LPGUID MessageGuid,
  USHORT MessageNumber,
  va_list MessageArgList
);

Parameters

LoggerHandle
[in] Handle to an event tracing session.
MessageFlags
[in] Values that control the information generated as part of the trace message.

The following table lists the valid values for the MessageFlags parameter.
Flag | Description
TRACE_MESSAGE_SEQUENCE | Include a sequence number in the message. For more information, see the Remarks section.
TRACE_MESSAGE_GUID | The MessageGuid parameter specifies a GUID. Always specify this flag.
TRACE_MESSAGE_TIMESTAMP | Include a time stamp in the message.
TRACE_MESSAGE_PERFORMANCE_TIMESTAMP | Time stamp is the performance counter (not the system clock). This flag is valid only if TRACE_MESSAGE_TIMESTAMP is also specified.
TRACE_MESSAGE_SYSTEMINFO | Include the thread identifier (TID) and process identifier (PID) in the message.

MessageGuid
[in] The GUID associated with the class of the current message.
MessageNumber
[in] A number that uniquely identifies each occurrence of the message. You must define the value specified for this parameter; the value should be meaningful to the application.
MessageArgList
A list of variable arguments to be appended to the message. The list must be composed of pairs of arguments, as described in the following table.
Data Type | Description
PVOID | Pointer to the argument data.
ULONG | The size of the argument data, in bytes.

The list must be terminated by an argument pair consisting of a pointer to NULL and zero.

The caller must ensure that the sum of the sizes of the arguments + 72 does not exceed the size of the event tracing session's buffer.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a non-zero error code. The following table lists common errors and their causes.

Error code | Meaning
ERROR_INVALID_HANDLE | TraceHandle is null. TraceHandle specified the NT Kernel Logger session handle.
ERROR_OUTOFMEMORY | There was insufficient memory to complete the function call. The causes for this error code are described in the following Remarks section.
ERROR_INVALID_PARAMETER | MessageFlags contains an invalid value.

Remarks

If you do not need to access the message tracing functionality from a wrapper function, you can call the TraceMessage version of this function.

To include a sequence number in the message, specify the TRACE_MESSAGE_SEQUENCE flag in the MessageFlags parameter and enable message sequence numbering for the event tracing session indicated by the LoggerHandle parameter.

You can enable message sequence numbering for an event tracing session when starting the session or by updating the session properties. To start a new event tracing session, call the StartTrace function or alter the properties of an existing event tracing session by calling the UpdateTrace function. Specify one of the following flags in the LogFileMode member of the EVENT_TRACE_PROPERTIES structure required by these functions.

LogFileMode flag | Description
EVENT_TRACE_USE_GLOBAL_SEQUENCE | Use sequence numbers that are unique across event tracing sessions.
EVENT_TRACE_USE_LOCAL_SEQUENCE | Use sequence numbers that are unique only for an individual event tracing session.

The ERROR_OUTOFMEMORY error code is returned if either of the following conditions is true:

  • The trace message has been discarded because the buffer pool has reached its maximum size and there is no buffer available to receive the trace. For possible solutions, see Setting Buffer Properties.
  • The trace message has been discarded because, although the buffer pool has not reached maximum size, there is insufficient available memory to allocate an additional buffer and there is no buffer available to receive the trace. If you are logging to a private logger, make additional paged memory available. If logging to one of the 32 system loggers, make additional non-paged memory available.

Requirements

Windows NT/2000 or later: Requires Whistler.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

StartTrace, TraceEvent, TraceEventInstance, TraceMessage, UpdateTrace


UnregisterTraceGuids

The UnregisterTraceGuids function unregisters an event trace provider and its event trace classes.

ULONG UnregisterTraceGuids(
  TRACEHANDLE RegistrationHandle
);

Parameters

RegistrationHandle
[in] Handle to the event trace provider, obtained from an earlier call to the RegisterTraceGuids function.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a non-zero error code.

If the RegistrationHandle parameter does not specify the handle to a registered provider, this function returns ERROR_INVALID_PARAMETER.

Remarks

The event trace provider must have been registered previously by calling the RegisterTraceGuids function.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

RegisterTraceGuids


UpdateTrace

The UpdateTrace function updates the properties of an event tracing session.

This function has been superseded by the ControlTrace function.

ULONG UpdateTrace(
  TRACEHANDLE TraceHandle,
  LPTSTR InstanceName,
  PEVENT_TRACE_PROPERTIES Properties
);

Parameters

TraceHandle
[in] Handle to the event tracing session being updated. Either TraceHandle or InstanceName is required.
InstanceName
[in] Name of the event tracing session to update. Either TraceHandle or InstanceName is required.
Properties
[in, out] Pointer to an EVENT_TRACE_PROPERTIES structure. On input, this parameter contains the new settings for the properties of the event tracing session. On output, it contains the updated settings and execution statistics for the event tracing session.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a non-zero error code.

Remarks

The value specified for the TraceHandle parameter can be obtained using the QueryTrace, ControlTrace, QueryAllTraces, or StartTrace functions.

To obtain the properties and executions statistics for an event tracing session, use the QueryTrace function.

This function assumes that the EVENT_TRACE_PROPERTIES structure has been properly initialized, as demonstrated in Configuring an EVENT_TRACE_PROPERTIES Structure.

For an example that uses UpdateTrace, see Updating an Event Tracing Session.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

Configuring an EVENT_TRACE_PROPERTIES Structure, ControlTrace, EVENT_TRACE_PROPERTIES, StartTrace, QueryAllTraces, QueryTrace, Updating an Event Tracing Session


Event Tracing Function Prototypes

Function prototypes are callback functions implemented by a developer to handle application-specific processing.

Function prototype | Description
BufferCallback Prototype | Does any processing required after each buffer of traces is delivered to the consumer. Implemented by event trace consumers.
ControlCallback Prototype | Notifies event trace providers to enable or disable event tracing. Implemented by event trace providers.
EventCallback Prototype | Processes each trace requested by a consumer. Implemented by event trace consumers.
EventClassCallback Prototype | Processes each trace belonging to a specific event trace class and requested by a consumer. Implemented by event trace consumers.


BufferCallback Prototype

A BufferCallback function is an application-defined function used to deliver information about each buffer of traces that is delivered to an event trace consumer.

This function must be implemented by an event trace consumer and is called after each buffer of traces is delivered.

ULONG WINAPI <FunctionName> (
  PEVENT_TRACE_LOGFILE Logfile
);

Parameters

Logfile
[in] Pointer to an EVENT_TRACE_LOGFILE structure containing information about the buffer processed. The members of the structure that are set each time this function is called are as follows.
Member | Value
BufferSize | Number of bytes allocated for the buffer.
Filled | Number of bytes used.
EventsLost | Number of lost events that should have been recorded in the buffer.

Return Values

If the function implementation returns TRUE, event trace processing continues.

If the function implementation returns FALSE, event trace processing terminates.

Remarks

Specify the implementation of a BufferCallback function using the BufferCallback member of an EVENT_TRACE_LOGFILE structure, before passing it to the OpenTrace function.

Trace processing started by calling the ProcessTrace function can be canceled by returning FALSE from this function.

For an example implementation of a BufferCallback function, see Implementing Buffer Notification.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

EVENT_TRACE_LOGFILE, Implementing Buffer Notification, OpenTrace, ProcessTrace


ControlCallback Prototype

A ControlCallback function is an application-defined function called by the EnableTrace function to enable or disable an event trace provider.

This function must be implemented by event trace providers, and is specified using the RegisterTraceGuids function.

ULONG WINAPI <FunctionName> (
  WMIDPREQUESTCODE RequestCode,
  PVOID Context,
  ULONG *InOutBufferSize,
  PVOID Buffer
);

Parameters

RequestCode
[in] Specifies WMI_ENABLE_EVENTS to enable the provider, or WMI_DISABLE_EVENTS to disable the provider.
Context
[in] User-defined context. This context is specified during registration by the RequestContext parameter passed into RegisterTraceGuids.
InOutBufferSize
[in] Reserved for internal use.
Buffer
[in] A WNODE_HEADER structure that contains information about the event tracing session for which the provider is being enabled/disabled..

Return Values

The value returned from this function is ignored.

Remarks

When EnableTrace is called, an event tracing session handle, user-defined flags, and a user-defined level in the range from 0 to 255 can be specified. A ControlCallback implementation can obtain the session handle by calling the GetTraceLoggerHandle function. The flags and level can be obtained by calling the GetTraceEnableFlags and GetTraceEnableLevel functions, respectively.

For an example implementation of a ControlCallback function, see Implementing a ControlCallback Function.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

EnableTrace, GetTraceEnableFlags, GetTraceEnableLevel, GetTraceLoggerHandle, Implementing a ControlCallback Function, RegisterTraceGuids, WNODE_HEADER


EventCallback Prototype

The EventCallback function is an application-defined function used to deliver traces to an event trace consumer.

This function must be implemented by event trace consumers, and is called once for each trace processed by the ProcessTrace function.

VOID WINAPI <FunctionName> (
  PEVENT_TRACE pEvent
);

Parameters

pEvent
[in] Pointer to an EVENT_TRACE structure containing trace information.

Return Values

The function does not return a value.

Remarks

The layout of the EVENT_TRACE structure passed to the EventCallback function is provider-specific. Contact the provider developer for details.

Specify the implementation of the EventCallback function using the EventCallback member of an EVENT_TRACE_LOGFILE structure, before passing it to the OpenTrace function.

To do special processing for the traces belonging to a specific event trace class, implement the EventClassCallback function.

For an example implementation of an EventCallback function, see Implementing Generic Event Delivery.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

EVENT_TRACE, EVENT_TRACE_LOGFILE, EventClassCallback Prototype, Implementing Generic Event Delivery, OpenTrace, ProcessTrace


EventClassCallback Prototype

The EventClassCallback functions are application-defined functions used to deliver traces belonging to specific event trace classes to an event trace consumer for special processing.

These functions are implemented by event trace consumers. Associate each EventClassCallback function and the trace GUID of the event trace class it processes, using the SetTraceCallback function.

VOID WINAPI <FunctionName> (
  PEVENT_TRACE pEvent
);

Parameters

pEvent
[in] Pointer to an EVENT_TRACE structure containing trace information.

Return Values

The function does not return a value.

Remarks

The layout of the EVENT_TRACE structure passed to EventClassCallback functions are provider-specific. Contact the provider developer for details.

To stop the ProcessTrace function from calling an EventClassCallback function as traces are processed, call the RemoveTraceCallback function.

To do generic processing for all traces, see the EventCallback function.

For an example implementation of an EventClassCallback function, see Implementing Event Class Delivery.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Library: Use Advapi32.lib.

See Also

EventCallback, Implementing Event Class Delivery, OpenTrace, ProcessTrace, RemoveTraceCallback, SetTraceCallback


Event Tracing Structures

Event tracing uses the following structures.

Structure | Used by
EVENT_INSTANCE_HEADER | TraceEventInstance
EVENT_INSTANCE_INFO | CreateTraceInstanceId TraceEventInstance
EVENT_TRACE | EventCallback EventClassCallback EVENT_TRACE_LOGFILE
EVENT_TRACE_HEADER | TraceEvent
EVENT_TRACE_LOGFILE | OpenTrace BufferCallback
EVENT_TRACE_PROPERTIES | ControlTrace QueryTrace QueryAllTraces StartTrace StopTrace UpdateTrace
MOF_FIELD | TraceEvent TraceEventInstance
TRACE_ENABLE_CONTEXT | ControlCallback
TRACE_GUID_PROPERTIES | EnumerateTraceGuids
TRACE_GUID_REGISTRATION | CreateTraceInstanceId RegisterTraceGuids
TRACE_LOGFILE_HEADER | EVENT_TRACE_LOGFILE
WNODE_HEADER | EVENT_TRACE_PROPERTIES


EVENT_INSTANCE_HEADER

The EVENT_INSTANCE_HEADER structure is used by the TraceEventInstance function to generate event traces that are linked to a specific transaction, or each other.

typedef struct _EVENT_INSTANCE_HEADER {
  USHORT          Size;
  UCHAR           HeaderType;
  UCHAR           MarkerFlags;
    union {
      ULONG       Version;
      struct {
        UCHAR     Type;
        UCHAR     Level;
        USHORT    Version;
      } Class;
    };
    ULONGLONG       ThreadId;
    LARGE_INTEGER   TimeStamp;
    ULONGLONG       RegHandle;
    ULONG           InstanceId;
    ULONG           ParentInstanceId;
    union {
      struct {
        ULONG     ClientContext;
        ULONG     Flags;
      };
      struct {
        ULONG     KernelTime;
        ULONG     UserTime;
      };
      ULONG64     ProcessorTime;
    };
    ULONGLONG       ParentRegHandle;
} EVENT_INSTANCE_HEADER;

Members

Size
Total number of bytes required to hold trace information for the event instance. Size must include the size of the EVENT_INSTANCE_HEADER structure, plus the size of any user-defined trace data appended to the structure.
HeaderType
Reserved.
MarkerFlags
Reserved.
Version
Reserved.
Type
Type of event instance. An event instance type is either user-defined or predefined. The following table identifies the predefined event types.
Event type | Description
EVENT_TRACE_TYPE_ACCEPT | Accept event. Use when a client accepts a connection for which a listen had previously completed.
EVENT_TRACE_TYPE_CHECKPOINT | Checkpoint event. Use for an event that is not at the start or end of an activity.
EVENT_TRACE_TYPE_CONFIG | Reserved for internal use.
EVENT_TRACE_TYPE_DC_END | Collection end event.
EVENT_TRACE_TYPE_DC_START | Collection start event.
EVENT_TRACE_TYPE_DEQUEUE | Dequeue event. Use when an activity is queued before it begins. Use EVENT_TRACE_TYPE_START to mark the time when a work item is queued. Use the dequeue event type to mark the time when work on the item actually begins. Use EVENT_TRACE_TYPE_END to mark the time when work on the item completes.
EVENT_TRACE_TYPE_END | End event. Use to trace the final state of a multi-part event.
EVENT_TRACE_TYPE_EXTENSION | Extension event. Use for an event that is a continuation of a previous event. For example, use the extension event type when an event trace records more data than can fit in a session buffer.
EVENT_TRACE_TYPE_GUIDMAP | Reserved for internal use.
EVENT_TRACE_TYPE_INFO | Informational event. This is the default event type.
EVENT_TRACE_TYPE_REPLY | Reply event. Use when an application that requests resources can receive multiple responses. For example, if a client application requests a URL, and the Web server reply is to send several files, each file received can be marked as a reply event.
EVENT_TRACE_TYPE_RESERVED9 | Reserved for internal use.
EVENT_TRACE_TYPE_RETRANSMIT | Data retransmission event.
EVENT_TRACE_TYPE_SECURITY | Reserved for internal use.
EVENT_TRACE_TYPE_SIDINFO | Reserved for internal use.
EVENT_TRACE_TYPE_START | Start event. Use to trace the initial state of an event that is divided into subevents.

Level
User defined value, ranging from 0 to 255.
Version
Reserved.
ThreadId
Identifier of the thread that generates the event instance trace.
TimeStamp
Time that an event instance occurs, in milliseconds since midnight, January 1, 1601.
RegHandle
Handle to a registered event trace class, obtained by calling the RegisterTraceGuids function.
InstanceId
Identifier that links related traces, obtained by calling the CreateTraceInstanceId function.
ParentInstanceId
Identifier for a previously generated parent event trace. ParentInstanceId is specified when tracing nested transactions.
ClientContext
Reserved.
Flags
Flags must contain WNODE_FLAG_TRACED_GUID, and may also contain WNODE_FLAG_USE_MOF_PTR if the trace data appended to this structure is stored in an array of MOF_FIELD structures.
KernelTime
Elapsed execution time for kernel mode instructions, in CPU ticks. If you are using a private logger, use the value in the ProcessorTime member instead.
UserTime
Elapsed execution time for user mode instructions, in CPU ticks. If you are using a private logger, use the value in the ProcessorTime member instead.
ProcessorTime
Specifies the cycle count if you are using a private logger.
ParentRegHandle
Handle to the registered event trace class of the parent event.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.

See Also

CreateTraceInstanceId, RegisterTraceGuids, TraceEventInstance


EVENT_INSTANCE_INFO

The EVENT_INSTANCE_INFO structure links a unique transaction identifier to a registered event trace class.

typedef struct EVENT_INSTANCE_INFO {
  HANDLE RegHandle;
  ULONG InstanceId;
} EVENT_INSTANCE_INFO, *PEVENT_INSTANCE_INFO;

Members

RegHandle
Handle to a registered event trace class.
InstanceId
Unique transaction identifier that links an event trace to a specific transaction.

Remarks

The CreateTraceInstanceId and TraceEventInstance functions use the EVENT_INSTANCE_INFO structure.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.

See Also

CreateTraceInstanceId, TraceEventInstance


EVENT_TRACE

The EVENT_TRACE structure is used to deliver trace information to event trace consumers.

This structure is passed into the EventCallback and EventClassCallback functions implemented by consumers.

typedef struct _EVENT_TRACE {
  EVENT_TRACE_HEADER Header;
  ULONG InstanceId;
  ULONG ParentInstanceId;
  GUID ParentGuid;
  PVOID MofData;
  ULONG MofLength;
  ULONG ClientContext;
} EVENT_TRACE, *PEVENT_TRACE;

Members

Header
An EVENT_TRACE_HEADER structure that contains standard trace information.
InstanceId
Instance identifier. InstanceId contains valid data when the EVENT_TRACE structure contains traces generated by the TraceEventInstance function. For traces generated by the TraceEvent function, this member is zero.
ParentInstanceId
Instance identifier for a parent event. ParentInstanceId will have valid data when the EVENT_TRACE structure contains traces generated by the TraceEventInstance function and parent information was specified. For traces generated by the TraceEvent function, this member is zero.
ParentGuid
Trace GUID of the parent event. ParentGuid contains valid data when the EVENT_TRACE structure contains traces generated by the TraceEventInstance function, and parent information was specified. For traces generated by the TraceEvent function, this member is zero.
MofData
Pointer to the beginning of the user-defined data for this event trace.
MofLength
Number of bytes pointed to by MofData.
ClientContext
Reserved.

Remarks

EVENT_TRACE structures are passed into consumer callback functions that are implemented for generic event delivery, and specific class delivery.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.

See Also

EventCallback, EventClassCallback, EVENT_TRACE_HEADER, TraceEvent, TraceEventInstance


EVENT_TRACE_HEADER

The EVENT_TRACE_HEADER structure contains standard trace information common to all event traces.

typedef struct _EVENT_TRACE_HEADER
{
  USHORT Size;
  UCHAR HeaderType;
  UCHAR MarkerFlags;
  union {
    ULONG Version;
    struct {
      UCHAR   Type;
      UCHAR   Level;
      USHORT  Version;
    } Class;
  };
  ULONGLONG  ThreadId;
  LARGE_INTEGER TimeStamp;
  union {
    GUID Guid;
    ULONGLONG GuidPtr;
  };
    union {
      struct {
        ULONG ClientContext;
        ULONG Flags;
      };
        struct {
          ULONG KernelTime;
          ULONG UserTime;
        };
        ULONG64 ProcessorTime;
    };
} EVENT_TRACE_HEADER, *PEVENT_TRACE_HEADER;

Members

Size
Total number of bytes required to contain the trace information. Size must include the size of the EVENT_TRACE_HEADER structure, plus the size of any user-defined trace data appended to this structure.
HeaderType
Reserved.
MarkerFlags
Reserved.
Version
Reserved.
Type
The type of event. An event type can be user-defined or predefined. The following table identifies general purpose event types that are predefined. For the event types defined for NT Kernel Logger events, see NT Kernel Logger Constants.
Event type | Description
EVENT_TRACE_TYPE_ACCEPT | Accept event. Use when a client accepts a connection for which a listen had previously completed.
EVENT_TRACE_TYPE_CHECKPOINT | Checkpoint event. Use for an event that is not at the start or end of an activity.
EVENT_TRACE_TYPE_CONFIG | Reserved for internal use.
EVENT_TRACE_TYPE_DC_END | Collection end event.
EVENT_TRACE_TYPE_DC_START | Collection start event.
EVENT_TRACE_TYPE_DEQUEUE | Dequeue event. Use when an activity is queued before it begins. Use EVENT_TRACE_TYPE_START to mark the time when a work item is queued. Use the dequeue event type to mark the time when work on the item actually begins. Use EVENT_TRACE_TYPE_END to mark the time when work on the item completes.
EVENT_TRACE_TYPE_END | End event. Use to trace the final state of a multi-part event.
EVENT_TRACE_TYPE_EXTENSION | Extension event. Use for an event that is a continuation of a previous event. For example, use the extension event type when an event trace records more data than can fit in a session buffer.
EVENT_TRACE_TYPE_GUIDMAP | Reserved for internal use.
EVENT_TRACE_TYPE_INFO | Informational event. This is the default event type.
EVENT_TRACE_TYPE_REPLY | Reply event. Use when an application that requests resources can receive multiple responses. For example, if a client application requests a URL, and the Web server reply is to send several files, each file received can be marked as a reply event.
EVENT_TRACE_TYPE_RESERVED9 | Reserved for internal use.
EVENT_TRACE_TYPE_RETRANSMIT | Data retransmission event.
EVENT_TRACE_TYPE_SECURITY | Reserved for internal use.
EVENT_TRACE_TYPE_SIDINFO | Reserved for internal use.
EVENT_TRACE_TYPE_START | Start event. Use to trace the initial state of an event that is divided into subevents.

Level
User defined value, ranging from 0 to 255.
Version
Reserved.
ThreadId
Identifier of the thread that generates the trace.
TimeStamp
Time the event occurs, in milliseconds since midnight, January 1, 1601.
Guid
Trace GUID of the event. You can also use the GuidPtr member to specify the trace GUID.
GuidPtr
Pointer to the trace GUID of the event. You can also use the Guid member to specify the trace GUID; however, if you use the GuidPtr member to specify the trace GUID, the Flags member must contain the WNODE_FLAG_USE_GUID_PTR flag.
ClientContext
Reserved.
Flags
Flags must contain WNODE_FLAG_TRACED_GUID, and may also contain any combination of the following.
Flag | Description
WNODE_FLAG_USE_GUID_PTR | A pointer to the trace GUID is located in the GuidPtr member of the EVENT_TRACE_HEADER structure.
WNODE_FLAG_USE_MOF_PTR | The trace data appended to this structure is stored in an array of MOF_FIELD structures.

KernelTime
Elapsed execution time for kernel mode instructions, in CPU ticks. If you are using a private logger, use the value in the ProcessorTime member instead.
UserTime
Elapsed execution time for user mode instructions, in CPU ticks. If you are using a private logger, use the value in the ProcessorTime member instead.
ProcessorTime
Specifies the cycle count if you are using a private logger.

Remarks

The EVENT_TRACE_HEADER structure is used by the TraceEvent function.

This structure is a member of the EVENT_TRACE structure passed into the EventCallback and EventClassCallback functions.

If the Flags member of an EVENT_TRACE_HEADER structure contains WNODE_FLAG_USE_GUID_PTR, then the GuidPtr member of this structure is valid, otherwise the Guid member is valid.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.

See Also

EventCallback, EventClassCallback, EVENT_TRACE, TraceEvent


EVENT_TRACE_LOGFILE

The EVENT_TRACE_LOGFILE structure contains information about event tracing session log files and buffers.

typedef struct _EVENT_TRACE_LOGFILE {
  LPTSTR LogFileName;
  LPTSTR LoggerName;
  LONGLONG CurrentTime;
  ULONG BuffersRead;
  ULONG LogFileMode;
  EVENT_TRACE CurrentEvent;
  TRACE_LOGFILE_HEADER LogfileHeader;
  PEVENT_TRACE_BUFFER_CALLBACK BufferCallback;
  ULONG BufferSize;
  ULONG Filled;
  ULONG EventsLost;
  PEVENT_CALLBACK EventCallback;
  ULONG IsKernelTrace;
  PVOID Context;
} EVENT_TRACE_LOGFILE, *PEVENT_TRACE_LOGFILE;

Members

LogFileName
Pointer to the name of an event tracing session log file.

The file name extension ETL is reserved for event tracing log files.

LoggerName
Pointer to the name of an event tracing session. The name must contain no more than 1024 characters.
CurrentTime
Current time, in milliseconds since midnight, January 1, 1601.
BuffersRead
Number of buffers processed.
LogFileMode
Specifies current logging modes for the event tracing session.

LogFileMode contains one or more of the following.
Mode | Description
EVENT_TRACE_ADD_HEADER_MODE | Add a log file header. Do not specify this setting; it is used internally.
EVENT_TRACE_BUFFERING_MODE | Event traces are not written to a log file or delivered in real-time. Do not specify this setting; it is used internally.
EVENT_TRACE_DELAY_OPEN_FILE_MODE | Delay opening file. Do not specify this setting; it is used internally.
EVENT_TRACE_FILE_MODE_APPEND

(Whistler only)

 Append to an existing sequential log file. Do not use this setting with EVENT_TRACE_REAL_TIME_MODE, or EVENT_TRACE_FILE_MODE_CIRCULAR.
EVENT_TRACE_FILE_MODE_CIRCULAR | Write traces to a log file. After the file reaches the maximum size, replace the oldest traces with incoming traces.
EVENT_TRACE_FILE_MODE_SEQUENTIAL | Write traces to a log file sequentially; stop when the file reaches the maximum size.
EVENT_TRACE_PRIVATE_LOGGER_MODE | Use a private logger. Do not use this setting with EVENT_TRACE_REAL_TIME_MODE.
EVENT_TRACE_USE_GLOBAL_SEQUENCE

(Whistler only)

 Use sequence numbers that are unique across event tracing sessions. See TraceMessage for usage details.
EVENT_TRACE_USE_LOCAL_SEQUENCE

(Whistler only)

 Use sequence numbers that are unique only for an individual event tracing session. See TraceMessage for usage details.
EVENT_TRACE_REAL_TIME_MODE | Deliver the traces to consumers in real-time. Do not use this setting with EVENT_TRACE_PRIVATE_LOGGER_MODE.

CurrentEvent
An EVENT_TRACE structure that contains the last event trace processed.
LogfileHeader
A TRACE_LOGFILE_HEADER structure that contains general information about this set of event traces.
BufferCallback
Pointer to the BufferCallback function called after each event trace buffer is processed.
BufferSize
Size of each event trace buffer, in bytes. This member contains valid data when the structure is passed into a BufferCallback function implementation.
Filled
Number of bytes in the event trace buffer that contain valid trace information. This member contains valid data when the structure is passed into a BufferCallback function implementation.
EventsLost
Number of event traces that were not stored in the event trace buffer. Events may be lost due to insufficient resource allocation.

This member contains valid data when the structure is passed into a BufferCallback function implementation.

EventCallback
Pointer to the EventCallback function that is called each time an event is delivered to the event trace consumer.
IsKernelTrace
Specifies whether the event tracing session is the NT Kernel Logger. Supported values are TRUE and FALSE.
Context
Reserved.

Remarks

This structure is passed to the OpenTrace function to specify the set of traces to open for processing. This structure is also passed into the BufferCallback function implementation to notify a consumer about each buffer of event traces.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

BufferCallback, EventCallback, EVENT_TRACE, OpenTrace, TRACE_LOGFILE_HEADER


EVENT_TRACE_PROPERTIES

The EVENT_TRACE_PROPERTIES structure stores information about an event tracing session.

typedef struct _EVENT_TRACE_PROPERTIES {
  WNODE_HEADER Wnode;
  ULONG BufferSize;
  ULONG MinimumBuffers;
  ULONG MaximumBuffers;
  ULONG MaximumFileSize;
  ULONG LogFileMode;
  ULONG FlushTimer;
  ULONG EnableFlags;
  LONG AgeLimit;
  ULONG NumberOfBuffers;
  ULONG FreeBuffers;
  ULONG EventsLost;
  ULONG BuffersWritten;
  ULONG LogBuffersLost;
  ULONG RealTimeBuffersLost;
  HANDLE LoggerThreadId;
  ULONG LogFileNameOffset;
  ULONG LoggerNameOffset;
} EVENT_TRACE_PROPERTIES, *PEVENT_TRACE_PROPERTIES;

Members

Wnode
A WNODE_HEADER structure. The BufferSize member of Wnode contains the total amount of memory allocated to the EVENT_TRACE_PROPERTIES structure and strings, in bytes. The Flags member of Wnode must include the WNODE_FLAG_TRACED_GUID flag.
BufferSize
The amount of memory allocated for each event tracing session buffer, in kilobytes.
MinimumBuffers
The minimum number of buffers allocated for the event tracing session's buffer pool.
MaximumBuffers
The maximum number of buffers allocated for the event tracing session's buffer pool.
MaximumFileSize
The maximum size of the file used to log event traces, in megabytes.
LogFileMode
Specifies current logging modes for the event tracing session.

LogFileMode contains one or more of the following.
Mode | Description
EVENT_TRACE_BUFFERING_MODE | Event traces are not written to a log file or delivered in real-time. Do not specify this setting; it is used internally.
EVENT_TRACE_DELAY_OPEN_FILE_MODE | Delay opening file. Do not specify this setting; it is used internally.
EVENT_TRACE_FILE_MODE_APPEND

(Whistler only)

 Append to an existing sequential log file. Do not use this setting with EVENT_TRACE_REAL_TIME_MODE or EVENT_TRACE_FILE_MODE_CIRCULAR.
EVENT_TRACE_FILE_MODE_CIRCULAR | Write traces to a log file. After the file reaches the maximum size, replace the oldest traces with incoming traces.
EVENT_TRACE_FILE_MODE_SEQUENTIAL | Write traces to a log file sequentially; stop when the file reaches the maximum size.
EVENT_TRACE_PRIVATE_LOGGER_MODE | Use a private logger. Do not use this setting with EVENT_TRACE_REAL_TIME_MODE. See Remarks.
EVENT_TRACE_REAL_TIME_MODE | Deliver traces to consumers in real-time. Do not use this setting with EVENT_TRACE_PRIVATE_LOGGER_MODE.
EVENT_TRACE_USE_GLOBAL_SEQUENCE

(Whistler only)

 Use sequence numbers that are unique across event tracing sessions. See TraceMessage for usage details.
EVENT_TRACE_USE_LOCAL_SEQUENCE

(Whistler only)

 Use sequence numbers that are unique only for an individual event tracing session. See TraceMessage for usage details.

FlushTimer
The time delay before dirty buffers get scheduled to be flushed, in seconds.
EnableFlags
This member is not used for sessions other than the NT Kernel Logger.

For the NT Kernel Logger session, indicates the traced events. EnableFlags can contain one or more of the following values.
Flag | Description
EVENT_TRACE_FLAG_DISK_FILE_IO | File IO events.
EVENT_TRACE_FLAG_DISK_IO | Physical disk IO events.
EVENT_TRACE_FLAG_IMAGE_LOAD | Image load events.
EVENT_TRACE_FLAG_MEMORY_HARD_FAULTS | Hard page fault events.
EVENT_TRACE_FLAG_MEMORY_PAGE_FAULTS | All page fault events.
EVENT_TRACE_FLAG_NETWORK_TCPIP | TCPIP/UDP events.
EVENT_TRACE_FLAG_PROCESS | Process events.
EVENT_TRACE_FLAG_REGISTRY | Registry access events.
EVENT_TRACE_FLAG_THREAD | Thread events.

AgeLimit
Time delay before unused buffers are freed, in minutes.
NumberOfBuffers
Number of buffers allocated for the event tracing session's buffer pool.
FreeBuffers
Number of buffers that are allocated but unused in the event tracing session's buffer pool.
EventsLost
Number of event traces that were not recorded.
BuffersWritten
Number of buffers written.
LogBuffersLost
Number of buffers that could not be written to the log file.
RealTimeBuffersLost
Number of buffers that could not be delivered in real-time.
LoggerThreadId
The thread identifier for the event tracing session.
LogFileNameOffset
The relative address of the null terminated string that contains the log file name.

The EVENT_TRACE_PROPERTIES structure and the string must be allocated in contiguous memory. LogFileNameOffset is specified as an offset from the beginning of the EVENT_TRACE_PROPERTIES structure.

The value specified must satisfy the following:

PropertiesStartingAddress < LogFileNameOffset < PropertiesStartingAddress + Wnode.BufferSize

LoggerNameOffset
The relative address of the null terminated string that contains the name of the event tracing session.

The EVENT_TRACE_PROPERTIES structure and the string must be allocated in contiguous memory. LoggerNameOffset is specified as an offset from the beginning of the EVENT_TRACE_PROPERTIES structure.

The value specified must satisfy the following:

PropertiesStartingAddress < LoggerNameOffset < PropertiesStartingAddress + Wnode.BufferSize

Remarks

The event trace controller functions use this structure to set, query, and update event tracing sessions.

Sufficient space to store the name of the event tracing session and a log file should be allocated in memory that is adjacent to the EVENT_TRACE_PROPERTIES structure.

The members that store the addresses of the session name and log file name strings are specified as offsets from the beginning of the EVENT_TRACE_PROPERTIES structure.

The EnableFlags member should not contain values in the range 0x01000000 through 0xff000000. These values are reserved for future use.

When the LogFileMode contains EVENT_TRACE_PRIVATE_LOGGER_MODE, the Wnode member structure's Guid member (Wnode.Guid) must contain the private logger's control GUID.

For an example that demonstrates allocating and initializing an EVENT_TRACE_PROPERTIES structure, see Configuring an EVENT_TRACE_PROPERTIES Structure.

For additional information about the properties that are stored in the EVENT_TRACE_PROPERTIES structure, see Setting Buffer Properties.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Configuring an EVENT_TRACE_PROPERTIES Structure, Setting Buffer Properties, Using the NT Kernel Logger, WNODE_HEADER


MOF_FIELD

MOF_FIELD structures may be used to append trace data to the EVENT_TRACE_HEADER or EVENT_INSTANCE_HEADER structures.

typedef struct _MOF_FIELD {
  ULONG64     DataPtr;
  ULONG       Length;
  ULONG       DataType;
} MOF_FIELD, *PMOF_FIELD;

Members

DataPtr
Pointer to a trace data item.
Length
Length of the item pointed to by DataPtr.
DataType
Reserved.

Remarks

If you use MOF_FIELD structures, you must set the WNODE_FLAG_USE_MOF_PTR flag in the Flags member of the EVENT_TRACE_HEADER or EVENT_INSTANCE_HEADER structure.

The event tracing session automatically dereferences MOF_FIELD data pointers before passing the data to event trace consumers using EVENT_TRACE structures.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.

See Also

EVENT_INSTANCE_HEADER, EVENT_TRACE, EVENT_TRACE_HEADER


TRACE_ENABLE_CONTEXT

The TRACE_ENABLE_CONTEXT structure redefines the contents of the handle to an event tracing session.

typedef struct _TRACE_ENABLE_CONTEXT {
  USHORT LoggerId;
  UCHAR Level;
  UCHAR InternalFlag;
  ULONG EnableFlags;
} TRACE_ENABLE_CONTEXT, *PTRACE_ENABLE_CONTEXT;

Members

LoggerId
A unique event tracing session identifier.
Level
User-defined value, ranging from 0 to 255. The value of this member is specified as an argument to the EnableTrace function. Use this member as an alternative to the GetTraceEnableLevel function.
InternalFlag
Reserved.
EnableFlags
The value of this member is specified as an argument to the EnableTrace function. Use this member as an alternative to the GetTraceEnableFlags function.

Remarks

The TRACE_ENABLE_CONTEXT structure redefines the TRACEHANDLE data type, which is a 64 bit unsigned integer that is used to store event tracing session handles.

The structure contains valid data when an event trace provider has been enabled for the event tracing session.

You can use this structure as an alternative to the GetTraceEnableLevel, and GetTraceEnableFlags functions.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.

See Also

EnableTrace, GetTraceEnableFlags, GetTraceEnableLevel


TRACE_GUID_PROPERTIES

[This is preliminary documentation and subject to change.]

The TRACE_GUID_PROPERTIES structure contains information about an event trace provider and session. This structure is used by the EnumerateTraceGuids function.

typedef struct _TRACE_GUID_PROPERTIES {
  GUID Guid;
  ULONG GuidType;
  ULONG LoggerId;
  ULONG EnableLevel;
  ULONG EnableFlags;
  BOOLEAN IsEnable;
} TRACE_GUID_PROPERTIES, *PTRACE_GUID_PROPERTIES;

Members

Guid
The GUID associated with the event trace provider.
GuidType
The type of GUID. Zero indicates a provider GUID.
LoggerId
The identifier of the event tracing session.
EnableLevel
The value passed for the Level parameter of the EnableTrace function.
EnableFlags
The value passed for the Flag parameter of the EnableTrace function.
IsEnable
Specifies whether the event trace provider identified by the Guid member is currently enabled for the session identified by the LoggerId member.

Requirements

Windows NT/2000 or later: Requires Whistler.
Header: Declared in Evntrace.h.


TRACE_GUID_REGISTRATION

TRACE_GUID_REGISTRATION structures are passed into the RegisterTraceGuids function to register event trace classes.

typedef struct _TRACE_GUID_REGISTRATION {
  LPCGUID Guid;
  HANDLE RegHandle;
} TRACE_GUID_REGISTRATION;

Members

Guid
The GUID of an event trace class.
RegHandle
Handle of a registered event trace class. The value for this member is supplied by the RegisterTraceGuids function.

Remarks

The CreateTraceInstanceId function requires the value that is stored in the RegHandle member.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.

See Also

CreateTraceInstanceId, RegisterTraceGuid


TRACE_LOGFILE_HEADER

The TRACE_LOGFILE_HEADER structure contains information about an event tracing session and its traces.

typedef struct _TRACE_LOGFILE_HEADER {
  ULONG       BufferSize;
  union {
    ULONG     Version;
    struct {
      UCHAR   MajorVersion;
      UCHAR   MinorVersion;
      UCHAR   SubVersion;
      UCHAR   SubMinorVersion;
    } VersionDetail;
  };
  ULONG       ProviderVersion;
  ULONG       NumberOfProcessors;
  LARGE_INTEGER   EndTime;
  ULONG       TimerResolution;
  ULONG       MaximumFileSize;
  ULONG       LogFileMode;
  ULONG       BuffersWritten;
  union {
    GUID LogInstanceGuid;
    struct {
      ULONG   StartBuffers;
      ULONG   PointerSize;
      ULONG   EventsLost;
      ULONG   Reserved32;
    };
  };
  LPWSTR LoggerName;
  LPWSTR LogFileName;
  TIME_ZONE_INFORMATION TimeZone;
  LARGE_INTEGER   BootTime;
  LARGE_INTEGER   PerfFreq;
  LARGE_INTEGER   StartTime;
  ULONG ReservedFlags;
  ULONG BuffersLost;
} TRACE_LOGFILE_HEADER, *PTRACE_LOGFILE_HEADER;

Members

BufferSize
Size of event tracing session buffers, in kilobytes.
Version
Event Tracer version number.
MajorVersion
Major version number of the operating system.
MinorVersion
Minor version number of the operating system.
SubVersion
Event Tracer major version number, currently one.
SubMinorVersion
Event Tracer minor version number, currently zero.
ProviderVersion
Build number of the operating system.
NumberOfProcessors
Number of processors on the system.
EndTime
Time the event tracing session stopped, in milliseconds since midnight, January 1, 1601.
TimerResolution
The resolution of the hardware timer.
MaximumFileSize
Maximum size of the log file, in megabytes.
LogFileMode
Specifies current logging modes for the event tracing session.

LogFileMode contains one or more of the following.
Mode | Description
EVENT_TRACE_ADD_HEADER_MODE Add a log file header.

Do not specify this setting; it is used internally.
EVENT_TRACE_BUFFERING_MODE Event traces are not written to a log file or delivered in real-time.

Do not specify this setting; it is used internally.
EVENT_TRACE_DELAY_OPEN_FILE_MODE Delay opening file.

Do not specify this setting; it is used internally.
EVENT_TRACE_FILE_MODE_APPEND

(Whistler only)

 Append to an existing sequential log file. Do not use this setting with EVENT_TRACE_REAL_TIME_MODE or EVENT_TRACE_FILE_MODE_CIRCULAR.
EVENT_TRACE_FILE_MODE_CIRCULAR | Write traces to a log file. After the file reaches the maximum size, replace the oldest traces with incoming traces.
EVENT_TRACE_FILE_MODE_SEQUENTIAL | Write traces to a log file sequentially; stop when the file reaches the maximum size.
EVENT_TRACE_PRIVATE_LOGGER_MODE | Use a private logger. Do not use this setting with EVENT_TRACE_REAL_TIME_MODE.
EVENT_TRACE_USE_GLOBAL_SEQUENCE

(Whistler only)

 Use sequence numbers that are unique across event tracing sessions. See TraceMessage for usage details.
EVENT_TRACE_USE_LOCAL_SEQUENCE

(Whistler only)

 Use sequence numbers that are unique only for an individual event tracing session. See TraceMessage for usage details.
EVENT_TRACE_REAL_TIME_MODE | Deliver the traces to consumers in real-time. Do not use this setting with EVENT_TRACE_PRIVATE_LOGGER_MODE.

BuffersWritten
The total number of buffers written by the event tracing session.
LogInstanceGuid
Reserved for internal use.
StartBuffers
Reserved for internal use.
PointerSize
Size of pointer type, in bits.
EventsLost
The number of events lost during the event tracing session.
Reserved32
Reserved for internal use.
LoggerName
The name of the event tracing session.

Session names are case insensitive and are not required to be unique.

LogFileName
The name of the file where event traces are written.

The file name extension ETL is reserved for event tracing log files.

TimeZone
A TIME_ZONE_INFORMATION structure that contains the time zone for BootTime, EndTime and StartTime.
BootTime
The time the system was started, in milliseconds since midnight, January 1, 1601.
PerfFreq
Frequency of the high-resolution performance counter, if one exists.
StartTime
The time the event tracing session started, in milliseconds since midnight, January 1, 1601.
ReservedFlags
Reserved for internal use.
BuffersLost
The total number of buffers lost.

Remarks

The TRACE_LOGFILE_HEADER structure is a member of the EVENT_TRACE_LOGFILE structure.

The memory allocated for the LoggerName and LogFileName members is contiguous and adjacent to the TRACE_LOGFILE_HEADER structure. Both members are specified as offsets from the start of the structure.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Evntrace.h.

See Also

EVENT_TRACE_LOGFILE


WNODE_HEADER

The WNODE_HEADER structure is a member of the EVENT_TRACE_PROPERTIES structure. This structure is overlaid with the EVENT_TRACE_HEADER structure for user-mode event tracing.

typedef struct _WNODE_HEADER
{
  ULONG BufferSize;
  ULONG ProviderId;
  union
  {
    ULONG64 HistoricalContext;
    struct
    {
      ULONG Version;
      ULONG Linkage;
    };
  };
  union
  {
    HANDLE KernelHandle;
    LARGE_INTEGER TimeStamp;
  };
  GUID Guid;
  ULONG ClientContext;
  ULONG Flags;
} WNODE_HEADER, *PWNODE_HEADER;

Members

BufferSize
The total size of the structure that contains the WNODE_HEADER, in bytes.
ProviderId
Reserved for internal use.
HistoricalContext
Handle to the event tracing session.
Version
Reserved for internal use.
Linkage
Reserved for internal use.
KernelHandle
Reserved for internal use.
TimeStamp
The time when the information in this structure was updated, in milliseconds since midnight, January 1, 1601.
Guid
The GUID for the information in this structure.
ClientContext
Reserved.
Flags
Flags must contain WNODE_FLAG_TRACED_GUID to indicate that the structure contains event tracing information.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Header: Declared in Wmistr.h.

See Also

EVENT_TRACE_PROPERTIES


Event Tracing Constants

The following constants are used in event tracing.

Constant | Description
Access Rights Constants | Permissions used with event tracing components.
Control Code Constants | Constants used to select the action of the ControlTrace function.
Event Type Constants | General purpose event types.
LogFileMode Constants | Event trace recording options used by the LogFileMode members of EVENT_TRACE_LOGFILE, EVENT_TRACE_PROPERTIES and TRACE_LOGFILE_HEADER structures.
NT Kernel Logger Constants | Constants defined for the operating system events that are traced by the NT Kernel Logger session.
Other Event Tracing Constants | Miscellaneous constants.
Header Structures Constants | Valid settings for the Flags members of EVENT_INSTANCE_HEADER, EVENT_TRACE_HEADER, and WNODE_HEADER structures.


Access Rights Constants

The following rights may be applied to the GUID assigned to an event tracing session to restrict access to it.

Constant | Description
TRACELOG_ACCESS_KERNEL_LOGGER | Requester has permission to access the NT Kernel Logger session. Checked during QueryTrace, StartTrace, StopTrace, and UpdateTrace.
TRACELOG_ACCESS_REALTIME | Requester has permission to process real-time traces from an event tracing session. Checked during ProcessTrace.
TRACELOG_CREATE_INPROC | Requester has permission to start a private logger. Checked during StartTrace.
TRACELOG_CREATE_ONDISK | Session can write traces to a log file. Checked during StartTrace, and UpdateTrace.
TRACELOG_CREATE_REALTIME | Session can record traces in real-time. Checked during StartTrace, and UpdateTrace.
TRACELOG_GUID_ENABLE | Session can be enabled. Checked during StartTrace, StopTrace, UpdateTrace.


Control Code Constants

Any one of the following may be used to select the action of the ControlTrace function.

Code | Meaning
EVENT_TRACE_CONTROL_FLUSH | Flushes an event tracing session's active buffers. Available in Whistler only.
EVENT_TRACE_CONTROL_QUERY | Query an event tracing session.
EVENT_TRACE_CONTROL_STOP | Stop an event tracing session.
EVENT_TRACE_CONTROL_UPDATE | Update an event tracing session.


Event Type Constants

The following predefined event types can be used to classify events.

Event type | Description
EVENT_TRACE_TYPE_ACCEPT | Accept event. Use when a client accepts a connection for which a listen had previously completed.
EVENT_TRACE_TYPE_CHECKPOINT | Checkpoint event. Use for an event that is not at the start or end of an activity.
EVENT_TRACE_TYPE_CONFIG | Reserved for internal use.
EVENT_TRACE_TYPE_DC_END | Collection end event.
EVENT_TRACE_TYPE_DC_START | Collection start event.
EVENT_TRACE_TYPE_DEQUEUE | Dequeue event. Use when an activity is queued before it begins. Use EVENT_TRACE_TYPE_START to mark the time when a work item is queued. Use the dequeue event type to mark the time when work on the item actually begins. Use EVENT_TRACE_TYPE_END to mark the time when work on the item completes.
EVENT_TRACE_TYPE_END | End event. Use to trace the final state of a multi-part event.
EVENT_TRACE_TYPE_EXTENSION | Extension event. Use for an event that is a continuation of a previous event. For example, use the extension event type when an event trace records more data than can fit in a session buffer.
EVENT_TRACE_TYPE_GUIDMAP | Reserved for internal use.
EVENT_TRACE_TYPE_INFO | Informational event. This is the default event type.
EVENT_TRACE_TYPE_REPLY | Reply event. Use when an application that requests resources can receive multiple responses. For example, if a client application requests a URL, and the Web server reply is to send several files, each file received can be marked as a reply event.
EVENT_TRACE_TYPE_RESERVED9 | Reserved for internal use.
EVENT_TRACE_TYPE_RETRANSMIT | Data retransmission event.
EVENT_TRACE_TYPE_SECURITY | Reserved for internal use.
EVENT_TRACE_TYPE_SIDINFO | Reserved for internal use.
EVENT_TRACE_TYPE_START | Start event. Use to trace the initial state of an event that is divided into subevents.

Remarks

You can use these event types, or define your own. User-defined event types must specify values greater than 0x09.

For NT Kernel Logger event types, see NT Kernel Logger Constants.


LogFileMode Constants

The following constants are defined for the LogFileMode member of the EVENT_TRACE_PROPERTIES structure.

Mode | Description
EVENT_TRACE_ADD_HEADER_MODE | Add a log file header. Do not specify this setting; it is used internally.
EVENT_TRACE_BUFFERING_MODE | Event traces are not written to a log file or delivered in real-time. Do not specify this setting; it is used internally.
EVENT_TRACE_DELAY_OPEN_FILE_MODE | Delay opening file. Do not specify this setting; it is used internally.
EVENT_TRACE_FILE_MODE_APPEND (Whistler only) | Append to an existing sequential log file. Do not use with EVENT_TRACE_REAL_TIME_MODE or EVENT_TRACE_FILE_MODE_CIRCULAR.
EVENT_TRACE_FILE_MODE_CIRCULAR | Write traces to a log file. After the file reaches the maximum size, replace the oldest traces with incoming traces.
EVENT_TRACE_FILE_MODE_NONE | Not used.
EVENT_TRACE_FILE_MODE_SEQUENTIAL | Write traces to a log file sequentially; stop when the file reaches the maximum size.
EVENT_TRACE_PRIVATE_LOGGER_MODE | Use a private logger. Do not use this setting with EVENT_TRACE_REAL_TIME_MODE.
EVENT_TRACE_REAL_TIME_MODE | Deliver the traces to consumers in real-time. Do not use this setting with EVENT_TRACE_PRIVATE_LOGGER_MODE.
EVENT_TRACE_USE_GLOBAL_SEQUENCE (Whistler only) | Use sequence numbers that are unique across event tracing sessions. See TraceMessage for usage details.
EVENT_TRACE_USE_LOCAL_SEQUENCE (Whistler only) | Use sequence numbers that are unique only for an individual event tracing session. See TraceMessage for usage details.


Other Event Tracing Constants

The following miscellaneous constants are defined in Evntrace.h and Wmistr.h.

Constant | Description
"GlobalLogger" | The literal string used to specify the Global Logger session name.
EVENT_TRACE_FLAG_ENABLE_RESERVE | Not used.
EVENT_TRACE_FLAG_EXTENSION | Not used.
EVENT_TRACE_FLAG_FORWARD_WMI | Not used.
MAX_MOF_FIELDS | The maximum number of MOF_FIELD structures that may be appended to EVENT_TRACE_HEADER or EVENT_INSTANCE_HEADER structures. Defined in Evntrace.h
WMI_GLOBAL_LOGGER_ID | Handle for the Global Logger event tracing session. Defined in Wmistr.h.


Header Structures Constants

The following constants are valid for the Flags members of the EVENT_INSTANCE_HEADER, EVENT_TRACE_HEADER, and WNODE_HEADER structures.

Flag | Description
WNODE_FLAG_TRACED_GUID | The structure contains event tracing information. Always set this flag.
WNODE_FLAG_USE_GUID_PTR | A pointer to the trace GUID is located in the GuidPtr member of the EVENT_TRACE_HEADER structure.
WNODE_FLAG_USE_MOF_PTR | The trace data appended to the structure is stored in an array of MOF_FIELD structures.


NT Kernel Logger Constants

The following table lists the constants used to identify the NT Kernel Logger session.

Constant | Description
SystemTraceControlGuid | The GUID used to specify the NT Kernel Logger event tracing session.
"NT Kernel Logger" | The instance name for the NT Kernel Logger event tracing session

Use the following values to identify operating system events traced by the NT Kernel Logger session.

Flag | GUID name | Type Description
(no flag needed) | EventTraceConfigGuid | Hardware Configuration. (Whistler only)
EVENT_TRACE_FLAG_DISK_FILE_IO | FileIoGuid | IO Events
EVENT_TRACE_FLAG_DISK_IO | DiskIoGuid | IO Events
EVENT_TRACE_FLAG_IMAGE_LOAD | ImageLoadGuid | Image Load Events
EVENT_TRACE_FLAG_MEMORY_HARD_FAULTS | HardFaultGuid | Page Fault Events
EVENT_TRACE_FLAG_MEMORY_PAGE_FAULTS | PageFaultGuid | Page Fault Events
EVENT_TRACE_FLAG_NETWORK_TCPIP | TcpIpGuid, UdpIpGuid | Network Events
EVENT_TRACE_FLAG_PROCESS | ProcessGuid | Process and Thread Events
EVENT_TRACE_FLAG_REGISTRY | RegistryGuid | Registry Events
EVENT_TRACE_FLAG_THREAD | ThreadGuid | Process and Thread Events

Remarks

The flag values are specified in the Flags member of the EVENT_TRACE_PROPERTIES structure, before calling the StartTrace, UpdateTrace, or ControlTrace functions.

The GUID names are passed into the SetTraceCallback function to set up special processing for each kind of operating system event.


Hardware Configuration

[This is preliminary documentation and subject to change.]

Beginning with Whistler, consumer applications can obtain the hardware configuration of a system where trace data was generated. This information is available from the NT Kernel Logger session.

The following table identifies the event types used to identify hardware configuration information.

Event type | Description
EVENT_TRACE_TYPE_CONFIG_CPU | CPU configuration.
EVENT_TRACE_TYPE_CONFIG_LOGICALDISK | Logical disk configuration.
EVENT_TRACE_TYPE_CONFIG_NIC | NIC configuration.
EVENT_TRACE_TYPE_CONFIG_PHYSICALDISK | Physical disk configuration.

Unlike other NT Kernel Logger events, hardware configuration information is available automatically; there is no flag to specify when starting the NT Kernel Logger session.

NT Kernel Logger event trace consumers can implement special processing for event traces containing hardware configuration information. To get this functionality, these consumers can call the SetTraceCallback function and specify EventTraceConfigGuid as the pGuid parameter.


Image Load Events

EVENT_TRACE_TYPE_LOAD is the event type for image load events.

Event trace controllers can include image load events by specifying EVENT_TRACE_FLAG_IMAGE_LOAD in the Flags member of an EVENT_TRACE_PROPERTIES structure.

NT Kernel Logger event trace consumers can implement special processing for image load events by calling the SetTraceCallback function, and specifying ImageLoadGuid as the pGuid parameter.


IO Events

The following table identifies the event types for the disk and file IO subsystems.

Event type | Description
EVENT_TRACE_TYPE_IO_READ | Read event.
EVENT_TRACE_TYPE_IO_WRITE | Write event.

Event trace controllers can include disk IO events by specifying EVENT_TRACE_FLAG_DISK_IO in the Flags member of an EVENT_TRACE_PROPERTIES structure.

Event trace controllers can include file IO events by specifying EVENT_TRACE_FLAG_DISK_FILE_IO in the Flags member of an EVENT_TRACE_PROPERTIES structure.

NT Kernel Logger event trace consumers can implement special processing for disk IO events by calling the SetTraceCallback function and specifying DiskIoGuid as the pGuid parameter.

NT Kernel Logger event trace consumers can implement special processing for file IO events by calling the SetTraceCallback function and specifying FileIoGuid as the pGuid parameter.


Network Events

The following table identifies the event types for the Transmission Control Protocol/Internet Protocol (TCP/IP) and User Datagram Protocol/Internet Protocol (UDP/IP) subsystems.

Event type | Description
EVENT_TRACE_TYPE_SEND | Send event.
EVENT_TRACE_TYPE_RECEIVE | Receive event.
EVENT_TRACE_TYPE_CONNECT | Connect event.
EVENT_TRACE_TYPE_DISCONNECT | Disconnect event.

Event trace controllers can include TCP/IP and UDP/IP events by specifying EVENT_TRACE_FLAG_NETWORK_TCPIP in the Flags member of an EVENT_TRACE_PROPERTIES structure.

NT Kernel Logger event trace consumers can implement special processing for TCP/IP events by calling the SetTraceCallback function and specifying TcpIpGuid as the pGuid parameter.

NT Kernel Logger event trace consumers can implement special processing for UDP/IP events by calling the SetTraceCallback function and specifying UdpIpGuid as the pGuid parameter.


Page Fault Events

The following table identifies the event types for the memory subsystem.

Event type | Description
EVENT_TRACE_TYPE_MM_TF | Transition fault event.
EVENT_TRACE_TYPE_MM_DZF | Demand zero fault event.
EVENT_TRACE_TYPE_MM_COW | Copy on write event.
EVENT_TRACE_TYPE_MM_GPF | Guard page fault event.
EVENT_TRACE_TYPE_MM_HPF | Hard page fault event.

Event trace controllers can include all page fault events by specifying EVENT_TRACE_FLAG_MEMORY_PAGE_FAULTS in the Flags member of an EVENT_TRACE_PROPERTIES structure.

Event trace controllers can include hard page fault events by specifying EVENT_TRACE_FLAG_MEMORY_HARD_FAULTS in the Flags member of an EVENT_TRACE_PROPERTIES structure.

NT Kernel Logger event trace consumers can implement special processing for all page fault events by calling the SetTraceCallback function and specifying PageFaultGuid as the pGuid parameter.

NT Kernel Logger event trace consumers can implement special processing for hard page fault events by calling the SetTraceCallback function and specifying HardFaultGuid as the pGuid parameter.


Process and Thread Events

The following table identifies the events that occur as processes and threads start and end on a system.

Event type | Description
EVENT_TRACE_TYPE_START | Start event.
EVENT_TRACE_TYPE_END | End event.

Event trace controllers can include process events by specifying EVENT_TRACE_FLAG_PROCESS in the Flags member of an EVENT_TRACE_PROPERTIES structure.

Event trace controllers can include thread events by specifying EVENT_TRACE_FLAG_THREAD in the Flags member of an EVENT_TRACE_PROPERTIES structure.

NT Kernel Logger event trace consumers can implement special processing for process events by calling the SetTraceCallback function and specifying ProcessGuid as the pGuid parameter.

NT Kernel Logger event trace consumers can implement special processing for thread events by calling the SetTraceCallback function and specifying ThreadGuid as the pGuid parameter.


Registry Events

The following table identifies the event types for the system registry.

Event type | Description
EVENT_TRACE_TYPE_REGKCBDMP | See Remarks.
EVENT_TRACE_TYPE_REGCREATE | NtCreateKey event.
EVENT_TRACE_TYPE_REGDELETE | NtDeleteKey event.
EVENT_TRACE_TYPE_REGDELETEVALUE | NtDeleteValueKey event.
EVENT_TRACE_TYPE_REGENUMERATEKEY | NtEnumerateKey event.
EVENT_TRACE_TYPE_REGENUMERATEVALUEKEY | NtEnumerateValueKey event.
EVENT_TRACE_TYPE_REGFLUSH | NtFlushKey event.
EVENT_TRACE_TYPE_REGOPEN | NtOpenKey event.
EVENT_TRACE_TYPE_REGQUERY | NtQueryKey event.
EVENT_TRACE_TYPE_REGQUERYMULTIPLEVALUE | NtQueryMultipleValueKey event.
EVENT_TRACE_TYPE_REGQUERYVALUE | NtQueryValueKey event.
EVENT_TRACE_TYPE_REGSETINFORMATION | NtSetInformationKey event.
EVENT_TRACE_TYPE_REGSETVALUE | NtSetValueKey event.

Remarks

Event trace controllers can include registry events by specifying EVENT_TRACE_FLAG_REGISTRY in the Flags member of an EVENT_TRACE_PROPERTIES structure.

NT Kernel Logger event trace consumers can implement special processing for registry events by calling the SetTraceCallback function and specifying RegistryGuid as the pGuid parameter.

The EVENT_TRACE_TYPE_REGKCBDMP event is generated when a registry operation uses handles rather than strings to reference subkeys. The event is recorded once for each handle, the first time the handle is referenced. Repeated references to the handle will not generate multiple event traces. This event type is available in Whistler only.


Image Help Library

This overview describes the function set provided by the ImageHlp DLL. These functions allow you to work with a portable executable (PE) image.

  • About ImageHlp
  • ImageHlp Reference

Warning Starting with Windows® 2000, you can no longer redistribute the ImageHlp DLL that is included with the operating system. A subset of the functions have been moved to a DLL that is redistributable. Existing applications will continue to work because ImageHlp uses forwarders to call into the new DLL. However, these applications should be modified to use the new DLL. For more information, see Debug Help Library.


About ImageHlp

The ImageHlp functions are used mostly by programming tools, application setup utilities, and other programs that need access to the data contained in a PE image.

The following topics describe PE images and the functionality provided by the ImageHlp functions.

  • PE Format
  • Image Access Functions
  • Image Integrity Functions
  • Image Modification Functions


PE Format

Win32-based executable (image) files are structured according to the Portable Executable (PE) format. For a description of this format, see the specification included in the Microsoft Developer Network (MSDN®) Library.


Image Access Functions

The image access functions access the data in an executable image. These functions provide high-level access to the base of images and very specific access to the most common parts of an image's data.

  • GetImageConfigInformation
  • GetImageUnusedHeaderBytes
  • ImageLoad
  • ImageUnload
  • MapAndLoad
  • SetImageConfigInformation
  • UnMapAndLoad


ImageHlp Image Integrity Functions

Platform SDK: Debugging and Error Handling

Image Integrity Functions

The image integrity functions manage the set of certificates in an image file. Routines are provided to add, remove, and query certificates. There is also a function available for obtaining the byte stream of an image file required to calculate a message digest of the image file. This is needed to create signature certificates.

Every certificate in a file has an index which can change as certificates are removed. New certificates will always be added "at the end" of the list of existing certificates. That is, they will be assigned indices that are greater than any index currently in use. In general, an application should not assume that a given certificate has the same index it had the last time it was referenced.

  • DigestFunction
  • ImageAddCertificate
  • ImageEnumerateCertificates
  • ImageGetCertificateData
  • ImageGetCertificateHeader
  • ImageGetDigestStream
  • ImageRemoveCertificate


ImageHlp Image Modification Functions

The image modification functions allow you to change the executable image. They are mostly for use by development tools and install programs. They can be used to bind an image, compute its checksum (which is important for ensuring image integrity), change its load address, and produce symbol files.

The following are the image modification functions.

  • BindImage
  • BindImageEx
  • CheckSumMappedFile
  • MapFileAndCheckSum
  • ReBaseImage
  • SplitSymbols
  • StatusRoutine
  • TouchFileTimes
  • UpdateDebugInfoFile
  • UpdateDebugInfoFileEx


ImageHlp Reference

The following elements are part of ImageHlp.

  • ImageHlp Functions
  • ImageHlp Structures


ImageHlp Functions

The following are the ImageHlp functions.

Image Access

The image access functions access the data in an executable image. The functions provide high-level access to the base of images and very specific access to the most common parts of an image's data.

GetImageConfigInformation
GetImageUnusedHeaderBytes
ImageLoad
ImageUnload
MapAndLoad
SetImageConfigInformation
UnMapAndLoad

Image Integrity

The image integrity functions manage the set of certificates in an image file.

DigestFunction
ImageAddCertificate
ImageEnumerateCertificates
ImageGetCertificateData
ImageGetCertificateHeader
ImageGetDigestStream
ImageRemoveCertificate

Image Modification

The image modification functions allow you to change the executable image.

BindImage
BindImageEx
CheckSumMappedFile
MapFileAndCheckSum
ReBaseImage
SplitSymbols
StatusRoutine
TouchFileTimes
UpdateDebugInfoFile
UpdateDebugInfoFileEx


BindImage

The BindImage function computes the virtual address of each imported function.

This function has been superseded by the BindImageEx function. Use BindImageEx to provide a status routine or flags to control the image binding.

BOOL BindImage(
  PSTR ImageName,
  PSTR DllPath,
  PSTR SymbolPath
);

Parameters

ImageName
[in] Pointer to a null-terminated string that specifies the name of the file to be bound. This value can be a file name, a partial path, or a full path.
DllPath
[in] Pointer to a null-terminated string that specifies the root of the search path to use if the file specified by the ImageName parameter cannot be opened.
SymbolPath
[in] Pointer to a null-terminated string that specifies the root of the path to search for the file's corresponding symbol file.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

A call to BindImage is equivalent to the following call:

BindImageEx( 0, ImageName, DllPath, SymbolPath, NULL );

For more information, see BindImageEx .

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions, BindImageEx


BindImageEx

The BindImageEx function computes the virtual address of each function that is imported.

This function supersedes the BindImage function. Use BindImageEx to provide a status routine or flags to control the image binding.

BOOL BindImageEx(
  DWORD Flags,
  PSTR ImageName,
  PSTR DllPath,
  PSTR SymbolPath,
  PIMAGEHLP_STATUS_ROUTINE StatusRoutine
);

Parameters

Flags
[in] Specifies the behavior of the function. This parameter can be a combination of the following values.
Value | Meaning
BIND_NO_BOUND_IMPORTS Do not generate a new import address table.

Windows 95/98/Me: This flag is required.

BIND_NO_UPDATE | Do not make changes to the file.
BIND_ALL_IMAGES | Bind all images in the call tree for this file.
BIND_CACHE_IMPORT_DLLS | Do not discard DLL information in the cache between calls. This improves performance when binding a large number of images.

ImageName
[in] Pointer to a null-terminated string that specifies the name of the file to be bound. This value can be a file name, a partial path, or a full path.
DllPath
[in] Pointer to a null-terminated string that specifies the root of the search path to use if the file specified by the ImageName parameter cannot be opened.
SymbolPath
[in] Pointer to a null-terminated string that specifies the root of the path to search for the file's corresponding symbol file.
StatusRoutine
[in] Pointer to a status routine. The status routine is called during the progress of the image binding. For more information, see StatusRoutine.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The process of binding an image consists of computing the virtual address of each imported function. The computed virtual address is then saved in the importing image's Import Address Table (IAT). As a result, the image is loaded much faster, particularly if it uses many DLLs, because the system loader does not have to computer the address of each imported function.

If a corresponding symbol file can be located, its time stamp and checksum are updated.

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions, StatusRoutine


CheckSumMappedFile

The CheckSumMappedFile function computes the checksum of the specified image file.

PIMAGE_NT_HEADERS CheckSumMappedFile(
  PVOID BaseAddress,
  DWORD FileLength,
  PDWORD HeaderSum,
  PDWORD CheckSum
);

Parameters

BaseAddress
[in] Specifies the base address of the mapped file. This value is obtained by calling the MapViewOfFile function.
FileLength
[in] Specifies the length of the file, in bytes.
HeaderSum
[out] Pointer to a variable that receives the original checksum from the image file, or zero if there is an error.
CheckSum
[out] Pointer to the variable that receives the computed checksum.

Return Values

If the function succeeds, the return value is a pointer to the IMAGE_NT_HEADERS structure contained in the mapped image.

If the function fails, the return value is NULL. To retrieve extended error information, call GetLastError.

Remarks

The CheckSumMappedFile function computes a new checksum for the file and returns it in the CheckSum parameter. This function is used by any application that creates or modifies an executable image. Checksums are required for kernel-mode drivers and some system DLLs. The linker computes the original checksum at link time, if you use the appropriate linker switch. For more details, see your linker documentation.

It is recommended that all images have valid checksums. It is the caller's responsibility to place the newly computed checksum into the mapped image and update the on-disk image of the file.

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions, IMAGE_NT_HEADERS, MapFileAndCheckSum, MapViewOfFile


DigestFunction

The DigestFunction function is an application-defined callback function used by the ImageGetDigestStream function to process data.

The DIGEST_FUNCTION type defines a pointer to this callback function. DigestFunction is a placeholder for the application-defined function name.

BOOL DigestFunction (
  DIGEST_HANDLE refdata,
  PBYTE pData,
  DWORD dwLength
);

Parameters

refdata
[in] User-supplied handle to the digest. This value is passed as a parameter to the ImageGetDigestStream function.
pData
[in] Specifies the data stream.
dwLength
[in] Specifies the length of the data stream, in bytes.

Return Value

If the function succeeds, the return value should be TRUE. If the function fails, the return value should be FALSE.

Remarks

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.

See Also

Image Help Library Overview, ImageHlp Functions, ImageGetDigestStream


GetImageConfigInformation

The GetImageConfigInformation function locates and returns the load configuration data of an image.

BOOL GetImageConfigInformation(
  PLOADED_IMAGE LoadedImage,
  PIMAGE_LOAD_CONFIG_DIRECTORY ImageConfigInformation
);

Parameters

LoadedImage
[in] Pointer to a LOADED_IMAGE structure that is returned from a call to MapAndLoad or LoadImage.
ImageConfigInformation
[out] Pointer to an IMAGE_LOAD_CONFIG_DIRECTORY structure that receives the configuration information.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The SetImageConfigInformation function locates and changes the load configuration data of an image.

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions, IMAGE_LOAD_CONFIG_DIRECTORY, LOADED_IMAGE, SetImageConfigInformation


GetImageUnusedHeaderBytes

The GetImageUnusedHeaderBytes function returns the offset and size of the part of the PE header that is currently unused.

DWORD GetImageUnusedHeaderBytes(
  PLOADED_IMAGE LoadedImage,
  PDWORD SizeUnusedHeaderBytes
);

Parameters

LoadedImage
[in] Pointer to a LOADED_IMAGE structure that is returned from a call to MapAndLoad or LoadImage.
SizeUnusedHeaderBytes
[out] Pointer to a variable to receive the size, in bytes, of the part of the image's header which is unused.

Return Values

If the function succeeds, the return value is the offset from the base address of the first unused header byte.

If the function fails, the return value is zero. To retrieve extended error information, call GetLastError.

Remarks

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions, LOADED_IMAGE


ImageAddCertificate

The ImageAddCertificate function is used to add a certificate to the specified file.

BOOL ImageAddCertificate(
  HANDLE FileHandle,
  LPWIN_CERTIFICATE Certificate,
  PDWORD Index
);

Parameters

FileHandle
[in] Handle to the image file to be modified. This handle must be opened for FILE_READ_DATA and FILE_WRITE_DATA access.
Certificate
[in] Specifies a buffer containing a WIN_CERTIFICATE header and all associated sections. The Length member in the certificate header will be used to determine the length of this buffer.
Index
[out] Receives the index of the newly added certificate.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The certificate is added at the end of the existing list of certificates and is assigned an index.

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions, ImageRemoveCertificate


ImageEnumerateCertificates

The ImageEnumerateCertificates function is used to return information about the certificates currently contained in an image file.

BOOL ImageEnumerateCertificates(
  HANDLE FileHandle,
  WORD TypeFilter,
  PDWORD CertificateCount,
  PDWORD Indices,
  DWORD IndexCount
);

Parameters

FileHandle
[in] Handle to the image file to be examined. This handle must be opened for FILE_READ_DATA access.
TypeFilter
[in] Specifies a certificate section type to be used as a filter when returning certificate information. CERT_SECTION_TYPE_ANY should be passed for information on all section types present in the image.
CertificateCount
[out] Receives the number of certificates in the image containing sections of the type specified by the TypeFilter parameter. If none are found, this parameter is zero .
Indices
[in/out] Optionally provides a buffer to use to return an array of indices to the certificates containing sections of the specified type. No ordering should be assumed for the index values, nor are they guaranteed to be contiguous when CERT_SECTION_TYPE_ANY is queried.
IndexCount
[in/out] Specifies the length, in double-words, of the Indices buffer. This parameter will be examined whenever Indices is present. If CertificateCount is greater than IndexCount, Indices will be filled in with the first IndexCount sections found in the image and an appropriate warning will be returned.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The ImageEnumerateCertificates function returns information about the certificates currently contained in an image file. It has filtering capabilities which allow certificates containing sections of any single type (or of any type) to be returned.

After the indices of interesting certificates are discovered, they can be passed to the ImageGetCertificateData function to obtain the actual bodies of the certificates.

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions, ImageGetCertificateData


ImageGetCertificateData

The ImageGetCertificateData function is used to return a complete certificate from a file.

BOOL ImageGetCertificateData(
  HANDLE FileHandle,
  DWORD CertificateIndex,
  LPWIN_CERTIFICATE Certificate,
  PDWORD RequiredLength
);

Parameters

FileHandle
[in] Handle to the image file to be modified. This handle must be opened for FILE_READ_DATA access.
CertificateIndex
[in] Specifies the index of the certificate to be returned.
Certificate
[out] Pointer to a WIN_CERTIFICATE structure that receives the certificate data.
RequiredLength
[in/out] On input, this parameter specifies the length of the Certificate buffer in bytes. On return, it receives the length of the certificate.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions


ImageGetCertificateHeader

The ImageGetCertificateHeader function is used to return only the header part of the specified certificate, up to, but not including, the section offset array.

BOOL ImageGetCertificateHeader(
  HANDLE FileHandle,
  DWORD CertificateIndex,
  LPWIN_CERTIFICATE CertificateHeader
);

Parameters

FileHandle
[in] Handle to the image file to be modified. This handle must be opened for FILE_READ_DATA access.
CertificateIndex
[in] Specifies the index of the certificate whose header is to be returned.
CertificateHeader
[in/out] Pointer to the WIN_CERTIFICATE structure that receives the certificate header.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions


ImageGetDigestStream

The ImageGetDigestStream function returns the data to be digested from a given image file, subject to the passed DigestLevel parameter.

BOOL ImageGetDigestStream(
  HANDLE FileHandle,
  DWORD DigestLevel,
  DIGEST_FUNCTION DigestFunction,
  DIGEST_HANDLE DigestHandle,
);

Parameters

FileHandle
[in] Handle to the image file to be modified. This handle must be opened for FILE_READ_DATA access.
DigestLevel
[in] Specifies which aspects of the image are to be included in the returned data stream. This parameter can be one or more of the following values.
Value | Meaning
CERT_PE_IMAGE_DIGEST_DEBUG_INFO | Include symbolic debugging information.
CERT_PE_IMAGE_DIGEST_RESOURCES | Include resource information.
CERT_PE_IMAGE_DIGEST_ALL_IMPORT_INFO | Include all import information.

DigestFunction
[in] Pointer to a callback routine to process the data. For more information, see DigestFunction.
DigestHandle
[in] User-supplied handle to the digest. This parameter is passed to DigestFunction as the first argument.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The ImageGetDigestStream function returns the data to be digested from a specified image file, subject to the passed DigestLevel parameter. The order of the bytes will be consistent for different calls, which is required to ensure that the same message digest is always produced from the retrieved byte stream.

To ensure cross-platform compatibility, all implementations of this function must behave in a consistent manner with respect to the order in which the various parts of the image file are returned.

Data should be returned in the following order:

  1. Image (executable and static data) information.
  2. Resource data.
  3. Debugging information.

If any of these are not specified, the remaining parts must be returned in the same order.

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions


ImageLoad

The ImageLoad function maintains a list of loaded DLLs.

PLOADED_IMAGE ImageLoad(
  PSTR DllName,
  PSTR DllPath
);

Parameters

DllName
[in] Pointer to a null-terminated string that specifies the name of the image that is loaded.
DllPath
[in] Pointer to a null-terminated string that specifies the path used to locate the image if the name provided cannot be found. If NULL is used, then the search path rules set forth in the SearchPath function apply.

Return Values

If the function succeeds, the return value is a pointer to a LOADED_IMAGE structure.

If the function fails, the return value is NULL. To retrieve extended error information, call GetLastError.

Remarks

The ImageLoad function is used to maintain a list of loaded DLLs. If the image has already been loaded, the prior LOADED_IMAGE is returned. Otherwise, the new image is added to the list.

The LOADED_IMAGE structure must be deallocated by the ImageUnload function.

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions, ImageUnload, LOADED_IMAGE


ImageRemoveCertificate

The ImageRemoveCertificate function is used to remove the specified certificate from the given file.

BOOL ImageRemoveCertificate(
  HANDLE FileHandle,
  DWORD Index
);

Parameters

FileHandle
[in] Handle to the image file to be modified. This handle must be opened for FILE_READ_DATA and FILE_WRITE_DATA access.
Index
[in] Specifies the index of the certificate to be removed.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions, ImageAddCertificate


ImageUnload

The ImageUnload function is used to deallocate resources from a previous call to the ImageLoad function.

BOOL ImageUnload(
  PLOADED_IMAGE LoadedImage
);

Parameters

LoadedImage
[in] Pointer to a LOADED_IMAGE structure that is returned from a call to the ImageLoad function.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

ImageLoad and ImageUnload share internal data that can be corrupted if multiple consecutive calls to ImageLoad are performed. Therefore, make sure that you have called ImageLoad only once before calling ImageUnload.

Remarks

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions, ImageLoad, LOADED_IMAGE


MapAndLoad

The MapAndLoad function maps an image and preloads data from the mapped file.

BOOL MapAndLoad(
  PSTR ImageName,
  PSTR DllPath,
  PLOADED_IMAGE LoadedImage,
  BOOL DotDll,
  BOOL ReadOnly
);

Parameters

ImageName
[in] Pointer to a null-terminated string that specifies the name of the image that is loaded.
DllPath
[in] Pointer to a null-terminated string that specifies the path used to locate the image if the name provided cannot be found. If NULL is used, then the search path rules set forth in the SearchPath function apply.
LoadedImage
[out] Pointer to a LOADED_IMAGE structure that receives information about the image after it is loaded.
DotDll
[in] Specifies the default extension, if the image name does not contain a file extension. If the value is TRUE, a .DLL extension is used. If the value is FALSE, then an .EXE extension is used.
ReadOnly
[in] Specifies the access mode. If this value is TRUE, the file is mapped for read-access only. If the value is FALSE, the file is mapped for read and write access.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The MapAndLoad function maps an image and preloads data from the mapped file. The corresponding function, UnMapAndLoad, must be used to deallocate all resources that are allocated by the MapAndLoad function.

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions, LOADED_IMAGE, UnMapAndLoad


MapFileAndCheckSum

The MapFileAndCheckSum function computes the checksum of the specified file.

DWORD MapFileAndCheckSum(
  PTSTR Filename,
  PDWORD HeaderSum,
  PDWORD CheckSum
);

Parameters

Filename
[in] Pointer to a null-terminated string that specifies the file name of the file for which the checksum is to be computed.
HeaderSum
[out] Pointer to a variable that receives the original checksum from the image file, or zero if there is an error.
CheckSum
[out] Pointer to the variable that receives the computed checksum.

Return Values

If the function succeeds, the return value is CHECKSUM_SUCCESS.

If the function fails, the return value is one of the following.

Value | Meaning
CHECKSUM_OPEN_FAILURE | Could not open the file.
CHECKSUM_MAP_FAILURE | Could not map the file.
CHECKSUM_MAPVIEW_FAILURE | Could not map a view of the file.
CHECKSUM_UNICODE_FAILURE | Could not convert the file name to Unicode.

Remarks

The MapFileAndCheckSum function computes a new checksum for the file and returns it in the CheckSum parameter. This function is used by any application that creates or modifies an executable image. Checksums are required for kernel-mode drivers and some system DLLs. The linker computes the original checksum at link time, if you use the appropriate linker switch. For more details, see your linker documentation.

It is recommended that all images have valid checksums. It is the caller's responsibility to place the newly computed checksum into the mapped image and update the on-disk image of the file.

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Image Help Library Overview, ImageHlp Functions, CheckSumMappedFile


ReBaseImage

The ReBaseImage function is used to change the load address for the specified image, which reduces the required load time for a DLL.

Alternatively, you can use the Rebase tool.

BOOL ReBaseImage(
  PSTR CurrentImageName,
  PSTR SymbolPath,
  BOOL fReBase,
  BOOL fRebaseSysfileOk,
  BOOL fGoingDown,
  ULONG CheckImageSize,
  ULONG *OldImageSize,
  ULONG_PTR *OldImageBase,
  ULONG *NewImageSize,
  ULONG_PTR *NewImageBase,
  ULONG TimeStamp
);

Parameters

CurrentImageName
[in] Pointer to a null-terminated string that specifies file name of the file to be rebased.
SymbolPath
[in] Pointer to a null-terminated string that specifies the path used to find the corresponding symbol file.
fReBase
[in] Specifies whether the image is to be rebased. If this value is TRUE, the image is rebased. Otherwise, the image is not rebased.
fRebaseSysfileOk
[in] Specifies whether a system image is to be rebased. If this value is TRUE, the system image is rebased. Otherwise, the system image is not rebased.
fGoingDown
[in] Specifies whether the image should be rebased below the given base. If this value is TRUE, the image can be rebased below the given base; otherwise, it cannot.
CheckImageSize
[in] Specifies the maximum size that the image can grow to, or zero if there is no limit.
OldImageSize
[out] Pointer to a variable that receives the original image size.
OldImageBase
[out] Pointer to a variable that receives the original image base.
NewImageSize
[out] Pointer to a variable that receives the new image size after the rebase operation.
NewImageBase
[in/out] Pointer to a variable that receives the new image base after the rebase operation.
TimeStamp
[in] Specifies the new time stamp for the image. The value must be represented in the number of seconds elapsed since midnight (00:00:00), January 1, 1970, Universal Coordinated Time, according to the system clock.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The ReBaseImage function changes the desired load address for the specified image. This operation involves reading the entire image and updating all fixups, debugging information, checksum, and time stamp values. You can rebase an image to reduce the required load time for its DLLs. If an application can rely on a DLL being loaded at the desired load address, then the system loader does not have to relocate the image. The image is simply loaded into the application's virtual address space and the DllMain function is called, if one is present.

A well-behaved application has its DLLs rebased so they each fall within a unique range of the virtual address space. The system DLLs are currently based in memory from 0x70000000 to 0x78000000 (0x68000000 to 0x78000000 on MIPS). Therefore, you should base your DLLs from 0x60000000 to 0x68000000. One possible scheme is to choose a base address based on the first letter of the DLL name, as shown in the following table.

First Letter | Base Address
A - C | 0x60000000
D - F | 0x61000000
G - I | 0x62000000
J - L | 0x63000000
M - O | 0x64000000
P - R | 0x65000000
S - U | 0x66000000
V - X | 0x67000000
Y - Z | 0x68000000

By using these suggestions with the ReBaseImage function, each DLL in an application can be assigned a unique base address. This process can be part of the build process or part of the final release procedure for the application.

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions, DllMain


SetImageConfigInformation

The SetImageConfigInformation function locates and changes the load configuration data of an image.

BOOL SetImageConfigInformation(
  PLOADED_IMAGE LoadedImage,
  PIMAGE_LOAD_CONFIG_DIRECTORY ImageConfigInformation
);

Parameters

LoadedImage
[in] Pointer to a LOADED_IMAGE structure that is returned from a call to MapAndLoad or LoadImage.
ImageConfigInformation
[in] Pointer to an IMAGE_LOAD_CONFIG_DIRECTORY structure.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The GetImageConfigInformation function locates and returns the load configuration data of an image.

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions, GetImageConfigInformation, IMAGE_LOAD_CONFIG_DIRECTORY, LOADED_IMAGE


SplitSymbols

The SplitSymbols function strips symbols from the specified image.

BOOL SplitSymbols(
  PSTR ImageName,
  PSTR SymbolsPath,
  PSTR SymbolFilePath,
  DWORD Flags
);

Parameters

ImageName
[in] Pointer to a null-terminated string that specifies the name of the image from which to split symbols.
SymbolsPath
[in] Pointer to a null-terminated string that specifies a subdirectory for storing symbols. This parameter is optional.
SymbolFilePath
[in] Pointer to a null-terminated string that specifies the name of the generated symbol file. This file typically has a .dbg extension.
Flags
[in] Specifies the information to be split from the image. This parameter can be zero or a combination of the following values.
Value | Meaning
SPLITSYM_EXTRACT_ALL | Usually, an image with the symbols split off will still contain a MISC debug directory with the name of the symbol file. Therefore, the debugger can still find the symbols. Using this flag removes this link. The end result is similar to using the -debug:none switch on the Microsoft linker.
SPLITSYM_REMOVE_PRIVATE | This strips off the private CodeView symbolic information when generating the symbol file.
SPLITSYM_SYMBOLPATH_IS_SRC | The symbol file path contains an alternate path to locate the .pdb file.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The SplitSymbols function should be used when stripping symbols from an image. It will create a symbol file that all Win32-compatible debuggers understand. The format is defined in WINNT.H and consists of an image header, followed by the array of section headers, the exception information (on RISC only) or FPO information (on X86 only), and all debugging symbolic information from the image.

If the SymbolsPath parameter is NULL, the symbol file is stored in the directory where the image exists. Otherwise, it is stored in the subdirectory below SymbolsPath that matches the extension of the image. Using this method reduces the chances of symbol file collision. For example, the symbols for myapp.exe will be in the SymbolsPath\exe directory and the symbols for myapp.dll will be in the SymbolsPath\dll directory.

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions


StatusRoutine

The StatusRoutine function is an application-defined callback function used with the BindImageEx function. The status routine is called during the process of the image binding.

The PIMAGEHLP_STATUS_ROUTINE type defines a pointer to this callback function. StatusRoutine is a placeholder for the application-defined function name.

BOOL StatusRoutine(
  IMAGEHLP_STATUS_REASON Reason,
  PSTR ImageName,
  PSTR DllName,
  ULONG_PTR Va,
  ULONG_PTR Parameter
);

Parameters

Reason
[in] Specifies the current status of the bind operation. This parameter can be one of the following values.
Value | Meaning
BindOutOfMemory | Out of memory. The Parameter value is the number of bytes in the allocation attempt.
BindRvaToVaFailed | The relative virtual address is invalid for the image. The Parameter value is not used.
BindNoRoomInImage | No room in the image for new format import table. The Parameter value is not used.
BindImportModuleFailed | Module import failed. The Parameter value is not used.
BindImportProcedureFailed | Procedure import failed. The Parameter value is the name of the function.
BindImportModule | Module import is starting. The Parameter value is not used.
BindImportProcedure | Procedure import is starting. The Parameter value is the name of the function.
BindForwarder | The Parameter value is the name of the function forwarded.
BindForwarderNOT | The Parameter value is the name of the function not forwarded.
BindImageModified | Image modified. The Parameter value is not used.
BindExpandFileHeaders | File headers expanded. The Parameter value is the number of bytes
BindImageComplete | Binding is complete. For more information on the Parameter value, see the following Remarks section.
BindMismatchedSymbols | Checksum did not match. The Parameter value is the name of the symbol file.
BindSymbolsNotUpdated | Symbol file was not updated. The Parameter value is the name of the symbol file not updated.

ImageName
[in] Pointer to a null-terminated string that specifies the name of the file to be bound. This value can be a file name, a partial path, or a full path.
DllName
[in] Pointer to a null-terminated string that specifies the name of the DLL.
Va
[in] Specifies the computed virtual address.
Parameter
[in] Specifies additional status information. This value depends on the value of the Reason parameter. For more information, see the code fragment in the following Remarks section.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

The following code fragment describes the contents of the Parameter value when the status is BindImageComplete.

case BindImageComplete:
    if (fVerbose) {
        fprintf(stderr, "BIND: Details of binding %s\n", ImageName );
        NewImports = (PIMAGE_BOUND_IMPORT_DESCRIPTOR)Va;
        NewImport = NewImports;
        while (NewImport->OffsetModuleName) {
            fprintf( stderr, "    Import from %s [%x]",
                     (LPSTR)NewImports + NewImport->OffsetModuleName,
                     NewImport->TimeDateStamp
                   );
            if (NewImport->NumberOfModuleForwarderRefs != 0) {
                fprintf( stderr, " with %u forwarders", NewImport->
                         NumberOfModuleForwarderRefs );
            }
            fprintf( stderr, "\n" );
            NewForwarder = (PIMAGE_BOUND_FORWARDER_REF)(NewImport+1);
            for (i=0; i<NewImport->NumberOfModuleForwarderRefs; i++) {
                fprintf( stderr, "        Forward to %s [%x]\n",
                   (LPSTR)NewImports + NewForwarder->OffsetModuleName,
                   NewForwarder->TimeDateStamp);
                NewForwarder += 1;
            }
            NewImport = (PIMAGE_BOUND_IMPORT_DESCRIPTOR)NewForwarder;
        }
    }
    break;

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.

See Also

Image Help Library Overview, ImageHlp Functions, BindImageEx


TouchFileTimes

The TouchFileTimes function updates the date and time at which the specified file was last modified.

BOOL TouchFileTimes (
  HANDLE FileHandle,
  PSYSTEMTIME pSystemTime
);

Parameters

FileHandle
[in] Handle to the file of interest.
pSystemTime
[in] Pointer to a SYSTEMTIME structure. If this parameter is NULL, the current system date and time is used.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions, SYSTEMTIME


UnMapAndLoad

The UnMapAndLoad function is used to deallocate all resources that are allocated by a previous call to the MapAndLoad function.

BOOL UnMapAndLoad(
  PLOADED_IMAGE LoadedImage
);

Parameters

LoadedImage
[in] Pointer to a LOADED_IMAGE structure. This structure is obtained through a call to the MapAndLoad function.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The UnMapAndLoad function must be used to deallocate all resources that are allocated by a previous call to MapAndLoad. This function also writes a new checksum value into the image before the file is closed. This ensures that if a file is changed, it can be successfully loaded by the system loader.

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions, LOADED_IMAGE, MapAndLoad


UpdateDebugInfoFile

The UpdateDebugInfoFile function uses the specified information to update the corresponding fields in the symbol file.

This function has been superseded by the UpdateDebugInfoFileEx function. Use UpdateDebugInfoFileEx to verify the checksum value.

BOOL UpdateDebugInfoFile(
  PSTR ImageFileName,
  PSTR SymbolPath,
  PSTR DebugFilePath,
  PIMAGE_NT_HEADERS NtHeaders
);

Parameters

ImageFileName
[in] Pointer to a null-terminated string that specifies the name of the image that is now out of date with respect to its symbol file.
SymbolPath
[in] Pointer to a null-terminated string that specifies the path in which to look for the symbol file.
DebugFilePath
[out] Pointer to a buffer that receives the name of the symbol file that was updated.
NtHeaders
[in] Pointer to an IMAGE_NT_HEADERS structure that specifies the new header information.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To retrieve extended error information, call GetLastError.

Remarks

The UpdateDebugInfoFile function takes the information stored in the IMAGE_NT_HEADERS structure and updates the corresponding fields in the symbol file. Any time an image file is modified, this function should be called to keep the numbers in sync. Specifically, whenever an image checksum changes, the symbol file should be updated to match.

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions, IMAGE_NT_HEADERS, UpdateDebugInfoFileEx


UpdateDebugInfoFileEx

The UpdateDebugInfoFileEx function uses the specified information to update the corresponding fields in the symbol file.

This function supersedes the UpdateDebugInfoFile function. Use UpdateDebugInfoFileEx to verify the checksum value.

BOOL UpdateDebugInfoFileEx(
  PSTR ImageFileName,
  PSTR SymbolPath,
  PSTR DebugFilePath,
  PIMAGE_NT_HEADERS NtHeaders,
  DWORD OldChecksum
);

Parameters

ImageFileName
[in] Pointer to a null-terminated string that specifies the name of the image that is now out of date with respect to its symbol file.
SymbolPath
[in] Pointer to a null-terminated string that specifies the path in which to look for the symbol file.
DebugFilePath
[out] Pointer to a buffer that receives the name of the symbol file that was updated.
NtHeaders
[in] Pointer to an IMAGE_NT_HEADERS structure that specifies the new header information.
OldChecksum
[in] Specifies the original checksum value. If this value does not match the checksum that is present in the mapped image, the flags in the symbol file contain IMAGE_SEPARATE_DEBUG_MISMATCH and the last error value is set to ERROR_INVALID_DATA.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The UpdateDebugInfoFileEx function takes the information stored in the IMAGE_NT_HEADERS structure and updates the corresponding fields in the symbol file. Any time an image file is modified, this function should be called to keep the numbers in sync. Specifically, whenever an image checksum changes, the symbol file should be updated to match.

All ImageHlp API functions, such as this one, are single threaded. Therefore, calls from more than one thread to this function will likely result in unexpected behavior or memory corruption. To avoid this, you must synchronize all concurrent calls from more than one thread to this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Imagehlp.h.
Library: Use Imagehlp.lib.

See Also

Image Help Library Overview, ImageHlp Functions, IMAGE_NT_HEADERS


ImageHlp Structures

The following are the ImageHlp data structures.

FPO_DATA
IMAGE_COFF_SYMBOLS_HEADER
IMAGE_DATA_DIRECTORY
IMAGE_DEBUG_DIRECTORY
IMAGE_FILE_HEADER
IMAGE_FUNCTION_ENTRY
IMAGE_LOAD_CONFIG_DIRECTORY
IMAGE_NT_HEADERS
IMAGE_OPTIONAL_HEADER
IMAGE_SECTION_HEADER


FPO_DATA

The FPO_DATA structure represents the stack frame layout for a function on an x86 computer when frame pointer omission (FPO) optimization is used. The structure is used to locate the base of the call frame.

typedef struct _FPO_DATA {
    DWORD ulOffStart;
    DWORD cbProcSize;
    DWORD cdwLocals;
    WORD cdwParams;
    WORD cbProlog : 8;
    WORD cbRegs   : 3;
    WORD fHasSEH  : 1;
    WORD fUseBP   : 1;
    WORD reserved : 1;
    WORD cbFrame  : 2;
} FPO_DATA, *PFPO_DATA;

Members

ulOffStart
Offset of the first byte of the function code.
cbProcSize
Number of bytes in the function.
cdwLocals
Number of local variables, in DWORDs.
cdwParams
Size of the parameters, in DWORDs.
cbProlog
Number of bytes in the function prolog code.
cbRegs
Number of registers saved.
fHasSEH
Indicates whether the function uses structured exception handling.
fUseBP
Indicates whether the EBP register has been allocated.
reserved
Reserved for future use.
cbFrame
Indicates the frame type.
Type | Meaning
FRAME_FPO | FPO frame
FRAME_TRAP | Trap frame
FRAME_TSS | TSS frame
FRAME_NONFPO | Non-FPO frame

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Winnt.h; include Windows.h.

See Also

Image Help Library Overview, ImageHlp Structures, FunctionTableAccessProc, STACKFRAME, SymFunctionTableAccess


IMAGE_COFF_SYMBOLS_HEADER

The IMAGE_COFF_SYMBOLS_HEADER structure represents the COFF symbols header.

typedef struct _IMAGE_COFF_SYMBOLS_HEADER {
    DWORD   NumberOfSymbols;
    DWORD   LvaToFirstSymbol;
    DWORD   NumberOfLinenumbers;
    DWORD   LvaToFirstLinenumber;
    DWORD   RvaToFirstByteOfCode;
    DWORD   RvaToLastByteOfCode;
    DWORD   RvaToFirstByteOfData;
    DWORD   RvaToLastByteOfData;
} IMAGE_COFF_SYMBOLS_HEADER, *PIMAGE_COFF_SYMBOLS_HEADER;

Members

NumberOfSymbols
Number of symbols.
LvaToFirstSymbol
Virtual address of the first symbol.
NumberOfLinenumbers
Number of line-number entries.
LvaToFirstLinenumber
Virtual address of the first line-number entry.
RvaToFirstByteOfCode
Relative virtual address of the first byte of code.
RvaToLastByteOfCode
Relative virtual address of the last byte of code.
RvaToFirstByteOfData
Relative virtual address of the first byte of data.
RvaToLastByteOfData
Relative virtual address of the last byte of data.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Winnt.h; include Windows.h.

See Also

Image Help Library Overview, ImageHlp Structures


IMAGE_DATA_DIRECTORY

The IMAGE_DATA_DIRECTORY structure represents the data directory.

typedef struct _IMAGE_DATA_DIRECTORY {
    DWORD   VirtualAddress;
    DWORD   Size;
} IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;

Members

VirtualAddress
The relative virtual address of the table.
Size
The size of the table, in bytes.

Remarks

The following is a list of the data directories:

Offset | Description
96 | Export table address and size
104 | Import table address and size
112 | Resource table address and size
120 | Exception table address and size
128 | Certificate table address and size
136 | Base relocation table address and size
144 | Debugging information starting address and size
152 | Architecture-specific data address and size
160 | Global pointer register relative virtual address
168 | Thread local storage (TLS) table address and size
176 | Load configuration table address and size
184 | Bound import table address and size
192 | Import address table address and size
200 | Delay import descriptor address and size
208 | Reserved

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Winnt.h; include Windows.h.

See Also

Image Help Library Overview, ImageHlp Structures, IMAGE_OPTIONAL_HEADER


IMAGE_DEBUG_DIRECTORY

The IMAGE_DEBUG_DIRECTORY structure represents the debug directory format.

typedef struct _IMAGE_DEBUG_DIRECTORY {
    DWORD   Characteristics;
    DWORD   TimeDateStamp;
    WORD    MajorVersion;
    WORD    MinorVersion;
    DWORD   Type;
    DWORD   SizeOfData;
    DWORD   AddressOfRawData;
    DWORD   PointerToRawData;
} IMAGE_DEBUG_DIRECTORY, *PIMAGE_DEBUG_DIRECTORY;

Members

Characteristics
Reserved.
TimeDateStamp
Time and date the debugging information was created.
MajorVersion
Major version number of the debugging information format.
MinorVersion
Minor version number of the debugging information format.
Type
Format of the debugging information. This parameter can be one of the following values.
Constant | Description
IMAGE_DEBUG_TYPE_UNKNOWN | Unknown value, ignored by all tools.
IMAGE_DEBUG_TYPE_COFF | COFF debugging information (line numbers, symbol table, and string table). This type of debugging information is also pointed to by fields in the file headers.
IMAGE_DEBUG_TYPE_CODEVIEW | CodeView debugging information. The format of the data block is described by the CodeView 4.0 specification.
IMAGE_DEBUG_TYPE_FPO | Frame pointer omission (FPO) information. This information tells the debugger how to interpret nonstandard stack frames, which use the EBP register for a purpose other than as a frame pointer.
IMAGE_DEBUG_TYPE_MISC | Miscellaneous information.
IMAGE_DEBUG_TYPE_EXCEPTION | Exception information.
IMAGE_DEBUG_TYPE_FIXUP | Fixup information.
IMAGE_DEBUG_TYPE_BORLAND | Borland debugging information.

SizeOfData
The size of the debugging information, in bytes, not including the debug directory itself.
AddressOfRawData
Address of the debugging information when the image is loaded, relative to the image base.
PointerToRawData
File pointer to the debugging information.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Winnt.h; include Windows.h.

See Also

Image Help Library Overview, ImageHlp Structures


IMAGE_FILE_HEADER

The IMAGE_FILE_HEADER structure represents the COFF header format.

typedef struct _IMAGE_FILE_HEADER {
    WORD Machine;
    WORD NumberOfSections;
    DWORD TimeDateStamp;
    DWORD PointerToSymbolTable;
    DWORD NumberOfSymbols;
    WORD SizeOfOptionalHeader;
    WORD Characteristics;
} IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;

Members

Machine
Specifies the architecture type of the computer. This parameter can be one of the following values.
Value | Meaning
IMAGE_FILE_MACHINE_I386 | Intel (32-bit)
IMAGE_FILE_MACHINE_IA64 | Whistler: Intel (64-bit)
IMAGE_FILE_MACHINE_AMD64 | Whistler: AMD (64-bit)
IMAGE_FILE_MACHINE_ALPHA | Windows NT 4.0 and earlier: DEC Alpha
IMAGE_FILE_MACHINE_POWERPC | Windows NT 4.0 and earlier: Power PC

NumberOfSections
Specifies the number of sections.
TimeDateStamp
Specifies the time stamp of the image. This represents the date and time the image was created by the linker.
PointerToSymbolTable
Offset of the symbol table, or zero if no symbol table exists.
NumberOfSymbols
Specifies the number of symbols in the symbol table.
SizeOfOptionalHeader
Specifies the size of the optional header, in bytes.
Characteristics
Specifies the characteristics of the image.
Value | Meaning
IMAGE_FILE_RELOCS_STRIPPED | Relocation information is stripped from the file.
IMAGE_FILE_EXECUTABLE_IMAGE | The file is executable (there are no unresolved external references).
IMAGE_FILE_LINE_NUMS_STRIPPED | Line numbers are stripped from the file.
IMAGE_FILE_LOCAL_SYMS_STRIPPED | Local symbols are stripped from file.
IMAGE_FILE_AGGRESIVE_WS_TRIM | Aggressively trim the working set.
IMAGE_FILE_LARGE_ADDRESS_AWARE | The application can handle addresses larger than 2 GB.
IMAGE_FILE_BYTES_REVERSED_LO | Bytes of the word are reversed.
IMAGE_FILE_32BIT_MACHINE | Computer supports 32-bit words.
IMAGE_FILE_DEBUG_STRIPPED | Debugging information is stored separately in a .dbg file.
IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP | If the image is on removable media, copy and run from the swap file.
IMAGE_FILE_NET_RUN_FROM_SWAP | If the image is on the network, copy and run from the swap file.
IMAGE_FILE_SYSTEM | System file.
IMAGE_FILE_DLL | DLL file.
IMAGE_FILE_UP_SYSTEM_ONLY | File should be run only on a uniprocessor computer.
IMAGE_FILE_BYTES_REVERSED_HI | Bytes of word are reversed.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Winnt.h; include Windows.h.

See Also

Image Help Library Overview, ImageHlp Structures, IMAGE_NT_HEADERS


IMAGE_FUNCTION_ENTRY

The IMAGE_FUNCTION_ENTRY structure represents an entry in the function table.

typedef struct _IMAGE_FUNCTION_ENTRY {
    DWORD StartingAddress;
    DWORD EndingAddress;
    DWORD EndOfPrologue;
} IMAGE_FUNCTION_ENTRY, *PIMAGE_FUNCTION_ENTRY;

Members

StartingAddress
Image address of the start of the function.
EndingAddress
Image address of the end of the function.
EndOfPrologue
Image address of the end of the prologue code.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Winnt.h; include Windows.h.

See Also

Image Help Library Overview, ImageHlp Structures, STACKFRAME


IMAGE_LOAD_CONFIG_DIRECTORY

The IMAGE_LOAD_CONFIG_DIRECTORY structure contains the load configuration data of an image.

typedef struct _IMAGE_LOAD_CONFIG_DIRECTORY {
    DWORD   Characteristics;
    DWORD   TimeDateStamp;
    WORD    MajorVersion;
    WORD    MinorVersion;
    DWORD   GlobalFlagsClear;
    DWORD   GlobalFlagsSet;
    DWORD   CriticalSectionDefaultTimeout;
    DWORD   DeCommitFreeBlockThreshold;
    DWORD   DeCommitTotalFreeThreshold;
    DWORD   LockPrefixTable;
    DWORD   MaximumAllocationSize;
    DWORD   VirtualMemoryThreshold;
    DWORD   ProcessHeapFlags;
    DWORD   ProcessAffinityMask;
    WORD    CSDVersion;
    WORD    Reserved1;
    DWORD   EditList;
    DWORD   Reserved[ 1 ];
} IMAGE_LOAD_CONFIG_DIRECTORY, *PIMAGE_LOAD_CONFIG_DIRECTORY;

64-bit Windows: This structure is defined as follows.

typedef struct {
    DWORD      Characteristics;
    DWORD      TimeDateStamp;
    WORD       MajorVersion;
    WORD       MinorVersion;
    DWORD      GlobalFlagsClear;
    DWORD      GlobalFlagsSet;
    DWORD      CriticalSectionDefaultTimeout;
    ULONGLONG  DeCommitFreeBlockThreshold;
    ULONGLONG  DeCommitTotalFreeThreshold;
    ULONGLONG  LockPrefixTable;
    ULONGLONG  MaximumAllocationSize;
    ULONGLONG  VirtualMemoryThreshold;
    ULONGLONG  ProcessAffinityMask;
    DWORD      ProcessHeapFlags;
    WORD       CSDVersion;
    WORD       Reserved1;
    ULONGLONG  EditList;
    DWORD      Reserved[ 2 ];
} IMAGE_LOAD_CONFIG_DIRECTORY64, *PIMAGE_LOAD_CONFIG_DIRECTORY64;

Members

Characteristics
Flags indicating attributes of the file. This member is currently unused.
TimeDateStamp
Specifies the date and time stamp value. The value is represented in the number of seconds elapsed since midnight (00:00:00), January 1, 1970, Universal Coordinated Time, according to the system clock. The time stamp can be printed using the C run-time (CRT) function ctime.
MajorVersion
Major version number.
MinorVersion
Minor version number.
GlobalFlagsClear
Global flags that control system behavior. For more information, see Gflags.exe, which is available as part of the Windows NT 4.0 Resource Kit or on the Windows 2000 CD in the Support\Tools directory.
GlobalFlagsSet
Global flags that control system behavior. For more information, see Gflags.exe, which is available as part of the Windows NT 4.0 Resource Kit or on the Windows 2000 CD in the Support\Tools directory.
CriticalSectionDefaultTimeout
Specifies the critical section default time-out value.
DeCommitFreeBlockThreshold
Specifies the memory that must be freed before it is returned to the system.
DeCommitTotalFreeThreshold
Specifies the total amount of free memory, in bytes.
LockPrefixTable
Reserved for use by the system.
MaximumAllocationSize
Specifies the maximum allocation size, in bytes.
VirtualMemoryThreshold
Specifies the maximum virtual memory size, in bytes.
ProcessHeapFlags
Specifies the process heap flags.
ProcessAffinityMask
Specifies the process affinity mask. For more information, see GetProcessAffinityMask.
CSDVersion
Specifies the CSD version.
Reserved1
Reserved for use by the operating system.
EditList
Reserved for use by the system.
Reserved
Reserved for use by the operating system.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Winnt.h; include Windows.h.

See Also

Image Help Library Overview, ImageHlp Structures, GetImageConfigInformation, SetImageConfigInformation


IMAGE_NT_HEADERS

The IMAGE_NT_HEADERS structure represents the PE header format.

typedef struct _IMAGE_NT_HEADERS {
    DWORD Signature;
    IMAGE_FILE_HEADER FileHeader;
    IMAGE_OPTIONAL_HEADER OptionalHeader;
} IMAGE_NT_HEADERS, *PIMAGE_NT_HEADERS;

Members

Signature
A 4-byte signature identifying the file as a PE image. The bytes are "PE\0\0".
FileHeader
Pointer to an IMAGE_FILE_HEADER structure that specifies the file header.
OptionalHeader
Pointer to an IMAGE_OPTIONAL_HEADER structure that specifies the optional file header.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Winnt.h; include Windows.h.

See Also

Image Help Library Overview, ImageHlp Structures, CheckSumMappedFile, IMAGE_FILE_HEADER, IMAGE_OPTIONAL_HEADER, ImageNtHeader, ImageRvaToSection, ImageRvaToVa, LOADED_IMAGE, UpdateDebugInfoFile


IMAGE_OPTIONAL_HEADER

The IMAGE_OPTIONAL_HEADER structure represents the optional header format.

typedef struct _IMAGE_OPTIONAL_HEADER {
    WORD    Magic;
    BYTE    MajorLinkerVersion;
    BYTE    MinorLinkerVersion;
    DWORD   SizeOfCode;
    DWORD   SizeOfInitializedData;
    DWORD   SizeOfUninitializedData;
    DWORD   AddressOfEntryPoint;
    DWORD   BaseOfCode;
    DWORD   BaseOfData;
    DWORD   ImageBase;
    DWORD   SectionAlignment;
    DWORD   FileAlignment;
    WORD    MajorOperatingSystemVersion;
    WORD    MinorOperatingSystemVersion;
    WORD    MajorImageVersion;
    WORD    MinorImageVersion;
    WORD    MajorSubsystemVersion;
    WORD    MinorSubsystemVersion;
    DWORD   Win32VersionValue;
    DWORD   SizeOfImage;
    DWORD   SizeOfHeaders;
    DWORD   CheckSum;
    WORD    Subsystem;
    WORD    DllCharacteristics;
    DWORD   SizeOfStackReserve;
    DWORD   SizeOfStackCommit;
    DWORD   SizeOfHeapReserve;
    DWORD   SizeOfHeapCommit;
    DWORD   LoaderFlags;
    DWORD   NumberOfRvaAndSizes;
    IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
} IMAGE_OPTIONAL_HEADER, *PIMAGE_OPTIONAL_HEADER;

Members

Magic
Specifies the state of the image file. This parameter may be one of the following values.
Value | Meaning
IMAGE_NT_OPTIONAL_HDR_MAGIC | The file is an executable image.
IMAGE_ROM_OPTIONAL_HDR_MAGIC | The file is a ROM image.

MajorLinkerVersion
Major version number of the linker.
MinorLinkerVersion
Minor version number of the linker.
SizeOfCode
The size of the code section, or the sum of all such sections if there are multiple code sections.
SizeOfInitializedData
The size of the initialized data section, or the sum of all such sections if there are multiple initialized data sections.
SizeOfUninitializedData
The size of the uninitialized data section, or the sum of all such sections if there are multiple uninitialized data sections.
AddressOfEntryPoint
Pointer to the entry point function, relative to the image base address. The entry point function is optional for DLLs. When no entry point is present, this member is zero.
BaseOfCode
Pointer to the beginning of the code section, relative to the image base.
BaseOfData
Pointer to the beginning of the data section, relative to the image base.
ImageBase
Preferred address of the first byte of the image when it is loaded in memory. This value is a multiple of 64K bytes. The default value for DLLs is 0x10000000. The default value for Win32-based applications on Windows CE is 0x00010000. The default value for Win32-based applications on Windows NT/Windows 2000 and Windows 95/98 is 0x00400000.
SectionAlignment
The alignment, in bytes, of sections loaded in memory. This value must be greater than or equal to the FileAlignment member. The default value is the page size for the system.
FileAlignment
The alignment, in bytes, of the raw data of sections in the image file. The value should be a power of 2 between 512 and 64K (inclusive). The default is 512. If the SectionAlignment member is less than the system page size, this member must be the same as SectionAlignment.
MajorOperatingSystemVersion
Major version number of the required operating system.
MinorOperatingSystemVersion
Minor version number of the required operating system.
MajorImageVersion
Major version number of the image.
MinorImageVersion
Minor version number of the image.
MajorSubsystemVersion
Major version number of the subsystem.
MinorSubsystemVersion
Minor version number of the subsystem.
Win32VersionValue
This member is reserved.
SizeOfImage
The size of the image, in bytes, including all headers. Must be a multiple of SectionAlignment.
SizeOfHeaders
Combined size of the MS-DOS stub, the PE header, and the section headers, rounded to a multiple of the value specified in the FileAlignment member.
CheckSum
Image file checksum.
Subsystem
Subsystem required to run this image. The following values are defined.
Subsystem | Description
IMAGE_SUBSYSTEM_UNKNOWN | Unknown subsystem.
IMAGE_SUBSYSTEM_NATIVE | No subsystem required.
IMAGE_SUBSYSTEM_WINDOWS_CUI | Windows character-mode subsystem.
IMAGE_SUBSYSTEM_POSIX_CUI | POSIX character-mode subsystem.
IMAGE_SUBSYSTEM_WINDOWS_CE_GUI | Windows CE.

DllCharacteristics
Specifies the DLL characteristics of the image. The following values are defined.
Value | Meaning
0x0001 | Reserved
0x0002 | Reserved
0x0004 | Reserved
0x0008 | Reserved
0x2000 | A WDM driver.

SizeOfStackReserve
The number of bytes to reserve for the stack.
SizeOfStackCommit
The number of bytes to commit for the stack.
SizeOfHeapReserve
The number of bytes to reserve for the local heap.
SizeOfHeapCommit
The number of bytes to commit for the local heap.
LoaderFlags
This member is obsolete.
NumberOfRvaAndSizes
Number of directory entries.
DataDirectory
Pointer to the first IMAGE_DATA_DIRECTORY structure in the data directory.

Remarks

The number of directories is not fixed. Check the NumberOfRvaAndSizes member before looking for a specific directory.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Winnt.h; include Windows.h.

See Also

Image Help Library Overview, ImageHlp Structures, IMAGE_DATA_DIRECTORY


IMAGE_SECTION_HEADER

The IMAGE_SECTION_HEADER structure represents the image section header format.

typedef struct _IMAGE_SECTION_HEADER {
    BYTE    Name[IMAGE_SIZEOF_SHORT_NAME];
    union {
        DWORD   PhysicalAddress;
        DWORD   VirtualSize;
    } Misc;
    DWORD   VirtualAddress;
    DWORD   SizeOfRawData;
    DWORD   PointerToRawData;
    DWORD   PointerToRelocations;
    DWORD   PointerToLinenumbers;
    WORD    NumberOfRelocations;
    WORD    NumberOfLinenumbers;
    DWORD   Characteristics;
} IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;

Members

Name
An 8-byte, null-filled string. There is no terminating null character if the string is exactly eight characters long. For longer names, this member contains a forward slash (/) followed by a decimal number that is an offset into the string table. Executable images do not use a string table and do not support section names longer than eight characters.
PhysicalAddress
Specifies the file address.
VirtualSize
Total size of the section when loaded into memory. If this value is greater than the SizeOfRawData member, the section is filled with zeroes.
VirtualAddress
The address of the first byte of the section when loaded into memory, relative to the image base.
SizeOfRawData
The size of the initialized data on disk. This value must be a multiple of the FileAlignment member of the IMAGE_OPTIONAL_HEADER structure. If this value is less than the VirtualSize member, the remainder of the section is filled with zeroes. If the section contains only uninitialized data, the member is zero.
PointerToRawData
File pointer to the first page within the COFF file. This value must be a multiple of the FileAlignment member of the IMAGE_OPTIONAL_HEADER structure. If a section contains only uninitialized data, this member is zero.
PointerToRelocations
File pointer to the beginning of the relocation entries for the section. If there are no relocations, this value is zero.
PointerToLinenumbers
File pointer to the beginning of the line-number entries for the section. If there are no COFF line numbers, this value is zero.
NumberOfRelocations
Number of relocation entries for the section. This value is zero for executable images.
NumberOfLinenumbers
Number of line-number entries for the section.
Characteristics
Specifies the characteristics of the image.
Flag | Description
IMAGE_SCN_TYPE_REG | Reserved.
IMAGE_SCN_TYPE_DSECT | Reserved.
IMAGE_SCN_TYPE_NOLOAD | Reserved.
IMAGE_SCN_TYPE_GROUP | Reserved.
IMAGE_SCN_TYPE_NO_PAD | Reserved.
IMAGE_SCN_TYPE_COPY | Reserved.
IMAGE_SCN_CNT_CODE | Section contains executable code.
IMAGE_SCN_CNT_INITIALIZED_DATA | Section contains initialized data.
IMAGE_SCN_CNT_UNINITIALIZED_DATA | Section contains uninitialized data.
IMAGE_SCN_LNK_OTHER | Reserved.
IMAGE_SCN_LNK_INFO | Reserved.
IMAGE_SCN_TYPE_OVER | Reserved.
IMAGE_SCN_LNK_COMDAT | Section contains COMDAT data.
IMAGE_SCN_MEM_FARDATA | Reserved.
IMAGE_SCN_MEM_PURGEABLE | Reserved.
IMAGE_SCN_MEM_16BIT | Reserved.
IMAGE_SCN_MEM_LOCKED | Reserved.
IMAGE_SCN_MEM_PRELOAD | Reserved.
IMAGE_SCN_ALIGN_1BYTES | Align data on a 1-byte boundary.
IMAGE_SCN_ALIGN_2BYTES | Align data on a 2-byte boundary.
IMAGE_SCN_ALIGN_4BYTES | Align data on a 4-byte boundary.
IMAGE_SCN_ALIGN_8BYTES | Align data on a 8-byte boundary.
IMAGE_SCN_ALIGN_16BYTES | Align data on a 16-byte boundary.
IMAGE_SCN_ALIGN_32BYTES | Align data on a 32-byte boundary.
IMAGE_SCN_ALIGN_64BYTES | Align data on a 64-byte boundary.
IMAGE_SCN_LNK_NRELOC_OVFL | Section contains extended relocations.
IMAGE_SCN_MEM_DISCARDABLE | Section can be discarded as needed.
IMAGE_SCN_MEM_NOT_CACHED | Section cannot be cached.
IMAGE_SCN_MEM_NOT_PAGED | Section cannot be paged.
IMAGE_SCN_MEM_SHARED | Section can be shared in memory.
IMAGE_SCN_MEM_EXECUTE | Section can be executed as code.
IMAGE_SCN_MEM_READ | Section can be read.
IMAGE_SCN_MEM_WRITE | Section can be written to.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Winnt.h; include Windows.h.

See Also

Image Help Library Overview, ImageHlp Structures, ImageDirectoryEntryToDataEx, ImageRvaToSection, ImageRvaToVa, LOADED_IMAGE


Structured Exception Handling

An exception is an event that occurs during the execution of a program, and requires the execution of code outside the normal flow of control. There are two kinds of exceptions: hardware exceptions and software exceptions. Hardware exceptions are initiated by the CPU. They can result from the execution of certain instruction sequences, such as division by zero or an attempt to access an invalid memory address. Software exceptions are initiated explicitly by applications or the operating system. For example, the system can detect when an invalid parameter value is specified.

Structured exception handling is a mechanism for handling both hardware and software exceptions. Therefore, your code will handle hardware and software exceptions identically. Structured exception handling enables you to have complete control over the handling of exceptions, provides support for debuggers, and is usable across all programming languages and machines.

The system also supports termination handling, which enables you to ensure that whenever a guarded body of code is executed, a specified block of termination code is also executed. The termination code is executed regardless of how the flow of control leaves the guarded body. For example, a termination handler can guarantee that clean-up tasks are performed even if an exception or some other error occurs while the guarded body of code is being executed.

  • About Structured Exception Handling
  • Using Structured Exception Handling
  • Structured Exception Handling Reference


About Structured Exception Handling

The structured exception handling and termination handling mechanisms are integral parts of the system; they enable the system to be robust. You can use these mechanisms to create consistently robust and reliable applications.

Structured exception handling is made available primarily through compiler support. For example, the Microsoft® C/C++ Optimizing Compiler supports the __try keyword that identifies a guarded body of code, the __except keyword that identifies an exception handler, and the __finally keyword that identifies a termination handler. Although this overview uses examples specific to the Microsoft C/C++ compiler, other compilers provide this support as well.

  • Exception Handling
  • Frame-based Exception Handling
  • Termination Handling
  • Handler Syntax
  • Vectored Exception Handling


Exception Handling

Exceptions can be initiated by hardware or software, and can occur in kernel-mode as well as user-mode code. Structured exception handling provides a single mechanism for the handling of kernel-mode and user-mode exceptions.

The execution of certain instruction sequences can result in exceptions that are initiated by hardware. For example, an access violation is generated by the hardware when a process attempts to read from or write to a virtual address to which it does not have the appropriate access.

Events that require exception handling may also occur during execution of a software routine (for example, when an invalid parameter value is specified). When this happens, a thread can initiate an exception explicitly by calling the RaiseException function. This function enables the calling thread to specify information that describes the exception.

An exception can be continuable or noncontinuable. A noncontinuable exception arises when the event is not continuable in the hardware, or if continuation makes no sense. A noncontinuable exception does not terminate the application. Therefore, an application may be able to catch the exception and run. However, a noncontinuable exception typically arises as a result of a corrupted stack or other serious problem, making it difficult to recover from the exception.


Exception Dispatching

When a hardware or software exception occurs, the processor stops execution at the point at which the exception occurred and transfers control to the system. First, the system saves both the machine state of the current thread and information that describes the exception. The system then attempts to find an exception handler to handle the exception.

The machine state of the thread in which the exception occurred is saved in a CONTEXT structure. This information (called the context record) enables the system to continue execution at the point of the exception if the exception is successfully handled. The description of the exception (called the exception record) is saved in an EXCEPTION_RECORD structure. Because it stores the machine-dependent information of the context record separately from the machine-independent information of the exception record, the exception-handling mechanism is portable to different platforms.

The information in both the context and exception records is available by means of the GetExceptionInformation function, and can be made available to any exception handlers that are executed as a result of the exception. The exception record includes the following information.

  • An exception code that identifies the type of exception.
  • Flags indicating whether the exception is continuable. Any attempt to continue execution after a noncontinuable exception generates another exception.
  • A pointer to another exception record. This facilitates creation of a linked list of exceptions if nested exceptions occur.
  • The address at which the exception occurred.
  • An array of arguments that provide additional information about the exception.

When an exception occurs in user-mode code, the system uses the following search order to find an exception handler:

  1. If the process is being debugged, the system notifies the debugger. For more information, see Debugger Exception Handling.
  2. If the process is not being debugged, or if the associated debugger does not handle the exception, the system attempts to locate a frame-based exception handler by searching the stack frames of the thread in which the exception occurred. The system searches the current stack frame first, then searches through preceding stack frames in reverse order.
  3. If no frame-based handler can be found, or no frame-based handler handles the exception, but the process is being debugged, the system notifies the debugger a second time.
  4. If the process is not being debugged, or if the associated debugger does not handle the exception, the system provides default handling based on the exception type. For most exceptions, the default action is to call the ExitProcess function.

When an exception occurs in kernel-mode code, the system searches the stack frames of the kernel stack in an attempt to locate an exception handler. If a handler cannot be located or no handler handles the exception, the system is shut down as if the ExitWindows function had been called.


Debugger Exception Handling

The system's handling of user-mode exceptions provides support for sophisticated debuggers. If the process in which an exception occurs is being debugged, the system generates a debug event. If the debugger is using the WaitForDebugEvent function, the debug event causes that function to return with a pointer to a DEBUG_EVENT structure. This structure contains the process and thread identifiers the debugger can use to access the thread's context record. The structure also contains an EXCEPTION_DEBUG_INFO structure that includes a copy of the exception record.

When the system is searching for an exception handler, it makes two attempts to notify a process's debugger. The first notification attempt provides the debugger with an opportunity to handle breakpoint or single-step exceptions. This is known as first-chance notification. The user can then issue debugger commands to manipulate the process's environment before any exception handlers are executed. The second attempt to notify the debugger occurs only if the system is unable to find a frame-based exception handler that handles the exception. This is known as last-chance notification. If the debugger does not handle the exception after the last-chance notification, the system terminates the process being debugged.

At each notification attempt, the debugger uses the ContinueDebugEvent function to return control to the system. Before returning control, the debugger can handle the exception and modify the thread state as appropriate, or it can choose not to handle the exception. Using ContinueDebugEvent, the debugger can indicate that it has handled the exception, in which case the machine state is restored and thread execution is continued at the point at which the exception occurred. The debugger can also indicate that it did not handle the exception, which causes the system to continue its search for an exception handler.


Floating-Point Exceptions

By default, the system has all FP exceptions turned off. Therefore, computations result in NAN or INFINITY, rather than an exception. Before you can trap floating-point (FP) exceptions using structured exception handling, you must call the _controlfp C run-time library function as follows:

// Get the default control word

int cw = _controlfp( 0, 0 );

// Set the exception masks off, turn exceptions on

cw &=~(EM_OVERFLOW | EM_UNDERFLOW | EM_INEXACT | EM_ZERODIVIDE | EM_DENORMAL

// Set the control word

_controlfp( cw, MCW_EM );

This turns on all possible FP exceptions To trap only particular exceptions, use only the flags that correspond to the exceptions to be trapped. Note that any handler for FP errors should call _clearfp as its first FP instruction. This function clears floating-point exceptions.


Frame-based Exception Handling

A frame-based exception handler allows you to deal with the possibility that an exception may occur in a certain sequence of code. A frame-based exception handler consists of the following elements.

  • A guarded body of code
  • A filter expression
  • An exception-handler block

Frame-based exception handlers are declared in language-specific syntax. For example, in the Microsoft C/C++ Optimizing Compiler, they are implemented using __try and __except. For more information, see Handler Syntax.

The guarded body of code is a set of one or more statements for which the filter expression and the exception-handler block provide exception-handling protection. The guarded body can be a block of code, a set of nested blocks, or an entire procedure or function. Using the Microsoft C/C++ Optimizing Compiler, a guarded body is enclosed by braces ({}) following the __try keyword.

The filter expression of a frame-based exception handler is an expression that is evaluated by the system when an exception occurs within the guarded body. This evaluation results in one of the following actions by the system.

  • The system stops its search for an exception handler, restores the machine state, and continues thread execution at the point at which the exception occurred.
  • The system continues its search for an exception handler.
  • The system transfers control to the exception handler, and thread execution continues sequentially in the stack frame in which the exception handler is found. If the handler is not in the stack frame in which the exception occurred, the system unwinds the stack, leaving the current stack frame and any other stack frames until it is back to the exception handler's stack frame. Before an exception handler is executed, termination handlers are executed for any guarded bodies of code that terminated as a result of the transfer of control to the exception handler. For more information about termination handlers, refer to Termination Handling.

The filter expression can be a simple expression, or it can invoke a filter function that attempts to handle the exception. You can call the GetExceptionCode and GetExceptionInformation functions from within a filter expression to get information about the exception being filtered. GetExceptionCode returns a code that identifies the type of exception, and GetExceptionInformation returns a pointer to an EXCEPTION_POINTERS structure that contains pointers to CONTEXT and EXCEPTION_RECORD structures.

These functions cannot be called from within a filter function, but their return values can be passed as parameters to a filter function. GetExceptionCode can be used within the exception-handler block, but GetExceptionInformation cannot because the information it points to is typically on the stack and is destroyed when control is transferred to an exception handler. However, an application can copy the information to safe storage to make it available to the exception handler.

The advantage of a filter function is that it can handle an exception and return a value that causes the system to continue execution from the point at which the exception occurred. With an exception-handler block, in contrast, execution continues sequentially from the exception handler rather than from the point of the exception.

Handling an exception may be as simple as noting an error and setting a flag that will be examined later, printing a warning or error message, or taking some other limited action. If execution can be continued, it may also be necessary to change the machine state by modifying the context record. For an example of a filter function that handles a page fault exception, see Using the Virtual Memory Functions.

The UnhandledExceptionFilter function can be used as a filter function in a filter expression. It returns EXCEPTION_EXECUTE_HANDLER unless the process is being debugged, in which case it returns EXCEPTION_CONTINUE_SEARCH.


Termination Handling

A termination handler ensures that a specific block of code is executed whenever flow of control leaves a particular guarded body of code. A termination handler consists of the following elements.

  • A guarded body of code
  • A block of termination code to be executed when the flow of control leaves the guarded body

Termination handlers are declared in language-specific syntax. Using the Microsoft C/C++ Optimizing Compiler, they are implemented using __try and __finally. For more information, see Handler Syntax.

The guarded body of code can be a block of code, a set of nested blocks, or an entire procedure or function. Whenever the guarded body is executed, the block of termination code will be executed. The only exception to this is when the thread terminates during execution of the guarded body (for example, if the ExitThread or ExitProcess function is called from within the guarded body).

The termination block is executed when the flow of control leaves the guarded body, regardless of whether the guarded body terminated normally or abnormally. The guarded body is considered to have terminated normally when the last statement in the block is executed and control proceeds sequentially into the termination block. Abnormal termination occurs when the flow of control leaves the guarded body due to an exception, or due to a control statement such as return, goto, break, or continue. The AbnormalTermination function can be called from within the termination block to determine whether the guarded body terminated normally.


Handler Syntax

This section describes the syntax and usage of structured exception handling as implemented in the Microsoft C/C++ Optimizing Compiler. The following keywords are interpreted by the compiler as part of the structured exception-handling mechanism.

Keyword | Description
__try | Begins a guarded body of code. Used with the __except keyword to construct an exception handler, or with the __finally keyword to construct a termination handler.
__except | Begins a block of code that is executed only when an exception occurs within its associated __try block.
__finally | Begins a block of code that is executed whenever the flow of control leaves its associated __try block.
__leave | Allows for immediate termination of the __try block without causing abnormal termination and its performance penalty.

The compiler also interprets the GetExceptionCode, GetExceptionInformation, and AbnormalTermination functions as keywords, and their use outside the appropriate exception-handling syntax generates a compiler error. The following are brief descriptions of these functions.

Function | Description
GetExceptionCode | Returns a code that identifies the type of exception. This function can be called only from within the filter expression or the exception-handler block.
GetExceptionInformation | Returns a pointer to an EXCEPTION_POINTERS structure containing pointers to the context record and the exception record. This function can be called only from within the filter expression of an exception handler.
AbnormalTermination | Indicates whether the flow of control left the associated __try block sequentially after executing the last statement in the block. This function can be called only from within the __finally block of a termination handler.


Exception-Handler Syntax

The __try and __except keywords are used to construct a frame-based exception handler. The following example shows the structure of an exception handler.

__try
{
    // guarded body of code

}
__except (filter-expression)
{
    // exception-handler block

}

Note that the __try block and the exception-handler block require braces ({}). Using a goto statement to jump into the body of a __try block or into an exception-handler block is not permitted. This rule applies to both exception handlers and termination handlers.

The __try block contains the guarded body of code that the exception handler protects. A function can have any number of exception handlers, and these exception-handling statements can be nested within the same function or in different functions. If an exception occurs within the __try block, the system takes control and begins the search for an exception handler. For a detailed description of this search, see Exception Handling.

The exception handler receives only exceptions that occur within a single thread. This means that if a __try block contains a call to the CreateProcess or CreateThread function, exceptions that occur within the new process or thread are not dispatched to this handler.

The system evaluates the filter expression of each exception handler guarding the code in which the exception occurred until either the exception is handled or there are no more handlers. A filter expression must be evaluated as one of the three following values.

Value | Meaning
EXCEPTION_EXECUTE_HANDLER | The system transfers control to the exception handler, and execution continues in the stack frame in which the handler is found.
EXCEPTION_CONTINUE_SEARCH | The system continues to search for a handler.
EXCEPTION_CONTINUE_EXECUTION | The system stops its search for a handler and returns control to the point at which the exception occurred. If the exception is noncontinuable, this results in an EXCEPTION_NONCONTINUABLE_EXCEPTION exception.

The filter expression is evaluated in the context of the function in which the exception handler is located, even though the exception may have occurred in a different function. This means that the filter expression can access the function's local variables. Similarly, the exception-handler block can access the local variables of the function in which it is located.

For more information about filter expressions and filter functions, see Frame-based Exception Handling.


Termination-Handler Syntax

The __try and __finally keywords are used to construct a termination handler. The following example shows the structure of a termination handler.

__try
{
    // guarded body of code

}
__finally
{
    // __finally block

}

As with the exception handler, both the __try block and the __finally block require braces ({}), and using a goto statement to jump into either block is not permitted.

The __try block contains the guarded body of code that is protected by the termination handler. A function can have any number of termination handlers, and these termination-handling blocks can be nested within the same function or in different functions.

The __finally block is executed whenever the flow of control leaves the __try block. However, the __finally block is not executed if you call any of the following functions within the __try block: ExitProcess, ExitThread, or abort.

The __finally block is executed in the context of the function in which the termination handler is located. This means that the __finally block can access that function's local variables. Execution of the __finally block can terminate by any of the following means.

  • Execution of the last statement in the block and continuation to the next instruction
  • Use of a control statement (return, break, continue, or goto)
  • Use of longjmp or a jump to an exception handler

If execution of the __try block terminates because of an exception that invokes the exception-handling block of a frame-based exception handler, the __finally block is executed before the exception-handling block is executed. Similarly, a call to the longjmp C run-time library function from the __try block causes execution of the __finally block before execution resumes at the target of the longjmp operation. If __try block execution terminates due to a control statement (return, break, continue, or goto), the __finally block is executed.

The AbnormalTermination function can be used within the __finally block to determine whether the __try block terminated sequentially — that is, whether it reached the closing brace (}). Leaving the __try block because of a call to longjmp, a jump to an exception handler, or a return, break, continue, or goto statement, is considered an abnormal termination. Note that failure to terminate sequentially causes the system to search through all stack frames in reverse order to determine whether any termination handlers must be called. This can result in performance degradation due to the execution of hundreds of instructions.

To avoid abnormal termination of the termination handler, execution should continue to the end of the block. You can also execute the __leave statement. The __leave statement allows for immediate termination of the __try block without causing abnormal termination and its performance penalty. Check your compiler documentation to determine if the __leave statement is supported.

If execution of the __finally block terminates because of the return control statement, it is equivalent to a goto to the closing brace in the enclosing function. Therefore, the enclosing function will return.


Vectored Exception Handling

[This is preliminary documentation and subject to change.]

Vectored exception handlers are not frame-based handlers. Therefore, you can add a handler and ensure that it gets called regardless of where you are in a call frame. The handlers are called in the order that they were added, after the debugger gets a first chance notification, but before frame-based dispatching occurs.

To add a handler, use the AddVectoredExceptionHandler function. To remove a handler, use the RemoveVectoredExceptionHandler function.


Windows Error Reporting

[This is preliminary documentation and subject to change.]

The error reporting system enables users to notify Microsoft of application faults, kernel faults, and unresponsive applications. This allows customer support to solve problems more effectively. It also enables developers to receive information that can be used to improve their products.

Users can enable fault reporting by using the System control panel application. They can choose to report errors in various parts of the system or from specific applications. Administrators can override these settings using Group Policy.

An application can report a fault by calling the ReportFault function. If error reporting is enabled, the system displays a dialog box to the user indicating that the application has encountered a problem and will close. If there is a debugger configured in the AeDebug key, the user is given the option to launch the debugger. The user is also given the option to send a report to Microsoft. If the user sends the report, the system displays another dialog box thanking the user for the report and providing a link to more information. Microsoft can use the error reporting feature to provide customers with troubleshooting information, workarounds, or updates for their specific problems.

The error reporting system supports the following operation modes.

Operation mode | Description
Shared memory reporting | If the application's security context is the same as the security context of the logged-on user, the error reporting system uses a block of shared memory for communication. This mode cannot be used with manifest reporting mode.
Manifest reporting | If the application's security context is not the same as the security context of the logged-on user, the error reporting system uses a file for communication. This mode is also used for reporting unresponsive applications and kernel faults. This mode cannot be used with shared memory reporting mode.
Internet reporting | The error reporting system sends all data to Microsoft through the Internet. This is the default mode of operation. It cannot be used with corporate reporting mode. This mode is used when there is no corporate upload path specified by the administrator.
Corporate reporting | The error reporting system sends all data to a file share instead of uploading it directly to Microsoft. This allows corporate IT managers to review data before it is sent to Microsoft. This mode is used when there is a corporate upload path specified by the administrator. It cannot be used with Internet reporting mode.
Headless reporting | The error reporting system will not display any dialog boxes to the user. This allows corporate IT managers to collect data from their employees at all times. This mode is used when reporting is enabled by the administrator, but notification is disabled. It can be used only with corporate reporting mode.


Using Structured Exception Handling

The following samples demonstrate how to use structured exception handling in your code.

  • Using an exception handler
  • Using a termination handler
  • Using a vectored exception handler


Using an Exception Handler

The following example shows a version of the strcpy C run-time library function that can handle an invalid pointer and return NULL if one is encountered.

Note This exception handler is intended to handle an access-violation exception, but is inappropriate if some other type of exception occurs. Therefore, the filter expression in the example uses the GetExceptionCode function to check the exception type before executing the handler. This enables the system to continue its search for an appropriate handler if some other type of exception occurs.

Also that there is no problem with using a return statement in the __try block of an exception handler. This differs from the use of return in the __try block of a termination handler, which causes an abnormal termination of the __try block.

LPTSTR SafeStrcpy(LPTSTR lpszString1, LPTSTR lpszString2)
{
    __try
    {
        return strcpy(string1, string2);
    }
    __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?
                EXCEPTION_EXECUTE_HANDLER :
                EXCEPTION_CONTINUE_SEARCH )
    {
        return NULL;
    }
}

The following example shows the interaction of nested handlers. The RaiseException function causes an exception in the guarded body of a termination handler that is inside the guarded body of an exception handler. The exception causes the system to evaluate the FilterFunction function, whose return value in turn causes the exception handler to be invoked. However, before the exception-handler block is executed, the __finally block of the termination handler is executed because the flow of control has left the __try block of the termination handler.

DWORD FilterFunction()
{
    printf("1 ");                     // printed first
    return EXCEPTION_EXECUTE_HANDLER;
}

VOID main(VOID)
{
    __try
    {
        __try
        {
            RaiseException(1,         // exception code
                0,                    // continuable exception
                0, NULL);             // no arguments
        }
        __finally
        {
            printf("2 ")              // this is printed second
        }
    }
    __except ( FilterFunction() )
    {
        printf("3\n");                // this is printed last
    }
}


Using a Termination Handler

The following example shows how a termination handler is used to ensure that resources are released when execution of a guarded body of code terminates. In this case, a thread uses the EnterCriticalSection function to wait for ownership of a critical section object. When the thread is finished executing the code that is protected by the critical section, it must call the LeaveCriticalSection function to make the critical section object available to other threads. Using a termination handler guarantees that this will happen.

For more information, see critical section objects.

LPTSTR lpBuffer = NULL;
CRITICAL_SECTION CriticalSection;

__try
{
    // EnterCriticalSection synchronizes code with other threads.

    EnterCriticalSection(&CriticalSection);

    // Perform a task that may cause an exception.

    lpBuffer = (LPTSTR) LocalAlloc(LPTR, 10);
    strcpy(lpBuffer,"Hello");  // possible access violation
    printf("%s\n",lpBuffer);
    LocalFree(lpBuffer);
}

// LeaveCriticalSection is called even if an exception occurred.

__finally
{
    LeaveCriticalSection(&CriticalSection);
}


Using a Vectored Exception Handler

[This is preliminary documentation and subject to change.]

The following sample code demonstrates how to use vectored exception handling. It uses the AddVectoredExceptionHandler function to add several handlers, tests the handlers, then uses the RemoveVectoredExceptionHandler function to remove the handlers.

64-bit Windows: This code is not suitable for 64-bit Windows.

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

LONG Sequence=1;
LONG Actual[3];

LONG
VectoredHandler1(
    struct _EXCEPTION_POINTERS *ExceptionInfo
    )
{
    Actual[0] = Sequence++;
    return EXCEPTION_CONTINUE_SEARCH;
}

LONG
VectoredHandler2(
    struct _EXCEPTION_POINTERS *ExceptionInfo
    )
{
    Actual[1] = Sequence++;
    return EXCEPTION_CONTINUE_SEARCH;
}
LONG
VectoredHandler3(
    struct _EXCEPTION_POINTERS *ExceptionInfo
    )
{
    Actual[2] = Sequence++;
    return EXCEPTION_CONTINUE_SEARCH;
}

LONG
VectoredHandlerSkip1(
    struct _EXCEPTION_POINTERS *ExceptionInfo
    )
{
    PCONTEXT Context;

    Sequence++;
    Context = ExceptionInfo->ContextRecord;
    Actual[0] = 0xcc;
    Context->Eip++;
    return EXCEPTION_CONTINUE_EXECUTION;
}

LONG
VectoredHandlerSkip2(
    struct _EXCEPTION_POINTERS *ExceptionInfo
    )
{
    PCONTEXT Context;

    Sequence++;
    Context = ExceptionInfo->ContextRecord;
    Actual[1] = 0xcc;
    Context->Eip++;
    return EXCEPTION_CONTINUE_EXECUTION;
}

LONG
VectoredHandlerSkip3(
    struct _EXCEPTION_POINTERS *ExceptionInfo
    )
{
    PCONTEXT Context;

    Sequence++;
    Context = ExceptionInfo->ContextRecord;
    Actual[2] = 0xcc;
    Context->Eip++;
    return EXCEPTION_CONTINUE_EXECUTION;
}

BOOL
CheckTest(
    char *Variation,
    PLONG e,
    PLONG a
    )
{
    int i;
    BOOL Pass = TRUE;

    for(i=0;i<3;i++)
    {
        if (e[i] != a[i])
        {
            if (Variation)
            {
                printf("%s Failed at %d Expected %d vs Actual %d\n", Variation, i, e[i], a[i]);
                }
            Pass = FALSE;
            }

        // Clear actual for next pass.
        a[i] = 0;
        }

    // Get ready for next pass.
    Sequence = 1;

    if (Variation)
    {
        printf("Variation %s %s\n",Variation,Pass ? "Passed" : "Failed");
        }
    return Pass;
}

void
CheckAllClear()
{
    LONG e[3];
    BOOL b;

    e[0]=0;e[1]=0;e[2]=0;
    try
    {
        RaiseException(1,0,0,NULL);
    }
    except(EXCEPTION_EXECUTE_HANDLER)
    {
        b = CheckTest(NULL,e,Actual);
    }
    if (!b)
    {
        printf("Fatal error, handlers still registered.\n");
    }
}

void
IllegalInst()
{
    _asm {cli};
}
void
Test1()
{

    PVOID h1,h2,h3;
    LONG e[3];

    e[0]=1;e[1]=2;e[2]=3;
    h2 = AddVectoredExceptionHandler(1,VectoredHandler2);
    h3 = AddVectoredExceptionHandler(0,VectoredHandler3);
    h1 = AddVectoredExceptionHandler(1,VectoredHandler1);

    try
    {
        RaiseException(1,0,0,NULL);
    }
    except(EXCEPTION_EXECUTE_HANDLER)
    {
        CheckTest("Test1a",e,Actual);
    }

    RemoveVectoredExceptionHandler(h1);
    RemoveVectoredExceptionHandler(h3);
    RemoveVectoredExceptionHandler(h2);
    CheckAllClear();
}

void
Test2()
{

    PVOID h1,h2,h3;
    LONG e[3];

    e[0]=0xcc;e[1]=0;e[2]=0;
    h1 = AddVectoredExceptionHandler(1,VectoredHandlerSkip1);
    IllegalInst();
    CheckTest("Test2a",e,Actual);
    RemoveVectoredExceptionHandler(h1);
    CheckAllClear();

    e[0]=1;e[1]=2;e[2]=0xcc;
    h2 = AddVectoredExceptionHandler(1,VectoredHandler2);
    h3 = AddVectoredExceptionHandler(0,VectoredHandlerSkip3);
    h1 = AddVectoredExceptionHandler(1,VectoredHandler1);
    IllegalInst();
    CheckTest("Test2b",e,Actual);
    RemoveVectoredExceptionHandler(h1);
    RemoveVectoredExceptionHandler(h2);
    RemoveVectoredExceptionHandler(h3);
    CheckAllClear();

    e[0]=1;e[1]=0xcc;e[2]=0;
    h1 = AddVectoredExceptionHandler(0,VectoredHandler1);
    h2 = AddVectoredExceptionHandler(0,VectoredHandlerSkip2);
    h3 = AddVectoredExceptionHandler(0,VectoredHandler3);
    IllegalInst();
    CheckTest("Test2c",e,Actual);
    RemoveVectoredExceptionHandler(h1);
    RemoveVectoredExceptionHandler(h2);
    RemoveVectoredExceptionHandler(h3);
    CheckAllClear();

    e[0]=2;e[1]=0xcc;e[2]=1;
    h1 = AddVectoredExceptionHandler(0,VectoredHandler1);
    h3 = AddVectoredExceptionHandler(1,VectoredHandler3);
    h2 = AddVectoredExceptionHandler(0,VectoredHandlerSkip2);
    try
    {
        IllegalInst();
    }
    except(EXCEPTION_EXECUTE_HANDLER)
    {
        // Should not make it to here.
        e[0]=0;e[1]=0;e[2]=0;
        CheckTest("Test2d-1",e,Actual);
    }
    CheckTest("Test2d-2",e,Actual);
    RemoveVectoredExceptionHandler(h1);
    RemoveVectoredExceptionHandler(h2);
    RemoveVectoredExceptionHandler(h3);
    CheckAllClear();
}

void main( )
{
    Test1();
    Test2();
}


Structured Exception Handling Reference

The following elements are used with structured exception handling.

  • Structured Exception Handling Functions
  • Structured Exception Handling Structures


Structured Exception Handling Functions

The following functions are used in structured exception handling.

Function | Description
AbnormalTermination | Indicates whether the __try block of a termination handler terminated normally.
AddVectoredExceptionHandler | Registers a vectored exception handler.
GetExceptionCode | Retrieves a code that identifies the type of exception that occurred.
GetExceptionInformation | Retrieves a machine-independent description of an exception, and information about the machine state that existed for the thread when the exception occurred.
RaiseException | Raises an exception in the calling thread.
RemoveVectoredExceptionHandler | Unregisters a vectored exception handler.
ReportFault | Allows an application that performs its own exception handling to report faults to Microsoft.
SetUnhandledExceptionFilter | Enables an application to supersede the top-level exception handler of each thread and process.
UnhandledExceptionFilter | Passes unhandled exceptions to the debugger, if the process is being debugged.
VectoredHandler | An application-defined function that serves as a vectored exception handler.


AbnormalTermination

The AbnormalTermination function indicates whether the __try block of a termination handler terminated normally. The function can be called only from within the __finally block of a termination handler.

Note The Microsoft C/C++ Optimizing Compiler interprets this function as a keyword, and its use outside the appropriate exception-handling syntax generates a compiler error.

BOOL AbnormalTermination(VOID);

Parameters

This function has no parameters.

Return Values

If the __try block terminated abnormally, the return value is nonzero.

If the __try block terminated normally, the return value is zero.

Remarks

The __try block terminates normally only if execution leaves the block sequentially after executing the last statement in the block. Statements (such as return, goto, continue, or break) that cause execution to leave the __try block result in abnormal termination of the block. This is the case even if such a statement is the last statement in the __try block.

Abnormal termination of a __try block causes the system to search backward through all stack frames to determine whether any termination handlers must be called. This can result in the execution of hundreds of instructions, so it is important to avoid abnormal termination of a __try block due to a return, goto, continue, or break statement. Note that these statements do not generate an exception, even though the termination is abnormal.

To avoid abnormal termination, execution should continue to the end of the block. You can also execute the __leave statement. The __leave statement allows for immediate termination of the __try block without causing abnormal termination and its performance penalty. Check your compiler documentation to determine if the __leave statement is supported.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

See Also

Structured Exception Handling Overview, Structured Exception Handling Functions


AddVectoredExceptionHandler

[This is preliminary documentation and subject to change.]

The AddVectoredExceptionHandler function registers a vectored exception handler.

PVOID AddVectoredExceptionHandler(
  ULONG FirstHandler,
  PVECTORED_EXCEPTION_HANDLER VectoredHandler
);

Parameters

FirstHandler
Specifies the order in which the handler should be called. If the parameter is nonzero, the handler is the first handler to be called. If the parameter is zero, the handler is the last handler to be called.
VectoredHandler
Pointer to the handler to be called. For more information, see VectoredHandler.

Return Values

If the function succeeds, the return value is a pointer to the exception handler.

If the function fails, the return value is NULL.

Remarks

If the FirstHandler parameter is nonzero, the handler is the first handler to be called until a subsequent call to AddVectoredExceptionHandler is used to specify a different handler as the first handler.

If the VectoredHandler parameter points to a function in a DLL and that DLL is unloaded, the handler is still registered. This can lead to application errors.

To unregister the handler, use the RemoveVectoredExceptionHandler function.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Structured Exception Handling Overview, Structured Exception Handling Functions, RemoveVectoredExceptionHandler, VectoredHandler


GetExceptionCode

The GetExceptionCode function retrieves a code that identifies the type of exception that occurred. The function can be called only from within the filter expression or exception-handler block of an exception handler.

Note The Microsoft C/C++ Optimizing Compiler interprets this function as a keyword, and its use outside the appropriate exception-handling syntax generates a compiler error.

DWORD GetExceptionCode(VOID);

Parameters

This function has no parameters.

Return Values

The return value identifies the type of exception. The following table describes the exception codes that are likely to occur due to common programming errors.

Value | Meaning
EXCEPTION_ACCESS_VIOLATION | The thread attempted to read from or write to a virtual address for which it does not have the appropriate access.
EXCEPTION_BREAKPOINT | A breakpoint was encountered.
EXCEPTION_DATATYPE_MISALIGNMENT | The thread attempted to read or write data that is misaligned on hardware that does not provide alignment. For example, 16-bit values must be aligned on 2-byte boundaries, 32-bit values on 4-byte boundaries, and so on.
EXCEPTION_SINGLE_STEP | A trace trap or other single-instruction mechanism signaled that one instruction has been executed.
EXCEPTION_ARRAY_BOUNDS_EXCEEDED | The thread attempted to access an array element that is out of bounds, and the underlying hardware supports bounds checking.
EXCEPTION_FLT_DENORMAL_OPERAND | One of the operands in a floating-point operation is denormal. A denormal value is one that is too small to represent as a standard floating-point value.
EXCEPTION_FLT_DIVIDE_BY_ZERO | The thread attempted to divide a floating-point value by a floating-point divisor of zero.
EXCEPTION_FLT_INEXACT_RESULT | The result of a floating-point operation cannot be represented exactly as a decimal fraction.
EXCEPTION_FLT_INVALID_OPERATION | This exception represents any floating-point exception not included in this list.
EXCEPTION_FLT_OVERFLOW | The exponent of a floating-point operation is greater than the magnitude allowed by the corresponding type.
EXCEPTION_FLT_STACK_CHECK | The stack overflowed or underflowed as the result of a floating-point operation.
EXCEPTION_FLT_UNDERFLOW | The exponent of a floating-point operation is less than the magnitude allowed by the corresponding type.
EXCEPTION_INT_DIVIDE_BY_ZERO | The thread attempted to divide an integer value by an integer divisor of zero.
EXCEPTION_INT_OVERFLOW | The result of an integer operation caused a carry out of the most significant bit of the result.
EXCEPTION_PRIV_INSTRUCTION | The thread attempted to execute an instruction whose operation is not allowed in the current machine mode.
EXCEPTION_NONCONTINUABLE_EXCEPTION | The thread attempted to continue execution after a noncontinuable exception occurred.

Remarks

The GetExceptionCode function can be called only from within the filter expression or exception-handler block of an exception handler. The filter expression is evaluated if an exception occurs during execution of the __try block, and it determines whether the __except block is executed.

The filter expression can invoke a filter function. The filter function cannot call GetExceptionCode. However, the return value of GetExceptionCode can be passed as a parameter to a filter function. The return value of the GetExceptionInformation function can also be passed as a parameter to a filter function. GetExceptionInformation returns a pointer to a structure that includes the exception-code information.

In the case of nested handlers, each filter expression is evaluated until one is evaluated as EXCEPTION_EXECUTE_HANDLER or EXCEPTION_CONTINUE_EXECUTION. Each filter expression can invoke GetExceptionCode to get the exception code.

The exception code returned is the code generated by a hardware exception, or the code specified in the RaiseException function for a software-generated exception.

When handling the breakpoint exception, it is important to increment the instruction pointer in the context record to continue from this exception.

For an example, see Using an Exception Handler.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

See Also

Structured Exception Handling Overview, Structured Exception Handling Functions, GetExceptionInformation, RaiseException


GetExceptionInformation

The GetExceptionInformation function retrieves a machine-independent description of an exception, and information about the machine state that existed for the thread when the exception occurred. This function can be called only from within the filter expression of an exception handler.

Note The Microsoft C/C++ Optimizing Compiler interprets this function as a keyword, and its use outside the appropriate exception-handling syntax generates a compiler error.

LPEXCEPTION_POINTERS GetExceptionInformation(VOID);

Parameters

This function has no parameters.

Return Values

The return value is a pointer to an EXCEPTION_POINTERS structure that contains pointers to two other structures: an EXCEPTION_RECORD structure containing a description of the exception, and a CONTEXT structure containing the machine-state information.

Remarks

The filter expression (from which the function is called) is evaluated if an exception occurs during execution of the __try block, and it determines whether the __except block is executed.

The filter expression can invoke a filter function. The filter function cannot call GetExceptionInformation. However, the return value of GetExceptionInformation can be passed as a parameter to a filter function.

To pass the EXCEPTION_POINTERS information to the exception-handler block, the filter expression or filter function must copy the pointer or the data to safe storage that the handler can later access.

In the case of nested handlers, each filter expression is evaluated until one is evaluated as EXCEPTION_EXECUTE_HANDLER or EXCEPTION_CONTINUE_EXECUTION. Each filter expression can invoke GetExceptionInformation to get exception information.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.

See Also

Structured Exception Handling Overview, Structured Exception Handling Functions, CONTEXT, EXCEPTION_POINTERS, EXCEPTION_RECORD, GetExceptionCode


RaiseException

The RaiseException function raises an exception in the calling thread.

VOID RaiseException(
  DWORD dwExceptionCode,       // exception code
  DWORD dwExceptionFlags,      // continuable exception flag
  DWORD nNumberOfArguments,    // number of arguments
  CONST ULONG_PTR *lpArguments // array of arguments
);

Parameters

dwExceptionCode
[in] Specifies the application-defined exception code of the exception being raised. The filter expression and exception-handler block of an exception handler can use the GetExceptionCode function to retrieve this value.

Note that the system will clear bit 28 of dwExceptionCode before displaying a message This bit is a reserved exception bit, used by the system for its own purposes.

dwExceptionFlags
[in] Specifies the exception flags. This can be either zero to indicate a continuable exception, or EXCEPTION_NONCONTINUABLE to indicate a noncontinuable exception. Any attempt to continue execution after a noncontinuable exception causes the EXCEPTION_NONCONTINUABLE_EXCEPTION exception.
nNumberOfArguments
[in] Specifies the number of arguments in the lpArguments array. This value must not exceed EXCEPTION_MAXIMUM_PARAMETERS. This parameter is ignored if lpArguments is NULL.
lpArguments
[in] Pointer to an array of arguments. This parameter can be NULL. These arguments can contain any application-defined data that needs to be passed to the filter expression of the exception handler.

Return Values

This function does not return a value.

Remarks

The RaiseException function enables a process to use structured exception handling to handle private, software-generated, application-defined exceptions.

Raising an exception causes the exception dispatcher to go through the following search for an exception handler:

  1. The system first attempts to notify the process's debugger, if any.
  2. If the process is not being debugged, or if the associated debugger does not handle the exception, the system attempts to locate a frame-based exception handler by searching the stack frames of the thread in which the exception occurred. The system searches the current stack frame first, then proceeds backward through preceding stack frames.
  3. If no frame-based handler can be found, or no frame-based handler handles the exception, the system makes a second attempt to notify the process's debugger.
  4. If the process is not being debugged, or if the associated debugger does not handle the exception, the system provides default handling based on the exception type. For most exceptions, the default action is to call the ExitProcess function.

The values specified in the dwExceptionCode, dwExceptionFlags, nNumberOfArguments, and lpArguments parameters can be retrieved in the filter expression of a frame-based exception handler by calling the GetExceptionInformation function. A debugger can retrieve these values by calling the WaitForDebugEvent function.

For exmaple see Using an Exception Handler.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Structured Exception Handling Overview, Structured Exception Handling Functions, ExitProcess, GetExceptionCode, GetExceptionInformation, WaitForDebugEvent


RemoveVectoredExceptionHandler

[This is preliminary documentation and subject to change.]

The RemoveVectoredExceptionHandler function unregisters a vectored exception handler.

ULONG RemoveVectoredExceptionHandler(
  PVOID VectoredHandlerHandle
);

Parameters

VectoredHandlerHandle
Specifies a vectored exception handler previously registered using the AddVectoredExceptionHandler function.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Structured Exception Handling Overview, Structured Exception Handling Functions, AddVectoredExceptionHandler


ReportFault

[This is preliminary documentation and subject to change.]

The ReportFault function allows an application that performs its own exception handling to report faults to Microsoft.

EFaultRepRetVal ReportFault(
  LPEXCEPTION_POINTERS pep,
  DWORD dwMode
);

Parameters

pep
[in] Pointer to an EXCEPTION_POINTERS structure.
dwMode
This value is reserved for system use and should be set to zero.

Return Values

This function returns one of the following values.

Value | Meaning
frrvOk | The function succeeded.
frrvOkManifest | The function succeeded and the client was launched in manifest reporting mode.
frrvErr | The function failed but the client was launched.
frrvErrNoDW | The client was unable to launch. The system will perform its default actions, such as displaying the standard exception dialog box and launching the debugger.
frrvErrTimeout | The function timed out.
frrvLaunchDebugger | The function succeeded and the user launched the debugger.

These return values indicate whether the reporting application was successfully launched. A successful return value does not indicate that the fault was successfully reported.

Remarks

The exact result of calling this function depends on how the user or system administrator has configured the error reporting system.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in ErrorRep.h.
Library: Use Faultrep.lib.

See Also

Structured Exception Handling Overview, Structured Exception Handling Functions, Windows Error Reporting , EXCEPTION_POINTERS


SetUnhandledExceptionFilter

The SetUnhandledExceptionFilter function enables an application to supersede the top-level exception handler of each thread and process.

After calling this function, if an exception occurs in a process that is not being debugged, and the exception makes it to the unhandled exception filter, that filter will call the exception filter function specified by the lpTopLevelExceptionFilter parameter.

LPTOP_LEVEL_EXCEPTION_FILTER SetUnhandledExceptionFilter(
  LPTOP_LEVEL_EXCEPTION_FILTER lpTopLevelExceptionFilter
);

Parameters

lpTopLevelExceptionFilter
[in] Pointer to a top-level exception filter function that will be called whenever the UnhandledExceptionFilter function gets control, and the process is not being debugged. A value of NULL for this parameter specifies default handling within UnhandledExceptionFilter.

The filter function has syntax similar to that of UnhandledExceptionFilter: It takes a single parameter of type LPEXCEPTION_POINTERS, and returns a value of type LONG. The filter function should return one of the following values.
Value | Meaning
EXCEPTION_EXECUTE_HANDLER | Return from UnhandledExceptionFilter and execute the associated exception handler. This usually results in process termination.
EXCEPTION_CONTINUE_EXECUTION | Return from UnhandledExceptionFilter and continue execution from the point of the exception. Note that the filter function is free to modify the continuation state by modifying the exception information supplied through its LPEXCEPTION_POINTERS parameter.
EXCEPTION_CONTINUE_SEARCH | Proceed with normal execution of UnhandledExceptionFilter. That means obeying the SetErrorMode flags, or invoking the Application Error pop-up message box.

Return Values

The SetUnhandledExceptionFilter function returns the address of the previous exception filter established with the function. A NULL return value means that there is no current top-level exception handler.

Remarks

Issuing SetUnhandledExceptionFilter replaces the existing top-level exception filter for all existing and all future threads in the calling process.

The exception handler specified by lpTopLevelExceptionFilter is executed in the context of the thread that caused the fault. This can affect the exception handler's ability to recover from certain exceptions, such as an invalid stack.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Structured Exception Handling Overview, Structured Exception Handling Functions, UnhandledExceptionFilter


UnhandledExceptionFilter

The UnhandledExceptionFilter function passes unhandled exceptions to the debugger, if the process is being debugged. Otherwise, it optionally displays an Application Error message box and causes the exception handler to be executed. This function can be called only from within the filter expression of an exception handler.

LONG UnhandledExceptionFilter(
  STRUCT _EXCEPTION_POINTERS *ExceptionInfo
);

Parameters

ExceptionInfo
[in] Pointer to an EXCEPTION_POINTERS structure containing a description of the exception and the processor context at the time of the exception. This pointer is the return value of a call to the GetExceptionInformation function.

Return Values

The function returns one of the following values.

Value | Meaning
EXCEPTION_CONTINUE_SEARCH | The process is being debugged, so the exception should be passed (as second chance) to the application's debugger.
EXCEPTION_EXECUTE_HANDLER | If the SEM_NOGPFAULTERRORBOX flag was specified in a previous call to SetErrorMode, no Application Error message box is displayed. The function returns control to the exception handler, which is free to take any appropriate action.

Remarks

If the process is not being debugged, the function displays an Application Error message box, depending on the current error mode. The default behavior is to display the dialog box, but this can be disabled by specifying SEM_NOGPFAULTERRORBOX in a call to the SetErrorMode function.

The system uses UnhandledExceptionFilter internally to handle exceptions that occur during process and thread creation.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Structured Exception Handling Overview, Structured Exception Handling Functions, EXCEPTION_POINTERS, GetExceptionInformation, SetErrorMode, SetUnhandledExceptionFilter, UnhandledExceptionFilter


VectoredHandler

[This is preliminary documentation and subject to change.]

The VectoredHandler function is an application-defined function that serves as a vectored exception handler. Specify this address when calling the AddVectoredExceptionHandler function. The PVECTORED_EXCEPTION_HANDLER type defines a pointer to this callback function. VectoredHandler is a placeholder for the application-defined name.

LONG WINAPI VectoredHandler(
  PEXCEPTION_POINTERS ExceptionInfo
);

Parameters

ExceptionInfo
Pointer to an EXCEPTION_POINTERS structure that receives the exception record.

Return Values

To return control to the point at which the exception occurred, return EXCEPTION_CONTINUE_EXECUTION. To continue the handler search, return EXCEPTION_CONTINUE_SEARCH.

Remarks

The handler should not call functions that acquire synchronization objects or allocate memory, because this can cause problems. Typically, the handler will simply access the exception record and return.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.

See Also

Structured Exception Handling Overview, Structured Exception Handling Functions, EXCEPTION_POINTERS


Structured Exception Handling Structures

The following structures are used with structured exception handling.

EXCEPTION_POINTERS
EXCEPTION_RECORD


EXCEPTION_POINTERS

The EXCEPTION_POINTERS structure contains an exception record with a machine-independent description of an exception and a context record with a machine-dependent description of the processor context at the time of the exception.

typedef struct _EXCEPTION_POINTERS {
  PEXCEPTION_RECORD ExceptionRecord;
  PCONTEXT ContextRecord;
} EXCEPTION_POINTERS, *PEXCEPTION_POINTERS;

Members

ExceptionRecord
Pointer to an EXCEPTION_RECORD structure that contains a machine-independent description of the exception.
ContextRecord
Pointer to a CONTEXT structure that contains a processor-specific description of the state of the processor at the time of the exception.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winnt.h; include Windows.h.

See Also

Structured Exception Handling Overview, Structured Exception Handling Structures, GetExceptionInformation, CONTEXT, EXCEPTION_RECORD


EXCEPTION_RECORD

The EXCEPTION_RECORD structure describes an exception.

typedef struct _EXCEPTION_RECORD {
  DWORD ExceptionCode;
  DWORD ExceptionFlags;
  struct _EXCEPTION_RECORD *ExceptionRecord;
  PVOID ExceptionAddress;
  DWORD NumberParameters;
  ULONG_PTR ExceptionInformation[EXCEPTION_MAXIMUM_PARAMETERS];
} EXCEPTION_RECORD, *PEXCEPTION_RECORD;

Members

ExceptionCode
Specifies the reason the exception occurred. This is the code generated by a hardware exception, or the code specified in the RaiseException function for a software-generated exception. The following tables describes the exception codes that are likely to occur due to common programming errors.
Value | Meaning
EXCEPTION_ACCESS_VIOLATION | The thread tried to read from or write to a virtual address for which it does not have the appropriate access.
EXCEPTION_ARRAY_BOUNDS_EXCEEDED | The thread tried to access an array element that is out of bounds and the underlying hardware supports bounds checking.
EXCEPTION_BREAKPOINT | A breakpoint was encountered.
EXCEPTION_DATATYPE_MISALIGNMENT | The thread tried to read or write data that is misaligned on hardware that does not provide alignment. For example, 16-bit values must be aligned on 2-byte boundaries; 32-bit values on 4-byte boundaries, and so on.
EXCEPTION_FLT_DENORMAL_OPERAND | One of the operands in a floating-point operation is denormal. A denormal value is one that is too small to represent as a standard floating-point value.
EXCEPTION_FLT_DIVIDE_BY_ZERO | The thread tried to divide a floating-point value by a floating-point divisor of zero.
EXCEPTION_FLT_INEXACT_RESULT | The result of a floating-point operation cannot be represented exactly as a decimal fraction.
EXCEPTION_FLT_INVALID_OPERATION | This exception represents any floating-point exception not included in this list.
EXCEPTION_FLT_OVERFLOW | The exponent of a floating-point operation is greater than the magnitude allowed by the corresponding type.
EXCEPTION_FLT_STACK_CHECK | The stack overflowed or underflowed as the result of a floating-point operation.
EXCEPTION_FLT_UNDERFLOW | The exponent of a floating-point operation is less than the magnitude allowed by the corresponding type.
EXCEPTION_ILLEGAL_INSTRUCTION | The thread tried to execute an invalid instruction.
EXCEPTION_IN_PAGE_ERROR | The thread tried to access a page that was not present, and the system was unable to load the page. For example, this exception might occur if a network connection is lost while running a program over the network.
EXCEPTION_INT_DIVIDE_BY_ZERO | The thread tried to divide an integer value by an integer divisor of zero.
EXCEPTION_INT_OVERFLOW | The result of an integer operation caused a carry out of the most significant bit of the result.
EXCEPTION_INVALID_DISPOSITION | An exception handler returned an invalid disposition to the exception dispatcher. Programmers using a high-level language such as C should never encounter this exception.
EXCEPTION_NONCONTINUABLE_EXCEPTION | The thread tried to continue execution after a noncontinuable exception occurred.
EXCEPTION_PRIV_INSTRUCTION | The thread tried to execute an instruction whose operation is not allowed in the current machine mode.
EXCEPTION_SINGLE_STEP | A trace trap or other single-instruction mechanism signaled that one instruction has been executed.
EXCEPTION_STACK_OVERFLOW | The thread used up its stack.

Another exception code is likely to occur when debugging console processes. It does not arise because of a programming error. The DBG_CONTROL_C exception code occurs when CTRL+C is input to a console process that handles CTRL+C signals and is being debugged. This exception code is not meant to be handled by applications. It is raised only for the benefit of the debugger, and is raised only when a debugger is attached to the console process.

ExceptionFlags
Specifies the exception flags. This member can be either zero, indicating a continuable exception, or EXCEPTION_NONCONTINUABLE indicating a noncontinuable exception. Any attempt to continue execution after a noncontinuable exception causes the EXCEPTION_NONCONTINUABLE_EXCEPTION exception.
ExceptionRecord
Pointer to an associated EXCEPTION_RECORD structure. Exception records can be chained together to provide additional information when nested exceptions occur.
ExceptionAddress
Specifies the address where the exception occurred.
NumberParameters
Specifies the number of parameters associated with the exception. This is the number of defined elements in the ExceptionInformation array.
ExceptionInformation
Specifies an array of additional arguments that describe the exception. The RaiseException function can specify this array of arguments. For most exception codes, the array elements are undefined. The following table describes the exception codes whose array elements are defined.
Exception code Array contents
EXCEPTION_ACCESS_VIOLATION The first element of the array contains a read-write flag that indicates the type of operation that caused the access violation. If this value is zero, the thread attempted to read the inaccessible data. If this value is 1, the thread attempted to write to an inaccessible address.

The second array element specifies the virtual address of the inaccessible data.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winnt.h; include Windows.h.

See Also

Structured Exception Handling Overview, Structured Exception Handling Structures, EXCEPTION_DEBUG_INFO, EXCEPTION_POINTERS, GetExceptionInformation, RaiseException, UnhandledExceptionFilter


Topic Not Found

No matching topic was found. Some possible reasons and remedies are as follows:

  • The file (.chm) that contains the destination topic is not in the expected location.

    Remedy: Rerun the MSDN Library Setup.

  • The file (.chm) that contains the current topic or destination topic is out-of-date and the link is no longer valid.

    Remedy: Install the latest version of the MSDN Library.

  • The MSDN Library CD is not in the CD-ROM drive.

    Remedy: Insert the MSDN Library CD into the CD-ROM drive.