The Role of the Loader
In a simple Z80 operating system, the loader is the kernel routine responsible for two primary tasks:
- Allocate Memory: Determine a safe, unused area of RAM for the user program.
- Transfer Code: Read the program’s machine code from the storage device (or RAM buffer) into the allocated space.
- Execute: Start the user program.
The Program Loading Routine (Simplified)
This routine assumes the program’s starting address and size are known (e.g., read from a file header).
The Steps:
LOAD_USER_PROGRAM:
; Assume HL = Program Load Address (e.g., 9000H)
; Assume DE = Source Address (e.g., file buffer)
; Assume BC = Program Size (e.g., 2000H)
; 1. Transfer the Code from Source to Destination (LDIR)
LDIR ; High-speed copy of the program code block
; 2. Clean up the Stack (Critical for a safe call)
; We often clear the stack below the user program's entry point.
LD SP, USER_STACK_TOP ; Set the stack pointer to a safe, high address
; 3. Jump to the Program's Entry Point
JP (HL) ; HL still holds the program's starting address (e.g., 9000H)
Returning Control to the Kernel
Once the user program begins, it must eventually return control to the OS.
Method 1: The Exit Call (Preferred)
The user program ends by executing a specific system call (a known RST
or CALL′ address, e.g.,
RST 08H′) defined by the OS.
USER_PROGRAM_END:
RST OS_EXIT_ROUTINE ; Jump to the kernel's dedicated exit handler
The OS_EXIT_ROUTINE then performs cleanup (e.g., closing open files, clearing memory) and jumps back to the KERNEL_MAIN loop.
Method 2: The Direct Jump (Less Safe) The user program executes a direct jump back to the kernel’s main loop address (`JP KERNEL_MAIN′). This is simpler but skips any necessary kernel cleanup.
Program Structure and Relocation
As discussed in Part 19, the user program must either be:
- Fixed/Absolute: Compiled specifically for the address it will be loaded into (e.g., `9000H′).
- Relocatable: Loaded by a sophisticated OS that ‘fixes up’ all the program’s internal addresses after it is loaded.
- Position-Independent (PIC): Written to run correctly wherever it is placed. Most simple Z80 OSes require PIC or fixed-address programs.