C++ function address -- using dladdr and backtrace()

1.2k views Asked by At

I want to use backtrace() and get function address for tracing purpose. I want to store function address from backtrace() during run time, and use it for analysis later on (e.g. load back function name, look at call stats etc using dladdr()). While doing that, I was trying to look at static address of a class member function.

Alib.so, A.h:

class A
{
public:
    void print_addr();
};

A.cpp

#include "A.h"
#include <iostream>

void A::print_addr()
{
   std::cout << (void*)&A::print_addr << std::endl;
}

main.cpp

#include <iostream>
#include "Alib/A.h"

int main()
{
   std::cout << (void*) &A::print_addr << std::endl;
   // if put the line below, with the line above, output is the same
   // It seems whenever the code pull in &A::print_addr into main, addr is 
   // always the same.  Only different if print .so itself
   // A a; a.print_address();
   return;
}

this outputs:

0x400870

If I rerun main multiple times, it gives me the same address. If I change main.cpp to this:

int main()
{
   A a;
   a.print_addr();
   return 0;
}

Outputs is different every time I run main executable, even without recompiling .so or main:

0x7fae48524aa0

The reason I'm checking this is that I'd like to use backtrace() to get function info (address) on the current stack function for tracing and it acts very similar. I tried call backtrace() within a .so library function, and get symbol info on the function using backtrace() and dladdr() on the current stack function. Printing a function address in .so versus doing it in main gives a different address. How can I use the function address for dladdr() to get info, such as symbol name?

Is there something to a class member function address mapped differently in .so and in main()?

EDITS: Re-word and give more code example to explain the problem.

0

There are 0 answers