Preloading my library for a few functions while using the original by others using LD_PRELOAD

让人想犯罪 __ 提交于 2019-12-02 00:57:40
jschmier

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!