动态加载
- 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.
- 原因:参见dlopen man page 的说明:
参考
- https://www.ibm.com/support/knowledgecenter/en/ssw_i5_54/apis/users_36.htm
- http://man7.org/linux/man-pages/man3/dlopen.3.html
- https://svn.boost.org/trac10/ticket/3926
- https://bugs.chromium.org/p/chromium/issues/detail?id=59318
- https://github.com/apple/cups/issues/4410
- https://software.intel.com/en-us/node/629264