Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runtime library reloading using `dlopen` [duplicate]

Is it possible for a running c++ based process to reload a c++ based dynamic library using dlopen.

The running process polls for a new version of the dynamic library (with the same API). once such file is detected, the following set of actions are taking place :

  1. The older Library gets unloaded using dlclose
  2. The newer dylib is copied and override the file of the older version.
  3. The process loads the newer version from that location using dlopen
  4. Setting the function pointer variables according to dlsym from the newly loaded library.

In the last stage, I actually get the desired API and place it in function pointer from my main code to be used later.

However, it seems like my program is unexpectedly gets crashed after the third phase. is it possible that the dlclose part leave some remnants of the older library in the process virtual space ? is there any better way to do so ?

by the way, in Windows it's working just fine using LoadLibrary, FreeLibrary and GetProcAddress instead of dlopen, dlclose and dlsym.

like image 216
Zohar81 Avatar asked Mar 14 '18 14:03

Zohar81


1 Answers

it seems like my program is unexpectedly gets crashed after the third phase. is it possible that the dlclose part leave some remnants of the older library in the process virtual space?

It is possible. Objects with function pointers to functions and objects with virtual functions defined in the library being unloaded are going to end up with invalid pointers. Even worse, one can attach a new facet to a standard stream (e.g. std::cout) and then unload the shared library implementing the facet. Later on it would crash when using std::cout in a unrelated place (true story). So, you must be in total control of what the shared library does.

Also, dlopen must be called with RTLD_LOCAL, so that nothing else can (accidentally) use the symbols of the shared library being loaded and prevent it from unloading. You must read and understand man dlopen if you do such feats.

like image 75
Maxim Egorushkin Avatar answered Oct 04 '22 03:10

Maxim Egorushkin