You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用dlopen加载构造函数访问全局变量的共享库时崩溃

动态加载共享库时构造函数崩溃问题

这个简单的库:

$ cat foo.c
int glob;

int foo() {
  return 0;
}

__attribute__((constructor))
void init() {
  glob = foo();
}

$ gcc -g -O0 -shared -fPIC foo.c -o libfoo.so

正常链接时可以正常加载运行:

$ cat prog1.c
extern int foo();

int main() {
  return foo();
}

$ gcc -g -O0 prog1.c libfoo.so
$ LD_LIBRARY_PATH=. ./a.out

但通过dlopen动态加载时会崩溃:

$ cat prog2.c
#include <dlfcn.h>

int main() {
  dlopen("./libfoo.so", RTLD_LAZY | RTLD_GLOBAL);
  return 0;
}

$ gcc -g -O0 prog2.c -ldl
$ ./a.out
Segmentation fault

使用gdb调试发现,崩溃发生在init函数中,尝试写入的地址与glob的实际地址不匹配。测试环境涵盖Ubuntu 24.04(Glibc 2.39)和Debian 11.11(Glibc 2.31)。

内容的提问来源于stack exchange,提问作者yugr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 22:32:33