This is the mail archive of the
binutils@sourceware.org
mailing list for the binutils project.
ld -shared -pie revisited
- From: Mark Lodato <lodatom at gmail dot com>
- To: binutils at sourceware dot org
- Date: Sat, 3 Oct 2009 19:10:42 -0400
- Subject: ld -shared -pie revisited
I saw a 2007 discussion* of whether to allow both -shared and -pie
from gcc, where it was decided to use only the last one specified.
But `ld -shared -pie` seems to work fine on x86_64, and in fact allows
one to have an executable shared library - you can both dlopen the
library and run it. This is awesome! Am I missing something here?
Will this break in subtle ways? If so, how do you properly make a
shared library that can be executed (like /lib/ld.so)? If not, should
gcc x86_64 allow both -shared and -pie to make such libraries, so that
one does not have to invoke the linker manually?
Here's an example:
-----
# My system
$ uname -a
Linux mark-desktop 2.6.28-11-generic #42-Ubuntu SMP Fri Apr 17
01:58:03 UTC 2009 x86_64 GNU/Linux
$ gcc --version
gcc (Ubuntu 4.3.3-5ubuntu4) 4.3.3
# Create a sample library.
$ cat <<EOF >library.c
#include <stdio.h>
#include <stdlib.h>
void foo(int x) {
printf("foo(%d)\n", x);
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "USAGE: %s n\n", argv[0]);
exit(1);
}
foo(atoi(argv[1]));
return 0;
}
EOF
# Compile.
$ gcc -fPIC -fPIE -c library.c
# Link with -pie and -shared.
# The following command was obtained by running
# gcc '-###' -pic -fPIC -fPIE -rdynamic -o library.so library.o
# and adding '-shared' before '-pie'.
$ /usr/lib/gcc/x86_64-linux-gnu/4.3.3/collect2 \
--eh-frame-hdr \
-m elf_x86_64 \
-shared \
-pie \
--export-dynamic \
-o library.so \
-z relro \
/usr/lib/Scrt1.o \
/usr/lib/crti.o \
/usr/lib/gcc/x86_64-linux-gnu/4.3.3/crtbeginS.o \
-L/usr/lib/gcc/x86_64-linux-gnu/4.3.3 \
-L/usr/lib \
-L/lib \
library.o \
main.o \
-lgcc \
--as-needed \
-lgcc_s \
--no-as-needed \
-lc \
-lgcc \
--as-needed \
-lgcc_s \
--no-as-needed \
/usr/lib/gcc/x86_64-linux-gnu/4.3.3/crtendS.o \
/usr/lib/crtn.o
$ ./library.so 12
foo(12)
$ python -c \
'import ctypes; x = ctypes.cdll.LoadLibrary("./library.so"); x.foo(13)'
foo(13)
-----
* http://sourceware.org/ml/binutils/2007-07/msg00059.html
--
Mark