How to see the object file contents of a .so file

2019-07-12 17:29发布

问题:

how to see what .o files constitute .so file?

Means how to notice what are the object files are used to build the .so file from the .so file (If I have only the .so file)

回答1:

You can't know, given just a shared library, what object files were compiled into it. If you're lucky, you may be able to make a reasonable guess.

A shared library is made, by the linker, from object files and possibly other shared libraries, but it does not contain the object files or shared libraries from which it was made. A static library, on the other hand, which is made by the archiver ar, does contain object files: it is just an ar archive of object files.

If a shared library has not been stripped of debugging information, then for debugging purposes its symbol table will contain the names of the source files from which the object files were compiled that were linked in the shared library - at least those source files which were compiled with debugging information. From the names of those source files you can infer the names of the object files with reasonable confidence, but not with certainty.

For example, here we make a shared library from source files foo.c and bar.c.

Compile the source files to object files:

$ gcc -Wall -fPIC -c -o foo.o foo.c
$ gcc -Wall -fPIC -c -o bar.o bar.c

Link the object files to make a shared library:

$ gcc -shared -o libfoobar.so foo.o bar.o

Then:

$ readelf -s libfoobar.so | grep FILE
26: 0000000000000000     0 FILE    LOCAL  DEFAULT  ABS crtstuff.c
35: 0000000000000000     0 FILE    LOCAL  DEFAULT  ABS foo.c
37: 0000000000000000     0 FILE    LOCAL  DEFAULT  ABS bar.c
39: 0000000000000000     0 FILE    LOCAL  DEFAULT  ABS crtstuff.c
42: 0000000000000000     0 FILE    LOCAL  DEFAULT  ABS 

indicates that three source files have contributed debugging info to the library, and we'd infer that the object files to which they were compiled were likely to be:

crtstuff.o
foo.o
bar.o

Note that crtstuff.c is not one of the source files that we compiled. It happens to contain program initialization and finalization code from the C runtime library, which has got into our library from a C runtime object file that is linked by default.

This inference could be wrong about any of the files, since:

$ gcc -Wall -fPIC -c -o abc.o foo.c
$ gcc -Wall -fPIC -c -o xyz.o bar.c
$ gcc -shared -o libfoobar.so abc.o xyz.o

is also a perfectly possible way of compiling and linking the library.

If debugging information has been stripped from the library:

$ strip -g libfoobar.so

then we are out of luck:

$ readelf -s libfoobar.so | grep FILE
$

No more FILE symbols.