LD_PRELOAD for C ++ class methods

I need to insert a method call into a C ++ program (the class is in a separate shared library). I thought I could use LD_PRELOAD, but I'm not sure how this will work (I just found examples of C functions): is there a way to set the interpolation for one method without copying any code from the implemented class implementation?

+5
c ++ methods library-interposition
source share
2 answers

It would not be very portable, but you could write your intermediate function in C and give it a garbled C ++ method name. Of course, you will have to handle this parameter explicitly, but I think that all ELF ABIs simply treat it as an invisible first argument.

+2
source share

Just create a file for the inserted code (make sure the implementation is out of line) ... the namespaces, class name and function should be the same as for the method you want to intercept. In the definition of your class, do not mention other methods that you do not want to intercept. Remember that LD_PRELOAD needs the full path to intercept the shared object.

For example, to intercept void X :: fn1 (), create the libx2.cc file with:

 #include <iostream>

 class X
 {
   public:
     void X :: fn1 ();
 };

 void X :: fn1 () {std :: cout << "X2 :: fn () \ n";  }

Then compile it:

 g ++ -shared -o libx2.so libx2.cc

Then run ala

 LD_PRELOAD = `pwd` / libx2.so ./libx_client

Greetings

+6
source share

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


All Articles