簡體   English   中英

如何確定哪個動態庫負責創建指針?

[英]How to determine which dynamic library is responsible for creation of a pointer?

假設您有一個使用dlopen()加載多個共享對象/動態庫的程序。 給定一個指向全局對象的指針(例如靜態成員變量),是否可以確定指針是在哪個庫的邊界中分配的?

您可以使用文件/proc/self/maps解析流程圖,並查看指針地址的界限,全局變量將位於.data.bss段中。

示例庫lib.c

static int object;

int *
dummy(void)
{
  return &object;
}

test.c ,為簡單起見,未處理錯誤:

#include <stdio.h>
#include <dlfcn.h>
#include <unistd.h>
#include <inttypes.h>
#include <assert.h>
#include <linux/limits.h>

static void which_library(void *p);

int
main(int argc, char **argv)
{
  void *handle;
  void *object;

  handle = dlopen("./lib.so", RTLD_NOW);
  assert(handle);

  object = ((int *(*)(void)) dlsym(handle, "dummy"))();
  which_library(object);
  dlclose(handle);

  return 0;
}

static void
which_library(void *p)
{
  FILE *maps;
  char buffer[49+PATH_MAX+1];

  maps = fopen("/proc/self/maps", "r");
  assert(maps);

  while(fgets(buffer, sizeof(buffer) - 1, maps)) {
    char path[PATH_MAX+1];
    uintptr_t starts;
    uintptr_t ends;

    sscanf(buffer, "%" PRIxPTR "-%" PRIxPTR " %*s %*x %*x:%*x %*d %s", &starts, &ends, path);
    if((uintptr_t)p >= starts && (uintptr_t)p < ends) {
      printf("%p => %s\n", p, path);
      break;
    }
  }

  fclose(maps);
}

測試:

$ gcc -Wall -shared lib.c -o lib.so 
$ gcc -Wall test.c -ldl
$ ./a.out 
0xb779f5f8 => /home/barakat/Desktop/lib.so
$ 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM