0

I was trying to print a backtrace using dladdr(). info.dli_fname in the following code snippet is displaying the file name of an ELF file. Could you please tell me if it is possible to resolve and print the name of the source file and line number programmatically without the help of addr2line or gdb?

Code:

void print_caller(void)
{
    int       rc = -1;
    Dl_info info = {0};
    void *pc =  __builtin_return_address(0);

    rc = dladdr(pc, &info);

    printf(" ==> %p: %s (in %s)\n", pc, info.dli_sname, info.dli_fname);
}

Output:

$ ./a.out 
 ==> 0x55a6b04a1589: foo2 (in ./a.out)
Kirubakaran
  • 378
  • 4
  • 20
  • Not really answering your question, but could you not make use of `__FILE__` to get the information you want? e.g. `void print_caller(const char *file) { .... }` then `print_caller(__FILE__);`. You could always wrap things with `#define` so `void print_calller_impl(const char *file) { ... }` then `#define print_caller() print_caller_impl(__FILE__)` then `print_caller();` – Andrew Aug 29 '22 at 07:26
  • If you really want to find the source file name then you will need to compile with debug information, grab the name of the elf using dladdr as you currently do, open the elf and parse the debug information (there's probably a library that can help with this), then map the address back to a source file. – Andrew Aug 29 '22 at 07:29
  • Yes I was compiled with debug enabled. In the man page of `dladdr` in ` Dl_info` we have only the object file name. Not sure how to parse the elf debug info programmatically. I will be a great if you share the resource. – Kirubakaran Aug 29 '22 at 08:44
  • Code from these stack backtracing libraries may help. https://stackoverflow.com/a/48925033/2554472 https://stackoverflow.com/a/65773334/2554472 – Mark Plotnick Aug 30 '22 at 09:24

1 Answers1

0

tell me if it is possible to resolve and print the name of the source file and line number programmatically

It is definitely possible -- addr2line and gdb do that.

But it is very non-trivial -- it requires understanding and decoding (possibly multiple) complicated debugging info formats.

If you only care about a single platform (looks like Linux), things are a bit easier -- you only need to decode DWARF.

But that format is still pretty complicated. You should start with a helper library, such as libdwarf.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362