关于主动加载动态库dlopen,dlsym的使用

最近看到前人写的一段代码:

typedef void (*fnFunc_t)(int);

void *gpDllHandle = NULL; /* 此变量只在以下代码用到 */

fnFunc_t fnFunc = NULL;


void func1()

{

    void *pDllHandle = gpDllHandle;

    pDllHandle = dlopen("...", RTLD_LAZY | RTLD_GLOBAL);

}

void func2()

{

    fnFunc = dlsym(gpDllHandle, "...");

}

void func3()

{

    fnFunc(10);

}

这段代码存在的问题是dlopen打开动态库得到的句柄pDllHandle并没有保存到全局变量,而dlsym时又将此变量作为入参。这样一来,就很怀疑为什么dlsym传入一个无效的句柄,也能正确找到相应函数了(fnFun非空)。

然后仔细看了看dlsym的man手册,有这么一段话:

There are two special pseudo-handles that may be specified in handle:

       RTLD_DEFAULT
              Find the first occurrence of the desired symbol using the
              default shared object search order.  The search will include
              global symbols in the executable and its dependencies, as well
              as symbols in shared objects that were dynamically loaded with
              the RTLD_GLOBAL flag.

       RTLD_NEXT
              Find the next occurrence of the desired symbol in the search
              order after the current object.  This allows one to provide a
              wrapper around a function in another shared object, so that,
              for example, the definition of a function in a preloaded
              shared object (see LD_PRELOAD in ld.so(8)) can find and invoke
              the "real" function provided in another shared object (or for
              that matter, the "next" definition of the function in cases
              where there are multiple layers of preloading).
大概意思是dlsym可以传入另外两个特殊的句柄,RTLD_DEFAULT和RTLD_NEXT,值分别是0和-1.当传入RTLD_DEFAULT时,意思是在当前进程环境中(包括已加载到全局可用的动态库)查找第一个匹配的函数或全局变量。

而我的代码中dlsym传入的第一个参数是NULL,也就是RTLD_DEFAULT,而这个动态库又是以GLOBAL加载的,所以没有问题,但是这样的代码逻辑让不清楚dlsym这个机制的人很费解,逻辑本身是存在问题的,但是因为巧合,或者说dlsym这种机制,让这段代码实际运行又恰好没有问题。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值