dlopen, RTLD_GLOBAL and global variables

Alan Modra amodra@bigpond.net.au
Mon Mar 25 16:30:00 GMT 2002


On Mon, Mar 25, 2002 at 04:59:21PM -0600, Scott Moser LTC wrote:
> Hey all,
>    I'm trying to make a wrapper library that is loaded via LD_LIBRARY_PATH,
> and then dlopens the wrapped library with RTLD_GLOBAL.  the wrapper library
> gets called for all functions it's interested in, does something (like log
> the call), and then calls the 'real' function, and returns its result.  The
> goal is to be completely transparent to the application; we want to avoid
> recompilation of either the original library or the application.
>    That sounds simple enough, and actually is, unless the original library
> has global variables.

This should "just work". :)  You'll need to provide definitions (and
initialisation) for the global vars involved, in your wrapper library.
Modulo bugs in ld.so, these definitions should be used by the "real"
library when it is loaded.

I applied the following patch to your testcase

diff -ur wraptest.orig/Makefile wraptest/Makefile
--- wraptest.orig/Makefile	Mon Mar 25 16:55:30 2002
+++ wraptest/Makefile	Tue Mar 26 10:34:31 2002
@@ -1,5 +1,6 @@
 MYPWD=$(PWD)
 CC=gcc
+CFLAGS=-fPIC -O2
 ARCHIVE=wraptest.sh
 
 testprog: testprog.c libtestlib.so lib/libtestlib.so
diff -ur wraptest.orig/wraplib.c wraptest/wraplib.c
--- wraptest.orig/wraplib.c	Mon Mar 25 16:02:48 2002
+++ wraptest/wraplib.c	Tue Mar 26 10:36:35 2002
@@ -2,6 +2,7 @@
 #include <dlfcn.h>
 
 static int (*old_sayHello)();
+int myvar = 0;
 
 int _init(void) {
    void * ptr;

then..

$ LD_LIBRARY_PATH=. ./testprog xxx
inside wrapper init
inside wrapper sayHello
Hellow orld
myvar=0
inside wrapper sayHello
Hellow orld
myvar=3
goodbye

-- 
Alan Modra
IBM OzLabs - Linux Technology Centre



More information about the Binutils mailing list