在共享库中查找已加载共享库的位置? [英] Find location of loaded shared library, from in that shared library?
问题描述
从共享库中的函数中,在运行的进程中(用C编写),如何发现共享库从何处加载?
From a function in a shared library, inside a running process (written in C), how do I discover where that shared library was loaded from?
我找到的所有答案都涉及在命令行中使用诸如 ldd
之类的东西,或者通过窥视/proc/self/maps
.
All of the answers I've found involve using things such as ldd
at the command line, or by peeking in /proc/self/maps
.
在Win32上,我只使用 GetModuleFileName(GetModuleHandle("foo.dll"),szPath,COUNTOF(szPath))
.什么是Linux等效项?
On Win32, I'd just use GetModuleFileName(GetModuleHandle("foo.dll"), szPath, COUNTOF(szPath))
. What's the Linux equivalent?
奖金问题:我需要在OS X中使用相同的信息.
推荐答案
实现此目标的一种方法是使用dladdr:
One method to achieve this is to make use of dladdr:
共享对象的代码:
$ cat so.c
#include <stdio.h>
#include <dlfcn.h>
void test_so_func()
{
Dl_info info;
if (dladdr(test_so_func, &info))
{
printf("Loaded from path = %s\n", info.dli_fname);
}
printf("hello\n");
}
主要执行者的代码:
$ cat test.c
void test_so_func();
int main() {
test_so_func();
return 0;
}
Makefile:
$ cat Makefile
test: test.o libso.so
gcc test.o -o $@ -Wl,-L.,-lso,-rpath,'$$ORIGIN'
clean:
-rm -f libso.so test.o test
libso.so: so.c
gcc -D_GNU_SOURCE=1 -fPIC -shared $< -o $@ -lc -ldl
test.o: test.c
gcc -fPIC -c $< -o $@
让我们编译吧!
$ make
gcc -fPIC -c test.c -o test.o
gcc -D_GNU_SOURCE=1 -fPIC -shared so.c -o libso.so -lc -ldl
gcc test.o -o test -Wl,-L.,-lso,-rpath,'$ORIGIN'
测试此二进制文件.
$ ./test
Loaded from path = /spare/scratch/1564054710/libso.so
hello
验证libso.so确实在讲真话.
Verify that libso.so is indeed speaking the truth.
$ ldd ./test
linux-vdso.so.1 => (0x00007ffdf55d5000)
libso.so => /spare/scratch/1564054710/./libso.so (0x00007fbcc4602000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fbcc4238000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fbcc4034000)
/lib64/ld-linux-x86-64.so.2 (0x00007fbcc4804000)
此答案的功劳归于 https://github.com/mingwandroid
这篇关于在共享库中查找已加载共享库的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!