【问题标题】:LD_PRELOAD and weak references minimal example doesn't workLD_PRELOAD 和弱引用最小示例不起作用
【发布时间】:2013-08-14 09:12:49
【问题描述】:

这可能会很尴尬:

我在其他项目中使用库预加载,但我无法让这个最小的示例工作:

weakref.h:

void f_weak() __attribute__((weak));

weakref.c:

#include <stdio.h>
#include "weakref.h"

void f_weak(){
    printf("f_weak()\n");
    fflush(stdout);
}

test_weakref.c:

#include <stdio.h>
#include "weakref.h"

int main(void)
{
    if (f_weak) {
        printf("main: f_weak()\n");
    }
    else {
        printf("main: ---\n");
    }

    fflush(stdout);
    return 0;
}

这是我的工作:

$ gcc weakref.c -shared -fPIC -o libweakref.so
$ nm libweakref.so | grep f_weak
0000000000000708 W f_weak
$ gcc test_weakref.c -o test_weakref
$ ./test_weakref
main: ---
$ LD_PRELOAD=./libweakref.so ./test_weakref
main: ---

最后一条命令的预期输出是

main: f_weak()

我错过了什么?

【问题讨论】:

    标签: c weak-references ld-preload


    【解决方案1】:

    据我所知,外部函数只有在你调用它们时才会被解析。因此,您的测试 if (f_weak) 将始终失败。如果你按照下面的方式做,你可以看到它的工作原理:

    weakref.c:

    #include <stdio.h>
    #include "weakref.h"
    
    void f_weak(){
       printf("original\n");
       fflush(stdout);
    }
    

    weak2.c:

    #include <stdio.h>
    #include "weakref.h"
    
    void f_weak(){
       printf("overridden\n");
       fflush(stdout);
    }
    

    test_weakref.c:

    #include <stdio.h>
    #include "weakref.h"
    
    int main(void)
    {
      f_weak();
      fflush(stdout);
      return 0;
    }
    

    然后:

    tmp> gcc weakref.c -shared -fPIC -o libweakref.so
    tmp> gcc weak2.c -shared -fPIC -o libweak2.so
    tmp> gcc -o test_weakref test_weakref.c ./libweakref.so 
    tmp> ./test_weakref 
    original
    tmp> LD_PRELOAD=./libweak2.so !.
    LD_PRELOAD=./libweak2.so ./test_weakref 
    overridden
    

    【讨论】:

    • 谢谢,但是当我使用 __attribute__((weak)) 时出现了我的问题。
    【解决方案2】:

    我在旧的 Makefile 中找到了解决方案:程序还必须使用 -fPIC 标志编译。

    $ gcc weakref.c -shared -fPIC -o libweakref.so
    $ nm libweakref.so | grep f_weak
    0000000000000708 W f_weak
    $ gcc test_weakref.c -o test_weakref -fPIC
    $ ./test_weakref
    main: ---
    $ LD_PRELOAD=./libweakref.so ./test_weakref
    main: f_weak()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-24
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多