gpt4 book ai didi

c++ - 有没有办法 "statically"将共享的 .so(或 .o)库插入可执行文件?

转载 作者:IT老高 更新时间:2023-10-28 22:38:54 27 4
gpt4 key购买 nike

首先,考虑以下情况。

下面是一个程序:

// test.cpp
extern "C" void printf(const char*, ...);

int main() {
printf("Hello");
}

下面是一个库:

// ext.cpp (the external library)
#include <iostream>

extern "C" void printf(const char* p, ...);

void printf(const char* p, ...) {
std::cout << p << " World!\n";
}

现在我可以用两种不同的方式编译上面的程序和库了。

第一种方式是编译程序不链接外部库:

$ g++ test.cpp -o test
$ ldd test
linux-gate.so.1 => (0xb76e8000)
libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xb7518000)
/lib/ld-linux.so.2 (0xb76e9000)

如果我运行上面的程序,它会打印:

$ ./test 
Hello

第二种方式是编译带有外部库链接的程序:

$ g++ -shared -fPIC ext.cpp -o libext.so
$ g++ test.cpp -L./ -lext -o test
$ export LD_LIBRARY_PATH=./
$ ldd test
linux-gate.so.1 => (0xb773e000)
libext.so => ./libext.so (0xb7738000)
libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xb756b000)
libstdc++.so.6 => /usr/lib/i386-linux-gnu/libstdc++.so.6 (0xb7481000)
/lib/ld-linux.so.2 (0xb773f000)
libm.so.6 => /lib/i386-linux-gnu/libm.so.6 (0xb743e000)
libgcc_s.so.1 => /lib/i386-linux-gnu/libgcc_s.so.1 (0xb7421000)
$ ./test
Hello World!

如您所见,在第一种情况下,程序使用 libc.so 中的 printf,而在第二种情况下,它使用 printf来自 libext.so.

我的问题是:从第一种情况下获得的 executable 和 libext 的目标代码(.so 或 .o),是否有可能获得像第二种情况一样的可执行文件案子?换句话说,对于后者中定义的所有符号,是否可以将 libc.so 的链接替换为 libext.so 的链接?

**请注意,通过 LD_PRELOAD 插入不是我想要的。我想获得一个直接链接到我需要的库的可执行文件。我再次强调这一事实,我只能访问第一个二进制文件和我想“静态”插入的外部对象**

最佳答案

这是可能的。了解 shared library interposition :

When a program that uses dynamic libraries is compiled, a list of undefined symbols is included in the binary, along with a list of libraries the program is linked with. There is no correspondence between the symbols and the libraries; the two lists just tell the loader which libraries to load and which symbols need to be resolved. At runtime, each symbol is resolved using the first library that provides it. This means that if we can get a library containing our wrapper functions to load before other libraries, the undefined symbols in the program will be resolved to our wrappers instead of the real functions.

关于c++ - 有没有办法 "statically"将共享的 .so(或 .o)库插入可执行文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18309633/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com