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

bfr*_*hle 5 dlopen static-linking dlsym

是否有希望dlopen(NULL, ...)为静态编译的二进制文件运行和获取符号?

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

$ gcc -o foo foo.c -ldl -rdynamic
$ ./foo bar
In bar!
Run Code Online (Sandbox Code Playgroud)

但随着-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
Run Code Online (Sandbox Code Playgroud)

以下来源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;
}
Run Code Online (Sandbox Code Playgroud)

Emp*_*ian 5

是否有希望运行dlopen(NULL,...)并获取静态编译二进制文件的符号?

没有.

在大多数UNIX系统,你甚至不能连接-static-ldl在同一时间.你可以使用glibc,但这样做的效用非常有限.基本上,这种能力仅用于支持/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)();
Run Code Online (Sandbox Code Playgroud)

如果你试图"可能"调用foo它是否链接,否则什么都不做,然后使用弱引用:

extern void foo(void) __attribute((weak));

if (&foo != 0) {
  // foo was linked in, call it
  foo();
}
Run Code Online (Sandbox Code Playgroud)