static-linking - 在静态二进制文件上使用 dlsym

标签 static-linking dlopen dlsym

有没有跑路的希望dlopen(NULL, ...)并为静态编译的二进制文件获取符号?

例如,使用以下代码,如果程序是动态编译的并且我使用 -rdynamic,我可以获得符号。 .

$ gcc -o foo foo.c -ldl -rdynamic
$ ./foo bar
In bar!

但与 -static我收到一条神秘的错误消息:
$ gcc -static -o foo foo.c -ldl -rdynamic
/tmp/cc5LSrI5.o: In function `main':
foo.c:(.text+0x3a): warning: Using 'dlopen' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
$ ./foo bar
/lib/x86_64-linux-gnu/: cannot read file data: Is a directory
foo.c的来源如下:
#include <dlfcn.h>
#include <stdio.h>

int foo() { printf("In foo!\n"); }
int bar() { printf("In bar!\n"); }

int main(int argc, char**argv)
{
  void *handle;
  handle = dlopen(NULL, RTLD_NOW|RTLD_GLOBAL);
  if (handle == NULL) {
    fprintf(stderr, "%s\n", dlerror());
    return 1;
  }

  typedef void (*function)();
  function f = (function) dlsym(handle, argv[1]);
  if (f == NULL) {
    fprintf(stderr, "%s\n", dlerror());
    return 2;
  }
  f();

  return 0;
}

最佳答案

Is there any hope of running dlopen(NULL, ...) and getting symbols for a statically compiled binary?



不。

在大多数 UNIX 上,您甚至无法与 -static 链接和 -ldl同时。使用 glibc 可以,但这样做的效用非常有限。基本上,此功能仅用于支持/etc/nsswitch.conf,仅用于支持/etc/nsswitch.conf。

进行您所做的动态查找也毫无意义。

如果您试图允许 foo 之一, barbaz根据命令行参数调用,只需放入一个表格,例如
struct { const char *fname, void (*fn)(void) } table[] =
  { {"foo", &foo}, {"bar", &bar}, ...};

for (int i = 0; i < ...; ++i)
  if (strcmp(argv[1], table[i].fname) == 0)
    // found the entry, call it
    (*table[i].fn)();

如果你想“也许”打电话 foo如果它已链接,并且不执行任何其他操作,则使用弱引用:
extern void foo(void) __attribute((weak));

if (&foo != 0) {
  // foo was linked in, call it
  foo();
}

关于static-linking - 在静态二进制文件上使用 dlsym,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14289488/

相关文章:

c++ - 如何静态链接 libstdc++

linux - 第二次插件崩溃时再次引用代码段

android - dlopen() 不适用于 android-n

c - Dlsym:从不同大小的整数转换为指针

c++ - 如何使用 LD_PRELOAD 拦截 dlsym 调用?

ios - 如何使用 dlsym 检查枚举值是否存在?

c++ - 如何在mingw中进行libwinpthread-1.dll的静态链接?

gcc - 为什么 gcc 在 x86_64 上编译静态库时不隐式提供 -fPIcflags

c++ - Boost 和 OpenCV 库与 Eclipse CDR 的静态链接。错误

c - 当调用 dlclose 时共享库中的全局变量会发生什么?