Kirubakaran
Kirubakaran

Reputation: 398

How to print source file name with dladdr() function?

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)

Upvotes: 0

Views: 546

Answers (1)

Employed Russian
Employed Russian

Reputation: 213935

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.

Upvotes: 0

Related Questions