FS and GS in x86-64: What Remains of Segmentation

This post started with a small question I ran into while working on a personal project that deals with x86-64 assembly: is a push fs followed by a pop fs really harmless? It isn’t, and finding out why took me back to a corner of x86-64 that I had been reading in disassembly for years without really understanding. I was used to seeing addresses such as fs:0x28, but I had never asked a more basic question: why can FS take part in address calculations when CS, DS, ES and SS seem to have been retired?

The short answer is that FS and GS sit at the intersection of two stories: x86’s legacy segmentation mechanism and a set of features that remain useful in 64-bit mode. While most of the traditional segmentation machinery no longer affects ordinary address calculations, their base addresses still do, which makes them handy for reaching data tied to a context, such as a thread in user space or a CPU in the kernel.

In this post, we’ll look at what remains of segmentation in x86-64 and why FS and GS are the exception, how their bases are managed, and how they are used in practice: thread-local storage (TLS), stack-protector canaries and swapgs in kernel code. We’ll close with the pop fs pitfall that started all this, which shows why a segment selector and its base are not the same thing.

A Brief Introduction to Segmentation

Segmentation has been part of the x86 architecture since the Intel 8086 and 8088. These 16-bit processors could address a 1 MiB physical address space by combining a 16-bit segment value with a 16-bit offset. The 8086 has four segment registers, each with a default use:

RegisterNameDefault use
CSCode SegmentInstruction fetches
DSData SegmentMost data accesses
SSStack SegmentStack accesses
ESExtra SegmentDestination of string operations

In real mode (the only mode of the 8086), the address is calculated as follows:

$$\text{Physical address} = (\text{Segment} \times 16) + \text{Offset}$$

The segment value determines the starting address of a 64 KiB region, while the offset identifies a location within that region. Since successive segment bases are only 16 bytes apart, these regions can overlap.

The model evolved significantly with the introduction of protected mode on the 80286 and its subsequent extension on the 80386. The latter brought 32-bit protected-mode addressing and paging, and introduced the FS and GS segment registers.

In protected mode, memory addressing works differently. Instead of directly providing a segment base, a segment register holds a segment selector that identifies a descriptor in either the Global Descriptor Table (GDT) or the Local Descriptor Table (LDT). This descriptor contains information about the segment, including its base address, limit, type, and access rights.

The 16-bit selector itself has three fields: a 13-bit index into the table, a table indicator (TI) bit that chooses between the GDT and the LDT, and a 2-bit requested privilege level (RPL).

Segment selector layout: a 13-bit index in bits 15 to 3, the table indicator bit (0 = GDT, 1 = LDT) in bit 2, and the requested privilege level (RPL) in bits 1 to 0
Extracted from Intel Software Developer’s Manual (SDM), Vol. 3A, Figure 3-6

A logical address consists of a segment selector and an offset. The processor uses the selector to locate the corresponding descriptor, performs the applicable access and limit checks, and combines the segment base with the offset to produce a linear address.

Logical address to linear address translation: the segment selector picks a descriptor in the GDT or LDT, whose base address is added to the offset
Extracted from Intel SDM, Vol. 3A, Figure 3-5

Segmentation and paging are separate mechanisms that can work together. Segmentation translates a logical address into a linear address, while paging translates that linear address into a physical address. Although paging provides the foundation for modern virtual memory, segmentation remains part of the architecture.

In practice, operating systems commonly use a flat memory model. Rather than assigning different base addresses to code, data and stack segments, they configure their descriptors with a base address of zero and a limit covering the 32-bit linear address space. As a result, the offset effectively becomes the linear address, and segmentation no longer divides memory into distinct regions for ordinary address calculations. Paging can then map the linear address space to physical memory independently.

What Remains in x86-64?

Long mode introduces a different approach to segmentation, but it is important to distinguish between its two submodes: 64-bit mode and compatibility mode. The latter allows existing 16-bit and 32-bit applications to run while retaining the traditional protected-mode segmentation behavior. The changes described below apply specifically to 64-bit mode.

