Search code examples
clinkershared-librarieshookld-preload

Can I compile inline function as shared library, and use LD_PRELOAD to hook to other executable as inline function?


I want to hook my shared library to other program binary, and the hooking function is like this:

void my_function(void *data){
    bool res = my_function_needed(data);
    if (res){
        // Do my work
    }
    else {
        original_function(data);
    }
}

The hooked function will use my procedure and original following the function parameter. The problem is that, this function will be called so frequently, and performance is important here. Since I cannot change the function calling address itself in runtime(since this is function, not function pointer), if-else has to be remained in order to decide right procedure.

So I want to, at least, make these functions(my_function() and my_function_needed()) as inline functions to reduce function calling overhead. Is it possible to make the code truly inline in dynamic library hooking?


Solution

  • The way to get the function inlined is to provide the function source to the compiler and allow it to inline it into the content of the calling function. In all the C and C++ compilers I'm familiar with, this has to happen before the code generation stage of compilation, typically sometime after parsing. A dynamically linked library or statically linked library are both bodies of code that's been generated that can be used; however, this code will not be inlined into other code that's being compiled. It's linked in either after compilation at link time for static libraries or at the time the OS loader loads the program into memory.

    If you want a function to potentially be inlined, you typically provide it in a C or C++ header file.