This example make full use of the output of gcc -v
, we link all files from scratch.
the source code:
///////////////////////////////////////////////////////////////////
//test.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dlfcn.h>
#include <string.h>
#include <mcheck.h>
const char dynamic_linker[] attribute ((section (".interp"))) = "/lib/ld-linux.so.2";
int wrap_printf(char s)
{
char t = s;
while(s) {
// if(isalpha(s))
// s = toupper(s);
s++;
}
return (int)write(0, t, strlen(t));
}
attribute((constructor))
static void foo()
{
mtrace();
printf("foon");
}
attribute__((destructor))
static void bar()
{
muntrace();
printf("barn");
}
int my_start()
{
void ntdll = NULL;
void (func)() = NULL;
_init();
printf("ahaha, OK!n");
free(malloc(0x12345));
ntdll = dlopen("/usr/local/lib/wine/ntdll.dll.so", RTLD_NOW);
if(!ntdll)
printf("fail to open dlln");
func = dlsym(ntdll, "dump_builtin_dlls");
printf("%pn", func);
_fini();
exit(0);
return 0;
}
int main()
{
my_start();
}
[jfo@Fedora4 src]$ gcc -c -fPIC -o test.o test.c
[jfo@Fedora4 src]$ ld -shared -o libtest.so -emy_start crti.o crtbeginS.o test.o -L /usr/lib/gcc/i386-redhat-linux/4.0.0 -ldl -lc crtendS.o crtn.o
[jfo@Fedora4 src]$ ld -o test -emy_start -dynamic-linker=/lib/ld-linux.so.2 crt1.o crti.o crtbegin.o test.o -L /usr/lib/gcc/i386-redhat-linux/4.0.0/ -ldl -lc crtend.o crtn.o
[jfo@Fedora4 src]$ ./test
foo
ahaha, OK!
0xb7e1ff10
bar
[jfo@Fedora4 src]$ ./libtest.so
foo
ahaha, OK!
0xb7d01f10
bar