c – 如何确定哪个动态库负责创建指针?
作者:互联网
假设您有一个使用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
$
标签:c-2,c-3,linux,dynamic-library,shared-objects 来源: https://codeday.me/bug/20190609/1206880.html