Search code examples
cbinaryfileself

Finding number of dlopen calls of an ELF binary in C


I would like to analyze an ELF binary file and figure out how many calls to dlopen() it makes in C, are there any libraries that can do this? Or how would I go about finding the count?


Solution

  • You could simply use ltrace:

    Example:

    #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());
        }
    
    }
    

    Compile it:

    $ gcc example.c -fpic -pie 
    

    Invoke it on self and count dlopen calls:

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