Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept and forward C calls to a third-party library

Tags:

c++

c

linux

macos

I have an application (A) which calls a third-party shared library (C). I want to write a library of my own (B) that intercepts calls from A to C, and in some cases replace the calls with my own code, in some cases do some extra processing, then call the matching function in C, and in some cases just forward the calls to C directly.

The application is open-source, so I could just change each call site to call a similarly-named function in B, then call the corresponding function in C when required, but that would be a lot of work and would make merging upstream changes in the application difficult. I do not have the source to the third-party library. If it was header-only then I could just use namespaces to achieve this but I'm not sure how to go about it when both my library and the third-party library seemingly need the exact same symbols defined.

Is there even any way to make this work? I'm primarily targeting OS X, but would like it to work on linux and then eventually Windows as well.

like image 519
user1832047 Avatar asked Feb 09 '23 04:02

user1832047


1 Answers

You can use LD_PRELOAD to point to your own shared library. With LD_PRELOAD all functions in your shared library will be called instead of functions with the same name in those other libraries.

If you wish to inject code and then call the original functions you will need to call dlsym to get the original function from the third party library.

There are some examples here: https://rafalcieslak.wordpress.com/2013/04/02/dynamic-linker-tricks-using-ld_preload-to-cheat-inject-features-and-investigate-programs/

like image 142
Henrik Carlqvist Avatar answered Feb 15 '23 11:02

Henrik Carlqvist