Background:
I'm hooking on windows COM object.
The method used is vtable modification. say we have an instance of interface A named instance, it contains oldmethod in the interface, I replaced with newmethod. However, in my newmethod I need to know the address of oldmethod so that I can call oldmethod after doing my own thing.
It is not safe to store the address of oldmethod in a global variable, since there might be more than one implementation behind interface A, let's say there are two implementations, class A1 and class A2. Thus my newmethod needs to store both A1->oldmethod and A2->oldmethod, and call appropriate function based on the instance type.
One way to accomplish this is that I keep a map, which stores the (address of vtable -> oldmethod). Since the address of vtable can act as a distinguisher of class A1 and class A2. In my newmethod, the map is checked for the correct oldmethod for current instance. However, this will make the program check the map every time, which imposes a cost, and thread safety on the map will increase the cost.
Another way is to make a closure, I allocate a chunk of executable memory, and write the binary code of my newmethod inside(which can be reduced to the minimum size, so size is not a problem). I modify the address of oldmethod in the binary code for each instance. In this case there is no searching on the map cost.
Question 1:
Is the second way a safe way to do this, or is the first way better? Is there any potential safety problems in either of them?
Question 2:
In the second way, the closure I created contains class specific data, which is the oldmethod pointer. If I need to store instance specific data in my newmethod is there any strategy other than keeping a (this pointer -> data) map? I tried my best and couldn't find a way.