Here is my test case:
#include <windows.h>
#include <imagehlp.h>
#include <cassert>
#include <cstddef>
#include <cstring>
#include <iostream>
struct symbol_buffer
{
static const std::size_t max_sym_length = 4096;
symbol_buffer()
{
std::memset(buffer, 0x00, sizeof buffer);
IMAGEHLP_SYMBOL *sym = get();
sym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
sym->MaxNameLength = max_sym_length;
}
IMAGEHLP_SYMBOL *get() { return reinterpret_cast<IMAGEHLP_SYMBOL *>(buffer); }
union
{
DWORD for_alignment;
unsigned char buffer[sizeof(IMAGEHLP_SYMBOL) + max_sym_length];
};
};
void print_function_name(UINT_PTR program_counter, HANDLE process)
{
const char *symbol_ptr = "???";
symbol_buffer sym_buff;
IMAGEHLP_SYMBOL *symbol = sym_buff.get();
//symbol->Address = program_counter; // don't think this is needed, but doesn't make any difference
if (SymGetSymFromAddr(process, program_counter, 0, symbol))
symbol_ptr = symbol->Name;
if (symbol_ptr)
std::cout << "function: '" << symbol_ptr << "'\n";
}
const char *splendid() { return "splendid"; }
int main()
{
const HANDLE process = GetCurrentProcess();
//SymSetOptions(
// SYMOPT_ALLOW_ABSOLUTE_SYMBOLS |
// SYMOPT_ALLOW_ZERO_ADDRESS |
// SymGetOptions()
//);
if (SymInitialize(process, 0, TRUE) == 0)
return 1;
const char *(*fp)() = &splendid;
UINT_PTR fp_val = 0;
assert(sizeof fp_val == sizeof fp);
std::memcpy(&fp_val, &fp, sizeof fp);
print_function_name(fp_val, process);
SymCleanup(process);
return 0;
}
I am building with the Visual C++ 2010 toolchain as follows:
P:\guff>cl /nologo /EHsc /W3 /WX /GR /Zi /GS /arch:SSE2 /MTd /Oy- /c symbols.cpp /Fdsymbols.obj.pdb /Fosymbols.obj
symbols.cpp
P:\guff>link /nologo /incremental /WX symbols.obj imagehlp.lib /debug /pdb:symbols.exe.pdb /out:symbols.exe
When running the code, the output tells me that the function name is the empty string, whereas I would have expected something like "splendid", or "splendid(void)", etc:
P:\guff>symbols
function: ''
When stepping though the code in the Visual C++ debugger, the watch window quite happily tells me that the 'fp' variable in main() refers to "splendid(void)" as shown in the attached screenshot, so it seems the necessary symbolic information is present.
Even more curiously, if I enable global optimization by adding /GL compiler switch and replacing the /incremental linker switch with /LTCG, I get the kind of output I'd expect:
P:\guff>symbols
function: 'splendid'
I have also tried SymFromAddr() instead of SymGetSymFromAddr(), and changing the options in the SymInitialize() (see commented-out code in main()), but the same behaviour persists.
Can anybody see what I'm doing wrong?