plthook icon indicating copy to clipboard operation
plthook copied to clipboard

How to hook a member function of some class in C++ ?

Open zsnjuts opened this issue 4 years ago • 2 comments

I want to hook a member function of some class in C++, for example, Helper::func()

class Helper {
public:
    void func(){
        // do something here...
    }
}

But I have not found related document here. Is this possible with plthook? If I want to achieve this, what efforts do I need to make? Thanks in advance.

zsnjuts avatar Feb 04 '21 12:02 zsnjuts

I have not tested the following. I hope it is correct.

  1. Methods defined in .cpp files Possible. The second argument of plthook_replace() must be the corresponding mangled name.

    // In a header file
    class Helper {
    public:
        void func(); // declaration
    };
    
    // In .cpp file
    Helper::func() {
       // do something here...  // definition
    }
    
  2. Methods defined in header files Impossible. The method definition may be inlined though plthook hooks only inter-module method calls.

    // In a header file
    class Helper {
    public:
        void func() {  // declaration
           // do something here...  // definition
        }
    }
    
  3. Virtual methods Impossible. It needs another technique.

kubo avatar Feb 06 '21 12:02 kubo

Maybe you can use a c wrapper to hook cpp function, for example.

void Foo::say_world()
{
        printf("Foo::say_world\n");
}
void say_world()
{
        Foo foo;
        foo.say_world();
}

gerryyang avatar Mar 05 '21 10:03 gerryyang

Is it possible to call the original c++ member function in the hooked function using the original address without knowing the type of the C++ class?

forunix avatar Apr 02 '22 10:04 forunix