Dynamic Linking
Posted: Sat Feb 10, 2007 12:08 pm
I want to implement SO libraries in my os. But I don't know how to do this!
I implemented elf execution.
I implemented elf execution.
how can a program use a function in an elf shared.Otter wrote:You have to support a binary format which contains relocation data, for example elf shared. Then, you need a dynamic linker, which performs the relocations when you load an elf executable.
Relocation means that you correct the offsets encoded in the binary data of your executable image. Relocation data contains position of these offsets and some hints how to relocate.
how can the dynamic linker know that 'hello' is a function of the library lib.so?Otter wrote:Lets say your program will be loaded to adress 0x00100000. The loader sees in the headers and symbol tables ( dynamic section ) that the executable uses a dynamic function, "hello". Then, the loader ( or the dynamic linker ) checks whether the shared lib "lib.so" is already loaded. If not, it loads it to a shared space which is visible to all user space processes.
Then, back to the executable, it looks for relocation data of "hello". These should be in the executable file. Using these data the dynamic linker finds all offsets and correct them this way that they point to the "hello" of "lib.so".
You should read something about relocation, there are lots of different types. For IA-32 the most important ones are absolute 32 bit relocation and relative 32 bit relocation. There are much informations available. If you have a good explanation of the elf binary format, you should find all you need in them.
You might want to read this.. http://en.wikipedia.org/wiki/Library_%2 ... science%29MarkOS wrote:how can the dynamic linker know that 'hello' is a function of the library lib.so?
Code: Select all
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
typedef void (*simple_demo_function)(void);
int main(void) {
const char *error;
void *module;
simple_demo_function demo_function;
/* Load dynamically loaded library */
module = dlopen("libhello.so", RTLD_LAZY);
if (!module) {
fprintf(stderr, "Couldn't open libhello.so: %s\n",
dlerror());
exit(1);
}
/* Get symbol */
dlerror();
demo_function = dlsym(module, "hello");
if ((error = dlerror())) {
fprintf(stderr, "Couldn't find hello: %s\n", error);
exit(1);
}
/* Now call the function in the DL library */
(*demo_function)();
/* All done, close things cleanly */
dlclose(module);
return 0;
}