I know this question was asked here before but it is not exactly what I need, and as much as I try to manipulate the answers from this thread I cannot get the result I'm looking for. So basically what I want to do is manipulate the virtual table in a C++ object so when calling one of the object's function it will call a different function It is only for educational purposes of course. my code is like that:
class Animal
{
private:
int height;
int length;
int type;
public:
virtual void makeNoise()
{
}
virtual void sleep()
{
}
};
Dog inherits from Animal such as:
class Dog : public Animal
{
public:
virtual void sleep() override
{
cout << "Going to sleep for Dog" << endl;
}
virtual void makeNoise() override
{
cout << "bark bark" << endl;
}
};
Theres another class A:
class A
{
public:
virtual void doSomething(void)
{
cout << "did nothing" << endl;
}
};
The function Hack is the function I want to override A->doSomething()
void Hack()
{
cout << "Hacked!" << endl;
}
main function:
void main()
{
int x = 0, y = 0, z = 0;
A* a = new A();
Animal * dog = new Dog();
someFunctionToManipulateVirtualTable(dog); //function get an object of type Dog but should hack into an object of type A's vtable
a->doSomething(); //should print "Hacked!"
}
Now the question is what should I do here:
void someFunctionToManipulateVirtualTable(Animal * dog)
{
//some code to manipulate main's local variable a (of type A).
}
So far, I have tried unsuccessfully , to get a's pointer through the dog reference from main, then get the virtual table pointer and override it with Hack's address, problem is , virtual table are in a read-only address location, I do manage to hack the vtable with local instances of A class, just with some pointer manipulation on the local instances..
Any lead on this will be awesome. Thanks