user2507809
user2507809

Reputation: 63

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

As we all know, virtual function table pointer is usually stored in the first 4 bytes in an instance. But I'm very curious about where the virtual function table stored in the specified ELF file. I wrote the following program to test, and I used the readelf -s a.out command to get the symbol table of the ELF file, but I can not found the "vtable" or something like this.

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

Upvotes: 6

Views: 2117

Answers (2)

taehwan legen
taehwan legen

Reputation: 1

correction note: corresponding segment is LOADed in memory. -> corresponding segment is loading it in memory. because segment is concept for in-memory, not for executable. I'm afraid there's some confusing parts when people read it to get help.

Here's additional detail as request: https://i.sstatic.net/mXVVX.png

Upvotes: -1

Ajay
Ajay

Reputation: 53

virtual table is stored in the section .rodata of ELF file and its corresponding segment is LOADed in memory.

Upvotes: 2

Related Questions