The Need for Error Trapping

In an operating system, a single unexpected event—such as a user program attempting to execute an illegal opcode or writing to protected memory—can lead to a total system crash. Error Trapping is the mechanism the OS uses to catch these faults and recover gracefully.

Trapping Illegal Instructions

The Z80 itself does not automatically trap illegal opcodes (machine code bytes that don’t correspond to any instruction). Executing an illegal opcode usually results in unpredictable behavior or a very slow, unintended operation.

The Solution: The Execution Trap Area A simple OS ensures that all unused memory (especially the area designated for user programs) is filled with a known Trap Instruction.

The Trap Instruction: The instruction chosen is typically an unconditional jump back to the OS error handler.

    ORG  9000H            ; Start of the User RAM
    
    ; Fill the area with the trap instruction (JP OS_ERROR)
    FILL_LOOP:
        LD   A, 0C3H      ; Opcode for JP (Unconditional Jump)
        LD   (HL), A      ; Write JP opcode to memory
        INC  HL
        LD   (HL), LOW(OS_ERROR) ; Write low byte of error handler address
        INC  HL
        LD   (HL), HIGH(OS_ERROR); Write high byte of error handler address
        INC  HL
        ; ... (Loop continues until area is filled)

If the CPU ever executes an instruction in an unused area of memory, it immediately jumps to the OS_ERROR routine, preventing a random crash.

Trapping Segmentation Faults

A Segmentation Fault occurs when a user program attempts to access memory outside its allocated space (Part 55) or tries to write to the kernel’s memory.

The Solution: Address Checking Since the Z80 relies on software checks:

  1. System Calls: The OS requires user programs to perform memory writes only through specific system calls.
  2. Boundary Checks: The system call routine checks the address against the KERNEL_START boundary (Part 55). If the address is illegal, the OS traps the error.

The OS Error Handler

When a fault is successfully trapped, the OS_ERROR routine takes over:

  1. Identify Cause: Determine the type of error (e.g., illegal instruction, segmentation fault).
  2. Display Message: Print an error code and the crash address to the screen.
  3. Halt/Terminate: Gracefully terminate the faulty user program and return control to the KERNEL_MAIN loop, ready for the next command.

Advantage: The OS itself never crashes; only the misbehaving user application is terminated.