Platform SDK: Debugging and Error Handling

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);
}