Interrupts, Traps, and Exceptions: Asynchronous vs. Synchronous Events
Interview Question: "What is the architectural difference between an interrupt, a trap, and an exception? In x86 architecture, how does the saved instruction pointer (
RIP) behave differently across faults, traps, and aborts?"
Whenever an operating system kernel wrests control of the CPU from a user program, the transfer occurs through one of three architectural vectors: Interrupts, Traps, or Exceptions.
The defining systems distinction hinges on two fundamental properties: Synchronicity (whether the event was triggered by the active instruction stream) and Intent (whether the event was deliberate or accidental).
The ELI5 Analogy: The Student Taking an Exam
Imagine a student (the Process) seated in a quiet exam hall, solving calculus problems on paper (executing instructions on the CPU):
- The Interrupt (External & Unrelated): The building's fire alarm blares, or a phone vibrates in their pocket. It has zero relationship to the calculus equation the student is currently writing. It was generated by an external physical device, forcing them to pause.
- The Exception (Internal & Accidental): The student attempts to divide by zero on their calculator, or writes on a page that is torn in half. Execution cannot continue because of an unhandled error inside the active step itself. The student raises their hand in distress for the proctor (the OS) to intervene.
- The Trap (Internal & Deliberate): The student finishes the first section and needs to visit the restroom. They intentionally pause, raise their hand, and politely ask the proctor for permission (a System Call). It is a planned, intentional handover of control.
The Processor Taxonomy: Synchronous vs. Asynchronous
CPU EVENT TAXONOMY
│
┌──────────────────────────────┴──────────────────────────────┐
▼ ▼
[ ASYNCHRONOUS EVENTS ] [ SYNCHRONOUS EVENTS ]
(External Hardware) (Current CPU Instruction)
│ │
INTERRUPTS EXCEPTIONS & TRAPS
├── Maskable (INTR pin, CLI/STI) │
└── Non-Maskable (NMI pin: ECC parity) ┌─────────────────┼─────────────────┐
▼ ▼ ▼
FAULTS TRAPS ABORTS
(Restartable: (Intentional: (Fatal crash:
Page Fault) Syscall, INT3) Double Fault)
1. Hardware Interrupts (Asynchronous)
An electrical signal generated by external hardware components, independent of the CPU instruction pipeline:
- Maskable Interrupts (
INTRpin): Device interrupts (keyboard keystrokes, network packet arrival, disk I/O completion). The OS kernel can temporarily disable them during critical kernel code execution using theCLI(Clear Interrupt Flag) instruction, clearing theIFbit inRFLAGS. - Non-Maskable Interrupts (
NMIpin): High-priority hardware events that cannot be masked or ignored by software. Reserved for hardware emergency conditions, such as ECC RAM parity errors, bus errors, or chipset temperature warnings. - Return Behavior: The saved instruction pointer (
RIP) pushed onto the stack points to the next instruction that was about to execute when the interrupt arrived.
2. Exceptions: Faults, Traps, and Aborts (Synchronous)
Exceptions are generated internally by CPU microcode during the execution of an instruction. They are strictly synchronous—executing the same instruction with the same register state will trigger the exact same exception every time.
Intel and AMD architectures divide exceptions into three distinct subclasses:
A. Faults (Recoverable Errors)
- Definition: An exceptional condition detected before or during the execution of an instruction that can potentially be corrected by the OS.
- Critical Architectural Behavior: The CPU pushes the memory address of the faulting instruction itself as the return
RIP! - Why this is essential (The Page Fault): When a thread dereferences a virtual address that has not yet been loaded into RAM (Vector 14: Page Fault), the CPU halts. The OS page fault handler allocates a physical RAM frame, reads the missing 4KB page from disk, and executes
iret. BecauseRIPpoints to the original faulting instruction, the CPU seamlessly re-executes the exact same instruction, this time succeeding without error!
B. Traps (Deliberate Software Transfers)
- Definition: An intentional invocation of the kernel initiated by an explicit software instruction.
- Critical Architectural Behavior: The CPU pushes the memory address of the subsequent instruction (the instruction immediately following the trap) as the return
RIP. - Use Cases:
- System Calls (
syscall/int 0x80): User programs intentionally trap into Ring 0 to request privileged kernel operations (e.g.,read(),write()). - Debugger Breakpoints (
int 3): Compilers insert the single-byte0xCC(INT 3) instruction to transfer control to a debugger (GDB). When resumed, execution continues at the next instruction.
- System Calls (
C. Aborts (Severe Unrecoverable Failures)
- Definition: Severe, catastrophic hardware errors or inconsistent system states.
- Critical Architectural Behavior: The return
RIPis undefined; the process or system cannot be restarted. - Examples: Double Fault (Vector 8, occurring when an exception happens while trying to invoke the handler for a prior exception) or Machine Check Exception (Vector 18). Results in an immediate process crash or Kernel Panic.
The Interrupt Descriptor Table (IDT)
In x86 architectures, the CPU vectors all interrupts and exceptions through a 256-entry table in memory called the Interrupt Descriptor Table (IDT), registered via the LIDT instruction:
| Vector Range | Assigned Purpose | Specific Examples |
|---|---|---|
0 – 31 | Architecture-Reserved Exceptions | 0: Divide-by-zero, 1: Debug, 3: Breakpoint (INT 3), 8: Double Fault, 13: General Protection Fault, 14: Page Fault |
32 – 255 | User-Defined Interrupts & Syscalls | 32: Local APIC Timer Interrupt, 33: Keyboard Controller, 128 (0x80): Legacy 32-bit Linux System Call |
Comprehensive Comparison Matrix
| Dimension | Interrupt (Hardware) | Trap (Software) | Exception (Fault) |
|---|---|---|---|
| Trigger Origin | External physical hardware (Timer, NIC, Disk) | Programmatic instruction (syscall, INT 3) | CPU microcode error detection (MMU, ALU) |
| Timing | Asynchronous (Unrelated to instruction) | Synchronous (Deterministic instruction) | Synchronous (Deterministic instruction) |
| Intent | Informational / Notification | Deliberate (Intentional request) | Accidental (Error or boundary condition) |
Saved RIP | Points to next instruction | Points to next instruction | Points to faulting instruction itself (for re-execution) |
| Maskability | Yes (via CLI / STI for maskable lines) | No (Software instruction cannot be masked) | No (CPU must handle immediately) |
Summary
"An interrupt is an asynchronous signal from external hardware (such as a timer or network card) that points the return RIP to the next instruction. A trap is an intentional synchronous instruction (such as a system call or breakpoint) used by software to enter kernel mode, also resuming at the next instruction. An exception is an accidental synchronous CPU error where faults save the RIP of the faulting instruction itself to permit re-execution after kernel remediation (as in page faults), while aborts signal unrecoverable system termination."
Python Verification: Traps, Exceptions & Interrupts Simulation
The following executable Python script models the hardware execution pipeline, demonstrating how the CPU distinguishes between synchronous exceptions (faults with instruction retry), deliberate software traps, and asynchronous interrupts:
"""
CPU Interrupt, Trap, and Exception Dispatcher Simulator
Demonstrates:
1. Synchronous Fault recovery with instruction re-execution (Page Fault)
2. Intentional Software Trap dispatch (Syscall)
3. Asynchronous Hardware Interrupt handling
"""
from typing import List, Dict, Any
class Instruction:
def __init__(self, op: str, arg: Any = None):
self.op = op
self.arg = arg
def __repr__(self):
return f"{self.op}({self.arg})" if self.arg is not None else self.op
class CPUExecutionPipeline:
def __init__(self, code: List[Instruction]):
self.code = code
self.rip = 0 # Instruction Pointer
self.page_table: Dict[int, str] = {} # Virtual Page -> Physical Frame
self.interrupt_pending = False
self.execution_log = []
def trigger_hardware_interrupt(self):
self.interrupt_pending = True
def run(self):
while self.rip < len(self.code):
# Check for Asynchronous Hardware Interrupts BEFORE fetching instruction
if self.interrupt_pending:
self.execution_log.append(f"[ASYNCHRONOUS INTERRUPT] Timer IRQ caught! Saved RIP = {self.rip}")
self.interrupt_pending = False
# Interrupt resumes at the exact same RIP after ISR
instr = self.code[self.rip]
self.execution_log.append(f"Executing [RIP={self.rip}]: {instr}")
# 1. Intentional Software Trap (System Call)
if instr.op == "SYSCALL":
self.execution_log.append(f" -> [SOFTWARE TRAP] Entering Ring 0 for {instr.arg}. Next RIP = {self.rip + 1}")
self.rip += 1 # Traps resume at NEXT instruction
# 2. Synchronous Fault (Page Fault)
elif instr.op == "ACCESS_MEM":
page = instr.arg
if page not in self.page_table:
self.execution_log.append(f" -> [SYNCHRONOUS FAULT] Page Fault on page {page}! Saved RIP = {self.rip}")
# OS Page Fault Handler allocates frame
self.page_table[page] = f"Frame_0x{page:04X}"
self.execution_log.append(f" -> OS loaded {page} into {self.page_table[page]}. Re-executing instruction at RIP={self.rip}!")
# DO NOT increment RIP! Re-execute the exact same instruction!
else:
self.execution_log.append(f" -> Resolved memory address in {self.page_table[page]}.")
self.rip += 1
else:
self.rip += 1
def main():
print("=== CPU Interrupt, Trap & Exception Dispatch Simulation ===\n")
program = [
Instruction("LOAD_REG", "RAX"),
Instruction("ACCESS_MEM", 42), # Triggers Page Fault first time, re-executed
Instruction("SYSCALL", "sys_write"), # Software Trap
Instruction("ADD", 5),
]
cpu = CPUExecutionPipeline(program)
# Simulate an external hardware timer firing mid-execution
cpu.trigger_hardware_interrupt()
cpu.run()
for entry in cpu.execution_log:
print(entry)
print("\nVerification: Page Fault re-executed RIP=1; Syscall advanced to RIP=3; Timer paused pipeline.")
if __name__ == "__main__":
main()