4

I am referring to Broken Thorn's OS development tutorial. I am currently at the stage of executing the second stage bootloader to load the GDT and enter protected mode.

I understood how the GDT works and how to enter into protected mode. However, my confusion is with the first instruction executed after loading the cr0 register:

jmp 08h:Stage3      ; far jump to fix CS. Remember that the code selector is 0x8!

At this point, CS has not been loaded with a selector value that points to the code descriptor, and we are already in protected mode. This CS value could be different than the value being used to execute real mode instructions, and hence adding value of IP would also result in an address different from that of the jmp. So wouldn't this result in the execution of some garbage code based on the value of CS ? Or is there something I am missing ?

Cygnus
  • 3,222
  • 9
  • 35
  • 65

1 Answers1

5

Every segment selector has shadow part which contains its actual base address. This hidden part is updated during segment loading instructions.

That means that before the far jump or some other instruction loading cs has been executed, it still has the base address set in real mode and eip offset is calculated relatively to it.

Read: Intel Software Developer Manual, vol.3, ch.3.

qwm
  • 1,005
  • 8
  • 10
  • The docs say the shadow register is used to hold the actual value of the descriptor (base address, limit, access bits etc). Thus, all of this is anyway loaded before I do the jmp. Now adding value of eip to the base address could result in a different address than that of the jmp, isn't that right ? – Cygnus Jan 27 '14 at 17:02
  • @Cygnus How can it be different? `mov` to `cr0` has been executed at address (`shadow cs base address` + `eip`) and so `eip` is incremented to point to the next instruction which is `jmp` in your code. As `shadow cs base address` hasn't been changed ('cause no `cs` loading instruction executed) that `jmp` is indeed instruction that's gonna be executed next -) – qwm Jan 28 '14 at 09:18
  • Yes, I understood that now. But, what are the contents of the shadow registers in real mode ? Because to execute the jmp (which will be in protected mode), the processor will check the access rights and segment limits from the shadow register which would have the same value as in real mode ? – Cygnus Jan 28 '14 at 17:29
  • @Cygnus `limit = 0xffff`, `flags = present, r/w, accessed`, `base = cs<<4`. Intel SDM, vol.3, ch. 9 & 20. – qwm Jan 28 '14 at 19:30