linux 动态库运行时加载

本文探讨了在程序运行过程中动态加载库文件时可能遇到的问题,包括如何安全地卸载动态库、解决动态库依赖问题的方法,并提供了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

动态加载

  • dlopen
  • dlsym
  • dlclose

覆盖旧库

一个程序mybin 运行时加载了 a.so, 如果 直接cp 新a.so 覆盖a.so 会导致mybin crash
因为:
TODO
正确做法:
install 新a.so a.so

注意事项

是否dlclose 安全

dlclose 会将整个库unload掉(dlopen没有指定NODLETE参数), 其中包括全局变量,静态变量等。 如果库里使用了 TSD , 一定要在库unload之前把 TSD也回收掉。
如zookeeper c sdk 里的log 使用了 tsd,在constructor 里创建, 但没有销毁, 如果使用dlopen/dlclose 使用zookeeper_mt.so , 在退出时就会导致 crash, 堆栈如下:

#0  0x00007f9d9fc38ec0 in ?? ()
#1  0x0000003d72405b19 in __nptl_deallocate_tsd () from /lib64/libpthread.so.0
#2  0x0000003d7240678b in start_thread () from /lib64/libpthread.so.0
#3  0x0000003d71cd49ad in clone () from /lib64/libc.so.6
#4  0x0000000000000000 in ?? ()

增加 destructor 并销毁TSD后解决该问题

static pthread_key_t time_now_buffer;
static pthread_key_t format_log_msg_buffer;

void freeBuffer(void* p){
    if(p) free(p);
}
__attribute__((constructor)) void prepareTSDKeys() {
    pthread_key_create (&time_now_buffer, freeBuffer);
    pthread_key_create (&format_log_msg_buffer, freeBuffer);
}
/* 
the destructor is used to delete tsd when the object is unloading 
--kevin.xw 
*/
__attribute__((destructor)) void deleteTSDKeys()
{
    pthread_setspecific(time_now_buffer, NULL);
    pthread_setspecific(format_log_msg_buffer, NULL);
    pthread_key_delete(time_now_buffer);
    pthread_key_delete(format_log_msg_buffer);
}

其它库的依赖

问题如:program 使用 dlopen(libA.so) , libA.so 依赖 libB.so 且 libA.so 并没有解决如何正确链接libB.so的问题。
三者路径如下:

./dir
`---- program 
`---- plugins/
		`---- libA.so 
		`---- libs/
				`---- libB.so 

此时 program dlopen libA.so 报错,找不到libB
问题参见: Dependency problem with dlopen

解决办法

  • 最好是由libA.so 来解决libB.so 的加载问题。
  • 也可以由 program 来解决, 办法是 在program 增加 rpath,如 $ORIGIN/plugins/libs, 这样dlopen libA的时候,可以在plugins/libs 下找到libB
    • 原因:参见dlopen man page 的说明:

      If the library has dependencies on other shared libraries, then these are also automatically loaded by the dynamic linker using the same rules.


参考

  1. https://www.ibm.com/support/knowledgecenter/en/ssw_i5_54/apis/users_36.htm
  2. http://man7.org/linux/man-pages/man3/dlopen.3.html
  3. https://svn.boost.org/trac10/ticket/3926
  4. https://bugs.chromium.org/p/chromium/issues/detail?id=59318
  5. https://github.com/apple/cups/issues/4410
  6. https://software.intel.com/en-us/node/629264
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值