当我尝试访问从虚拟基类继承的派生类对象的内存布局时,出现了问题。
编程环境:GNU/Linux 3.19.0-32-generic、x86_64
编译器:gcc 4.8.4
//virtual base class
class Base {
public :
virtual void f() {
cout << "Base::f()" << endl;
}
private:
long x;
};
//derived class
class Derived : public virtual Base {
public:
virtual void f() {
cout << "Derived::f()" << endl;
}
private:
long y;
};
int main() {
typedef void (*FUNC)(void);
Derived d;
//In my machine, sizeof(long) == sizeof(pointers). My code below is neither portable nor concise. You can just read the annotation.
//dereference the first element of the first virtual function table(equals to *(vptr1->slot[0]))
cout << hex << *((long*)*((long*)(&d) + 0) + 0) << endl;
((FUNC)*((long*)*((long*)(&d) + 0) + 0))();//invoke Derived::f()
//dereference the first element of the second virtual function table(equals to *(vptr2->slot[0]))
cout << hex << *((long*)*((long*)(&d) + 2) + 0) << endl;
((FUNC)*((long*)*((long*)(&d) + 2) + 0))();//maybe Derived::f()?
return 0;
}
当我运行代码时,出现“段错误”:
400c12
Derived::f()
400c3c
segment fault
所以我反汇编了可执行文件。
我在 0x400c3c 中找到了函数 <_ztv0_n24_n7derived1fev>:
0000000000400c3c <_ZTv0_n24_N7Derived1fEv>:
400c3c: 4c 8b 17 mov (%rdi),%r10
400c3f: 49 03 7a e8 add -0x18(%r10),%rdi
400c43: eb cd jmp 400c12 <_ZN7Derived1fEv>
400c45: 90 nop
在我的终端中对符号进行分解:
> c++filt _ZTv0_n24_N7Derived1fEv
virtual thunk to Derived::f()
那么 Derived::f() 的虚拟 thunk 是什么?为什么会有它呢?
某些函数的虚拟 thunk 是一个辅助函数,用于修复this
调用实际函数之前的参数。看这个例子:
Derived *d = new Derived();
// d now points to some address, e.g. 0x6eac40
d->f(); // This calls _ZN7Derived1fEv (Derived::f() directly)
Base *b = d;
// b now points to some other address (!), e.g. 0x6eac50
b->f(); // This calls _ZTv0_n24_N7Derived1fEv (the virtual thunk
// of Derived::f()), which subtracts some amount from `this`
// and then jumps to the _ZN7Derived1fEv (Derived::f())
A Base
内存中的对象看起来像这样:
* Pointer to part of Base vtable with Base's virtual functions.
This vtable contains Base::f()
* Data of Base class (variable `x`)
A Derived
内存中的对象看起来像这样:
|> * Pointer to part of Derived vtable with Derived's virtual functions.
|> This vtable contains the Derived::f()
|>
|> |> * Pointer to part of Derived vtable with the same layout as Base vtable.
|> |> This vtable contains the thunk of Derived::f()
|> |>
|> |> * Data of Base class (variable `x`)
| |>
| |> * Data of Derived class (variable `y`)
| |
| \ This is complete Derived object.
| The `d` pointer points at the beginning of this.
|
\ This is the part of Derived object that can act as a Base object.
The `b` pointer points at beginning of this.
PS:现在应该也清楚为什么打电话了_ZTv0_n24_N7Derived1fEv
on the d
指针崩溃。该函数仅在给定时才起作用this
指向内部的指针Derived
对象 - 进入它可以像使用一样的部分Base
object.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)