2021年3月10日星期三

how to lookup c++ virtual table?

a simple example code as below:

#include <iostream>    class Base  {  public:      virtual void func0() { std::cout << "Base::func0" << std::endl; };      virtual void func1() { std::cout << "Base::func1" << std::endl; };  };      int main()  {      auto instance = Base();      uint64_t* vtableAddr = reinterpret_cast<uint64_t*>(&instance);      uint64_t* pVtable = reinterpret_cast<uint64_t*>(*vtableAddr);      auto func0 = reinterpret_cast<void(*)(Base*)>(*(pVtable + 0));      auto func1 = reinterpret_cast<void(*)(Base*)>(*(pVtable + 1));      func0(&instance);      func1(&instance);        auto func2 = reinterpret_cast<void(*)(Base*)>(*(pVtable + 2)); // exceed the limitation      func2(&instance); // core dump  }  

I can get the virtual table address by read the class fisrt 8 bytes(64bits compiler). But I don't know if there is a way to get the max legal offset of pVtable in runtime.
As above example, if I set the offset of pVtable is 2, and invoke the converted function, it will lead to a coredump.
Is any where stored the virtual table "size" for each class?

https://stackoverflow.com/questions/66575810/how-to-lookup-c-virtual-table March 11, 2021 at 10:52AM

没有评论:

发表评论