Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position-independent code and vtable

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 know 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.

like image 601
anatolyg Avatar asked Mar 21 '11 12:03

anatolyg


1 Answers

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).
like image 122
Simon Richter Avatar answered Sep 20 '22 07:09

Simon Richter