在不修改源代码的情况下隐藏动态库中的符号

hea*_*bar 5 c++ symbols dynamic-library

我有一个我需要链接的闭源第三方共享库.不幸的是,第三方库的创建者并不打算限制导出和导出所有符号的符号.第三方库内部使用我在代码中使用的流行库的不兼容版本,但导出冲突的符号(谷歌的protobuf库).当protobuffer库版本检查发现编译时间和库的运行时版本不兼容时,这会导致运行时错误.我可以通过恢复到与第三方库中使用的版本匹配的旧版本protobufs 2.3来解决问题.但是,protbuf 2.3的性能问题使得我的应用程序无法使用它.我需要一种方法在我的代码中使用protobuf 2.4并让第三方库使用它自己的内部v 2.3.

有没有办法生成第三方库的新版本,该版本不从仅在给定文件的内部使用的protobuf v 2.3库中导出符号?如果我有源,那将是一个更容易的问题.似乎像objcopy和strip这样的工具实际上无法修改动态符号表.到目前为止,我唯一的想法是创建我自己的垫片库,通过将调用重定向到第三方库(可能用dlopen打开),只导出我需要的符号.

有更好的解决方案吗?

hea*_*bar 5

我找到了一个有效的解决方案......我创建了一个 shim 库,它将调用重定向到第三方库,允许库外的代码看到 protbuf v2.4 符号,而第三方库内的代码看到 protobuf v2.3 符号。此解决方法基于此处发布的想法:http : //www.linuxjournal.com/article/7795

我不得不修改 dlopen 标志以包含 RTLD_LAZY | RTLD_LOCAL | RTLD_DEEPBIND。RTLD_LOCAL 标志使第三方库内的符号不会在 shim 库外被看到(防止符号泄漏)。RTLD_DEEPBIND 强制从第 3 方库内部调用以仅查看符号的内部版本(防止符号泄漏)。

具体来说,这是我的 shim 库中的一个示例摘录。

#include <stdio.h>
#include <stdint.h>
#include <dlfcn.h>
#include "libhdfs/hdfs.h"

//#define PRINT_DEBUG_STUFF

// Helper function to retrieve a function pointer to a function from libMapRClient
// while isolating the symbols used internally from those already linked externaly
// to workaround symbol collision problem with the current version of libMapRClient.
void* GetFunc(const char* name){
  #ifdef PRINT_DEBUG_STUFF
    printf("redirecting %s\n", name);
  #endif
  void *handle;
  char *error;

  handle = dlopen("/opt/mapr/lib/libMapRClient.so", RTLD_LAZY | RTLD_LOCAL | RTLD_DEEPBIND);

  if (!handle) {
    fputs(dlerror(), stderr);
    exit(1);
  }
  void* fp = dlsym(handle, name);
  if ((error = dlerror()) != 0) {
    fprintf(stderr, "%s\n", error);
    exit(1);
  }
  return fp;
}


hdfsFS hdfsConnect(const char* host, tPort port) {
  typedef hdfsFS (*FP) (const char* host, tPort port);
  static FP ext = 0;
  if (!ext) {
    ext = (FP)GetFunc("hdfsConnect");
  }
  return ext(host, port);
}


int hdfsCloseFile(hdfsFS fs, hdfsFile file) {
  typedef int (*FP) (hdfsFS fs, hdfsFile file);
  static FP ext = 0;
  if (!ext) {
    ext = (FP)GetFunc("hdfsCloseFile");
  }
  return ext(fs, file);
}
Run Code Online (Sandbox Code Playgroud)

... 等其他公共 API 函数