I want to create a shared library which can be loaded in two different ways into targets:
- LD_PRELOAD
- Dynamic loading via
dlsym
My shared library looks like this:
#include "stdio.h"
void __attribute__ ((constructor)) my_load(void);
void my_load(void) {
printf("asdf");
}
void someFunc(void) {
printf("someFunc called");
}
I am compiling it like so:
all:
gcc -fPIC -g -c -Wall MyLib.c
gcc -shared -W1,-soname,MyLib.so.1 -o MyLib.so.1.0.1 -lc
I do not wish to install it with ldconfig
, etc. The target process looks like this:
#include <stdio.h>
#include <dlfcn.h>
void func1() {
printf("%d\n", 1);
}
void func2() {
printf("%d\n", 2);
}
void func3() {
printf("%d\n", 3);
}
int main() {
void* lib_handle = dlopen("/home/mike/Desktop/TargetProcess/MyLib.so.1.0.1",
RTLD_NOW|RTLD_GLOBAL);
if(lib_handle == NULL) {
printf("Failed loading lib\n");
} else {
printf("Loaded lib successfully\n");
void (*some_func)() = dlsym(lib_handle, "someFunc");
printf("%p\n", some_func);
dlclose(lib_handle);
}
func1();
func2();
func3();
return 0;
}
The target is compiled as so:
all:
gcc TestProg.c -ldl -o TestProg
My questions are:
- With the dynamic loading with
dlopen
as above, why doesmy_load
not appear to be called? - With the same method, why does
dlsym
always returnnil
even thoughdlopen
returns non-null? Similarly,nm
doesn't list eithermy_load
orsomeFunc
as symbols of the .so. - Is it possible to use
LD_PRELOAD
to load the library? I tried copying the .so into the same directory as the target then invokingLD_PRELOAD="./MyLib.so.1.0.1" ./TestProg
but againmy_load
seems not to be being called.