C - What library (.so file) is the c function open() in, and how would I find that out for an arbitrary function?

1k views Asked by At

How can I find the library where the function open() is? Like, the name of the actual "xxxxxx.so" file that contains that function? Also, is there a place I could typically get this information for other functions?

1

There are 1 answers

0
Armali On

I didn't know how to find the library a given function was in, which was required for dlopen

Knowing the library is not required for dlopen():

If file is a null pointer, dlopen() shall return a global symbol table handle for the currently running process image. This symbol table handle shall provide access to the symbols from an ordered set of executable object files consisting of the original program image file, any executable object files loaded at program start-up as specified by that process file (for example, shared libraries), and the set of executable object files loaded using dlopen() operations with the RTLD_GLOBAL flag. …

But if you really want to know:

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>

int main()
{
    // We don't need to know the library for dlopen():
    void *handle = dlopen(NULL, RTLD_NOW);
    if (!handle) puts(dlerror()), exit(1);
    void *p = dlsym(handle, "open");
    char *s = dlerror();
    if (s) puts(s), exit(1);
    printf("open = %p\n", p);

    // But we can find the library with a Glibc extension:
    Dl_info info;
    if (dladdr(p, &info))
        printf("%s contains %s\n", info.dli_fname, info.dli_sname);
}