In 64-bit mode, the flat model is no longer just a convention but a rule enforced by the hardware: the bases of CS, DS, ES and SS are treated as zero and segment-limit checks are not performed. These registers therefore no longer influence ordinary address calculations.

CS, however, is not unused. Its descriptor attributes, particularly the L bit, determine whether execution takes place in 64-bit mode or compatibility mode when long mode is active, and the low two bits of its selector hold the current privilege level (CPL). Switching between the two submodes involves loading an appropriate code-segment descriptor through a suitable control transfer. What CS no longer does is contribute a base to address calculations.

Segmentation has therefore largely disappeared from ordinary memory addressing in 64-bit mode, but it has not disappeared entirely. The Intel manual describes the exception this way:

The exceptions are the FS and GS segments, whose segment registers (which hold the segment base) can be used as additional base registers in some linear address calculations.

Intel SDM, Vol. 1, section 3.7.4.1

This makes FS and GS useful for accessing thread-specific data and operating-system data structures. The table below summarizes the situation for all six segment registers:

RegisterBase in 64-bit modeRole in 64-bit mode
CSTreated as 0Selects 64-bit or compatibility mode (L bit) and holds the current privilege level
DS, ES, SSTreated as 0No effect on address calculations
FS, GSUsedAdded to the address of any fs: or gs: memory operand

FS and GS: Selectors vs. Base Addresses

Each segment register has a visible part and a hidden part, sometimes referred to as a descriptor cache. The visible part holds a 16-bit segment selector, while the hidden part contains the segment’s base address, limit and access-control information.

Segment registers: a visible 16-bit selector and a hidden part holding the base address, limit and access information
Extracted from Intel SDM, Vol. 3A, Figure 3-7

When a selector that identifies a descriptor is loaded into a segment register, the processor also loads the corresponding information from that descriptor into the hidden state. Caching this information allows the processor to use it without having to retrieve the descriptor from memory for every access.

Consider the following instruction:


mov rax, [fs:0x28]

The fs: prefix tells the processor to use the FS.base when calculating the memory address. In this example, the effective address is simply the displacement 0x28, so the processor reads eight bytes from the linear address FS.base + 0x28 and loads the resulting value into rax.

More generally, for a memory operand using an FS segment override, the linear address is calculated as follows:

$$\text{Linear Address} = \text{FS.base} + \text{Effective Address}$$

The same principle applies to GS-based memory operands, using GS.base instead.

FS.base and GS.base are full 64-bit values, but they can be set in two very different ways. Loading a non-null selector (mov fs, ax, pop fs) makes the processor read a descriptor from the GDT or LDT, and such a descriptor holds only a 32-bit base. To install a full 64-bit base, software writes it directly: through the IA32_FS_BASE / IA32_GS_BASE MSRs, the fsgsbase instructions, or arch_prctl on Linux. Keep this distinction in mind; it is the key to the pitfall at the end of the post.

A Few Instructions Involving FS and GS

x86-64 provides several instructions that interact with FS and GS, but they do not all operate on the same architectural state. Here are a few examples:

  • mov ax, fs: Reads the visible 16-bit segment selector into ax.
  • mov fs, ax and pop fs: Load a selector and reload the hidden state from the descriptor it names.
  • mov rax, [fs:0x28]: Reads eight bytes from the linear address FS.base + 0x28 and loads the result into rax.
  • swapgs: Swaps GS.base with IA32_KERNEL_GS_BASE (more on this later).

These examples illustrate four distinct operations: reading a selector, loading a selector, accessing memory through a segment base, and exchanging GS.base state.

Let’s look at how software can read and configure these bases directly.

Reading and Writing FS.base and GS.base

The fsgsbase instruction family, available on newer x86-64 processors, reads and writes the FS and GS bases directly:

  • rdfsbase rax: Reads FS.base into rax.
  • rdgsbase rax: Reads GS.base into rax.
  • wrfsbase rax: Sets FS.base to the value in rax.
  • wrgsbase rax: Sets GS.base to the value in rax.

