In which segment is the virtual table stored in the ELF file, data segment, or other?

As we all know, a virtual function table pointer is usually stored in the first 4 bytes in an instance. But I'm very curious where the virtual function table is stored in the specified ELF file. I wrote the following program for testing, and I used the readelf -s a.out command to get the character table of the ELF file, but I cannot find "vtable" or something like that.

 #include <iostream> #include <stdio.h> using namespace std; typedef void (*fun_pointer)(void); class Test { public: Test() { cout<<"Test()."<<endl; } virtual void print() { cout<<"Test::Virtual void print()."<<endl; } virtual void print2() { cout<<"Test::Virtual void print2()."<<endl; } }; class TestDrived:public Test { public: TestDrived() { cout<<"TestDrived()."<<endl; } virtual void print() { cout<<"TestDrived::virtual void print()."<<endl; } virtual void print2() { cout<<"TestDrived::virutual void print2()."<<endl; } void GetVtblAddress() { cout<<"vtbl address:"<<(int*)this<<endl; } void GetFirstVtblFunctionAddress(void) { cout<<"First function address in vtbl:"<< (int*)*(int*)this+0; } void GetSecondVtblFunctionAddress(void) { cout<<"First function address in vtbl:"<< (int*)*(int*)this+2<<endl; //my os is 64bit //linux, if you use 32bit OS, please replace the "this+2" with "this+1" } void CallFirstVtblFunction() { fun = (fun_pointer)* ( (int*)*(int*)this+0 ); fun(); } void CallSecondVtblFunction() { fun = (fun_pointer)* ( (int*)*(int*)this+2 ); //my os is 64bit //linux, if you use 32bit OS, please replace the "this+2" with "this+1" fun(); } private: fun_pointer fun; }; int main() { cout<<"sizeof(int):"<<sizeof(int)<<"sizeof(int*)"<<endl<<sizeof(int*)<<endl; fun_pointer fun = NULL; TestDrived a; a.GetVtblAddress(); a.GetFirstVtblFunctionAddress(); a.GetSecondVtblFunctionAddress(); a.CallFirstVtblFunction(); a.CallSecondVtblFunction(); return 0; } 
+4
source share
1 answer

the virtual table is stored in the .rodata section of the ELF file, and the corresponding segment is loaded into memory.

+1
source

Source: https://habr.com/ru/post/1488230/


All Articles