|
Calling A Function At ELF Shared Library Load Time
Submitted by |
This text was only tested under Linux 2.4.x, on x86 processor.
It could be usefull to define a function in a library to be call at load
time, like Windows do with 'DllMain()'.
On an ELF shared library, it is a bit more tricky, and I spent some
hours on the problem. Here is the solution :
Let's say you have a library, and you want to call 'Elf_Init()' function
BEFORE the main() (or _start) defined on the caller program.
Just define your function, like another one, but put a small piece of
assembly in it :
int Elf_Init(void)
{
__asm__ (".section .init \n call Elf_Init \n .section .text\n");
if(!Init_some_stuff())
{
exit(-1);
}
So_do_more_and_more();
return 1;
} |
So how does this work ?
According to ELF format (http://www.lnxscene.org/jylam/elf2.ps), there
is a special section called '.init'. This section can contain code which
will be launched immediadly after the shared library will be loaded by
ld.so .
If you try to do this in assembly and think it'll be easy, be prepared
to have some problems. In fact, the problem is that ld (the linker) will
add some more code in this section, then put your own, and will fuck up
the stack, then will lose the start entry address.
That's why it's easier to put that in a C file, sometimes it's good to
let the C compiler do the bad stuff :)
Happy hacking.
--
Jean-Yves Lamoureux
|
The zip file viewer built into the Developer Toolbox made use
of the zlib library, as well as the zlibdll source additions.
|