October 12, 2011

linux dynamic library executable and initialization


-----------
C file
-------------




/* initialization when .so is loaded */
static int (*libc_flock)(int fd, int operation)=NULL;
int flock(int fd, int operation){
    printf("my flock called.  fd=%d operation=%d\n",fd,operation);


    if (!handle){
        handle=dlopen("/lib/libc.so.6",RTLD_LAZY);
    }
    if (!libc_flock){
        libc_flock=dlsym(handle,"flock");
        if (libc_flock==NULL)
            return NULL;
    }
    return libc_flock(fd,operation);
}


__attribute__((constructor)) static void mylib_init(void){
    printf("============>\nmylib is initialized\n================>\n");
}




/* this part of code make your .so executable */
const char my_interp[] __attribute__((section(".interp"))) = "/lib/ld-linux.so.2";


void my_main(int argc, char **argv) {
    int i;


    printf("Called as:");
    for (i = 0; i < argc; i++)
        printf(" %s", argv[i]);
    printf("\n");


    exit(0);
}



--------------
Makefile:
----------------
libmylib.so: mylib.c
        $(CC) -shared -Wl,-soname,$@ -fPIC -O2 -s -o $@ $^ -ldl  -Wl,-e,my_main


No comments:

Post a Comment