Skip to content

Instantly share code, notes, and snippets.

@netguy204
Created July 28, 2013 02:11
Show Gist options
  • Save netguy204/6097063 to your computer and use it in GitHub Desktop.
Save netguy204/6097063 to your computer and use it in GitHub Desktop.
Monkey patching a C++ class by modifying its VTABLE.
#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