2

Given an c++ object pointer and compatible method pointer to a virtual method, is there any remotely robust/portable way to get a pointer to the actual concert function that would be called?

The use case is that I want to run said pointer thought the debug symbols to get the name of the type/function that would be called (without actually calling it).

If this is only possible via implementation specific solutions, then I'm primarily interested in supporting GCC/LLVM.

BCS
  • 75,627
  • 68
  • 187
  • 294
  • Have a look at http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes . It might help. – cup Jan 10 '14 at 07:20
  • @cup looks like that covers the "given pointer, get usable string" bit that I already know more or less how to handle. – BCS Jan 10 '14 at 14:56

1 Answers1

0

Both LLVM and GCC follow the Itanium C++ ABI, so you need to find a way to read the data structures as specified therein. I'll give a rough outline.
A pointer to virtual member is represented by an offset into the virtual function table, +1 for some reason.

class A {
public:
    virtual void f();
    virtual void g();
};

void (A::*pAg)() = & A::g;
ptrdiff_t offset = *(ptrdiff_t*)(&pAg) - 1;

The pointer to the virtual table is typically located right at the beginning of an object:

A a;
void* vtable = *(void**)&a;

Then you look at the calculated offset within that virtual table and find your actual function pointer.

void* function = *(void**)(vtable+offset)
pentadecagon
  • 4,717
  • 2
  • 18
  • 26
  • I'll give that a try as soon as I give up m forlorn hope of a portable solution showing up. – BCS Jan 10 '14 at 14:58