3

In glibc (and also EGLIBC I believe), the libc.so library has a main() method:

$ /lib/i386-linux-gnu/libc.so.6
GNU C Library (Debian GLIBC 2.19-18+deb8u1) stable release version 2.19, by Roland McGrath et al.
Copyright (C) 2014 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.8.4.
Compiled on a Linux 3.16.7 system on 2015-08-30.
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.debian.org/Bugs/>.

Now I want to do the same with the following minimalistic example (i. e. I want my own SO to also have a main()):

#include <stdio.h>

int main(int argc, char *argv[]) {
        printf("Hello, World!\n");
        return 0;
}

Linking as a regular executable:

$ gcc -g -O0 -Wall -c test.c
$ gcc -o test test.o
$ ./test
Hello, World!

Now linking as a shared object:

$ gcc -g -O0 -Wall -c test.c
$ gcc -shared -o libtest.so test.o
$ ./libtest.so
Segmentation fault
  • nm shows that main symbol is present (000004f5 T main)
  • When debugging, gdb doesn't show any meaningful backtrace.
  • Adding -fpic or -fPIC to the gcc command line doesn't help.

What am I doing wrong?

Bass
  • 4,977
  • 2
  • 36
  • 82
  • @Someprogrammerdude There's no particular problem I want to solve. I fully understand having a `main()` in a SO is almost useless. I'm just trying to find out how it is done in glibc. – Bass Jun 06 '17 at 10:03

1 Answers1

7

the libc.so library has a main() method

No, the implementation of C library of gcc has an entry point not a main symbol.

You can find an example of how to do this here.

Stargateur
  • 24,473
  • 8
  • 65
  • 91