Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

thread fs segment register switching between user and kernel land

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?

like image 259
user2153720 Avatar asked Oct 05 '22 18:10

user2153720


1 Answers

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.

like image 50
Alexey Frunze Avatar answered Oct 26 '22 05:10

Alexey Frunze