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 containing the addresses of all virtual functions and stores a pointer to vtable in every object of my class.

Now, if my code is position-independent, the compiler cannot know the addresses of virtual functions (or any function, for that matter). So what is he doing?

I would like to know what real compilers do (and not what is theoretically possible); I'm most interested in 32-bit Linux platforms, but other platforms are also a little interesting.

+6
c ++ gcc virtual-functions dynamic-linking vtable
source share
3 answers

There are two options:

  • accept that your vtable will not be position-independent and try to move it away from the code section so that all code that needs dynamic linking corrections lives next to each other to reduce the number of inconspicuous pages. gcc does this .
  • use relative jumps in the vtable. I don’t know of any implementation that does this, and only works as long as the vtable lives with a fixed offset from the method implementation, and they cannot be overridden at boot time (that they can be in typical ELF systems).
+7
source share

I suggest you write some sample programs and study them yourself, for example, using IDA Pro. Download the free version or the demo version .

-one
source share

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

-one
source share

All Articles