How can my C code find the character matching the address at runtime (on Linux)?

Given the address of a function or a run-time variable, my code should find out the name and, if it is a variable, enter the symbol information. Or at least provide enough information for subsequent autonomous extraction of the name (and type of information).

This is Linux code, and it is assumed that debugging information is available.

I tried to peek into the ELF file format, binutils, and everything except the theme is huge, so I was hoping someone could help me narrow the scope.

I see the following types of solutions:

  • Find the range of code / data segments of modules loaded into memory - HOW TO DO? Save the address module and its name and offset in it. Off-line then use binutils to search for a symbol in the module debugging information - again, HOW TO DO?

  • use some API / system services that I don’t know about to find the symbol and information at runtime - HOW?

Thanks in advance.

+4
source share
3 answers

GNU libc provides a dladdrfunction for this purpose. However, it only works with functions, not variables.

   #define _GNU_SOURCE         /* See feature_test_macros(7) */
   #include <dlfcn.h>

   int dladdr(void *addr, Dl_info *info);

   The  function  dladdr()  takes  a function pointer and tries to resolve
   name and file where it  is  located.   Information  is  stored  in  the
   Dl_info structure:

       typedef struct {
           const char *dli_fname;  /* Pathname of shared object that
                                      contains address */
           void       *dli_fbase;  /* Address at which shared object
                                      is loaded */
           const char *dli_sname;  /* Name of symbol whose definition
                                      overlaps addr */
           void       *dli_saddr;  /* Exact address of symbol named
                                      in dli_sname */
       } Dl_info;

   If no symbol matching addr could be found, then dli_sname and dli_saddr
   are set to NULL.

   dladdr() returns 0 on error, and nonzero on success.

Of course, I usually do such things from gdb, and not inside the program itself.

+5
source

, Binary File Descriptor library, . libbfd . , , . ELF, , , .

, libbfd , , libelf - . , gelf_getsym.

+2

C is a fully compiled language. Names, types, and other variable information are usually discarded during compilation.

The exception is that most compilers will create an executable file with debugging information enabled, so that the live debugger has access to this information. This information is completely OS dependent and even specific to the compiler and may even not be available in some parts of the memory.

+1
source

All Articles