Thursday, June 12, 2008

Accessing libc,runtime linker,shared libraries functions using pragma weak

Sometimes you are working on libc, glibc linker ,shared libraries.
You have seen in the code of these libraries as follows:
#pragma weak dlopen = _dlopen
#pragma weak dlcose= _dlclose

What is this? what is the use of these lines of code written in libc,glibc etc.
The above lines code indicates that any user applications can call/use "dlopen" and "dlclose"
functions.

How is this possible?
There is little trick/work done by compiler, which creates the
symbol as a weak.

#pragma weak symbol1 = symbol2
This pragma declares symbol1 to be a weak alias of symbol2. It is an error if symbol2 is not defined in the
current translation unit.
for more information please refers following link.
http://gcc.gnu.org/onlinedocs/gcc/Pragmas.html#Pragmas

Now we have some idea on weak symbol,so move forwards to do some R&D.
I have done this R&D on Open-Soalris. Its also applicable to Linux.

$cat mylibc.c

#pragma weak my_function = _my_function
void _my_function()
{

printf("inside _my_fnction()\n");

}

$ cat main.c

int
main()
{
my_function();
return 0;

}

Now build the shared library:
$ gcc -o mylibc.so -fpic -shared mylibc.c
$ elfdump -s mylibc.so |fgrep my_function
[1] 0x0000049c 0x0000002f FUNC WEAK D 0 .text my_function
[10] 0x0000049c 0x0000002f FUNC GLOB D 0 .text _my_function
[49] 0x0000049c 0x0000002f FUNC WEAK D 0 .text my_function
[58] 0x0000049c 0x0000002f FUNC GLOB D 0 .text _my_function

You can see here my_function as a weak symbol.

Now build the executable using mylibc.so as a dependency:
$ gcc -o main main.c ./mylibc.so
$ elfdump -s main |fgrep my_function
[27] 0x08050680 0x00000000 FUNC GLOB D 0 UNDEF my_function
[81] 0x08050680 0x00000000 FUNC GLOB D 0 UNDEF my_function

Now run the executable:
$ ./main
inside _my_function

Cool! we got the result, Now try yourself.
Happy Hacking.

No comments: