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:
- 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.
- 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.
精彩评论