Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
820 views
in Technique[技术] by (71.8m points)

shared libraries - Given a library function how can I get its file offset?

Using backtrace and backtrace_symbols, I can get a mangled function name of interest (lets call it funcA_mangledName that belongs to libfsw.so.

My goal is to get the source file and line number where it is defined. I can do this for functions that are not defined in a library file as shown below. stacktrace holds the backtrace. filename = S_main_executable in regular cases.

sprintf(syscom[jj], "addr2line %p -e %s", stacktrace[jj], filename);
system(syscom[jj]);

However, this does not work when the function is part of a library, ie filename = libfsw.so.

Working backwards I can do this on a linux terminal:

nm libfsw.so | grep funcA_mangledName

to get: 000000000020cbea T funcA_mangledName

Then when I enter in the linux terminal:

addr2line 0x000000000020cbea -e libfsw.so

I get the correct source file and line number.

What am I missing to from the beginning to that correct file offset number?

question from:https://stackoverflow.com/questions/65713981/given-a-library-function-how-can-i-get-its-file-offset

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I figured it out! I am able to convert the "virtual address" given by backtrace into a file offset, by subtracting the virtual base address of the library file. I'm assuming as long as the library is loaded into continuous memory, this should always work.

for (jj=2; jj < trace_size; ++jj) {
   void *handle;
   struct link_map *map;

   handle = dlopen(filename, RTLD_LAZY);
   dlinfo(handle, RTLD_DI_LINKMAP, &map);

   // Override the address given by backtrace (only needed for library files)
   stacktrace[jj] = stacktrace[jj] - map->l_addr;

   sprintf(syscom[jj], "addr2line %p -e %s", stacktrace[jj], filename);
   system(syscom[jj]);
   dlclose(handle);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...