God's in his heaven.
All's right with the world.

0%

Overriding the virtual table in a C++ object(转载)

Yesterday I was discussing with a friend of mine about how polymorphism is implemented in C++, and that is, using a virtual table ( remember the “virtual” keyword in method definitions? ). A virtual table is, rawly speaking, just like an array of function pointers. Each created object with virtual methods needs a virtual table. So, where does the virtual table is stored?, I really don’t know, but I do know where I can find the address of the virtual table associated to an object ( at least in g++ 4.1.1 ), the first sizeof(void*) bytes of an object are used to store a pointer to the virtual table. With this knowledge, one could think that is possible to override the virtual table pointer of the object and call arbitrary functions, and yes, we can. Let’s see some fun code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>

using namespace std;

class Parent
{
public:
virtual void VirtFunc1() { cout << "Parent::VirtFunc1" << endl; }

virtual void VirtFunc2() { cout << "Parent::VirtFunc2" << endl; }
};

class Child : public Parent
{
public:

void VirtFunc1() { cout << "Child::VirtFunc1" << endl; }
void VirtFunc2() { cout << "Child::VirtFunc2" << endl; }
};

typedef void (*virtual_function)();

struct FakeVirtualTable {
virtual_function virtual_one;

virtual_function virtual_two;
};

void fake_virtual_one()
{
cout << "Faked virtual call 1" << endl;
}

void fake_virtual_two()
{
cout << "Faked virtual call 2" << endl;
}

int main()
{
/* declare a Child class and a base pointer to it. */
Child child_class_obj;
Parent* parent_class_ptr = &child_class_obj;

/* create our fake virtual table with pointers to our fake methods */
FakeVirtualTable custom_table;
custom_table.virtual_one = fake_virtual_one;

custom_table.virtual_two = fake_virtual_two;

/* take the address of our stack virtual table and override the real object pointer to the virtual table */
FakeVirtualTable* table_ptr = &custom_table;

memcpy(parent_class_ptr, &table_ptr, sizeof(void*));

/* call the methods ( but we're really calling the faked functions ) */

parent_class_ptr->VirtFunc1();
parent_class_ptr->VirtFunc2();

return 0;
}

So, try to run that code and, of course, the expected result is having fake_virtual_one() and fake_virtual_two() functions called. No magic there, we just replace the first sizeof(void*) bytes of the object with our own table pointer. There is not a use I can think of right now, but it is funny ….


本文地址:http://xnerv.wang/overriding-the-virtual-table-in-a-cpp-object/
转载自:Overriding the virtual table in a C++ object