哪个段是存储在ELF文件,数据段或其他中的虚拟表?

时间:2013-06-26 08:47:33

标签: c++ vtable

众所周知,虚函数表指针通常存储在实例的前4个字节中。但我很好奇虚拟功能表存储在指定的ELF文件中的位置。我编写了以下程序进行测试,并使用readelf -s a.out命令获取ELF文件的符号表,但我找不到“vtable”或类似的东西。

#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;
}

1 个答案:

答案 0 :(得分:1)

虚拟表存储在ELF文件的.rodata部分中,其相应的段在内存中被加载。