在 C 中查找 ELF 二进制文件的 dlopen 调用次数

Finding number of dlopen calls of an ELF binary in C

我想分析一个 ELF 二进制文件并弄清楚它在 C 中对 dlopen() 调用了多少次,是否有任何库可以执行此操作?或者我将如何找到计数?

解决方案取决于操作系统,归结为对目标进程进行热修补。您想查看 linux(https://sourceware.org/systemtap/SystemTap_Beginners_Guide/userspace-probing.html)上的 systemtap 用户空间跟踪或 bsd 相关系统(如 osx)上的 dtrace。没有关于 windows 的线索,但他们大概有一个等价物。

您可以简单地使用 ltrace:

示例:

#include <dlfcn.h>
#include <stdio.h>
int main(int C, char **V)
{
    char **a = V+1;
    while(*a){
        void *h;
        if(0==(h=dlopen(*a++, RTLD_LAZY)))
            fprintf(stderr, "%s\n", dlerror());
    }

}

编译它:

$ gcc example.c -fpic -pie 

自己调用它并计算 dlopen 次调用:

$ ltrace -o /dev/fd/3 \ 
  ./a.out ./a.out ./a.out ./a.out 3>&1 >/dev/null| \
  grep ^dlopen\( -c
3