Low-level · C++

From Ring 3 to Ring 0: what happens when your code crosses into the kernel

On this page
  1. A trip you take thousands of times a second
  2. What a privilege ring actually is
  3. Crossing the border: what a syscall is
  4. How much does crossing cost?
  5. Ring 0 doesn't forgive: why a bug there is different
  6. The defenses guarding that border today
  7. Why this should matter to you even if you never write drivers

A trip you take thousands of times a second#

You save a file. You hit Ctrl+S, your editor asks to write to disk, and within microseconds the file is safe. It looks trivial.

It isn't. In that instant your CPU switched worlds: it stopped running your editor's code, an unprivileged program that can't touch the disk directly, and started running code from the operating system's kernel, which can do anything. Then it came back, as if nothing happened. And that occurs thousands of times a second on any computer you use.

That border has a name: the jump from Ring 3 to Ring 0. Understanding it explains why your browser can freeze without taking down the rest of the system, why a faulty driver produces a blue screen, and why in July 2024 millions of Windows machines failed to boot at the same time.

What a privilege ring actually is#

x86 defines four privilege levels, numbered 0 to 3 and traditionally drawn as concentric rings. The lower the number, the more power the code running there has.

In one sentence

Ring 0 is where the kernel lives and has full access to the hardware. Ring 3 is where your applications live, and all they can do is ask the kernel for things.

The CPU knows which ring it's in through the CPL (Current Privilege Level), stored in the two lowest bits of the code segment register. No external table lookup is needed: every instruction carries with it the question of whether whoever is running it is allowed to.

You can check it yourself. This program reads the CS register and keeps those two bits:

cpl.cpp
// g++ -std=c++20 cpl.cpp -o cpl   (Linux x86-64)
#include <cstdint>
#include <format>
#include <iostream>

int main() {
    std::uint16_t cs;
    asm volatile("mov %%cs, %0" : "=r"(cs));
    std::cout << std::format("CS = {:#06x}  ->  CPL = {}\n", cs, cs & 3);
}
output
$ ./cpl
CS = 0x0033  ->  CPL = 3

CPL 3: your program, like every other, lives in the outer ring.

Why does almost nobody use rings 1 and 2? Two practical reasons: the paged memory system only distinguishes two levels (user and supervisor, a single bit), so splitting into more levels adds no real memory protection; and a kernel that only uses two levels ports far better to other architectures such as ARM or RISC-V, where the operating system also works with two: user and kernel (the extra levels are reserved for the hypervisor or firmware).

Ring 3 — user modeRing 0 — kernel mode
Who lives thereYour applicationsThe kernel and its drivers
Memory it can seeOnly its own processAll of system memory
Privileged instructionsForbiddenAllowed
Hardware accessAlways mediated by the kernelDirect
If something fails thereThe process is killedThe whole system goes down

That last row is the one that really matters, and we come back to it at the end.

Crossing the border: what a syscall is#

If your program can't touch the disk, how does it manage to write a file? By asking the kernel. That request is called a system call (syscall), and it's the only legitimate door between the two worlds.

The interesting part is that your program doesn't choose where it jumps to. If it could pick the exact address, any application could try to run arbitrary code in Ring 0. Instead, during boot the kernel configures a special CPU register with the exact address of its own entry point. When a program executes the syscall instruction, the CPU always jumps there, never anywhere else. It's a door with a single lock, and the kernel holds the key, not the caller.

The trip, simplified, is always the same:

  1. Your program sets up the call's parameters and executes the syscall instruction.
  2. The CPU switches the CPL from 3 to 0 and jumps to the entry point the kernel fixed. The first thing the kernel does on arrival is switch to its own stack: the user stack can't be trusted.
  3. The kernel validates the parameters — it never trusts what comes from Ring 3 — and performs the actual operation.
  4. The kernel returns control, the CPU switches the CPL back to 3, and your program continues as if nothing happened.

Step 3 is the key to the whole system's security: every syscall is a point where the kernel decides whether to trust you or not. That's where file permissions, memory quotas, and process limits get checked. It's the border where a large part of an operating system's security actually lives.

Normally the standard library does this for you (std::cout ends up calling write()), but there's nothing magic about it. Here's a syscall made by hand, without going through any library:

