Dynamic Linking – Must Dynamic Link Library Be Loaded into RAM?

dynamic-linking

As we know, any executable file, which is running, is loaded into RAM.

Also, we have two kinds of libs: static link library and dynamic link library.

The two kinds of libs should be loaded into RAM too while they are needed.

As I know, we have two ways to load the dynamic library:

  1. link it while compiling, such as g++ -lsofile
  2. load dynamically in the code, we have dlopen to do this

I've post this question but I can't still make sure that we could list all lib files. For the first case above, I think we can get the link file with ldd, or check /proc/{PID}/maps. But for the second case, I'm thinking if I can get the link files with some method, here is an example:

void SomeModule()
{
    //dlopen here to link mysofile
}

int main()
{
    if (user_enter == 'a')
    {
        printf("hello world");
    }
    else
    {
        SomeModule();
    }
}

In this example, when we execute it and type always a, the dlopen will never be called, so mysofile will never be linked, which means that mysofile will never be loaded into RAM. Am I right?

If so, how can I get the necessary lib files of the executable file except reading the source code?

Best Answer

You’re right, if dlopen is never called, the target library is never loaded into (the process’) memory.

Determining the necessary libraries without reading the source code feels like a variant of the halting problem. You could use some heuristics: if the program doesn’t link to libdl, then it can’t use dlopen; if it does, then you can use strace (see How to find out the dynamic libraries executables loads when run?) or try to figure out the arguments to dlopen using static analysis. But the program could include libdl directly (either through static linking, or by building the code); and since the dynamic linker isn’t magic, there’s nothing preventing a program from re-implementing it itself, so you can’t be absolutely sure you’ve caught all the libraries needed using these heuristics. Perhaps there are programs which figure out they’re being traced, and skip library-loading...

The only sure way of listing all the libraries required is to read the source code.

Related Question