假设您有一个使用dlopen()加载多个共享对象/动态库的程序。给定一个指向全局对象的指针(例如静态成员变量),是否可以确定指针是在哪个库的边界中分配的?
答案 0 :(得分:5)
您可以使用文件/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
$