syscall.cpp
// write(1, msg, len) bypassing libc   (Linux x86-64)
#include <cstddef>
#include <string_view>

static long raw_write(int fd, const void* buf, std::size_t len) {
    long ret;
    asm volatile(
        "syscall"
        : "=a"(ret)                              // result in rax
        : "a"(1L), "D"(fd), "S"(buf), "d"(len)   // rax = 1 = SYS_write
        : "rcx", "r11", "memory");               // clobbers rcx, r11
    return ret;
}

int main() {
    constexpr std::string_view msg = "Ring 3 -> Ring 0 -> Ring 3\n";
    raw_write(1, msg.data(), msg.size());
}

Look at the rcx and r11 line: when syscall runs, the CPU stores the return address and the flags there so it can come back later. It's proof that the hardware controls the jump, not your program. And the number 1 isn't an address, it's an index: you tell the kernel what you want, never where to jump.

How much does crossing cost?#

Switching rings isn't free: stacks have to be switched, registers saved and restored and, with modern mitigations, sometimes even page tables switched. You can measure it:

cost.cpp
// g++ -std=c++20 -O2 cost.cpp -o cost   (Linux x86-64)
#include <chrono>
#include <format>
#include <iostream>
#include <unistd.h>
#include <sys/syscall.h>

int main() {
    using clock = std::chrono::steady_clock;
    constexpr int N = 1'000'000;

    auto t0 = clock::now();
    for (int i = 0; i < N; ++i)
        syscall(SYS_getppid);   // round trip to the kernel
    auto t1 = clock::now();

    std::chrono::duration<double, std::nano> ns = t1 - t0;
    std::cout << std::format("{:.0f} ns per syscall\n", ns.count() / N);
}

Depending on your CPU and active mitigations, you'll see somewhere between tens and hundreds of nanoseconds per round trip. A normal function call costs about one nanosecond. That's why high-performance software tries to cross the border as rarely as possible: it batches writes, uses buffers and, in extreme cases, relies on APIs like io_uring that queue many operations with very few syscalls.

Fun fact

The very clock the program uses to measure (std::chrono::steady_clock, which calls clock_gettime() under the hood) almost never enters the kernel. Linux maps a small area called the vDSO into every process, with read-only kernel code and data, so the most frequent calls, like reading the time, are answered without crossing the border.

Ring 0 doesn't forgive: why a bug there is different#

