Good documentation for linkers required!

I need to write a small library so that it can be loaded by setting LD_PRELOAD and which will override some functions in the standard C library and also call these functions in the standard library. In particular, I want my shiny new library to allow users to provide their own resolv.conf so that they can, for example, specify their default domain or set aliases for them for long host names. I need a good understanding of how the linker works if I do this, so that someone can point me to a good documentation that does not assume that I know all this and just need a link, but also does not assume that I am a complete idiot ?

+4
source share
3 answers

If you are using the GNU linker, you need to know that this is RTLD_NEXT. This allows you to "find the next occurrence of a function in the search order after the current library."

That way you can override the standard function and still be able to call the original version.

I used this function in the malloc version, which tracks distribution statistics. I needed to override malloc to collect statistics, but I still wanted the original version of malloc to perform the allocation:

static void *(*next_malloc)(size_t) = NULL; __attribute__ ((constructor)) static void bootstrap() { next_malloc = dlsym(RTLD_NEXT, "malloc"); } void * malloc(size_t size) { void *ptr = next_malloc(size); // collect some stats return ptr; } 
+3
source

It looks like you are interested in dynamic loading , and not generally a link. How ODBC finds and uses a specific driver at runtime, for example, what you want to do with your resolver.

Instead of getting a random link to google, I will give you some dynamic linking keywords:

Basic concepts: "dynamic loading" "Value" Independent position code "

Tools: LD_DEBUG ldconfig ldd nm objdump

C API for dynamic loading: dlfcn.h dlopen dlsym dlerror dlclose

I found one good tutorial that I remember was useful when I was working with ODBC: http://www.ibm.com/developerworks/library/l-shobj/

However, he recommends accessing ld directly, which does not matter gcc. Use the -shared option instead:

 g++ -shared -fPIC foo.c -o libfoo.so.1.0 -Wl,soname,libfoo.so.1 

Also: you should look for solutions that do not include LD_PRELOAD or LD_LIBRARY_PATH, which are mostly debugging tools, and libraries that require them in production are wrong: Why LD_LIBRARY_PATH is bad LD_LIBRARY_PATH is not LD_LIBRARY_PATH's answer - just say no

ODBC avoids it with the odbc.ini configuration file, where you specify the full path to .so to use.

+1
source

Some good answers, but no one mentioned the one resource that led me to this: Creating library intermediate elements for fun and profit .

+1
source

Source: https://habr.com/ru/post/1301763/


All Articles