linux 动态加载代码研究

本文探讨了使用动态链接库(.so文件)时如何处理未定义符号的问题,并通过对比RTLD_LAZY与RTLD_NOW两种不同加载模式的效果来说明如何在程序运行前检查符号缺失情况。

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

main.c 

#include <dlfcn.h>
#include <stdio.h>
#include "plugin.h"


int main()
{
    void *dlp = dlopen("./a.so", RTLD_LAZY);
    if(!dlp)
    {
        printf("dlp Is NULL\n");
        return 0;
    }


    aFunc ap = (aFunc)dlsym( dlp,"a");


    printf("ap is [%u] dlerror[%s]\n",ap,dlerror());


    if( ap)
    {


        (*ap)();
    }


    printf(" normal end\n");


    return 0;
}


plugin.h

void a();                
                         
typedef void (*aFunc)(); 

a.c


#include "plugin.h"  
                     
void a()             
{                    
    c();             
}                    


执行 ./a.out时输出结果

 user00@devnet_191_79_sles10_64~/learn/so_test$./a.out 
ap is [3591325244] dlerror[(null)]
./a.out: symbol lookup error: ./a.so: undefined symbol: c


如果修改RTLD_NOW则可以检测出未定义符号错误。

dlp Is NULL dlerror[./a.so: undefined symbol: c]


反向引用

gcc -Wl,-export-dynamic main.c -ldl


main.c中包含 函数c的定义

int main()
{
    void *dlp = dlopen("./a.so", RTLD_NOW);
    if(!dlp)
    {
        printf("dlp Is NULL dlerror[%s]\n",dlerror());
        return 0;
    }


    aFunc ap = (aFunc)dlsym( dlp,"a");


    printf("ap is [%u] dlerror[%s]\n",ap,dlerror());


    if( ap)
    {


        (*ap)();
    }


    printf(" normal end\n");


    return 0;
}


void c()
{
    printf("c called\n");
}


最终输出

ap is [4204455484] dlerror[(null)]
c called
 normal end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值