开发者

Position-independent code and vtable

开发者 https://www.devze.com 2023-02-17 22:50 出处:网络
How are virtual functions implemented in position-independent code? I know that if my class has virtual functions, the compiler usually generates a vtable for it that contains addresses of all virtua

How are virtual functions implemented in position-independent code?

I know that if my class has virtual functions, the compiler usually generates a vtable for it that contains addresses of all virtual functions, and stores a pointer to the vtable in each object of my class.

Now, if my code is position-independent, the compiler cannot kno开发者_StackOverflow中文版w addresses of virtual functions (or any function, for that matter). So what does it do?

I would like to know what real compilers do (not what is theoretically possible); i am mostly interested in linux 32-bit platforms but other platforms are slightly interesting too.


There are two options:

  1. accept that your vtable is not going to be position independent, and try to move it away from the code section, so that all code that needs dynamic linking fixups lives next to each other in order to reduce the number of unshareable pages. gcc does this.
  2. use relative jumps in the vtable. I'm not aware of any implementation that does this, and it only works as long as the vtable lives at a fixed offset from the method implementations and these cannot be overridden at load time (which they can be on typical ELF systems).


Basically, a vtable is everywhere implemented as a table of function pointers.


I suggest that you write some example programs and examine them yourself with for example IDA Pro. Download the freeware version or demo version.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号