Vi.
Vi.

Reputation: 38732

Why can't I directly start a shared library in Linux?

$ chmod +x libsomelibrary.so
$ ./libsomelibrary.so
Segmentation fault

$ gcc -O2 http://vi-server.org/vi/bin/rundll.c -ldl -o rundll
$ ./rundll ./libsomelibrary.so main
(application starts normally)

Why can't I just start libsomelibrary.so if it has usable entry point?

rundll.c is trivial:

void* d = dlopen(argv[1], RTLD_LAZY);
void* m = dlsym(d, argv[2]);
return ((int(*)(int,char**,char**))m)(argc-2, argv+2, envp);

Why is it not used internally when attempting to load a binary?

Upvotes: 3

Views: 2023

Answers (3)

caf
caf

Reputation: 239241

main is not the entry point recognised by the kernel or the dynamic linker - it is called by the startup code linked into your executable when you compile it (such startup code isn't linked into shared libraries by default).

The ELF header contains the start address.

Upvotes: 4

Jörg W Mittag
Jörg W Mittag

Reputation: 369554

You can start shared libraries in Linux.

For example, if you start /lib/libc.so.6, it will print out its version number:

$ /lib/libc.so.6
GNU C Library stable release version 2.12, by Roland McGrath et al.
Copyright (C) 2010 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.5.0 20100520 (prerelease).
Compiled on a Linux 2.6.34 system on 2010-05-29.
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
libc ABIs: UNIQUE IFUNC
For bug reporting instructions, please see:
<http://www.gnu.org/software/libc/bugs.html>.

There must be something missing from your library.

Upvotes: 3

bta
bta

Reputation: 45077

Shared libraries are not designed to be directly runnable. They are designed to be linked into another codebase. It may have a usable entry point, but being executable entails more than merely having a usable entry point. The rundll utility is proof of this. Your second test shows that the shared library is indeed executable, but only after rundll does some work. If you are curious as to what all has to be done before the library code can be executed, take a look at the source code for rundll.

Upvotes: 3

Related Questions