我正在尝试编写在运行时加载我的共享对象(.so)的最小程序。
不幸的是,尽管进行了错误检查,它仍会在运行时挂起: - (
我对我在源代码级别上忽略的内容非常感兴趣。
运行我的程序的源代码和我的shell会话如下。
文件“libsample.c”:
#include <stdio.h>
#include <dlfcn.h>
typedef void (*sample_func_t) (void);
int main(void)
{
setbuf(stdout, NULL);
setbuf(stderr, NULL);
void* h_lib = dlopen("./libsample.so.1", RTLD_LAZY); // RTLD_LAZY || RTLD_NOW
if (! h_lib)
{
fprintf(stderr, "ERROR(%d): %s\n", __LINE__, dlerror());
return 1;
}
sample_func_t* symver = NULL;
dlerror();
symver = dlsym(h_lib, "sample_check");
char* reter = dlerror();
if (reter)
{
fprintf(stderr, "ERROR(%d): %s\n", __LINE__, reter);
return 1;
}
printf("INFO(%d): Resolved library sample_check() symbol at %p\n", __LINE__, symver);
printf("INFO(%d): About to call library sample_check() ...\n", __LINE__);
(*symver)();
printf("INFO(%d): sample_check() called !\n", __LINE__);
int retcl = dlclose(h_lib);
if (retcl)
{
fprintf(stderr, "ERROR(%d): %s\n", __LINE__, dlerror());
return 1;
}
return 0;
}
文件“test.c”:
#! /bin/bash
echo "Begin of compilation ..."
rm test test.o libsample.so.1 libsample.so.1.0.1 libsample.o 2>/dev/null
gcc -fpic -c -o libsample.o libsample.c || exit 1
gcc -shared -Wl,-soname,libsample.so.1 -o libsample.so.1.0.1 libsample.o || exit 1
ln -s libsample.so.1.0.1 libsample.so.1 || exit 1
gcc -c -o test.o test.c || exit 1
gcc -o test test.o -ldl || exit 1
echo "Compilation successful !"
文件“build”:
valentin@valentin-SATELLITE-L875-10G:~/PROGRAMMING/C/Libraries/libsample$
valentin@valentin-SATELLITE-L875-10G:~/PROGRAMMING/C/Libraries/libsample$ ./build
Begin of compilation ...
Compilation successful !
valentin@valentin-SATELLITE-L875-10G:~/PROGRAMMING/C/Libraries/libsample$ ./test
INFO(27): Resolved library sample_check() symbol at 0x7f5e96df86f0
INFO(28): About to call library sample_check() ...
Erreur de segmentation
valentin@valentin-SATELLITE-L875-10G:~/PROGRAMMING/C/Libraries/libsample$
我的shell会话日志:
-l
有什么想法吗?
答案 0 :(得分:2)
这里
(*symver)();
代码重新引用已作为要运行的库函数的入口点接收的内容。这解析为一个随机地址,当被调用时,通常会使程序崩溃。
修复此定义
sample_func_t symver = NULL;
由于
,samle_func_t
已经是指针类型
typedef void (*sample_func_t) (void);
(记住*
。)
然后分配symver
有两种可能性:
&#34;脏&#34;一个
symver = dlsym(h_lib, "sample_check");
&#34;脏&#34;因为编译器可能会发出如下警告:
ISO C forbids assignment between function pointer and ‘void *’
&#34;清洁工&#34;一个
*(void**)(&symver) = dlsym(h_lib, "sample_check");
最后调用这个函数:
symver(); /* No need to dereference here. */