These instructions are not available on every processor: the CPU must report the FSGSBASE feature, and the operating system must enable them by setting bit 16 of CR4 (CR4.FSGSBASE). Linux has enabled them by default since 5.9, in commit b745cfba44c1.

Linux also provides the arch_prctl(2) syscall for accessing these bases. Its relevant operations are:

  • ARCH_GET_FS and ARCH_SET_FS
  • ARCH_GET_GS and ARCH_SET_GS

The ARCH_GET_* operations retrieve the corresponding base, while ARCH_SET_* configure it. The C library uses ARCH_SET_FS to set the base of the initial thread, and passes CLONE_SETTLS to clone for each new thread.

Finally, the processor exposes the bases through the IA32_FS_BASE (0xC0000100) and IA32_GS_BASE (0xC0000101) MSRs, which can be accessed with the rdmsr and wrmsr instructions. Both are privileged (ring 0 only), so ordinary user-space applications cannot use them directly.

FS and GS in Practice on Linux x86-64

Now that we understand how FS and GS work and how their base addresses can be configured, let’s look at some practical examples.

We’ll start with thread-local storage, then look at how compilers use FS-based addressing to implement stack protection. After that, we’ll move into the Linux kernel to see why swapgs is needed. Finally, we’ll go back to push fs and pop fs.

Thread-Local Storage

TLS allows a variable to have a separate instance for each thread. This means that multiple threads can access a variable with the same name without sharing the same underlying instance.

Consider the following example on Compiler Explorer:


#include <pthread.h>
#include <stdio.h>

__thread int var_per_thread = 0;

static void *worker(void *arg)
{
    var_per_thread = *(int *)arg;
    printf("Thread-local value: %d\n", var_per_thread);
    return NULL;
}

int main(void)
{
    pthread_t t1, t2;
    int a = 10, b = 20;

    if (pthread_create(&t1, NULL, worker, &a) != 0)
        return 1;

    if (pthread_create(&t2, NULL, worker, &b) != 0) {
        pthread_join(t1, NULL);
        return 1;
    }

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    return 0;
}

Here, both threads access var_per_thread, but each has its own instance of the variable. One thread assigns it the value 10, while the other assigns it 20.

How does the processor know which instance to access?

On Linux x86-64, the compiler and runtime can use FS-relative addressing to access thread-local variables. To see it, compile the example and inspect the worker function with:


gcc -std=c11 -O0 -fno-pie -no-pie -pthread tls.c -o tls
objdump -d -M intel --disassemble=worker tls

The -fno-pie -no-pie flags keep the generated code simple by letting the compiler use the most direct TLS access model. The same output is available in the Compiler Explorer link above. The function looks like this:


worker:
    push   rbp
    mov    rbp, rsp
    sub    rsp, 0x10
    mov    QWORD PTR [rbp-0x8], rdi
    mov    rax, QWORD PTR [rbp-0x8]
    mov    eax, DWORD PTR [rax]
    mov    DWORD PTR fs:0xfffffffffffffffc, eax    ; var_per_thread = *(int *)arg
    mov    eax, DWORD PTR fs:0xfffffffffffffffc    ; read var_per_thread for printf
    mov    esi, eax
    mov    edi, 0x402004
    mov    eax, 0x0
    call   401030 <printf@plt>
    mov    eax, 0x0
    leave
    ret

Both accesses to var_per_thread go through FS. The displacement 0xfffffffffffffffc is simply -4 displayed as an unsigned 64-bit value, so the effective address is FS.base - 4. The exact instruction and displacement depend on the compiler, linker and TLS model.

The important point is that the processor knows nothing about threads or TLS: it only computes FS.base plus an offset. The meaning comes from software. When a thread is created, the C library allocates its thread control block (TCB) and the kernel is asked to point FS.base at it, via arch_prctl(ARCH_SET_FS) or clone with CLONE_SETTLS. The kernel then restores that base every time the thread is scheduled. On x86-64 the thread’s TLS variables sit just below FS.base, hence the negative displacement, while the TCB itself starts at FS.base and extends upward, which is why fs:0x28 shows up in the next example.

