简体   繁体   English

在ELF可执行文件中检测未解析的符号

[英]Detecting unresolved symbols in an ELF executable

Let's say I have two files: 假设我有两个文件:

// shared.c (will be compiled to 'shared.so')
#include <stdio.h>
int f() { printf("hello\n"); }

and

// exe.c (will be compiled to 'exe')
#include <stdio.h>
int f();
int main() { 
    int i;
    scanf("%d", &i);
    if (i == 5) f(); 
}

I compile both files as following: 我将两个文件编译如下:

gcc -shared shared.c -o libshared.so
gcc exe.c -o exe -lshared -L.

When I run exe and type 5, it will call f and then exit. 当我运行exe并键入5时,它将调用f然后退出。 However, if I delete f from shared.c and recompile it I will get a runtime symbol lookup error only if I type 5. Is there a way that I can check that exe has all its symbols that will work independent of user input in this case? 但是,如果我从shared.c删除f并重新编译它,则仅当我键入5时,我才会得到运行时符号查找错误。有没有一种方法可以检查exe是否具有其所有符号都可以独立于用户输入运行?案件? Preferrably without running it. 最好不运行它。

You can use ldd -r exe command to list the shared library dependencies. 您可以使用ldd -r exe命令列出共享库的依赖关系。 Here is my output for your example without the f function: 这是我的不带f函数的示例的输出:

$ LD_LIBRARY_PATH=. ldd -r ./exe
        linux-vdso.so.1 (0x00007ffcfa7c3000)
        libshared.so => ./libshared.so (0x00007f303a02e000)
        libc.so.6 => /lib64/libc.so.6 (0x0000003e26c00000)
        /lib64/ld-linux-x86-64.so.2 (0x0000003e26400000)
undefined symbol: f     (./exe)

(Don't mind the LD_LIBRARY_PATH=. part. It is used to tell to look for shared libraries in the current directory) (不要在意LD_LIBRARY_PATH=.部分。它用于告诉您在当前目录中查找共享库)

@tohava When you compile the executable and link it with the shared object, ld (linker) checks if all referenced symbols are available in the list of shared objects your executable is dependent on and will throw an error if any symbol was unresolved. @tohava编译可执行文件并将其与共享库链接时,ld(链接程序)检查可执行文件所依赖的共享库列表中是否所有引用的符号均可用,如果未解析任何符号,将引发错误。

So, I am not sure how you managed to get a runtime error when you removed f() from the shared library and rebuilt the executable. 因此,我不确定从共享库中删除f()并重建可执行文件时如何设法获得运行时错误。 (I did the exercise myself and got the linker error). (我自己进行了练习,但得到了链接器错误)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM