Getting pointer to bottom of the call stack and resolving symbol by address (like dladdr) under Windows?

StackOverflow https://stackoverflow.com/questions/3802710

  •  25-09-2019
  •  | 
  •  

Question

I want to implement an analog of backtrace utility under windows in order to add this information to exception for example.

I need to capture return addresses and then translate it into symbols names.

I'm aware of StackWalk64 and of StackWalker project but unfortunately it has several important drawbacks:

  • It is known to be very slow (the StackWalk64) and I don't want to waste much time for collecting the trace the basically can be done as fast as walking on linked list.
  • The function StackWalk64 is known to be not thread safe.

I want to support only x86 and possible x86_64 architectures

Basic idea I have is following:

  1. Run on stack using esp/ebp registers similarly to what GCC's __builtin_return_address(x)/__builtin_frame_address(x) doe till I reach the bottom of the stack (this is what glibc does).
  2. Translate addresses to symbols
  3. Demangle them.

Problems/Questions:

  1. How do I know that I reach the to of the stack? For example glibc implementation has __libc_stack_end so it is easy to find where to stop. Is there any analog of such thing under Windows? How can I get stack bottom address?
  2. What are the analogs of dladdr functionality. Now I know that unlike ELF platform that keeps most of symbol names, PE format does not. So it should read somehow the debug information. Any ideas?
Was it helpful?

Solution

  • Capturing Stack Trace: RtlCaptureStackBackTrace
  • Getting Symbols: Using DBG Help library (MSVC only). Key functions:

    // Initialization
    hProcess = GetCurrentProcess()
    SymSetOptions(SYMOPT_DEFERRED_LOADS)
    SymInitialize(hProcess, NULL, TRUE)
    // Fetching symbol
    SymFromAddr(...)
    

    Implementation can be found there

OTHER TIPS

You use StackWalk but resolve symbols later.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top