In Ring 3, a memory fault (reading somewhere you shouldn't, say) normally just kills your process. The operating system detects it, frees its resources, and keeps running completely normally.

The same happens if you try to do something reserved for Ring 0. The hlt instruction, which halts the CPU until the next interrupt, is one of them:

hlt.cpp
// g++ hlt.cpp -o hlt   (Linux x86-64)
#include <iostream>

int main() {
    // std::endl flushes, so the line gets out before we die
    std::cout << "Trying 'hlt' from Ring 3..." << std::endl;
    asm volatile("hlt");
    std::cout << "This never gets printed.\n";
}
output
$ ./hlt
Trying 'hlt' from Ring 3...
Segmentation fault (core dumped)

The CPU compares the CPL with the level the instruction requires, sees it's 3, and raises a general protection exception (#GP). The kernel receives it, sees it came from a user process, and terminates it. The rest of the system never notices. That's Ring 3's safety net.

If you compile it on Windows (with MinGW, for example), the result is the same under a different name: the process exits with code 0xC0000096, STATUS_PRIVILEGED_INSTRUCTION.

In Ring 0 there's no such safety net. The kernel is the thing that decides what to do when something goes wrong, so if the fault happens inside the kernel itself — or inside a driver, which runs with the same privileges — there's nobody above it to contain it. The usual response is to stop the machine before the damage spreads: that's a blue screen on Windows (BSOD) or a kernel panic on Linux. It isn't a clumsy decision by the OS: it's the only safe option left.

This is made worse because drivers often run at an elevated IRQL (interrupt request level), where you aren't even allowed to touch pageable memory or take certain kinds of locks. An error that would be a simple crash in user mode can be a much deeper failure in kernel mode.

Real case

In July 2024, a content update to CrowdStrike Falcon's sensor — a driver loaded in Ring 0 on Windows — made the driver read memory outside valid bounds while processing a new configuration file. The result wasn't a simple application error: it was cascading blue screens across millions of machines worldwide, many of them at airports, hospitals, and banks. The incident is the most-cited example of why software running in Ring 0 demands a very different level of rigor than user-space software.

The defenses guarding that border today#

Windows and Linux don't trust that "the kernel never fails." They've layered on defenses over the years, each aimed at a different kind of bug or attack:

  • SMEP (Supervisor Mode Execution Prevention): stops the kernel from executing code that lives in pages marked as user memory. Without this, a bug that redirected kernel execution toward a normal process's data would be far more dangerous.
  • SMAP (Supervisor Mode Access Prevention): the equivalent for reads and writes. The kernel can't touch user memory by accident or outside routines that explicitly know they're handling untrusted data.
  • KASLR (Kernel Address Space Layout Randomization): places the kernel at a different memory address on every boot, so an attacker who knows about a bug can't assume where the code or data they want to reach actually is.
  • KPTI (Kernel Page Table Isolation): almost completely separates the kernel's page tables from each user process's. It was rolled out broadly after Meltdown (2018), a speculative-execution flaw that let Ring 3 code read kernel memory it had no business seeing. If cost.cpp gives you higher numbers than expected, KPTI is one of the suspects: every crossing means switching page tables.
  • Driver signing: on modern Windows, a driver can't load into Ring 0 unless it's digitally signed by a certificate valid for that purpose. It isn't bureaucracy: it's the last gate before letting new code into the ring that doesn't forgive.

None of these defenses make Ring 0 "safe" in an absolute sense. What they do is make it far more expensive to turn an ordinary bug into something exploitable, and in practice that's the difference between a contained incident and a catastrophic one.

Why this should matter to you even if you never write drivers#

Almost no developer writes kernel code day to day, and yet this border affects you constantly:

  • Every time an antivirus, an intrusion detection system, or a monitoring tool says it "requires a kernel component," it's asking to live in Ring 0, with everything that implies if something goes wrong.
  • Windows' Virtualization-Based Security (VBS) and HVCI use an even more privileged level than Ring 0 — the hypervisor — precisely so they can watch over the kernel itself from outside. That ring, informally called Ring -1, has a post of its own.
  • All of modern cloud computing — virtual machines, hardened containers — rests on this same privilege hierarchy pushed one level further down.
Personal note

I learned this the hard way while writing an academic hypervisor as a Windows kernel driver. The first thing you discover in Ring 0 is that your C++ stops being C++: no exceptions, no RTTI, no STL, and every memory allocation comes from a non-paged pool you pick deliberately, because a mistake there doesn't throw an exception: it reboots the machine. The second lesson cost me more: Windows refused to load my driver, even signed and with test mode enabled. Figuring out why forced me to understand how many layers the kernel's integrity chain has (Secure Boot, the certificate type, memory integrity…) and to always work inside a test virtual machine. Since then I see that signature for what it is: the gate that keeps just anyone out of the ring that doesn't forgive.

Next time your editor saves a file without you noticing, you'll know what just happened underneath: your code crossed the most closely guarded border in the operating system, and made it back just in time for you not to notice at all.

References

  1. Intel® 64 and IA-32 Architectures Software Developer's ManualsIntel · intel.com
  2. syscall(2) — Linux manual pageman7.org · man7.org
  3. Page Table Isolation (PTI)Linux kernel documentation · docs.kernel.org

Share

Keep reading

Low-level

Anatomy of a Windows driver: from DriverEntry to the IRP

What happens inside a Windows driver: DriverEntry, IRQL, an IRP's journey, the dispatch table, IOCTLs and why a misused spinlock brings the system down. With real code.

· 12 min

Low-level · Part 3

Ring -2: SMI, SMRAM and RSM, how firmware takes over the CPU below the hypervisor

What lives below the hypervisor: System Management Mode, the firmware code that runs hidden from the OS, and how to check from C++ which protections your firmware declares.

· 12 min

Does your project need to go below the application layer?

Systems software, performance and security on Windows and Linux: diagnostics, custom tooling and low-level code review.

Let's talk→

Comments

Commenting requires a GitHub account. Comments live in GitHub Discussions (SoftDryzz/blog-comments) and are moderated: no promotional links.