April 11, 2001, 1:50 PM —
Summary: Library interposition is a useful technique for tuning performance, collecting runtime statistics, or debugging applications. This article offers helpful tips and tools for working with the technique and gets you started on your own interposer.
Most of today's applications use shared libraries and dynamic linking, especially for such system libraries as the standard C library (libc), or the X Window or OpenGL libraries. Operating system vendors encourage this method because it provides many advantages.
With dynamic linking, you can intercept any function call that an application makes to any shared library. Once you intercept it, you can do whatever you want in that function, as well as call the real function that the application originally intended to call.
Performance tuning is one use of this technology. Even if you have access to profilers and other development tools, or the application's source code itself, having your own library interposer puts you completely in control. You can see exactly what you're doing and make adjustments at any time.
Building and running your first interposer
To use library interposition, you need to create a special shared library and set the
LD_PRELOAD environment variable. When
LD_PRELOAD is set, the dynamic linker will use the specified library before any other when it searches for shared libraries.
Let's create a simple interposer for
malloc(), which is normally a part of
/usr/lib/libc.so.1, the standard C library. A message, displaying the argument passed to each
malloc() call, will be printed out each time the application calls
Here's the source for this interposer:
In the above example,
func is a function pointer to the real
malloc() routine, which is in
RTLD_NEXT argument passed to
dlsym(3X) tells the dynamic linker to find the next reference to the specified function, using the normal dynamic linker search sequence.