Stack-Protector Canary

FS-based addressing is also used by compiler-generated security mechanisms. One example is the stack-protector canary, which helps detect certain stack-buffer overflows.

Consider this program on Compiler Explorer:


#include <stdio.h>
#include <unistd.h>

int main(void)
{
    char buf[20];

    ssize_t n = read(STDIN_FILENO, buf, sizeof(buf) - 1);
    if (n < 0) {
        perror("read");
        return 1;
    }

    buf[n] = '\0';
    printf("Printing the string %s\n", buf);

    return 0;
}

The program reads at most 19 bytes into a 20-byte buffer and terminates the string. The input is deliberately bounded; our goal here is to inspect the code generated by the compiler, not to exploit a buffer overflow.

We can enable stack protection explicitly using GCC’s -fstack-protector-strong flag:


gcc -O0 -fstack-protector-strong -fno-pie -no-pie canary.c -o canary
objdump -d -M intel --disassemble=main canary

When inspecting the assembly, we should find instructions that read the stack guard through FS. In the common GNU/Linux x86-64 environment using glibc, they look like this (the full output is in the Compiler Explorer link above):


main:
    push   rbp
    mov    rbp, rsp
    sub    rsp, 0x30
    mov    rax, QWORD PTR fs:0x28         ; read the stack guard...
    mov    QWORD PTR [rbp-0x8], rax       ; ...and keep a copy in the frame
    xor    eax, eax
    ...
    mov    rdx, QWORD PTR [rbp-0x8]
    sub    rdx, QWORD PTR fs:0x28         ; compare the copy with the guard
    je     4011dc <main+0x86>
    call   401030 <__stack_chk_fail@plt>
    leave
    ret

The prologue copies the value at fs:0x28 into the stack frame; the epilogue compares that copy with fs:0x28 again and calls __stack_chk_fail if they differ.

Notice that the offset 0x28 is not defined by the x86-64 architecture. It is a convention used by the relevant software environment: in the glibc x86-64 thread-control-block layout, this offset contains the stack guard. The compiler-generated code and runtime agree on the location, allowing the guard to be accessed efficiently through FS.

This is another example of the distinction we established earlier: the processor knows how to calculate an address using FS.base + 0x28, but the meaning of the value stored there comes from the software using it.

swapgs in the Linux Kernel

So far, we have looked at FS-based addressing in user space. GS has an important role in the Linux kernel, where it is used to access per-CPU data.

To understand why swapgs exists, let’s look at the syscall entry path in the Linux x86-64 kernel. When the syscall instruction enters the kernel, it does not switch stacks and does not touch GS: every register still holds user-space values, and GS.base is whatever user space set. The kernel needs a pointer to its per-CPU data before it can even save anything.

swapgs (privileged, so only usable in ring 0) solves this by exchanging the active GS.base with the value stored in the IA32_KERNEL_GS_BASE MSR (0xC0000102), which the kernel preloaded with the CPU’s per-CPU base. This allows the kernel to switch from the user-space GS base to its own without needing a free register or having to load a segment selector.

For example, the Linux kernel’s entry_SYSCALL_64 path includes the following sequence:


SYM_CODE_START(entry_SYSCALL_64)
	UNWIND_HINT_ENTRY
	ENDBR

	swapgs
	/* tss.sp2 is scratch space. */
	movq	%rsp, PER_CPU_VAR(cpu_tss_rw + TSS_sp2)
	...

PER_CPU_VAR(x) expands to a GS-relative operand (%gs:x(%rip)), so this store goes to the current CPU’s data through the GS.base that swapgs just installed.

When returning to user space, the appropriate exit path switches the bases back so that user-space execution resumes with its original GS.base. The exact handling depends on the entry and exit path; swapgs is not something the processor executes automatically on every transition into the kernel.

Back to the Trigger: push fs and pop fs

At the start of this post I asked whether a push fs followed by a pop fs is really harmless. Now we have what we need to answer it, and the answer lies in the distinction between the visible selector and the hidden base.

