I have written a wrapper for the open()
syscall and preload it using开发者_开发问答 the LD_PRELOAD
environment variable. I want only a few functions of the program to use the modified open()
whereas others would use the original. Separating the functions in two programs is not an option as one calls the other. How can it be done?
The use of function interposition in the following example is similar to this answer.
The example provides a write()
wrapper function that calls the original write()
. It is important to note that you cannot directly call the original write()
because it will be interpreted as a call to the wrapper. The use of function pointers in main()
demonstrates how you might go about avoiding confusion as to which write()
you are calling.
Code: test.c
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <dlfcn.h>
size_t write(int fd, const void *buf, size_t count)
{
static size_t (*write_func)(int, const void *, size_t) = NULL;
/* get reference to original (libc provided) write */
if (!write_func)
{
write_func = (size_t(*)(int, const void *, size_t)) dlsym(RTLD_NEXT, "write");
}
/* perform wrapper specific actions */
/* ... */
/* call original write() */
return write_func(fd, buf, count);
}
int main(int argc, char *argv[])
{
size_t (*wrap_write)(int, const void *, size_t);
size_t (*orig_write)(int, const void *, size_t);
char buf1[] = "write() wrapper called\n";
char buf2[] = "orignial write() called\n";
/* set pointer to write() wrapper to differentiate */
wrap_write = write;
/* get reference to original (libc provided) write() */
orig_write = (size_t(*)(int, const void *, size_t)) dlsym(RTLD_NEXT, "write");
/* call write() wrapper */
wrap_write(1, buf1, strlen(buf1));
/* call original write() */
orig_write(1, buf2, strlen(buf2));
return 0;
}
Output:
$ gcc -Wall -Werror -ldl test.c -o test
$ ./test
write() wrapper called
orignial write() called
$
First there must be a established way to distiguish the to-be-preloaded open from the default open. This can be done using a helper library (must be loaded dynamically), that offers another wrapped version of that special open. Replacing that one happens by preloading a variant of this library.
精彩评论