问题描述
我写了一个程序来 dlopen
I wrote a program to dlopen itself
void hello()
{
printf("hello world\n");
}
int main(int argc, char **argv)
{
char *buf="hello";
void *hndl = dlopen(argv[0], RTLD_LAZY);
void (*fptr)(void) = dlsym(hndl, buf);
if (fptr != NULL)
fptr();
dlclose(hndl);
}
但我收到分段错误"错误我用一个 .so 库测试了这个程序,它可以工作,但不能让它自己工作
but I get "segemention fault" errorI tested this program with a .so library and it works but can not get it working with itself
推荐答案
你需要编码:
// file ds.c
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
void hello ()
{
printf ("hello world\n");
}
int main (int argc, char **argv)
{
char *buf = "hello";
void *hndl = dlopen (NULL, RTLD_LAZY);
if (!hndl) { fprintf(stderr, "dlopen failed: %s\n", dlerror());
exit (EXIT_FAILURE); };
void (*fptr) (void) = dlsym (hndl, buf);
if (fptr != NULL)
fptr ();
else
fprintf(stderr, "dlsym %s failed: %s\n", buf, dlerror());
dlclose (hndl);
}
仔细阅读dlopen(3),始终检查dlopen
成功 &dlsym
在那里起作用,并在失败时使用 dlerror
.
Read carefully dlopen(3), always check the success of the dlopen
& dlsym
functions there, and use dlerror
on failure.
并用
gcc -std=c99 -Wall -rdynamic ds.c -o ds -ldl
不要忘记 -Wall
以获取所有警告和 -rdynamic
标志(以便能够 dlsym
您自己的符号应该进入动态表).
Don't forget the -Wall
to get all warnings and the -rdynamic
flag (to be able to dlsym
your own symbols which should go into the dynamic table).
在我的 Debian/Sid/x86-64 系统上(带有 gcc
4.8.2 版和 libc6
2.17-93 版,提供 -ldl
,我编译的内核 3.11.6,binutils
包 2.23.90 提供 ld
),./ds
的执行给出了预期的输出:
On my Debian/Sid/x86-64 system (with gcc
version 4.8.2, and libc6
version 2.17-93 providing the -ldl
, kernel 3.11.6 compiled by me, binutils
package 2.23.90 providing ld
), the execution of ./ds
gives the expected output:
% ./ds
hello world
甚至:
% ltrace ./ds
__libc_start_main(0x4009b3, 1, 0x7fff1d0088b8, 0x400a50, 0x400ae0 <unfinished ...>
dlopen(NULL, 1) = 0x7f1e06c9e1e8
dlsym(0x7f1e06c9e1e8, "hello") = 0x004009a0
puts("hello world"hello world
) = 12
dlclose(0x7f1e06c9e1e8) = 0
+++ exited (status 0) +++
这篇关于如何自 dlopen 可执行二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!