From mboxrd@z Thu Jan 1 00:00:00 1970 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: fee84,b3cc53a4cd752b49 X-Google-Attributes: gidfee84,public From: Craig Neth USG Subject: Re: Wrappers for shared library functions? Date: 1997/03/11 Message-ID: <3325B36A.41C6@zk3.dec.com>#1/1 X-Deja-AN: 224738897 References: <331D5BCE.5329@netcomuk.co.uk> To: john hall Organization: Digital UNIX Development Environment Group Newsgroups: comp.unix.osf.osf1 john hall wrote: > > I would be very grateful for any advice on how to create "wrappers" for > one or two functions in large shared libraries, such that a calling > program will invoke the wrapper function which in turn calls the original > function to do the majority of the "work". One way to do this would be to write the wrappers to use dlopen()/dlsym() to open the library that contains the symbol in question and then have the wrapper call the function. For example, suppose I wanted to provide a 'sqrt()' wrapper that printed a message to stdout every time sqrt() was called: hook.c: ----------------------------------------------- #include #include double sqrt(double x) { void *handle; double (*sqrt_sym)(); double result; handle = dlopen("/usr/shlib/libm.so", RTLD_LAZY); sqrt_sym = dlsym(handle, "sqrt"); printf ("calling sqrt\n"); result = (*sqrt_sym) (x); dlclose(handle); return (result); } Build this function in a .so file, say hook.so: cc -shared -o hook.so hook.o /* this works on V4.0 or greater. Pre-V4.0, use 'ld' */ Now link your program against hook.so: cc -o sqrt sqrt.c hook.so -lm Now, at this point, you haven't hooked anything yet. You need one more thing: setenv _RLD_LIST hook.so:DEFAULT This tells the loader to always load your library before any others. (If hook.so is not in your LD_LIBRARY_PATH you'll need to add that before running this example). What happens is that because the hook library is loaded first, the calls in sqrt.c to sqrt() will get resolved to the one in the hook library. The hooked sqrt() implementation will find the 'real' sqrt() function in libm and call it directly. You need to be careful doing things like this. Some functions in the standard libraries are implemented as a 'family' of routines that share static data. If you preempt one of the routines and change it's implementation, but don't also preempt the other symbols in the family, then you could have all sorts of nasty problems. (malloc() is one example of such a 'family' of routines) Also, there are no guarantees that you will catch *all* calls to a given entry point this way - for example, internal calls in a library may or may not call the function in such a way that you can preempt it. Craig -- -------------------------------------------------------------------------------- Craig Neth ! neth@zk3.dec.com DIGITAL Equipment Corporation ! 110 Spit Brook Road ZKO3-3/W17 ! Nashua, NH 03062 ! Opinions expressed herein are my own. ================================================================================