Click here to Skip to main content
15,886,574 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Folks,
If I use LD_PRELOAD to load a library say "wrapper.so" to all processes and then dynamically modify the LD_PRELOAD environment from wrapper.so like

C++
static void MyInit() __attribute__((constructor));
void MyInit() 
{
   // Set preload env variable here to modify preload chain and use it
   // It is mandatory to load yetanotherlibrary.do using preload
   setenv(LD_PRELOAD, "yetanotherlibrary.do", true);
    
}


Experts, please share your insights if you see cases where this may not work as expected.

What I have tried:

Found working on Ubuntu and CentOS.
Posted
Updated 23-Dec-21 0:51am
v2
Comments
Richard MacCutchan 23-Dec-21 3:42am    
The setenv function only changes the environment for that single process.
Member 15329325 23-Dec-21 6:36am    
Hey Richard,
Thanks for your response.

We are going to sit inside every process with wrapper.so
Based on few conditions we may decide to preload yetanotherlibrary.so
So modifying the preload chain for that process is the intention.

Do you see any misuse of LD_PRELOAD here?
Richard MacCutchan 23-Dec-21 6:42am    
Looking at the documentation at ld.so(8) - Linux manual page[^] I do not think this will work. The LD_PRELOAD environment variable is only used by the loader when a program is first loaded into memory. So setting it inside the process will be too late.

There is a simple way to confirm what happens.

1 solution

As Richard points out, LD_PRELOAD only affects the current process, and then only applies to processes spawned via one of the exec() functions, or system(), popen() etc. It doesn't affect the current process. LD_PRELOAD is a list so you can do
Shell
$ LD_PRELOAD=lib1.so:lib2.so:lib3.so myprog 
. This does the expected thing and preloads lib1, lib2 and lib3 before starting myprog. There are other environment variables that affect link-load which are detailed in the ld.so man page.

If what you are trying to do is to dynamically load a library after program launch, you might want to look into dlopen() and friends. There's a very basic intro to them here: https://tldp.org/HOWTO/Program-Library-HOWTO/dl-libraries.html[^] So, for example, if you wanted to write a program that the end user might want to use Postgresql, MySQl, Firebird, or some other database. You could write the low level database access functions and put them in a shared library eg pgsql.so, mysql.so, etc. Then based on the config details for the program, selectively load the shared library to talk to the database in question.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900