Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LD_PRELOAD for C++ class methods

I need to interpose on a method call in a C++ program (the class resides in a separate shared library). I thought I could use LD_PRELOAD, but i am not sure how this would work (i only found examples of C functions): is there a way to setup interposition for a single method without copying over any code from the interposed class implementation?

like image 726
BruceBerry Avatar asked Aug 05 '10 00:08

BruceBerry


2 Answers

Just create a file for the interposed code (making 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 your class definition, don't mention the other methods you don't want to intercept. Remember that LD_PRELOAD needs a full path to the intercepting shared object.

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

#include <iostream>

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

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

Then compile it up:

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

Then run ala

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

Cheers

like image 181
Tony Delroy Avatar answered Oct 16 '22 22:10

Tony Delroy


It wouldn't be very portable, but you could write your interposing function in C and give it the mangled name of the C++ method. You would have to handle the this parameter explicitly, of course, but I think all ELF ABIs just treat it as an invisible first argument.

like image 37
zwol Avatar answered Oct 16 '22 22:10

zwol