Determining to which function a pointer is pointing in C?

后端 未结 9 1013
情话喂你
情话喂你 2021-02-01 12:25

I have a pointer to function, assume any signature. And I have 5 different functions with same signature.

At run time one of them gets assigned to the pointer, and that

9条回答
  •  庸人自扰
    2021-02-01 13:17

    The debugger could tell you that (i.e. the name of a function, given its address).

    The symbol table of an unstripped ELF executable could also help. See nm(1), objdump(1), readelf(1)

    Another Linux GNU/libc specific approach could be to use at runtime the dladdr(3) function. Assuming your program is nicely and dynamically linked (e.g. with -rdynamic), it can find the symbol name and the shared object path given some address (of a globally named function).

    Of course, if you have only five functions of a given signature, you could compare your address (to the five addresses of them).

    Notice that some functions don't have any ((globally visible) names, e.g. static functions.

    And some functions could be dlopen-ed and dlsym-ed (e.g. inside plugins). Or their code be synthetized at runtime by some JIT-ing framework (libjit, gccjit, LLVM, asmjit). And the optimizing compiler can (and does!) inline functions, clone them, tail-call them, etc.... so your question might not make any sense in general...

    See also backtrace(3) & Ian Taylor's libbacktrace inside GCC.

    But in general, your quest is impossible. If you really need such reflective information in a reliable way, manage it yourself (look into Pitrat's CAIA system as an example, or somehow my MELT system), perhaps by generating some code during the build.

提交回复
热议问题