Created
July 28, 2013 02:11
-
-
Save netguy204/6097063 to your computer and use it in GitHub Desktop.
Monkey patching a C++ class by modifying its VTABLE.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdint.h> | |
class A { | |
public: | |
virtual void doThing() { | |
printf("I'm an A\n"); | |
} | |
}; | |
void dynamicOverride(A* a) { | |
printf("I'm an imposter!\n"); | |
} | |
int main(int argc, char *argv[]) { | |
A* a = new A(); | |
// grab the vtable for the A class | |
void** vtable = *(void***)a; | |
a->doThing(); | |
// out: "I'm an A" | |
void (A::* ptr)() = &A::doThing; | |
void* offset = *(void**)&ptr; | |
vtable[((uintptr_t)offset)/sizeof(void*)] = (void*)&dynamicOverride; | |
a->doThing(); | |
// out: "I'm an imposter!" | |
// affects future instances as well | |
A* a2 = new A(); | |
a->doThing(); | |
// out: "I'm an imposter!" | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment