ngoncalves ngoncalves - 1 year ago 61
Linux Question

Linux shared library is being loaded twice

I have the following setup:

  • a quite complex Qt+QML based application

  • a shared linux library that also has some Qt functionality

The shared library is injected onto the application using the LD_PRELOAD trick. Once loaded it starts a TCP server, through which it exposes the application internal objects. The goal is to access the application internals without specifically modifying the source code of the application.

The strange thing that I am seeing is that the shared library is being loaded twice and I cannot understand why. Since both the library and the application depend on Qt, I would understand if Linux would load multiple copies of the same Qt libraries.

But the application does not depend on the shared library and I am not overriding any functions on the application itself.

I would like to know:

  1. how to prevent the shared library from being loaded twice (I was thinking about using shell environment variables but it seems an ugly hack)

  2. what could possibly cause the shared library to be loaded twice


The answer from Employed-Russian steered me in the right direction for solving question #2. The target application is launching a child process which inherits the environment variables, LD_PRELOAD included. The child process is the reason why the library is being loaded twice.

As for question #1, I just used environment variables:

  1. on the library initialization function, check if environment variable LIBRARY_IS_LOADED is set

  2. If set, do nothing. Otherwise set the env variable and continue with business as usual

This is a bit ugly (I think) but gets the job done

Answer Source

what could possibly cause the shared library to be loaded twice

The loader goes through great lengths to not load the same shared library twice.

It is exceedingly likely that you have your code linked into two separate shared libraries, and that is what is causing all the confusion.

Setting LD_DEBUG=libs,files should clearly show what libraries are loaded from which paths.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download