Executable shared libraries

后端 未结 3 1268
后悔当初
后悔当初 2021-01-03 02:58

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

$ ./libfoobarbaz.so
Segmentation fault         


        
相关标签:
3条回答
  • 2021-01-03 03:20

    The answer lies in the name "Executable and Linking Format". The same file format is used for both executables and libraries.

    0 讨论(0)
  • 2021-01-03 03:37

    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.

    0 讨论(0)
  • 2021-01-03 03:46

    There is a howto about this subject here. The principle is to define an entry point in the library and populate the interp section of the ELF file with the interpreter's pathname (e.g. /lib/ld-linux.so.2).

    0 讨论(0)
提交回复
热议问题