如何自我的dlopen可执行的二进制 [英] how to self dlopen an executable binary

查看:471
本文介绍了如何自我的dlopen可执行的二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个程序来执行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);
}

但我得到segemention错误错误
我测试这个程序有.so库和它的作品,但可以得到它与自己的工作没有

but I get "segemention fault" error I tested this program with a .so library and it works but can not get it working with itself

推荐答案

您需要code:

  // 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.

和编译上面 ds.c

  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 包90年2月23日提供 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可执行的二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