5

I've found MSDN documentation on the purpose of the FS register:

https://msdn.microsoft.com/en-us/library/ms253960(v=vs.90).aspx

which states that:

"In an x86 environment, the FS register points to the current value of the Thread Information Block (TIB) structure."

But I cannot seem to find any rigorous documentation of the purpose of the GS register in a Windows based environment.

Can someone tell me where to look, or give an explanation?

Shuzheng
  • 11,288
  • 20
  • 88
  • 186
  • 2
    Pretty much the same thing. See e.g. [this](http://stackoverflow.com/questions/6611346/how-are-the-fs-gs-registers-used-in-linux-amd64) and [this](https://github.com/wishstudio/flinux/wiki/Difference-between-Linux-and-Windows). – Michael Aug 25 '16 at 05:39
  • @Michael: I looked, but I don't see an answer to this question in either of them. So Windows uses `FS` for the TIB, but what about `GS`? Does it hold anything useful for user-space? A quick google found that [`GS` holds the TIB reference on x86-64 Windows](https://en.wikipedia.org/wiki/Win32_Thread_Information_Block), which seems odd since `swapgs` makes it less convenient for the kernel to modify the user-space value of `gs`. (Linux uses `fs` for TLS for this reason, IIRC). But anyway, then the question is, what's the other segment register used for on 64-bit Windows? – Peter Cordes Aug 25 '16 at 06:18
  • 1
    The usage of FS and GS on Windows is an implementation detail and intentionally undocumented. If I remember correctly, reverse engineering suggests that on 32-bit Windows, FS holds a pointer to the TIB/TEB while GS either holds a pointer to thread-local storage (TLS) or is not used at all. On 64-bit Windows, GS points to the TIB/TEB. Why do you need to know this information? What problem are you trying to solve? – Cody Gray - on strike Aug 27 '16 at 14:34

1 Answers1

17

On 32 bit Windows GS is reserved for future use.
The FS segment points to the Thread information block.

In x64 mode the FS and GS segment registers have been swapped around.

In x86 mode FS:[0] points to the start of the TIB, in X64 it's GS:[0].
The reason Win64 uses GS is that there the FS register is used in the 32 bit compatibility layer (confusingly called Wow64).
Because 32-bit apps use FS the bookkeeping for Win64 is simplified.
32 bit applications never cause GS to be altered and 64 bit applications never cause FS to be altered.

Note that the fact that GS is non-zero in Win64 and Wow64 can be used to detect if a 32-bit application is running in 64-bit Windows.
In a 'true' 32 bit Windows GS is always zero.

Johan
  • 74,508
  • 24
  • 191
  • 319