Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executable shared libraries

Most of the time, when you compile a shared library, executing it is meaningless and doing so produces nothing useful:

$ ./libfoobarbaz.so
Segmentation fault

However, the folks at GNU have been able to stick in some output when glibc is executed:

$ /lib/libc.so.6
GNU C Library (Debian EGLIBC 2.11.2-10) stable release version 2.11.2, by Roland McGrath et al.
Copyright (C) 2009 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.
Compiled by GNU CC version 4.4.5.
Compiled on a Linux 2.6.32 system on 2011-01-23.
Available extensions:
    crypt add-on version 2.1 by Michael Glad and others
    GNU Libidn by Simon Josefsson
    Native POSIX Threads Library by Ulrich Drepper et al
    BIND-8.2.3-T5B
For bug reporting instructions, please see:
<http://www.debian.org/Bugs/>.

Although this particular use seems like plain old bloat to me, how did they achieve making a shared library that also acts as a working executable?

like image 738
Delan Azabani Avatar asked Nov 04 '22 17:11

Delan Azabani


1 Answers

The trick here is, that executables and shared object libraries use the same format called ELF and that libc.so, in collaboration with code found in crt0.o (on *nixes), part of the compiler, actually is responsible for setting up the runtime environment and then call the proper int main(...) function. Without linking against libc.so and crt0.o a program with just int main(...) will not execute. Technically it is possible to set the main function to be the executable entry point, but being started like that the program will not recieve command line arguments, no environment, etc. that's all in the responsibility of the standard runtime library libc.so

So libc.so, being also responsible for preparing the call of the int main(...) function can easily determine if it got linked by some other program, or if it is "stand alone". If the process got started through the libc.so entry point in it will display this message, then exit. Only if the process is started through an executables binary entry point, which the binary recieves through that magic crt0.o the process will run as usual.

like image 118
datenwolf Avatar answered Nov 13 '22 19:11

datenwolf