LD_PRELOAD for C++ class methods

妖精的绣舞 提交于 2019-12-04 23:15:59

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/3410990/ld-preload-for-c-class-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!