Position-independent code and vtable
Asked Answered
I

3

8

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.

Infrequency answered 21/3, 2011 at 12:21 Comment(1)
The linker knows, it won't have trouble fixing up the offsets as long as they don't cross module boundaries. Finding one that actually does this would be the harder problem.Demars
A
10

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).
Adnopoz answered 21/3, 2011 at 12:29 Comment(0)
H
0

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

Honourable answered 21/3, 2011 at 12:26 Comment(0)
R
-2

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

Readymix answered 21/3, 2011 at 12:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.