At first glance, push fs and pop fs might seem like ordinary save-and-restore instructions. We push the FS register onto the stack, then pop it back. Shouldn’t that leave FS unchanged?

The problem is that push fs saves the visible segment selector, not the full 64-bit FS.base.

In 64-bit mode, the selector is zero-extended to the stack operand size when pushed. In a typical Linux x86-64 user-space process, the FS selector is zero, while FS.base points to the thread’s thread-control-block area.

Consider the following experiment:


#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>

int main(void)
{
    unsigned short selector;
    uintptr_t before, after;

    __asm__ volatile("mov %%fs, %0" : "=r"(selector));
    __asm__ volatile("rdfsbase %0" : "=r"(before));

    __asm__ volatile("push %%fs\n\tpop %%fs" ::: "memory");

    __asm__ volatile("rdfsbase %0" : "=r"(after));

    /* Restore FS.base before calling library functions. */
    __asm__ volatile("wrfsbase %0" :: "r"(before) : "memory");

    printf("FS selector = 0x%x, base before = 0x%" PRIxPTR
           ", after pop fs = 0x%" PRIxPTR "\n",
           selector, before, after);

    return 0;
}

You can build and run it with:


gcc -std=c11 -O0 pop_fs.c -o pop_fs
./pop_fs

This example requires a processor that supports fsgsbase and an operating system that has enabled it. The program also restores the original FS.base before calling printf, because the C runtime may rely on FS-based TLS.

On my AMD Ryzen 7 5700U running Linux 7.0.0-38-generic, the result was:


FS selector = 0x0, base before = 0x779095959740, after pop fs = 0x0

The important observation is that push fs does not change the base, but pop fs reloads the saved null selector. On this processor, loading the null selector clears FS.base. Without the restore in the program above, the next library operation that accesses TLS would read from an address near zero and fault. This is what happens step by step:

StepHidden FS.baseWhat wrote it
Process startup0x7790…9740C library at startup, via arch_prctl(ARCH_SET_FS) (selector stays 0)
mov rax, [fs:0x28]uses 0x7790…9740No table lookup
pop fs (pops 0)0Selector load: refilled from the null selector
mov rax, [fs:0x28]uses 0Address 0x28: crash

This behavior illustrates why the architectural details matter. Loading a segment selector is not simply a write to the visible 16-bit value: it invokes the segment-register loading semantics, which refill the hidden state. There is no descriptor the processor could refill the base from, because a descriptor holds a 32-bit base at most, and a value such as 0x779095959740 does not fit in it. The base was written directly, so a selector load can only erase it. This is also why the kernel saves and restores the FS base explicitly on every context switch.

The precise treatment of a null selector has varied across processor implementations. Some AMD CPUs historically left the base untouched on a null-selector load, a quirk Linux tracks as X86_BUG_NULL_SEG (“nulling a selector preserves the base”). The Ryzen used here is a Zen 2 part, which clears it, and Linux does not flag Intel CPUs with this bug. Treat the result above as the behavior observed on the tested system.

In practice, compilers do not emit segment-register loads in 64-bit user code, and doing so natively crashes the program unless it restores the base itself. The lesson is straightforward: saving and restoring a segment selector is not equivalent to saving and restoring its base address.

Conclusion

So why do FS and GS still work when CS, DS, ES and SS don’t? Because in 64-bit mode the processor forces those four bases to zero, while FS.base and GS.base remain real, writable 64-bit values that are added to the effective address of any fs: or gs: operand. The processor adds the hidden base, not the 16-bit selector. That single addition is enough for the operating system to give each thread its TLS block (FS in user space) and each CPU its per-CPU area (GS in the kernel), with swapgs switching bases on kernel entry.

The same split between selector and base is what made pop fs dangerous: it reloads the hidden state from a descriptor and, on the tested CPU, replaces the base with zero. If you need to preserve FS.base, save and restore it explicitly with rdfsbase/wrfsbase, arch_prctl or the MSR.

References