How does the fs segment register point to the TEB and KPCR. Are these data structures saved on the threads user and kernel stack? So is it a case of when a thread context switch takes place from user to kernel, the fs segment reg containing a pointer the TEB is saved onto the threads user stack and then the kernel fs segment register which points to the KPCR is loaded back into fs segment register? Is this how the fs segment register points to both TEB and KPCR?
The FS
register has a segment base address associated with it either in the LDT
or in the GDT
(local/global segment descriptor tables). FS
is pretty much an index into the descriptor table and it selects one of segments defined in the table.
When you access memory through FS
(using the FS
segment override prefix in the instruction), you access memory at a virtual address equal to the address in the instruction plus the segment base address.
That segment base address must coincide with the location of the thread-specific control data structures. And so, when a thread is created with its specific control data structures, the base is set to point to that data.
Those locations are different for different threads within the same process because they all share memory and shouldn't step onto each other's structures. A context switch either just updates FS
to point to a different segment or updates the base address of the segment in the descriptor table and then reloads FS
so the change is observed by the CPU.
When a thread transitions from user mode to kernel mode, FS
and what it points to is untrusted from the kernel's POV, and I expect the kernel to reload FS
with a value pointing to the kernel-side thread-specific data structures. On the way back, the user mode FS
should be restored. In reality things may be a little more complicated, but this should give you an idea.
In 64-bit mode you even have the SWAPGS
instruction to quickly exchange the contents of the GS
register, playing a role similar to that of FS
in 32-bit modes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With