簡體   English   中英

通過LD_PRELOAD由其他人使用原始功能時預加載我的庫以獲取一些功能

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

我已經為open()系統調用編寫了一個包裝器,並使用LD_PRELOAD環境變量對其進行了預加載。 我只希望程序的某些功能使用修改后的open()而其他功能則使用原始功能。 不能將功能分開在兩個程序中,因為一個程序調用另一個程序。 如何做呢?

在下面的示例中,函數插入的用法與此答案類似。

該示例提供了一個write()包裝函數,該函數調用原始的write() 重要的是要注意,您不能直接調用原始的write()因為它將被解釋為對包裝器的調用。 main()使用函數指針演示了如何避免對正在調用的write()混淆。

代碼: 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;
}

輸出:

$ gcc -Wall -Werror -ldl test.c -o test
$ ./測試
調用write()包裝器
原始的write()稱為
$

首先,必須有一種確定的方法來將要預加載的打開與默認打開區分開。 這可以使用幫助程序庫(必須動態加載)來完成,該程序庫提供了該特殊打開的另一個包裝版本。 通過預加載該庫的一個變體來替換這種情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM