Chapter 6 247
Shared Library Management Routines
The dlopen Shared Library Management Routines
necessary information, and use dlsym with RTLD_NEXT to find the “real”
malloc, which would perform the actual memory allocation. Of course,
this “real” malloc could be another user-defined interface that added its
own value and then used RTLD_NEXT to find the system malloc.
Examples
The following example shows how to use dlopen and dlsym to access
either function or data objects. (For simplicity, error checking has been
omitted.)
void *handle;
int i, *iptr;
int (*fptr)(int);
/* open the needed object */
handle = dlopen("/usr/mydir/mylib.so", RTLD_LAZY);
/* find address of function and data objects */
fptr = (int (*)(int))dlsym(handle, "some_function");
iptr = (int *)dlsym(handle, "int_object");
/* invoke function, passing value of integer as a parameter */
i = (*fptr)(*iptr);
The next example shows how to use dlsym with RTLD_NEXT to add
functionality to an existing interface. (Error checking has been omitted.)
extern void record_malloc(void *, size_t);
void *
malloc(size_t sz)
{
void *ptr;
void *(*real_malloc)(size_t);
real_malloc = (void * (*) (size_t))
dlsym(RTLD_NEXT, "malloc");
ptr = (*real_malloc)(sz);
record_malloc(ptr, sz);
return ptr;
}