Can I use the Shared Object Designer to set the library search path?

I store shared objects in a hierarchical folder structure. Shared libraries can depend on each other. During runtime, shared library X may need to load shared library Y. I'm not sure what mechanism I can use to get X library to find Y.

I'd rather not use -rpath because it doesn't translate well across platforms:

I am unable to put shared objects in the same directory due to potential name conflicts. LD_LIBRARY_PATH and PATH cannot be used as I am adding many paths.

I'm wondering if I can change LD_LIBRARY_PATH in the constructor of the shared object (using -Wl, -init). This would require the constructor to run before the runtime connection occurs. I couldn't find if this is the case.

In essence, I am thinking about doing the following (haven't tried this code yet):

Add this function to your library source code:

extern char *searchPath;

void construct() {
    char *libPath = getenv("LD_LIBRARY_PATH");
    char *new_libPath = malloc(1 + snprintf(NULL, 0, "%s:%s", libPath, searchPath);
    sprintf(new_libPath, "%s:%s", libPath, searchPath);
    setenv("LD_LIBRARY_PATH", new_libPath, 0);
}

      

And compile with:

gcc foo.c --shared -o foo -Wl,-init,construct

      

+3


source to share


1 answer


No , you cannot at all. Some linkers may support this, but others definitely won't. Many dynamic linkers simply ignore changes to LD_LIBRARY_PATH

or equivalent after the main executable is loaded, so you won't even be able to influence the load path at all at runtime. Other linkers may not even try to call initializers or constructors before all libraries are linked (for example, Mac OS X dyld

behaves this way).

Also, some linkers don't even load two libraries that are the same soname

as they will be considered the same library. Therefore, given that you have potential name conflicts in your libraries, this would even prevent them from being loaded automatically.




To load libraries at boot time, POSIX provides dlopen

and dlsym

. dlopen

allows you to load an arbitrary library at the file path, and dlsym

allows you to capture pointers to symbols defined in this library. Consider using this data instead of dynamically changing the path - dlopen

and dlsym

are portable and reasonably easy to use. Yes, you don't get "automatic" symbol resolution (which is that you have dlsym

to do it all yourself), but there are ways to design your libraries to make it easier (or use macros to make resolution easier).

On Windows, you can use LoadLibrary

it GetProcAddress

similarly. If you want a good cross-platform library that flattens out platform differences, consider something like libltdl .

+1


source







All Articles