System Software Notes
DSC course under University of Kerala (UoK FYUGP Regulations). Credits: 4 | 60 Hours (4 Hrs/Week).
Chapter-Wise Module Notes & PDF Downloads
Short Notes
All Modules IncludedComplete syllabus revision notes covering all modules in one single PDF
Module 1
Types of Software & Machine Architecture
Module 2
Assemblers
Module 3
Linkers and Loaders
Module 4
Macroprocessor and System Software Tools
Module 5
Compilers, Automata, Grammars & Assembler Labs
Read Module Notes Online
Module I: Types of Software & Machine Architecture
Chapter 1: Foundations of System Software and Application Software
1.1 Nature and Role of System Software
Modern computing hardware consists of electronic circuits, registers, arithmetic-logic units, memory arrays, and peripheral controllers that execute binary machine instructions. Because raw hardware interfaces are intricate and unforgiving, software layers are organized to bridge the gap between physical circuitry and human problem-solving. At the broadest level, computer programs are divided into two major categories: application software and system software.
Application software is designed to solve specific end-user or domain problems, such as payroll accounting, hospital management, scientific simulation, word processing, or web browsing. Its primary concern is the logic of the application domain rather than the internal mechanics of the processor or memory bus. System software, by contrast, consists of a collection of programs that support the operation, management, and development of computer systems themselves. System programs create an abstract, predictable execution environment in which application programs can be written, translated, loaded, debugged, and executed reliably.
The defining distinction between system software and application software lies in machine dependency and purpose. An application program written in a high-level language typically remains portable across different hardware architectures once recompiled, whereas system software must interact directly with processor registers, instruction formats, addressing modes, interrupt vectors, and memory-mapped input/output ports. Even when two systems share an identical operating system kernel, low-level utilities such as assemblers, linkers, loaders, and device drivers must reflect the exact architecture of the underlying machine.
1.2 Detailed Comparison: System Software vs. Application Software
Understanding how system software differs from application software clarifies why specialized data structures, binary encodings, and hardware-aware algorithms are central to this discipline. The following table summarizes the structural and operational contrasts between the two software classes.
| Dimension | System Software | Application Software |
|---|---|---|
| Primary Objective | Manage hardware resources, translate programs, and provide an execution platform. | Perform domain-specific tasks for end users, businesses, or scientific workflows. |
| Hardware Dependency | Highly machine-dependent; directly manipulates registers, memory layouts, and I/O ports. | Largely machine-independent; relies on operating system APIs and runtime libraries. |
| Execution Context | Often executes in privileged kernel mode or invokes system calls directly. | Executes in restricted user mode with virtualized memory and controlled I/O. |
| Development Languages | Assembly language, C, C++, or Rust for deterministic memory and timing control. | Python, Java, C#, JavaScript, SQL, or domain-specific high-level languages. |
| User Interaction | Minimal direct end-user interaction; operates mostly in the background or via CLI/tools. | Rich graphical or command-driven user interfaces tailored to end-user workflows. |
| Failure Impact | A defect can halt the entire system, corrupt file systems, or crash all running tasks. | A defect generally affects only the individual application process and its data. |
| Examples | Assembler, Linker, Loader, Compiler, Operating System, Device Driver, Debugger. | Word processor, Spreadsheet, Database client, CAD suite, Web browser. |
1.3 Taxonomy of System Software Components
A complete software development and execution toolchain comprises several cooperating system programs. Each tool handles a distinct stage in transforming human-readable source code into an executing process on physical hardware:
- Assembler: A language translator that converts symbolic assembly language programs—containing mnemonic operation codes, symbolic labels, and assembler directives—into binary machine-level object code. It also maintains location counters and symbol tables to resolve memory addresses.
- Linker (Linkage Editor): A system program that combines multiple independently assembled or compiled object modules along with standard library routines into a single cohesive executable module. It resolves external symbol references across separate compilation units and adjusts relative addresses.
- Loader: A utility that reads an executable object program from secondary storage into main memory, performs any remaining address relocation, initializes processor registers such as the program counter, and transfers control to the program's entry point.
- Macro Processor: A text-processing preprocessor that recognizes macro definitions—named blocks of parameterized code—and expands every macro invocation inline before the assembler or compiler processes the source text.
- Compiler: A translator that converts an entire high-level language program (such as C or Pascal) into equivalent assembly language or machine code. Unlike an assembler, a compiler performs lexical analysis, syntax parsing, semantic verification, intermediate optimization, and target code generation.
- Interpreter: A language processor that directly analyzes and executes high-level source statements or intermediate bytecode one instruction or block at a time, without producing a standalone machine-code executable file.
- Text Editor: An interactive software tool designed for creating, viewing, navigating, and modifying source code and configuration files. Programmers' editors provide line or screen editing, search-and-replace, syntax highlighting, and buffer management.
- Debugger: An interactive diagnostic tool that allows developers to observe and control program execution in real time. It supports breakpoints, single-step instruction execution, register inspection, memory dumps, and call-stack tracebacks.
- Device Driver: A specialized kernel-level module that acts as a translator between the operating system's generic I/O subsystem and a specific hardware peripheral such as a disk controller, network interface card, or printer.
- Operating System: The foundational master control program that schedules CPU time, allocates physical and virtual memory, manages file systems, enforces security isolation, and coordinates all hardware peripherals and user processes.
Chapter 2: System Software and Machine Architecture
2.1 Why Architecture Governs System Software
Most system software is intimately tied to the architecture of the target computer. An assembler must know the exact binary opcode for every mnemonic, the bit width of each instruction format, the rules for computing effective addresses, and the byte ordering (endianness) of memory. Similarly, a compiler's code generator must know how many general-purpose registers exist, which registers are reserved for stack pointers or return addresses, and whether floating-point arithmetic is performed in hardware or software.
Real-world commercial processors such as x86-64 or ARMv8 contain hundreds of instructions, complex privilege rings, cache coherency protocols, and legacy compatibility modes that obscure the fundamental algorithms of assemblers, loaders, and compilers. To study system software principles clearly without being overwhelmed by hardware idiosyncrasies, computer scientists use a clean, representative model architecture known as the Simplified Instructional Computer (SIC).
2.2 The Simplified Instructional Computer (SIC) Standard Model
The SIC architecture is a hypothetical machine designed to incorporate the most common hardware features found in real computers while eliminating unnecessary complexity. SIC comes in two upward-compatible versions: the Standard SIC model and the SIC/XE (Extra Equipment) extended model. Programs written for the standard SIC machine can execute without modification on a SIC/XE machine, establishing clean backward compatibility.
Memory Organization
Standard SIC memory consists of 8-bit bytes. Any 3 consecutive bytes form a word of 24 bits. All memory addresses are byte addresses, meaning each individual byte has a unique address, and a word is addressed by the location of its lowest-numbered byte. Total addressable memory on standard SIC is bytes, which equals 32,768 bytes (32 KB).
Register Set in Standard SIC
Standard SIC provides five 24-bit registers, each identified by a unique mnemonic and numeric register code used internally by the hardware and assembler:
| Mnemonic | Number | Width | Special Use and Architectural Role |
|---|---|---|---|
| A | 0 | 24 bits | Accumulator; primary register used for arithmetic, logical, and data operations. |
| X | 1 | 24 bits | Index register; holds displacement offsets used for indexed addressing. |
| L | 2 | 24 bits | Linkage register; stores the return address during a Jump to Subroutine (JSUB) call. |
| PC | 8 | 24 bits | Program Counter; contains the address of the next instruction to be fetched. |
| SW | 9 | 24 bits | Status Word; holds condition codes (CC) and processor state flags. |
Data Formats in Standard SIC
Standard SIC supports two primary data representations in memory:
- Integers: Stored as 24-bit binary numbers. Negative values are represented using two's complement notation, giving a representable integer range from to .
- Characters: Stored using standard 8-bit ASCII codes, allowing three characters to be packed into a single 24-bit word.
Standard SIC does not include floating-point hardware; floating-point arithmetic on standard SIC would have to be emulated by software subroutines.
Instruction Format and Addressing Modes in Standard SIC
Every machine instruction in standard SIC occupies exactly 24 bits (3 bytes) with a fixed layout:
- Opcode (8 bits): Bits 0–7 specify the operation code.
- Index Flag x (1 bit): Bit 8 indicates whether indexed addressing is active () or direct addressing is used ().
- Address Field (15 bits): Bits 9–23 contain the 15-bit target memory address.
Because there is only one flag bit (), standard SIC supports exactly two addressing modes. Let denote the target (effective) address and denote the contents of index register X:
Instruction Set and I/O in Standard SIC
The standard SIC instruction set provides essential operations grouped into five functional categories:
- Load and Store Instructions: Move 24-bit words or 8-bit bytes between registers and memory—for example,
LDA,LDX,LDL,STA,STX,STL,LDCH(load character into rightmost byte of A), andSTCH(store rightmost byte of A). - Integer Arithmetic Instructions: Operate on 24-bit words using register A and a memory operand—
ADD,SUB,MUL, andDIV. - Comparison and Conditional Jump Instructions:
COMPcompares the value in register A with a word in memory and sets the Condition Code (CC) in the Status Word (SW) to Less Than (<), Equal (=), or Greater Than (>). Conditional jumpsJLT,JEQ, andJGTinspect CC and branch accordingly, whileJperforms an unconditional jump. - Subroutine Linkage Instructions:
JSUBsaves the current PC into linkage register L and jumps to the subroutine address;RSUBreturns to the caller by loading PC from L. - Input and Output Instructions: Standard SIC transfers one byte at a time between the rightmost 8 bits of register A and an external device identified by an 8-bit device code. Three instructions govern I/O:
TD(Test Device, sets CC to<if ready or=if busy),RD(Read Data byte into A), andWD(Write Data byte from A).
Chapter 3: The SIC/XE Extended Architecture
3.1 Architectural Enhancements in SIC/XE
While standard SIC is adequate for illustrating basic translation, it lacks hardware support for larger memories, additional registers, floating-point arithmetic, and relocatable instruction formats. The SIC/XE (Extra Equipment) architecture extends standard SIC to reflect modern CISC/RISC design trade-offs while preserving full upward compatibility.
Expanded Memory and Additional Registers
SIC/XE expands the address space to 20 bits, yielding bytes = 1,048,576 bytes = 1 megabyte (1 MB) of byte-addressable memory. To support register-to-register computation, base-relative addressing, and floating-point arithmetic, SIC/XE adds four registers to the original five:
| Mnemonic | Number | Width | Architectural Purpose in SIC/XE |
|---|---|---|---|
| B | 3 | 24 bits | Base register; holds a base address for base-relative addressing. |
| S | 4 | 24 bits | General working register; no special hardware restriction. |
| T | 5 | 24 bits | General working register; no special hardware restriction. |
| F | 6 | 48 bits | Floating-point accumulator; holds 48-bit IEEE-like floating-point values. |
SIC/XE Floating-Point Data Format
In addition to 24-bit two's complement integers and 8-bit ASCII characters, SIC/XE introduces a 48-bit floating-point format partitioned into three fields: a 1-bit sign (0 for positive, 1 for negative), an 11-bit biased exponent , and a 36-bit normalized fraction . The numeric value is interpreted as:
3.2 Four Instruction Formats in SIC/XE
Because SIC/XE supports a 1 MB memory (requiring 20-bit addresses) alongside fast register-to-register operations that need no memory address at all, using a single fixed 24-bit format would waste memory and limit reachability. Therefore, SIC/XE defines four variable-length instruction formats:
| Format | Length | Bit Field Layout | Typical Usage |
|---|---|---|---|
| Format 1 | 1 byte (8 bits) | opcode (8) | Zero-operand instructions (e.g., FIX, FLOAT, HIO, SIO). |
| Format 2 | 2 bytes (16 bits) | opcode (8) | r1 (4) | r2 (4) | Register-to-register operations (e.g., ADDR, COMPR, CLEAR, TIXR). |
| Format 3 | 3 bytes (24 bits) | opcode (6) | n | i | x | b | p | e | disp (12) | Memory-reference instructions using PC-relative, Base-relative, or direct 12-bit offset. |
| Format 4 | 4 bytes (32 bits) | opcode (6) | n | i | x | b | p | e | address (20) | Extended memory-reference instructions carrying a full 20-bit absolute address (). |
Notice a critical encoding detail in Format 3 and Format 4: all standard SIC/XE opcodes are multiples of 4 in hexadecimal, which means the lowest two bits of the 8-bit opcode are always 00. SIC/XE reuses those two lowest bits as the n (indirect) and i (immediate) addressing flags! When and , the hardware interprets bits 6–23 using the legacy Standard SIC 15-bit format, guaranteeing seamless backward compatibility.
3.3 Addressing Modes and Effective Address Calculation in SIC/XE
The six control flags in Format 3 and Format 4—n, i, x, b, p, and e—govern how the processor computes the Target Address () and how it fetches the operand. First, flags b, p, and e determine the base calculation of :
- Base-Relative Addressing (): The 12-bit displacement is treated as an unsigned integer between 0 and 4095 and added to register B: .
- PC-Relative Addressing (): The 12-bit displacement is treated as a signed two's complement integer between and and added to PC: . Note that during execution, PC already points to the instruction immediately following the current one.
- Direct Addressing (): In Format 3 (), the 12-bit displacement is used directly as an unsigned address (). In Format 4 (), the full 20-bit address field is used directly ().
- Indexed Addressing (): Regardless of whether the address is base-relative, PC-relative, or direct, setting adds the contents of index register X to .
Once is computed, flags n and i determine how the operand value is obtained:
- Simple Addressing (, or legacy ): The operand is the value stored in memory at location , written as .
- Immediate Addressing (): No memory fetch occurs; the target address itself is used directly as the operand value. Indexing () cannot be combined with immediate mode.
- Indirect Addressing (): The word at memory location is fetched and interpreted as a pointer to the actual operand, meaning the operand is . Indexing () cannot be combined with indirect mode.
Worked Numerical Example: Decoding a SIC/XE Format 3 Instruction
Suppose a Format 3 instruction at memory address 0030 (hexadecimal) has the 3-byte machine code 032600 (hex), and the registers hold , , and . Let us decode the exact operation and operand:
- Convert the 6 hex digits
032600into 24 binary bits:0000 0011 0010 0110 0000 0000. - Extract the 6-bit opcode (with trailing
00):00000000=00(hex), which isLDA. - Extract flags: .
- Extract 12-bit displacement:
600(hex) = (positive since the leading bit is 0). - Since , PC-relative mode is active: .
- Since , simple addressing is active: register A is loaded with the 24-bit word stored at memory address
003600.
3.4 Complete SIC/XE Assembly Program Example
The following SIC/XE assembly program illustrates how registers, Format 2 instructions, immediate addressing, and looping constructs work together to sum an array of 100 integers stored in memory.
SUMARR START 1000
LDS #3 . S = 3 (word size in bytes)
LDT #300 . T = 300 (100 words * 3 bytes)
LDX #0 . X = 0 (index offset)
LDA #0 . A = 0 (running sum)
LOOP ADD ARRAY,X . Add ARRAY[X] to accumulator A
ADDR S,X . Increment index X by 3 (Format 2)
COMPR X,T . Compare X with limit T (Format 2)
JLT LOOP . Repeat if X < 300
STA TOTAL . Store final sum in TOTAL
RSUB . Return to caller
ARRAY RESW 100 . Reserve 100 words for array
TOTAL RESW 1 . Reserve 1 word for result
END SUMARRIn Listing 1.1, instructions such as LDS #3 and LDT #300 use immediate addressing so no extra memory constants need to be allocated. The loop body uses Format 2 instructions (ADDR S,X and COMPR X,T) that execute in 2 bytes without any memory access, significantly improving both code density and execution speed compared to standard SIC.
3.5 Standard SIC vs. SIC/XE: Architectural Comparison
Although SIC/XE preserves full backward compatibility with Standard SIC, the architectural enhancements in SIC/XE fundamentally transform how assemblers, linkers, and compilers generate code. The table below contrasts every hardware subsystem across the two models.
| Architectural Feature | Standard SIC | SIC/XE (Extra Equipment) |
|---|---|---|
| Memory Capacity | bytes (32 KB), 15-bit byte addresses. | bytes (1 MB), 20-bit byte addresses. |
| General & Special Registers | 5 registers (24-bit): A, X, L, PC, SW. | 9 registers: A, X, L, PC, SW, B, S, T (24-bit) plus F (48-bit). |
| Floating-Point Hardware | None; must be emulated in software subroutines. | 48-bit hardware floating-point unit (1 sign, 11 exponent, 36 fraction). |
| Instruction Formats | Single fixed 3-byte (24-bit) format. | Four variable-length formats: 1, 2, 3, and 4 bytes. |
| Addressing Modes | Direct () and Indexed () only. | Direct, Indexed, PC-relative, Base-relative, Immediate, Indirect, Extended. |
| I/O Mechanism | Programmed byte-by-byte polling via TD, RD, WD. | Byte polling plus autonomous I/O channels (SIO, TIO, HIO) and interrupts. |
| Program Relocation | Requires modifying 15-bit absolute addresses via relocation bit mask. | PC-relative and Base-relative Format 3 instructions are position-independent. |
3.6 Input/Output Architecture and Channel Programming
Input and output on Standard SIC rely exclusively on programmed I/O polling. Each peripheral device is assigned an 8-bit device code (00 to FF in hexadecimal). Before transferring a byte, the CPU executes TD (Test Device) specifying the memory byte containing the device code. The hardware sets the Condition Code (CC) in the Status Word (SW) to Less Than (<) when the device is ready to send or accept a byte, and Equal (=) when the device is busy. A tight polling loop executes JEQ back to TD until the device becomes ready, after which RD reads one byte into the rightmost 8 bits of register A, or WD writes the rightmost 8 bits of A to the device.
While simple, programmed polling wastes millions of CPU cycles waiting for slow mechanical peripherals such as card readers, magnetic tape drives, and line printers. SIC/XE solves this bottleneck by introducing autonomous I/O Channels. An I/O channel is a specialized coprocessor that executes its own sequence of channel commands directly against main memory without involving the main CPU for every byte:
- SIO (Start I/O): Initiates an I/O channel program on the channel number specified in register A, allowing the main CPU to continue executing user or operating system instructions concurrently.
- TIO (Test I/O): Tests the current status of the specified I/O channel and sets the Condition Code accordingly.
- HIO (Halt I/O): Immediately terminates an active transfer on the specified I/O channel, used during error recovery or process termination.
3.7 Complete Reference of Core SIC and SIC/XE Instructions
System programmers and assembler writers must be fluent in the binary opcodes, mnemonic names, and semantic effects of the machine instruction set. The following reference table summarizes the primary instructions used throughout assembler, linker, and macro processor design.
| Mnemonic | Format | Opcode (Hex) | Semantic Effect |
|---|---|---|---|
| LDA m | 3 / 4 | 00 | Loads 24-bit word at target address m into register A. |
| LDB m | 3 / 4 | 68 | Loads 24-bit word at target address m into base register B (SIC/XE). |
| LDCH m | 3 / 4 | 50 | Loads single byte at m into rightmost byte of register A. |
| LDL m | 3 / 4 | 08 | Loads 24-bit word at m into linkage register L. |
| LDX m | 3 / 4 | 04 | Loads 24-bit word at m into index register X. |
| STA m | 3 / 4 | 0C | Stores 24-bit word from register A into memory at m. |
| STCH m | 3 / 4 | 54 | Stores rightmost byte of register A into memory byte m. |
| STL m | 3 / 4 | 14 | Stores 24-bit return address from register L into memory at m. |
| ADD m | 3 / 4 | 18 | Adds word at memory m to register A; stores result in A. |
| ADDR r1,r2 | 2 | 90 | Adds register r1 to register r2; stores result in r2 (SIC/XE). |
| SUB m | 3 / 4 | 1C | Subtracts word at memory m from register A; stores result in A. |
| MUL m | 3 / 4 | 20 | Multiplies register A by word at m; stores result in A. |
| DIV m | 3 / 4 | 24 | Divides register A by word at m; stores quotient in A. |
| COMP m | 3 / 4 | 28 | Compares register A with word at m and sets CC in SW. |
| COMPR r1,r2 | 2 | A0 | Compares register r1 with register r2 and sets CC (SIC/XE). |
| J m | 3 / 4 | 3C | Unconditional jump: sets PC to target address m. |
| JEQ / JLT / JGT m | 3 / 4 | 30 / 38 / 34 | Conditional jump to m if CC is '=', '<', or '>' respectively. |
| JSUB m | 3 / 4 | 48 | Saves PC in L and jumps to subroutine at m. |
| RSUB | 3 / 4 | 4C | Returns from subroutine by setting PC to contents of L. |
| CLEAR r1 | 2 | B4 | Sets all 24 bits of register r1 to zero (SIC/XE). |
| TIX m / TIXR r1 | 3/4 / 2 | 2C / B8 | Increments X by 1 and compares X with word at m (or register r1). |
| TD / RD / WD m | 3 / 4 | E0 / D8 / DC | Tests, reads 1 byte from, or writes 1 byte to device code at m. |
3.8 Worked Example: Encoding a Standard SIC and SIC/XE Subroutine
To solidify how machine architecture shapes system software, consider a subroutine RDREC that reads characters from input device F1 into a buffer until either a newline/null byte (00) is read or 4096 bytes have been stored. In Standard SIC, the programmer must define memory constants ZERO WORD 0 and MAXLEN WORD 4096, and every loop iteration must fetch those constants from memory, perform TIX MAXLEN, and test TD INPUT. Each instruction occupies 3 bytes and incurs memory fetch latency.
In SIC/XE, the same routine uses CLEAR X, CLEAR A, CLEAR S (each 2 bytes), loads the loop limit via immediate extended format +LDT #4096 (4 bytes), tests the device, and increments and compares using TIXR T (2 bytes). Because TIXR T requires zero memory accesses for the limit comparison and LDCH/STCH operate directly on register bytes, the SIC/XE version is both significantly shorter in object code size and dramatically faster at execution time. Understanding these exact architectural trade-offs is the foundation for building assemblers, linkers, loaders, and compilers in subsequent modules.
3.9 Summary of Architectural Principles for System Programmers
Every system software component studied in this course maps directly onto the hardware abstractions introduced in this module. Assemblers depend on exact instruction formats, flag bits (n, i, x, b, p, e), and register numbers. Linkers and loaders depend on whether instructions use absolute 15-bit/20-bit addresses or position-independent PC-relative and base-relative displacements. Compilers rely on general-purpose registers (A, S, T, F) for expression evaluation and register allocation, while operating systems and device drivers interact directly with status words, I/O channels, and interrupt vectors.
3.10 Worked Numerical Examples: SIC/XE Address & Format Encoding
Mastering instruction encoding in SIC/XE requires fluency in converting mnemonic instructions and register states into 24-bit (Format 3) or 32-bit (Format 4) binary representations. Below are three additional worked examples illustrating immediate, indirect, and indexed base-relative addressing.
Example A: Immediate Addressing with Format 3 (LDA #3)
The opcode for LDA is 00 (hex). Because immediate mode is requested (#), we set , leaving . The 12-bit displacement holds the constant value 003 (hex). Combining the 6-bit opcode 000000 with yields the first byte 01 (hex). The flag nibble yields 0, and the 12-bit displacement is 003. Thus, the complete 3-byte machine instruction is 010003 (hex).
Example B: Indirect Addressing with PC-Relative Mode (J @RETADR)
Suppose J @RETADR is located at address 003C (so ), and RETADR is at address 0030. The opcode for J is 3C (hex). Indirect mode (@) sets , so the first byte becomes . The PC-relative displacement is . In 12-bit two's complement, . With (), the complete 3-byte instruction is 3E2FF1 (hex). At runtime, the processor fetches the 24-bit pointer stored at 0030 and jumps to the address contained inside that word.
Example C: Indexed Base-Relative Addressing (STCH BUFFER,X)
Suppose STCH BUFFER,X (opcode 54) is located at address 104E (so ), register B holds 0033, and BUFFER is at address 0036. Note that is far outside the PC-relative range , so the assembler selects base-relative mode () with . Because indexing is active (,X), , giving . With simple addressing (), the first byte is , yielding the complete 3-byte object code 57C003 (hex).
3.11 System Software Ecosystem: How Tools Interact in Practice
In a real software build pipeline, the system programs introduced in Chapter 1 never operate in isolation. Consider what happens when a developer writes a high-level C program and executes it:
- Text Editor: The developer creates
main.candhelper.cinside a buffer-managed editor. - Preprocessor / Macro Processor: Expands
#includeheader files and#definemacros into pure C source. - Compiler: Translates each preprocessed
.cfile into target assembly language (.s). - Assembler: Translates each
.sfile into a relocatable binary object module (.o) containing machine instructions, symbol tables, and relocation records. - Linker: Combines
main.o,helper.o, and standard runtime libraries (libc) into an executable binary. - Loader: Maps the executable into virtual memory, performs dynamic linking if required, and starts execution.
- Debugger & OS Device Drivers: Allow step-by-step inspection if a fault occurs and handle all disk, terminal, and network I/O requests transparently through kernel drivers.
Module II: Assemblers
Chapter 4: Basic Assembler Functions and Two-Pass SIC Assembler
4.1 Core Responsibilities of an Assembler
An assembler translates symbolic assembly language programs into binary machine code ready for loading and execution. To accomplish this, an assembler must perform three fundamental tasks:
- Mnemonic-to-Opcode Translation: Convert human-readable instruction mnemonics (such as
LDA,ADD,STA) into their numeric machine operation codes (such as00,18,0C). - Symbolic-to-Numeric Address Resolution: Replace symbolic operand labels (such as
TOTALorLOOP) with their assigned numeric memory addresses. - Data Generation and Object Formatting: Convert data constants specified via assembler directives (such as
BYTEandWORD) into internal binary representation and package the resulting machine code into a standardized object program format containing Header, Text, and End records.
Assembler Directives
Unlike machine instructions, assembler directives (also called pseudo-instructions) are not translated into machine opcodes. Instead, they instruct the assembler how to organize memory, define constants, or mark program boundaries:
START addr: Specifies the program name and starting memory address for the object program.END label: Marks the end of the source program and optionally specifies the address of the first executable instruction.BYTE value: Generates character or hexadecimal constants occupying as many bytes as needed (e.g.,C'EOF'generates 3 bytes454F46;X'F1'generates 1 byteF1).WORD value: Generates a one-word (3-byte) integer constant.RESB n: Reservesnbytes of uninitialized storage without emitting object code.RESW n: Reservesnwords (3 * nbytes) of uninitialized storage.
4.2 The Forward Reference Problem and Two-Pass Design
In assembly programs, instructions frequently reference labels that are defined later in the source file—for example, a jump instruction JLT ENDFIL appearing at line 15 while the label ENDFIL is defined at line 45. Such a reference is called a forward reference. Because the assembler cannot know the numeric address of ENDFIL when it first encounters line 15 during a single top-to-bottom scan, a classic assembler operates in two passes:
- Pass 1 (Define Symbols): Scans the source program from start to finish, maintains a Location Counter (LOCCTR) to track the byte offset of each instruction or data area, assigns addresses to all labels, and stores every label–address pair in the Symbol Table (SYMTAB). Pass 1 writes an intermediate file containing each source line paired with its assigned address.
- Pass 2 (Assemble Instructions and Generate Object Code): Reads the intermediate file, looks up instruction opcodes in the Operation Code Table (OPTAB), looks up operand addresses in SYMTAB, assembles the binary object code for each instruction and constant, and writes the final object program and assembly listing.
- Header Record (H): Columns 1:
H; Columns 2–7: Program name; Columns 8–13: Starting address (hex); Columns 14–19: Length of object program in bytes (hex). - Text Record (T): Column 1:
T; Columns 2–7: Starting address of object code in this record; Columns 8–9: Length of object code in this record in bytes (max1E= 30 bytes); Columns 10–69: Assembled machine instructions and constants in hexadecimal. - End Record (E): Column 1:
E; Columns 2–7: Address of the first executable instruction in the object program. - Column 1:
M - Columns 2–7: Starting address of the field to be modified, relative to the beginning of the program (in hex).
- Columns 8–9: Length of the field to be modified in half-bytes (nibbles). For a Format 4 instruction, the 20-bit address field spans 5 half-bytes (
05), starting 1 byte after the opcode. - Optional Columns 10+: Modification sign (
+or-) and external symbol name (used in program linking). MAXLEN EQU 4096bindsMAXLENto the absolute value 4096, improving readability.BASE EQU *bindsBASEto the current value of LOCCTR (represented by*).- Absolute Expression: Contains only constants, or pairs of relative terms with opposite signs whose relocation offsets cancel out. For example,
BUFEND - BUFFERevaluates to , which is independent of . - Relative Expression: Evaluates to a single net relocation offset , such as
BUFFER + 10. Expressions likeBUFEND + BUFFER(producing ) or2 * BUFFERare illegal in standard relocatable assembly because a single Modification record cannot represent double relocation. - Program Blocks (
USE): Allow segments of a single assembly unit to be rearranged by the assembler into contiguous blocks (e.g., default code block,CDATAblock,CBLKSblock). Each block has its own independent LOCCTR during Pass 1; at the end of Pass 1, blocks are assigned sequential starting addresses, keeping all symbols within one unified object program. - Control Sections (
CSECT): Partition a program into completely independent, separately relocatable units that can be assembled, linked, and loaded independently. Each control section has its own LOCCTR starting at 0. Cross-section symbol references must be explicitly declared usingEXTDEF(external definitions exported by the section) andEXTREF(external symbols imported from other sections), generatingD(Define) andR(Refer) records in the object file. - Load-and-Go One-Pass Assembler: Generates machine code directly into main memory rather than writing an object file. When a forward reference to symbol
SYMis encountered,SYMis entered into SYMTAB with its address marked as unassigned, and the address of the incomplete instruction field is added to a linked list of forward references attached toSYM's SYMTAB entry. Later, whenSYMis finally defined, the assembler walks the linked list and patches (backpatches) every waiting instruction directly in memory before executing the program. - Object-Generating One-Pass Assembler: Writes assembled Text records to an object file as soon as each buffer fills. When a forward reference occurs, the assembler emits the incomplete instruction with
0000in the address field and records the reference in SYMTAB's linked list. When the symbol is later defined, instead of rewriting earlier Text records on disk, the assembler emits new Text records containing only the resolved 2-byte or 3-byte address patches at the appropriate memory locations; the loader then overwrites those bytes during loading. - Line
0000: STL RETADR: Opcode forSTLis14. With , the first byte becomes . During execution, . Target address . Thus . Since , the middle nibble is2, yielding17202D. - Line
0017: J CLOOP: Opcode forJis3C. With , first byte is . Here , and targetCLOOPis0006. The signed displacement is . In 12-bit two's complement, , yielding3F2FEC. - Line
0006: +JSUB RDREC: Format 4 instruction () with opcode48(). AssumingRDRECis at1036, the 20-bit address is01036, yielding4B101036. Because this uses a 20-bit absolute address, Pass 2 emits a Modification recordM00000705(starting at offset000007, modifying 5 half-bytes). MAXLEN EQU BUFEND - BUFFER: At assembly time, . At load time, . Because cancels out,MAXLENis an absolute symbol.NEXT EQU BUFFER + 10: Evaluates to , with net relocation factor . ThusNEXTis a relative symbol.BAD1 EQU BUFEND + BUFFER: Net relocation factor is , which is illegal in standard SIC/XE assembly.M00002806+BUFEND(at offset000028, length 6 half-bytes, add address ofBUFEND)M00002806-BUFFER(at offset000028, length 6 half-bytes, subtract address ofBUFFER)
4.3 Essential Assembler Data Structures
A two-pass assembler relies on three primary internal structures:
| Data Structure | Contents and Organization | Primary Usage Across Passes |
|---|---|---|
| OPTAB (Operation Code Table) | Static lookup table mapping mnemonic opcodes to binary machine codes, instruction formats, and lengths. Usually implemented as a hash table. | Pass 1 checks OPTAB to validate mnemonics and determine instruction length for incrementing LOCCTR. Pass 2 retrieves the binary opcode. |
| SYMTAB (Symbol Table) | Dynamic hash table storing each user-defined label, its assigned address, error flags (e.g., duplicate definition), and optional type/length attributes. | Pass 1 inserts newly defined labels with the current LOCCTR. Pass 2 queries SYMTAB to resolve operand addresses. |
| LOCCTR (Location Counter) | Integer variable initialized to the starting address from START (or 0 if omitted). |
Incremented in Pass 1 by 3 for SIC instructions, 1/2/3/4 for SIC/XE formats, or the byte size of WORD/BYTE/RESW/RESB. |
4.4 Standard SIC Object Program Format
The output of Pass 2 is an object program consisting of three record types, each represented as structured text or binary fields:
begin
read first input line
if OPCODE = 'START' then
save #[OPERAND] as starting address
initialize LOCCTR to starting address
write line to intermediate file
read next input line
else
initialize LOCCTR to 0
while OPCODE != 'END' do
if this is not a comment line then
if there is a symbol in the LABEL field then
search SYMTAB for LABEL
if found then set error flag (duplicate symbol)
else insert (LABEL, LOCCTR) into SYMTAB
search OPTAB for OPCODE
if found then add 3 {or format length} to LOCCTR
else if OPCODE = 'WORD' then add 3 to LOCCTR
else if OPCODE = 'RESW' then add 3 * #[OPERAND] to LOCCTR
else if OPCODE = 'RESB' then add #[OPERAND] to LOCCTR
else if OPCODE = 'BYTE' then add byte_length(OPERAND) to LOCCTR
else set error flag (invalid operation code)
write line and LOCCTR to intermediate file
read next input line
write last line to intermediate file
save (LOCCTR - starting address) as program length
endChapter 5: Machine-Dependent Assembler Features (SIC/XE)
5.1 Assembling SIC/XE Instruction Formats and Addressing Modes
When assembling for SIC/XE rather than standard SIC, Pass 1 and Pass 2 must handle variable-length instructions and multiple addressing modes. In Pass 1, the assembler checks for a leading + prefix on the mnemonic (such as +JSUB), which signals Format 4 (4 bytes). Otherwise, it consults OPTAB to determine whether the instruction is Format 1 (1 byte), Format 2 (2 bytes), or Format 3 (3 bytes).
In Pass 2, Format 3 instructions require the assembler to compute a 12-bit displacement relative to either PC or B:
BASE directive.The assembler always attempts PC-relative addressing first because PC is automatically maintained by the hardware. Only if falls outside the signed 12-bit range does the assembler attempt base-relative addressing, provided the programmer has supplied a BASE directive (e.g., BASE LENGTH). Note that BASE and NOBASE are assembler directives that inform the assembler of the runtime contents of register B; the programmer must still load register B at runtime using an instruction such as LDB #LENGTH.
5.2 Program Relocation and Modification Records
A relocatable program can be loaded anywhere in physical memory by the operating system. Most SIC/XE instructions—such as Format 1, Format 2, immediate constants, and PC-relative or base-relative Format 3 instructions—are inherently position-independent because their displacements depend only on the relative distance between instructions and data, not on absolute memory addresses.
However, Format 4 instructions carrying a direct 20-bit address (such as +JSUB RDREC) and address constants defined by WORD contain absolute addresses computed assuming a starting address of 0000. If the loader places the program at starting address 5000 instead of 0000, those absolute addresses must be incremented by 5000. To inform the loader exactly which fields require adjustment, the assembler emits Modification Records (M) in the object program:
Chapter 6: Machine-Independent Assembler Features
6.1 Literals
Programmers often want to write a constant operand directly inside an instruction—such as LDA =C'EOF' or COMP =X'05'—without manually defining a labeled BYTE or WORD directive elsewhere in the program. Such an operand is called a literal, identified by the leading = prefix. Unlike immediate operands (#5), which embed the value inside the instruction itself, a literal causes the assembler to allocate a memory location for the constant, store the constant value there, and insert the memory address of that location into the instruction.
To manage literals, the assembler maintains a Literal Table (LITTAB) storing each literal's name, operand value, byte length, and assigned address. During Pass 1, whenever the assembler encounters a literal, it adds it to LITTAB (avoiding duplicates) with its address initially unassigned. When the assembler encounters the directive LTORG (Literal Origin)—or reaches the END directive—it assigns sequential addresses from LOCCTR to all unassigned literals in LITTAB, creating a literal pool. Placing LTORG periodically inside large programs ensures that literals remain within the 12-bit PC-relative displacement range of the instructions that reference them.
6.2 Symbol-Defining Statements (EQU and ORG)
The EQU directive defines a symbolic name and binds it to a constant or expression without allocating memory:
The ORG directive temporarily alters LOCCTR to a specified value, allowing programmers to define structured memory layouts or overlay record fields without wasting space. For example, ORG STAB+100 moves LOCCTR to 100 bytes past STAB, and a subsequent ORG with no operand restores LOCCTR to its previous value.
6.3 Expressions: Absolute vs. Relative
Assembler operands may contain arithmetic expressions combining symbols and constants, such as BUFEND - BUFFER. Because relocatable programs shift by a relocation offset when loaded, expressions must be classified as either absolute (invariant under relocation) or relative (shifted by when loaded):
6.4 Program Blocks and Control Sections
To separate code, constants, and large data buffers logically without forcing the programmer to reorder source lines, assemblers provide two modularization mechanisms:
Chapter 7: One-Pass and Multi-Pass Assemblers
7.1 One-Pass Assemblers and Forward Reference Handling
In environments where secondary storage is slow or immediate execution is desired, a one-pass assembler eliminates the intermediate file and Pass 2 by translating the source program in a single scan. The central challenge is resolving forward references without a prior symbol-collection pass. Two architectures solve this problem:
7.2 Multi-Pass Assemblers
Even a standard two-pass assembler fails when a symbol-defining statement contains a forward reference—for example:
ALPHA EQU BETA BETA EQU DELTA DELTA RESW 1
In Listing 2.2, during Pass 1, ALPHA cannot be evaluated because BETA is not yet defined, and BETA cannot be evaluated because DELTA is not yet defined. A multi-pass assembler solves this by storing unevaluated symbol definitions in SYMTAB along with a count of how many unresolved symbols each expression depends on, plus a dependency list pointing to those symbols. Whenever a symbol such as DELTA is finally defined, the assembler decrements the dependency count of every waiting symbol (BETA), evaluates it once its count reaches zero, and propagates the resolution up the chain (ALPHA) until all symbols are resolved.
7.3 Worked Trace: Two-Pass SIC/XE Assembly and Object Code Generation
To understand how Pass 1 and Pass 2 cooperate in practice, consider the complete hand-trace of a SIC/XE program fragment starting at address 0000. Notice how LOCCTR advances by 3 bytes for Format 3 instructions, 4 bytes for Format 4 (+), and 2 bytes for Format 2 instructions, while BASE and END do not advance LOCCTR.
| Loc | Label | Opcode | Operand | Format / Mode | Object Code (Hex) |
|---|---|---|---|---|---|
| 0000 | COPY | START | 0 | Directive | — |
| 0000 | FIRST | STL | RETADR | F3, PC-rel () | 17202D |
| 0003 | LDB | #LENGTH | F3, Imm, PC-rel () | 69202D |
|
| 0006 | BASE | LENGTH | Directive (B = 0033) | — | |
| 0006 | CLOOP | +JSUB | RDREC | F4, Extended () | 4B101036 |
| 000A | LDA | LENGTH | F3, PC-rel () | 032026 |
|
| 000D | COMP | #0 | F3, Imm Direct () | 290000 |
|
| 0010 | JEQ | ENDFIL | F3, PC-rel () | 332007 |
|
| 0013 | +JSUB | WRREC | F4, Extended () | 4B10105D |
|
| 0017 | J | CLOOP | F3, PC-rel backward () | 3F2FEC |
|
| 0030 | RETADR | RESW | 1 | Reserve 3 bytes | — |
| 0033 | LENGTH | RESW | 1 | Reserve 3 bytes | — |
Step-by-Step Displacement Calculations
7.4 Pass 2 Algorithm for Standard SIC and SIC/XE
While Pass 1 is responsible for address assignment and symbol collection, Pass 2 performs the actual binary encoding and object file formatting. Below is the structured algorithmic flow of Pass 2:
begin
read first input line from intermediate file
if OPCODE = 'START' then
write listing line
read next input line
write Header record (H) to object program
initialize first Text record (T)
while OPCODE != 'END' do
if this is not a comment line then
search OPTAB for OPCODE
if found then
if there is a symbol in OPERAND field then
search SYMTAB for OPERAND
if found then store symbol value as operand address
else
store 0 as operand address
set error flag (unresolved symbol)
else store 0 as operand address
assemble object code instruction (apply n,i,x,b,p,e for SIC/XE)
else if OPCODE = 'BYTE' or 'WORD' then
convert constant to object code
if object code will not fit into current Text record then
write Text record to object program
initialize new Text record
add object code to Text record
write listing line
read next input line
write last Text record to object program
emit Modification records (M) for Format 4 / relocatable WORDs
write End record (E) to object program
end7.5 Program Blocks vs. Control Sections: Structural Comparison
Students frequently confuse Program Blocks (USE) with Control Sections (CSECT) because both partition an assembly source file into logical regions. The table below highlights their exact architectural differences.
| Criterion | Program Blocks (USE) |
Control Sections (CSECT) |
|---|---|---|
| Assembly Output | Produces a single unified object program. | Produces multiple independent object modules. |
| LOCCTR Scope | Each block has its own LOCCTR during Pass 1, merged sequentially at end of Pass 1. | Each section has an independent LOCCTR starting at 0000; never merged by assembler. |
| Cross-References | All symbols are shared automatically within the same SYMTAB. | Requires explicit EXTDEF and EXTREF declarations plus D, R, and M records. |
| Relocation | Relocated as one contiguous unit by the loader. | Each section can be independently relocated, linked, or replaced. |
7.6 Worked Example: Absolute vs. Relative Expressions
Suppose in a control section starting at relative address 0000, symbol BUFFER is at 0036 and BUFEND is at 1036. Let denote the load-time relocation offset:
7.7 Worked Trace: Program Blocks (USE) and Block Table
To see how an assembler rearranges code and large buffers using Program Blocks, consider a program using three blocks: the default unnamed block (Block 0) for executable instructions, CDATA (Block 1) for small constants and variables, and CBLKS (Block 2) for large 4096-byte buffers. During Pass 1, the assembler maintains a separate location counter for each block inside a Block Table:
| Block Name | Block Number | Length (Hex) | Assigned Starting Address (Hex) |
|---|---|---|---|
| (default) | 0 | 0066 | 0000 |
| CDATA | 1 | 000B | 0066 |
| CBLKS | 2 | 1000 | 0071 |
In Pass 1, every symbol is stored in SYMTAB along with both its block number and its relative address within that block. At the end of Pass 1, the assembler assigns sequential starting addresses to the blocks (0000, 0066, 0071). In Pass 2, to compute the target address of any symbol, the assembler simply adds the symbol's block-relative address to the starting address of its block. Notice why this is so effective: placing the huge 4096-byte CBLKS buffer at the very end of the program keeps all executable instructions and small CDATA variables close together in memory, allowing nearly every instruction to use fast 3-byte PC-relative addressing instead of 4-byte extended Format 4 instructions or base-relative addressing.
7.8 Worked Trace: Control Sections, EXTDEF, and EXTREF
When a large software project is written by multiple programmers or divided into reusable library routines (COPY, RDREC, WRREC), each module is written as an independent Control Section (CSECT). Consider two control sections where COPY calls RDREC and shares buffer BUFFER and LENGTH:
COPY START 0
EXTDEF BUFFER,BUFEND,LENGTH
EXTREF RDREC,WRREC
FIRST STL RETADR
CLOOP +JSUB RDREC . External call -> M record +RDREC
LDA LENGTH
COMP #0
JEQ ENDFIL
+JSUB WRREC . External call -> M record +WRREC
J CLOOP
BUFFER RESB 4096
BUFEND EQU *
LENGTH RESW 1
END FIRST
RDREC CSECT
EXTREF BUFFER,LENGTH,BUFEND
CLEAR X
CLEAR A
CLEAR S
LDT MAXLEN
RLOOP TD INPUT
JEQ RLOOP
RD INPUT
COMPR A,S
JEQ EXIT
+STCH BUFFER,X . External data -> M record +BUFFER
TIXR T
JLT RLOOP
EXIT +STX LENGTH . External data -> M record +LENGTH
RSUB
INPUT BYTE X'F1'
MAXLEN WORD BUFEND-BUFFER . Expression -> M +BUFEND, M -BUFFERIn Listing 2.4, observe the last line of RDREC: MAXLEN WORD BUFEND-BUFFER. Because both BUFEND and BUFFER are external symbols defined in COPY, the assembler cannot compute BUFEND - BUFFER during assembly of RDREC. Instead, it emits 000000 in the Text record for MAXLEN and generates two Modification records:
When the linking loader executes Pass 2, it resolves both symbols from ESTAB and stores the exact difference into MAXLEN automatically.
7.9 Worked Trace: Literal Pool Management (LITTAB and LTORG)
Suppose a program uses two literals: =C'EOF' at address 001A and =X'05' at address 002D. During Pass 1, both are entered into LITTAB with their lengths (3 bytes and 1 byte) and unassigned addresses. When Pass 1 encounters LTORG at LOCCTR = 0027, it assigns 0027 to =C'EOF' (advancing LOCCTR to 002A). Later, at END (LOCCTR = 1073), the remaining literal =X'05' is assigned address 1073. In Pass 2, the literal values 454F46 and 05 are emitted into Text records at 0027 and 1073 just like ordinary BYTE constants, and instructions referencing them encode PC-relative displacements pointing to those pool addresses.
7.10 One-Pass Assembler Forward-Reference Trace
To see how a one-pass load-and-go assembler resolves forward references in memory without a second pass, suppose at address 2009 the assembler encounters JEQ ENDFIL before ENDFIL has been defined. The assembler inserts ENDFIL into SYMTAB with value -1 (unassigned) and creates a linked-list node pointing to address 200A (the 2-byte address field of JEQ), emitting 300000 into memory. Later, at address 201B, the assembler encounters the label ENDFIL. It updates SYMTAB[ENDFIL] = 201B, traverses the linked list of pending references, and overwrites memory bytes 200A–200B with 201B, turning the instruction into 30201B.
7.11 Assembler Error Detection and Diagnostics
A production-quality assembler must detect and report source errors cleanly rather than emitting corrupt machine code. Common errors detected in Pass 1 include duplicate symbol definitions, invalid mnemonic opcodes, illegal characters in hexadecimal/character constants, and invalid expressions. Errors detected in Pass 2 include unresolved operand symbols, illegal addressing mode combinations (such as immediate + indexed), and 12-bit displacement overflow when neither PC-relative nor base-relative addressing can reach the target without Format 4.
Module III: Linkers and Loaders
Chapter 8: Basic Loader Functions and Absolute Loaders
8.1 Role of Loaders and Linkers
An object program produced by an assembler or compiler resides on secondary storage (disk) and cannot execute until its binary instructions and data are placed into main memory. Three fundamental operations must occur before execution begins:
- Allocation: Reserving contiguous or paged space in main memory for the program's code and data segments.
- Linking: Resolving symbolic references between independently compiled or assembled control sections and external libraries.
- Relocation: Adjusting address-sensitive instructions and data words to reflect the actual physical or virtual memory address where the program is placed.
Loading copies the finalized executable bytes into memory and transfers CPU control to the entry point. Depending on system complexity, these tasks may be handled by a simple absolute loader, a relocating loader, a linking loader, or a separate linkage editor.
8.2 Design of an Absolute Loader
An absolute loader is the simplest type of loader. It performs neither linking nor relocation; it assumes the assembler has already assigned fixed, absolute memory addresses to every instruction and data item. Because no address adjustments are needed, an absolute loader is small, fast, and requires no Modification records.
The algorithm for an absolute loader reads the object program record by record:
- Read the Header (H) record and verify that the program name and length match available memory.
- Loop through Text (T) records until an End (E) record is encountered. For each Text record, convert the hexadecimal starting address into a binary memory pointer, and copy each pair of hexadecimal digits (1 byte) sequentially into consecutive memory locations.
- When the End (E) record is read, extract the execution starting address and jump to that address to begin program execution.
The major limitation of an absolute loader is rigidity: the programmer must specify the exact physical starting address at assembly time. Two programs assembled for the same memory region cannot coexist in memory simultaneously, and shared subroutine libraries cannot be placed flexibly without reassembling every caller.
Chapter 9: Machine-Dependent Loader Features
9.1 Relocation Loaders
To allow the operating system to load a program at any available memory region, the loader must perform relocation at load time. Two primary techniques are used to identify which bytes in a Text record require relocation:
- Modification Records (SIC/XE): Each
Mrecord specifies the exact starting offset and half-byte length of an address field to be adjusted by adding the program's actual starting address (PROGADDR). This method is flexible and handles both 20-bit Format 4 instructions and 24-bitWORDconstants cleanly. - Relocation Bit Mask (Standard SIC): Because standard SIC instructions are fixed at 3 bytes (with a 15-bit address field) and a single Text record holds up to 10 words (30 bytes), each Text record can include a 12-bit relocation mask (3 hex digits) immediately after the record length. Each bit corresponds to one word in the Text record: a bit of
1instructs the loader to addPROGADDRto that word, while0leaves the word unchanged.
9.2 Program Linking and Linking Loaders
When a program is divided into multiple control sections (using CSECT, EXTDEF, and EXTREF), the object file contains two additional record types:
- Define Record (D): Lists external symbols defined within this control section along with their relative addresses inside the section.
- Refer Record (R): Lists external symbols referenced by this control section but defined elsewhere.
A linking loader combines linking, relocation, and loading into a single execution-time utility using two passes over the input object files:
- Pass 1 (Assign Addresses and Build ESTAB): Assigns a starting load address (
CSADDR) to each control section, starting fromPROGADDR. For everyDrecord, it computes the symbol's absolute address () and inserts the symbol into the External Symbol Table (ESTAB). - Pass 2 (Perform Loading, Relocation, and Linking): Loads all Text records into memory at their assigned
CSADDRoffsets. For everyMrecord, it looks up the referenced external symbol in ESTAB and adds or subtracts that symbol's absolute address from the target memory field. Finally, it transfers control to the starting address specified by the End record.
for each M record in current control section do
target_addr = CSADDR + M.offset
if M.symbol found in ESTAB then
sym_val = ESTAB[M.symbol].address
if M.sign == '+' then
memory[target_addr] += sym_val
else
memory[target_addr] -= sym_val
else
report error: unresolved external symbolChapter 10: Machine-Independent Loader Features
10.1 Automatic Library Search
Programs routinely invoke standard mathematical, string, or I/O subroutines (such as SQRT, SIN, or PRINTF) without explicitly including their object files on the command line. A linking loader supports automatic library search by scanning system library archives (such as libc or libm) after Pass 1. Any symbol present in R records that remains unresolved in ESTAB triggers a search of the library directory index. When a matching library module is found, the loader includes that module in Pass 1 and Pass 2 just as if the user had supplied it explicitly.
To prevent unnecessary disk reads, libraries are indexed by a directory table mapping exported symbol names directly to module offsets. Furthermore, if a user supplies a custom version of a library routine in their own object file, Pass 1 already enters that symbol into ESTAB before the library is searched, allowing programmers to override standard routines cleanly.
10.2 Loader Options and Control Commands
Most loaders provide a command language or option flags allowing programmers to customize linking behavior without modifying or recompiling source code:
INCLUDE program(library): Directs the loader to read and link a specific module from a designated library.DELETE csect-name: Instructs the loader to omit a named control section from the linked output, useful when replacing a defective module.CHANGE name1, name2: Renames an external symbol reference fromname1toname2at link time, enabling a caller to bind to an alternative implementation without editing source code.LIBRARY libname: Specifies additional user libraries to be searched before standard system libraries.NOCALL symbol1, symbol2: Marks specified external symbols as deliberately unresolved so the loader does not search libraries or report errors for optional modules that will never be invoked during a particular run.
Chapter 11: Linkage Editors, Dynamic Linking, and Bootstrap Loaders
11.1 Linking Loader vs. Linkage Editor
A linking loader performs all linking and relocation every time a program is executed, writing the linked image directly into main memory. If a production program is executed hundreds of times without modification, repeating symbol resolution on every run wastes CPU and I/O time.
A linkage editor solves this inefficiency by separating linking from loading. It reads multiple object modules and libraries, resolves all external references, combines control sections, and writes a single linked load module back to secondary storage. Only minimal relocation (adjusting addresses for the final load address) remains for a simple relocating loader at execution time. Linkage editors also support replacing individual control sections inside an existing load module without re-linking the entire application.
| Feature | Linking Loader | Linkage Editor |
|---|---|---|
| Output Destination | Loads linked program directly into main memory for immediate execution. | Writes a resolved load module to disk for repeated future execution. |
| Re-linking Overhead | Repeats Pass 1, ESTAB construction, and library search on every run. | Links once; subsequent runs require only fast relocation and loading. |
| Memory Footprint | Must remain resident or active during load-time linking. | Runs as an offline build tool; runtime loader is much smaller. |
| Module Replacement | Must re-supply all object files each time. | Can replace a single control section inside an existing load module. |
11.2 Dynamic Linking
In both linking loaders and static linkage editors, all referenced library modules are bound into the program before execution begins—even error-handling routines that may never be called during a typical run. Dynamic linking (also called dynamic loading or shared library binding) defers the linking and loading of a subroutine until the exact moment it is first called at runtime.
Under dynamic linking, the compiler or static linker replaces calls to a shared routine with a small stub or call to the operating system's dynamic linker, passing the symbolic name of the target routine. When execution reaches that call for the first time, the dynamic linker checks whether the target library is already in memory (possibly shared by another running process). If not, it loads the library, updates the caller's jump table (Procedure Linkage Table / Global Offset Table) with the resolved memory address, and transfers control to the routine. Subsequent calls branch directly to the routine at full native speed. Dynamic linking dramatically reduces disk usage and physical RAM consumption across multitasking operating systems.
11.3 Bootstrap Loaders
When a computer is powered on or reset, main memory is empty or holds uninitialized data, and no operating system or relocating loader is resident in RAM to load programs from disk. The hardware solves this "chicken-and-egg" problem using a bootstrap loader.
A bootstrap loader is a tiny, fixed absolute program stored permanently in non-volatile Read-Only Memory (ROM) or flash firmware (such as BIOS or UEFI). When power is applied, the processor's program counter is hardware-initialized to the ROM address of the bootstrap loader. The bootstrap routine performs minimal hardware checks, reads a small fixed sector (the boot sector or Master Boot Record) from the boot disk into a predetermined RAM address, and jumps to it. That first disk sector contains a slightly larger second-stage loader capable of understanding the file system and loading the full operating system kernel into memory.
11.4 Worked Numerical Example: Linking Loader Address Assignment and Relocation
To trace how a two-pass linking loader assigns addresses and resolves external references, consider three control sections—PROGA (length 0063), PROGB (length 007F), and PROGC (length 0051)—loaded starting at PROGADDR = 4000 (hex).
Pass 1: Building ESTAB (External Symbol Table)
The loader initializes CSADDR = 4000 and processes each section's Header (H) and Define (D) records:
| Control Section | Symbol | Relative Address (Hex) | Assigned Load Address (Hex) | Length (Hex) |
|---|---|---|---|---|
| PROGA | — | 0000 | 4000 | 0063 |
| PROGA | LISTA | 0040 | 4040 | — |
| PROGA | ENDA | 0054 | 4054 | — |
| PROGB | — | 0000 | 4063 | 007F |
| PROGB | LISTB | 0060 | 40C3 | — |
| PROGB | ENDB | 0070 | 40D3 | — |
| PROGC | — | 0000 | 40E2 | 0051 |
| PROGC | LISTC | 0030 | 4112 | — |
| PROGC | ENDC | 0042 | 4124 | — |
Pass 2: Resolving Modification Records in Memory
Suppose PROGA contains a 3-byte data word at relative offset 0054 initialized to 000000, accompanied by three Modification records representing the expression LISTB + ENDC - LISTC:
M00005406+LISTB: Adds40C3.M00005406+ENDC: Adds4124.M00005406-LISTC: Subtracts4112.
In Pass 2, the loader targets physical memory address and computes:
11.5 Absolute Loader Algorithm and Implementation
Because an absolute loader performs no relocation or linking, its entire logic fits in a compact loop. Below is the structured pseudocode for an absolute loader reading standard SIC object records.
begin
read Header record (H)
verify program name and length
read next input record
while record type != 'E' do
if record type = 'T' then
convert starting address (cols 2-7) to integer ADDR
convert length (cols 8-9) to byte count LEN
for i = 0 to LEN - 1 do
read next 2 hex digits as 1 byte B
memory[ADDR + i] = B
read next input record
jump to execution address specified in End record (E)
end11.6 Relocation Bit Mask Worked Example (Standard SIC)
On Standard SIC, each Text record carries a 12-bit relocation mask (3 hex digits) in columns 10–12, followed by up to 10 three-byte words. Suppose a Text record is T0000001EFFC140033... with PROGADDR = 2000:
- The relocation mask is
FFC(hex) =1111 1111 1100(binary). - This mask indicates that the first 10 words in this Text record have mask bit
1(relocatable), while the remaining 2 bit positions are unused (0). - For each word with mask bit
1, the loader adds2000(hex) to its 15-bit address field. For example,140033(STL 0033) becomes142033in memory. - Any word containing a constant integer (e.g.,
WORD 5) or an instruction using an absolute address would have a mask bit of0so the loader leaves it untouched.
11.7 Dynamic Linking Architecture in Modern Operating Systems
Modern operating systems such as Linux (using ELF shared objects .so) and Windows (using Dynamic Link Libraries .dll) rely heavily on dynamic linking. Rather than patching code pages directly—which would prevent multiple processes from sharing the same read-only code pages in physical RAM—the compiler generates Position-Independent Code (PIC). Calls to external shared functions route through a Procedure Linkage Table (PLT) that reads the resolved target address from a per-process Global Offset Table (GOT). On the very first call to a function such as printf, the GOT entry points back to the dynamic linker (ld.so), which resolves printf in libc.so, updates the GOT entry, and jumps to printf. Every subsequent call reads the GOT directly in a single indirect jump with zero dynamic-linker overhead.
11.8 Summary of Binding Times in System Software
A unifying theme across Modules I, II, and III is binding time—the exact stage at which symbolic names are bound to physical memory addresses:
- Assembly/Compile Time: Absolute assemblers bind symbols directly to fixed physical addresses; absolute loaders simply copy bytes.
- Link Time: Linkage editors bind external symbols across control sections into a unified load module on disk.
- Load Time: Linking loaders and relocating loaders bind relocatable offsets to actual memory addresses (
PROGADDR) right before execution begins. - Execution Time (Runtime): Dynamic linking defers symbol resolution and library loading until the first invocation of a shared routine.
11.9 Complete Linking Loader Pass 1 and Pass 2 Algorithms
To solidify the design of a two-pass linking loader, Listing 3.3 presents the complete algorithmic structure of Pass 1 (building ESTAB and assigning control section addresses) and Pass 2 (loading Text records, processing Modification records, and transferring control).
// PASS 1: Assign addresses to control sections and build ESTAB
begin
get PROGADDR from operating system
CSADDR = PROGADDR
while not end of input do
read next input record (Header record for control section)
set CSLTH to control section length
search ESTAB for control section name
if found then set error flag (duplicate external symbol)
else enter control section name into ESTAB with value CSADDR
while record type != 'E' do
read next input record
if record type = 'D' then
for each symbol in D record do
search ESTAB for symbol name
if found then set error flag (duplicate external symbol)
else enter symbol into ESTAB with value (CSADDR + relative addr)
CSADDR = CSADDR + CSLTH
end
// PASS 2: Perform actual loading, relocation, and linking
begin
CSADDR = PROGADDR
EXECADDR = PROGADDR
while not end of input do
read next input record (Header record)
set CSLTH to control section length
while record type != 'E' do
read next input record
if record type = 'T' then
move object code from T record to memory at (CSADDR + specified addr)
else if record type = 'M' then
search ESTAB for modifying symbol name
if found then
add or subtract symbol value at memory location (CSADDR + M.addr)
else set error flag (unresolved external symbol)
if an address is specified in End record then
EXECADDR = CSADDR + address in E record
CSADDR = CSADDR + CSLTH
jump to location given by EXECADDR to start execution
end11.10 Reference Numbers for Faster External Symbol Lookup
In Listing 3.3, Pass 2 searches ESTAB by symbol name string on every Modification record. In large programs with thousands of external references, repeated hash-table string lookups during Pass 2 add noticeable overhead. To eliminate this bottleneck, assemblers and linking loaders use reference numbers inside R (Refer) and M (Modification) records:
- In each control section, reference number
01is implicitly assigned to the control section name itself. - Each symbol listed in the
Rrecord is preceded by a two-digit hexadecimal reference number (e.g.,R02LISTB 03ENDB 04LISTC 05ENDC). - In Pass 1 (or at the start of Pass 2 for that section), the loader resolves each symbol in the
Rrecord once and stores its absolute address in a small local arrayREF_ARRAY[1..N]. - Every subsequent
Mrecord simply specifies the 2-digit reference number (e.g.,M00005406+02) instead of the full symbol name, reducing Pass 2 symbol lookup from a hash search to a single array index.
11.11 Static Linking vs. Dynamic Linking: Architectural Trade-offs
Choosing between static linking (via a linkage editor) and dynamic linking (via shared libraries) involves balancing memory efficiency, startup latency, distribution simplicity, and version stability. The table below summarizes the key engineering trade-offs.
| Criterion | Static Linking (Linkage Editor) | Dynamic Linking (Shared Libraries) |
|---|---|---|
| Executable File Size | Large; every binary embeds its own copy of library routines. | Compact; binaries store only symbolic stubs and library names. |
| Physical RAM Usage | High when multiple programs run simultaneously (duplicate code pages). | Low; a single copy of libc code pages in RAM is shared by all processes. |
| Startup & Call Latency | Zero runtime symbol lookup; all calls are direct static jumps. | Slight startup/first-call overhead for dynamic symbol resolution via PLT/GOT. |
| Library Updates & Bug Fixes | Requires re-linking and redistributing every application binary. | Updating the shared library on disk automatically patches all dependent apps. |
| Dependency Stability | Self-contained; immune to missing or incompatible system library versions. | Vulnerable to version mismatch ("DLL/library incompatibility") if ABI changes. |
11.12 Case Study: Two-Stage Bootstrap Process in Modern Systems
Although a SIC-level bootstrap loader is only a few dozen bytes in ROM, the same staged architecture scales directly to modern PCs and servers:
- Stage 0 (Firmware — BIOS/UEFI in Flash ROM): Executes Power-On Self-Test (POST), initializes memory controllers and PCIe buses, and locates the bootable storage device.
- Stage 1 (Boot Sector / EFI System Partition): A tiny fixed-size loader (e.g., 512 bytes in MBR or an EFI binary) loaded into RAM at a known address; its sole job is to load Stage 2.
- Stage 2 (Boot Manager — e.g., GRUB / Windows Boot Manager): Understands file systems (ext4, NTFS, FAT32), presents an OS selection menu, loads the compressed operating system kernel image and initial RAM disk into memory, and transfers CPU control to the kernel's entry point.
11.13 Loader Options Worked Scenario
Suppose a developer builds a scientific simulation consisting of MAIN, SOLVER, and PLOTTER, where SOLVER has a known bug in library MATHLIB and PLOTTER is not needed for a headless batch run. Using loader control commands, the developer can issue:
LIBRARY MYLIB— searches the developer's patchedMYLIBbefore the system library.DELETE SOLVER— removes the buggySOLVERcontrol section from the input stream.INCLUDE FASTSOLV(MYLIB)— pulls in the replacementFASTSOLVmodule.CHANGE SOLVER, FASTSOLV— redirects all external calls toSOLVERtowardFASTSOLV.NOCALL PLOTTER— suppresses library search and unresolved-symbol errors forPLOTTER.
All of these structural substitutions happen cleanly at link/load time without editing or recompiling a single line of source code.
11.14 Object File Formats: SIC vs. ELF (Executable and Linkable Format)
The fundamental concepts of Header, Text, Define, Refer, and Modification records in SIC/XE map directly onto modern industry-standard binary formats such as ELF (Executable and Linkable Format) used on Linux and Unix systems, and PE/COFF used on Windows. Understanding this correspondence bridges academic theory with real-world toolchains:
| SIC/XE Object Concept | Modern ELF Equivalent | Purpose in Linking & Loading |
|---|---|---|
Header Record (H) |
ELF Header + Program Headers | Identifies architecture, entry point address, and memory segment layout. |
Text Record (T) |
.text, .data, .rodata sections |
Contains machine instructions, initialized globals, and read-only constants. |
RESB / RESW (uninitialized) |
.bss section |
Reserves zero-initialized memory at load time without storing zeros on disk. |
Define (D) & Refer (R) Records |
.symtab / .dynsym symbol tables |
Lists exported and imported symbols for static and dynamic linkers. |
Modification Record (M) |
.rel.text / .rela.text relocation tables |
Specifies offsets and relocation types to patch addresses at link or load time. |
11.15 Memory Protection and Segment Permissions During Loading
Unlike a bare-metal SIC machine where all memory is uniformly readable, writable, and executable, modern operating system loaders configure hardware Memory Management Unit (MMU) page-table permissions when mapping an executable into virtual memory:
- Code Segment (
.text): Mapped as Read + Execute (R-X), preventing accidental or malicious self-modifying code and allowing multiple processes running the same program to share identical physical RAM pages safely. - Read-Only Data (
.rodata): Mapped as Read-Only (R--) for string literals and constant lookup tables. - Data and BSS Segments (
.data,.bss): Mapped as Read + Write (RW-) with the No-Execute (NX) bit enabled, mitigating buffer-overflow code-injection attacks.
11.16 Overlay Structures for Memory-Constrained Systems
Before virtual memory and demand paging became universal, large programs often exceeded the physical RAM capacity of early computers. Linkers and loaders supported overlay structures, in which mutually exclusive program phases (such as an initialization module, a computation phase, and a report-printing phase) were assigned to share the same physical memory region. A small resident overlay supervisor remained permanently in RAM and dynamically loaded each overlay segment from disk into the shared region on demand when called.
11.17 Worked Trace: Complete Object Program for Multi-Section Linking
To observe how all record types (H, D, R, T, M, E) fit together in an actual object stream fed into a linking loader, consider the complete object output for control section PROGA from Section 11.4:
HPROGA 000000000063 DLISTA 000040ENDA 000054 RLISTB ENDB LISTC ENDC T0000001D03201D77100004050014... T00002016032018... T0000540F000014FFFFF600003F000014FFFFC0 M00002405+LISTB M00005406+LISTB M00005406+ENDC M00005406-LISTC E000000
In Listing 3.4, the D record exports LISTA (000040) and ENDA (000054). The R record declares imports LISTB, ENDB, LISTC, and ENDC. Notice the first Modification record M00002405+LISTB: its length is 05 half-bytes because it patches the 20-bit address field of a Format 4 instruction, whereas the three Modification records at 000054 have length 06 half-bytes because they patch a full 24-bit WORD data constant. This distinction between 5-nibble instruction relocation and 6-nibble data-word relocation is essential when implementing Pass 2 of a linking loader.
11.18 Common Linking Errors and Resolution Diagnostics
During static linking or load-time linking, linkers enforce strict symbol integrity rules across all object modules and libraries:
- Unresolved External Symbol: Occurs when a control section references an imported symbol in an
Rrecord (e.g.,+JSUB MYFUNC) that is never exported by anyDrecord across the linked object files or searched libraries. The linker aborts and reports the missing symbol name. - Multiple (Duplicate) Symbol Definition: Occurs when two different control sections both export the exact same global symbol name in their
Drecords. Unless one is explicitly marked as a weak symbol, the linker halts with a duplicate-definition error to prevent ambiguous binding. - Library Order Sensitivity: In traditional single-pass archive scanning (e.g., Unix
ararchives), ifmain.ocallsfoo()inlibA.a, andlibA.acallsbar()inlibB.a,libA.amust appear beforelibB.aon the linker command line so thatbaris already marked unresolved in ESTAB whenlibB.ais scanned.
Module IV: Macroprocessor and System Software Tools
Chapter 12: Macro Processors — Definition, Expansion, and Data Structures
12.1 Concept of a Macro and Comparison with Subroutines
Assembly programmers frequently encounter short sequences of instructions that must be repeated at multiple points in a program with slight variations in registers or operands. Using a subroutine (JSUB / RSUB) for a 3-instruction sequence introduces call-and-return overhead, linkage register saving, and parameter-passing instructions that may exceed the work of the routine itself. A macro provides an alternative: it is a named, parameterized abbreviation for a sequence of source statements.
When the programmer writes a macro invocation (macro call), the macro processor replaces that single line with the complete body of the macro definition, substituting actual arguments for formal parameters. This process is called macro expansion and occurs before assembly (during preprocessing), whereas subroutine calls occur at runtime.
| Aspect | Macro Expansion | Subroutine Call |
|---|---|---|
| Processing Time | Expanded inline at assembly/preprocessing time. | Invoked dynamically at runtime via JSUB/RSUB. |
| Memory Size | Increases object code size because body is duplicated at each call site. | Code appears only once in memory regardless of call count. |
| Execution Speed | Faster; zero call, return, or stack-frame overhead. | Slightly slower due to jump, return, and register-save overhead. |
| Parameter Passing | Textual substitution of source tokens before assembly. | Runtime passing via registers, memory blocks, or call stack. |
12.2 Macro Definition and Expansion Mechanics
A macro definition is enclosed between the directives MACRO and MEND. The header line specifies the macro name in the label field, MACRO in the opcode field, and a comma-separated list of formal parameters (each prefixed by &) in the operand field.
RDBUFF MACRO &INDEV,&BUFADR,&RECLTH
CLEAR X
CLEAR A
CLEAR S
+LDT #4096
$LOOP TD =X'&INDEV'
JEQ $LOOP
RD =X'&INDEV'
COMPR A,S
JEQ $EXIT
STCH &BUFADR,X
TIXR T
JLT $LOOP
$EXIT STX &RECLTH
MENDNotice the labels $LOOP and $EXIT prefixed with $. If a macro containing ordinary labels were expanded twice in the same program, the assembler would report a duplicate symbol error. To prevent this, the macro processor generates unique labels for every expansion by replacing $ with $AA on the first expansion, $AB on the second, and so forth.
12.3 Core Data Structures of a One-Pass Macro Processor
A standard one-pass macro processor processes definitions and expansions in a single scan using three primary tables:
- NAMTAB (Macro Name Table): Stores the name of each defined macro along with pointers to the beginning and end of its body in DEFTAB. During processing, every source opcode is checked against NAMTAB to detect macro invocations.
- DEFTAB (Definition Table): Stores the body lines of every macro definition. Comments are stripped, and formal parameters (like
&INDEV) are converted into positional index markers (like?1,?2,?3) so that argument substitution during expansion is a fast array lookup. - ARGTAB (Argument Table): Used during macro expansion to store the actual arguments supplied in the current macro invocation. Entry 1 holds the first argument, entry 2 holds the second, and so on. As DEFTAB lines are emitted, each
?imarker is replaced byARGTAB[i].
12.4 Advanced Macro Processor Features
Production macro processors support several powerful extensions beyond simple positional substitution:
- Concatenation of Parameters: When a parameter must be joined adjacent to literal characters (e.g.,
LDA X&ID1), an explicit concatenation operator such as->(X&ID->1) separates the parameter name from trailing characters. - Keyword Macro Parameters: Instead of matching arguments strictly by position, callers can specify
&INDEV=F1, &RECLTH=LENin any order, and omitted parameters automatically receive default values specified in the macro header. - Conditional Macro Expansion: Macro-time control directives—such as
IF,ELSE,ENDIF,WHILE,ENDW, and macro-time variables (SET)—allow the macro processor to conditionally include or omit instructions, or unroll loops at assembly time. - Nested Macro Calls: A macro body may invoke another macro. Handling nested calls requires maintaining an expansion stack (or recursive
EXPANDprocedure) so that each active expansion preserves its ownARGTABand DEFTAB line pointer without overwriting the outer macro's state.
Chapter 13: Text Editors — Structure, Editing Process, and User Interface
13.1 Overview of the Interactive Editing Process
A text editor is an interactive system tool used to create, inspect, and modify text documents and source programs. Regardless of whether an editor is line-oriented or full-screen visual, the editing process consists of four fundamental tasks:
- Traveling: Moving the logical editing cursor (or selection point) to the target location within the document without altering text (e.g., next line, find pattern, jump to line number).
- Editing: Modifying the underlying document buffer by inserting characters, deleting lines, cutting, copying, pasting, or performing global search-and-replace.
- Viewing: Selecting and formatting a contiguous portion of the internal document buffer into an abstract display buffer suitable for presentation.
- Display: Mapping the abstract display buffer onto physical screen coordinates, terminals, or graphical windows, handling scrolling, line wrapping, and cursor rendering.
13.2 Internal Architecture of an Editor
To keep editing logic independent of specific terminal hardware or display protocols, a well-designed text editor is organized into four cooperating components:
- Editing Component: Manages the internal document representation (such as a linked list of lines, gap buffer, or piece table) and executes insertion, deletion, undo/redo, and file save/load operations.
- Traveling Component: Implements navigation commands, regular-expression searches, and bookmarking, updating the current editing pointer inside the buffer.
- Viewing Component: Applies formatting rules (tab expansion, line numbering, syntax coloring, window clipping) to produce a logical view of the visible portion of the document.
- Display Component: Sends low-level terminal control sequences or GUI rendering calls to update the physical screen efficiently, minimizing redraw flicker by updating only modified regions.
In addition, the Command Language Processor parses user keystrokes, menus, or typed commands and dispatches them to the Editing or Traveling components.
13.3 Editor User-Interface Criteria
An effective programmer's text editor satisfies clear human-factors and interface criteria: predictable command structure (consistent keybindings and mnemonics), immediate visual feedback (WYSIWYG or instant screen updates after every keystroke), robust error recovery (multi-level undo/redo and auto-save crash recovery), and clean separation of modes or modeless input so users do not accidentally overwrite code.
Chapter 14: Interactive Debugging Systems
14.1 Debugging Functions and Capabilities
Even syntactically valid programs that assemble and link cleanly frequently contain logical bugs—off-by-one loop bounds, uninitialized pointers, or incorrect conditional branches. An interactive debugging system allows the programmer to inspect and control a running program at the source-code or machine-instruction level.
Essential capabilities of an interactive debugger include:
- Execution Tracing and Single-Stepping: Executing one source statement or machine instruction at a time (step into subroutines or step over subroutines) while displaying updated variable and register values.
- Breakpoints: Suspending program execution whenever the program counter reaches a specified line or address. Conditional breakpoints pause execution only when a boolean predicate (e.g.,
i == 99) holds true. - Watchpoints (Data Breakpoints): Halting execution automatically whenever a specific variable or memory location is read or modified, invaluable for catching memory corruption.
- State Inspection and Modification: Displaying formatted values of local/global variables, CPU registers, and raw hexadecimal memory dumps, and allowing the developer to alter variable values mid-run to test fixes.
- Call-Stack Traceback: Printing the active chain of nested function or subroutine calls (stack frames) that led to the current suspension point or crash.
14.2 Relationship with Other System Software
An interactive debugger cannot operate in isolation; it depends tightly on the rest of the system software toolchain:
- Compiler and Assembler: Must emit debugging symbol tables (such as DWARF or STABS records) mapping machine addresses back to source file names, line numbers, variable names, and data types.
- Linker and Loader: Must preserve debugging symbol sections inside the executable and inform the debugger of the exact base address where each shared library or control section was loaded.
- Operating System Kernel: Provides hardware-assisted debugging primitives (such as
ptraceon Unix-like systems), trap/interrupt handling when a breakpoint instruction (e.g.,INT 3) executes, and safe read/write access to the target process's address space.
14.3 Debugger User-Interface Criteria
Because debugging is cognitively demanding, the debugger interface must present information clearly without overwhelming the user. Key criteria include source-level abstraction (showing source lines and variable types rather than forcing raw hex inspection unless requested), synchronized multi-pane views (displaying source code, watch variables, call stack, and console output simultaneously), non-intrusive interaction (avoiding altering program timing or memory layout during observation), and concise command syntax with full scripting support for automated regression diagnostics.
14.4 One-Pass Macro Processor Algorithm (DEFINE, EXPAND, PROCESSLINE)
A clean one-pass macro processor is structured around three cooperating procedures—PROCESSLINE, DEFINE, and EXPAND—coupled with a boolean flag EXPANDING. When PROCESSLINE reads a source statement, it first checks NAMTAB. If the opcode matches a defined macro, it invokes EXPAND; otherwise, if the opcode is MACRO, it invokes DEFINE; otherwise, it writes the line directly to the expanded output stream.
procedure PROCESSLINE()
search NAMTAB for OPCODE
if found then EXPAND()
else if OPCODE = 'MACRO' then DEFINE()
else write source line to expanded file
procedure DEFINE()
enter macro name into NAMTAB
enter macro prototype into DEFTAB
LEVEL = 1
while LEVEL > 0 do
GETLINE()
if this is not a comment line then
substitute positional notation (?1, ?2, ...) for parameters
enter line into DEFTAB
if OPCODE = 'MACRO' then LEVEL = LEVEL + 1
else if OPCODE = 'MEND' then LEVEL = LEVEL - 1
store DEFTAB start and end pointers in NAMTAB
procedure EXPAND()
EXPANDING = TRUE
get first line of macro definition (prototype) from DEFTAB
set up arguments from macro invocation in ARGTAB
write macro invocation to expanded file as a comment
while not end of macro definition do
GETLINE()
PROCESSLINE()
EXPANDING = FALSENotice the subtle use of the LEVEL counter inside DEFINE: if a macro definition contains a nested MACRO ... MEND definition inside its body, LEVEL increments on every inner MACRO and decrements on every inner MEND, ensuring the outer definition does not terminate prematurely at an inner MEND. Similarly, calling PROCESSLINE() recursively inside EXPAND() automatically supports nested macro invocations, provided ARGTAB and the DEFTAB cursor are stored on a call stack.
14.5 Worked Example: Conditional Macro Expansion and Macro-Time Loops
Consider a macro RDBUFF that adapts its generated code depending on whether the caller specifies a buffer-end character (&EOR) or uses a default length. Using macro-time conditional directives (IF, ELSE, ENDIF) and macro-time variables (&EORCK SET 1), the macro processor evaluates boolean conditions during expansion and emits only the matching assembly instructions:
- If
&EORis non-null, the macro emitsLDCH =X'&EOR'andCOMPR A,Sto stop reading when the end-of-record character is encountered. - If
&EORis omitted (null), those comparison instructions are completely omitted from the expanded assembly output, saving both memory and execution cycles. - Using
%NITEMS(&LIST)andWHILEloops, a macro can iterate over a variable-length list of arguments (e.g.,CLEAR_REGS (A,X,S,T)) and emit oneCLEARinstruction per list item at assembly time.
14.6 General-Purpose Macro Processors vs. Integrated Macro Assemblers
A general-purpose macro processor (such as the C preprocessor cpp or Unix m4) operates purely on character streams without understanding the syntax or rules of any specific programming language. It can preprocess C, assembly, HTML, or configuration files, but it cannot inspect assembler expressions or symbol attributes. Conversely, an integrated macro assembler shares its expression evaluator, symbol table, and lexical scanner with the assembler itself, enabling tight integration such as conditional assembly based on symbol types, operand lengths, or location counter values.
14.7 Text Editor Buffer Data Structures
The performance of an interactive text editor's Editing Component depends directly on how the document is stored in memory. Three classic data structures are used in production editors:
| Data Structure | Internal Representation | Strengths and Trade-offs |
|---|---|---|
| Linked List of Lines | Doubly linked list where each node holds one line of text. | O(1) line insertion/deletion; easy line-number navigation; higher per-line pointer overhead. |
| Gap Buffer | Contiguous character array with a movable empty "gap" at the cursor. | O(1) localized typing/backspace at cursor; fast screen redraw; costly only on large cursor jumps. |
| Piece Table | Read-only original file buffer + append-only add buffer + list of piece descriptors. | Instant file open for huge files; trivial infinite undo/redo; no data copying on edits. |
14.8 Hardware vs. Software Breakpoints in Interactive Debuggers
When a user sets a breakpoint in an interactive debugger, the debugger implements it using one of two mechanisms:
- Software Breakpoints: The debugger saves the original instruction byte at the target address in an internal table and overwrites that byte in memory with a special single-byte trap instruction (e.g.,
INT 3/ opcode0xCCon x86, orBRKon ARM). When the CPU executes the trap, the OS suspends the process and notifies the debugger. To resume, the debugger restores the original instruction, single-steps one instruction, re-inserts the trap byte, and continues execution. Unlimited software breakpoints can be set in RAM. - Hardware Breakpoints and Watchpoints: The processor provides a small set of dedicated debug registers (e.g., 4 address registers on x86). Because the hardware comparator monitors instruction fetches and data reads/writes on every bus cycle without modifying memory, hardware breakpoints work even in read-only memory (ROM) and enable fast data watchpoints without slowing down execution.
14.9 Worked Trace: Macro Expansion with NAMTAB, DEFTAB, and ARGTAB
To trace how a one-pass macro processor transforms source code, consider the macro definition RDBUFF from Listing 4.1 followed by two invocations: RDBUFF F1,BUFFER,LENGTH and RDBUFF 05,BUF2,LEN2.
Step 1: Processing the Definition (DEFINE)
When the processor reads RDBUFF MACRO &INDEV,&BUFADR,&RECLTH, it enters RDBUFF into NAMTAB and stores the prototype and body lines into DEFTAB with positional parameter markers:
&INDEVbecomes?1&BUFADRbecomes?2&RECLTHbecomes?3
For example, the line TD =X'&INDEV' is stored in DEFTAB as TD =X'?1', and STCH &BUFADR,X is stored as STCH ?2,X. When MEND is reached, NAMTAB[RDBUFF] records the start and end indices in DEFTAB.
Step 2: First Invocation (RDBUFF F1,BUFFER,LENGTH)
The processor populates ARGTAB: ARGTAB[1] = F1, ARGTAB[2] = BUFFER, ARGTAB[3] = LENGTH. It emits the call as a comment (. RDBUFF F1,BUFFER,LENGTH) and reads lines from DEFTAB, replacing ?1 with F1, ?2 with BUFFER, ?3 with LENGTH, and $ with $AA:
. RDBUFF F1,BUFFER,LENGTH
CLEAR X
CLEAR A
CLEAR S
+LDT #4096
$AALOOP TD =X'F1'
JEQ $AALOOP
RD =X'F1'
COMPR A,S
JEQ $AAEXIT
STCH BUFFER,X
TIXR T
JLT $AALOOP
$AAEXIT STX LENGTHOn the second invocation RDBUFF 05,BUF2,LEN2, ARGTAB is overwritten with [05, BUF2, LEN2] and the unique label suffix advances to $AB ($ABLOOP, $ABEXIT), guaranteeing zero label collisions in the assembler.
14.10 Keyword Parameters and Default Values
When a macro accepts ten or fifteen parameters, positional notation becomes error-prone because callers must remember exact parameter positions and write consecutive commas for omitted arguments (e.g., GENER ,,DIRECT,,,3). Keyword macro parameters solve this by allowing callers to bind arguments by name in any order:
GENER MACRO &TYPE=DIRECT,&CHANNEL=1,&BUFFER=BUF1,&LENGTH=100
...
MEND
. Invocation overriding only &LENGTH and &TYPE:
GENER &LENGTH=256,&TYPE=INDEXEDDuring EXPAND, the macro processor initializes ARGTAB with the default values from the prototype (DIRECT, 1, BUF1, 100) and then overwrites only the entries explicitly specified in the invocation (&LENGTH=256, &TYPE=INDEXED).
14.11 Text Editor Types: Line Editors vs. Screen Editors vs. Structure Editors
Text editors have evolved across three major paradigms, each shaping how the Editing, Viewing, and Display components interact:
- Line Editors (e.g.,
ed,ex): Operate on one numbered line at a time via typed commands (e.g.,10,20dto delete lines 10–20). Suitable for slow teletype terminals and automated batch scripting, but poor for visual spatial orientation. - Full-Screen / Visual Editors (e.g.,
vi,emacs, VS Code): Maintain a continuous two-dimensional viewport over the buffer. Cursor movement keys immediately update the Viewing and Display components, providing instant visual context. - Structure / Syntax-Directed Editors: Understand the grammar of the programming language, maintaining an Abstract Syntax Tree internally rather than raw text lines, preventing syntax errors and enabling semantic refactoring.
14.12 Debugging Techniques: Post-Mortem vs. Interactive vs. Remote Debugging
In addition to live interactive debugging on a local workstation, system software engineers rely on two complementary debugging workflows:
- Post-Mortem Debugging (Core Dumps): When a program crashes with a segmentation fault or illegal instruction in production, the operating system writes a snapshot of the process's memory, registers, and call stack to disk (a core dump). A debugger loads the core file alongside the unstripped symbol table to inspect the exact state at the moment of failure.
- Remote / Kernel Debugging: Embedded systems and operating system kernels cannot run a full GUI debugger locally. Instead, a lightweight debug stub runs on the target machine and communicates over a serial port or network socket with a full interactive debugger running on a host workstation.
14.13 Macro-Time Conditional Expansion Worked Listing
To illustrate how conditional macro-time directives eliminate redundant runtime checks, Listing 4.5 shows a macro RDBUFF that adapts its generated code based on whether the caller supplies an end-of-record character &EOR and a maximum byte count &MAXLTH.
RDBUFF MACRO &INDEV,&BUFADR,&RECLTH,&EOR,&MAXLTH
IF (&EOR NE '')
&EORCK SET 1
ENDIF
CLEAR X
CLEAR A
IF (&EORCK EQ 1)
LDCH =X'&EOR'
RMO A,S
ENDIF
IF (&MAXLTH EQ '')
+LDT #4096
ELSE
+LDT #&MAXLTH
ENDIF
$LOOP TD =X'&INDEV'
JEQ $LOOP
RD =X'&INDEV'
IF (&EORCK EQ 1)
COMPR A,S
JEQ $EXIT
ENDIF
STCH &BUFADR,X
TIXR T
JLT $LOOP
$EXIT STX &RECLTH
MENDWhen invoked as RDBUFF F1,BUFFER,LENGTH,,80, &EOR is empty so &EORCK is not set to 1, and &MAXLTH is 80. Consequently, the macro processor omits LDCH =X'&EOR', RMO A,S, COMPR A,S, and JEQ $EXIT completely, and emits +LDT #80. Every decision is resolved at assembly time with zero runtime branching overhead.
14.14 Text Editor Input/Output and Undo/Redo Architecture
Reliable text editors must guarantee that user edits are never lost during unexpected power failures or software crashes. Two complementary mechanisms achieve this durability:
- Command-Log (Delta) Undo/Redo: Every editing mutation (insert character, delete range, replace block) is pushed onto an Undo Stack as an inverse command record containing the offset, deleted text, and inserted text. Invoking Undo pops the record, applies the inverse edit, and pushes it onto a Redo Stack.
- Journaling and Atomic File Save: Rather than overwriting the target file in place—which risks partial corruption if a crash occurs mid-write—production editors write the modified buffer to a temporary sibling file, flush OS disk caches (
fsync), and atomically rename the temporary file over the original.
14.15 Relationship Between Debugger, Compiler Optimization, and Symbol Tables
When a program is compiled with aggressive optimization (such as -O2 or -O3), instructions are reordered, loop variables are kept strictly in registers, and dead variables are eliminated. As a result, the 1-to-1 correspondence between source lines and machine addresses weakens: single-stepping may jump backward and forward across lines, and inspecting an optimized-out variable reports that its value is unavailable. For this reason, developers routinely compile development builds with debugging flags enabled and optimization disabled (-g -O0) so the compiler emits complete, unoptimized DWARF symbol tables.
14.16 Macro Processor Implementation Details: Recursive Expansion and Stack Management
When a macro body invokes another macro (nested macro call), a single global ARGTAB and a single global DEFTAB pointer are insufficient because the inner macro expansion would overwrite the outer macro's arguments and return position. To support arbitrary nesting depth, the macro processor maintains an explicit Macro Expansion Stack. Each stack frame stores:
- Saved DEFTAB Cursor: The exact line index inside
DEFTABwhere the outer macro should resume once the inner macro finishes. - Local ARGTAB Copy: The array of actual arguments bound to the current invocation.
- Unique Label Counter: The two-letter suffix (
AA,AB,AC, ...) assigned to this specific expansion frame so inner and outer labels never collide.
When EXPAND begins, it pushes a new frame onto the stack; when MEND is reached in DEFTAB, it pops the frame and resumes emitting the outer macro's remaining lines seamlessly.
14.17 Integrated Summary: Comparing System Software Tools
Module IV brings together three complementary programmer productivity tools—macro processors, text editors, and interactive debuggers. While each operates at a different stage of the software lifecycle, all three manipulate structured representations of program text and execution state:
| Tool | Primary Input | Primary Output / Effect | Core Internal Data Structures |
|---|---|---|---|
| Macro Processor | Assembly source with MACRO/MEND |
Expanded assembly source without macro calls | NAMTAB, DEFTAB, ARGTAB, Expansion Stack |
| Text Editor | User keystrokes & source files | Modified text buffers & updated display viewport | Gap Buffer / Piece Table, Undo/Redo Stacks, Display Buffer |
| Interactive Debugger | Executable + DWARF symbol table + user commands | Controlled execution, register/variable inspection, tracebacks | Breakpoint Table, Call Stack Frames, OS ptrace hooks |
Module V: Compilers, Automata, Grammars & Assembler Labs
Chapter 15: Introduction to Compilers and Phases of Compilation
15.1 Role of a Compiler
A compiler is a system program that reads a complete source program written in a high-level language (such as C, Java, or Pascal) and translates it into an equivalent target program in assembly language or binary machine code. Unlike an interpreter, which executes source statements directly, a compiler separates translation time from execution time, enabling aggressive optimization and producing standalone executables that run at native hardware speed.
15.2 Six Phases of Compilation
A modern compiler is structured as a pipeline of six logical phases supported by two cross-cutting modules—the Symbol Table Manager and the Error Handler. The first three phases form the Analysis (Front-End), which is source-language dependent; the last three phases form the Synthesis (Back-End), which is target-machine dependent.
| Phase | Primary Input | Primary Output | Core Responsibility |
|---|---|---|---|
| 1. Lexical Analysis | Character stream | Token stream | Groups characters into meaningful lexemes (identifiers, keywords, operators) and strips whitespace/comments. |
| 2. Syntax Analysis | Token stream | Parse tree / AST | Verifies grammatical structure against a Context-Free Grammar and builds an Abstract Syntax Tree. |
| 3. Semantic Analysis | AST + Symbol Table | Annotated AST | Checks type compatibility, scope rules, argument counts, and inserts implicit type conversions. |
| 4. Intermediate Code Gen | Annotated AST | Three-Address Code | Produces machine-independent intermediate representation (IR) such as quadruples or triples. |
| 5. Code Optimization | Intermediate Code | Optimized IR | Eliminates dead code, folds constants, hoists loop invariants, and reduces instruction cost. |
| 6. Code Generation | Optimized IR | Target Assembly / Machine Code | Allocates CPU registers, selects target machine instructions, and schedules memory accesses. |
Example Walkthrough Across Phases
Consider the high-level assignment statement position = initial + rate * 60 where all variables are floating-point numbers:
- Lexical Analysis produces tokens:
<id,1> <=> <id,2> <+> <id,3> <*> <60>. - Syntax Analysis builds an expression tree respecting operator precedence (
*binds tighter than+). - Semantic Analysis detects that
60is an integer whilerateis floating-point, inserting an explicit conversion nodeinttofloat(60). - Intermediate Code Generation emits Three-Address Code:
t1 = inttofloat(60),t2 = id3 * t1,t3 = id2 + t2,id1 = t3. - Code Optimization folds the constant conversion at compile time:
t1 = id3 * 60.0,id1 = id2 + t1. - Code Generation emits target assembly using floating-point registers (e.g.,
LDF,MULF,ADDF,STF).
Chapter 16: Finite Automata and Lexical Analysis
16.1 Regular Expressions and Token Specification
Lexical analyzers (scanners) recognize tokens whose patterns are defined by regular expressions. For example, an identifier in C is specified as , where denotes concatenation, denotes union, and denotes Kleene closure (zero or more repetitions). To recognize such patterns efficiently in linear time relative to input length, regular expressions are compiled into Finite Automata.
16.2 Deterministic and Non-Deterministic Finite Automata
A Finite Automaton is formally defined as a 5-tuple :
- Non-Deterministic Finite Automaton (NFA): Allows multiple outgoing transitions from a state on the same input symbol, as well as spontaneous -transitions (state changes without consuming any input character). NFAs are easy to construct directly from regular expressions using Thompson's Construction.
- Deterministic Finite Automaton (DFA): Prohibits -transitions and enforces that for every state and every input symbol , there is at most one next state . DFAs execute in strictly deterministic time per character via a 2D transition table.
Every NFA can be converted into an equivalent DFA using the Subset Construction algorithm, where each DFA state represents a set of NFA states reachable together. The resulting DFA can then be minimized by merging indistinguishable states.
Chapter 17: Context-Free Grammars and Syntax Analysis
17.1 Formal Definition of a Context-Free Grammar (CFG)
While regular expressions capture flat token patterns, they cannot express nested structures such as balanced parentheses or nested if-else blocks. Syntax analyzers (parsers) therefore rely on Context-Free Grammars. A CFG is a 4-tuple :
17.2 Derivations, Parse Trees, and Ambiguity
A derivation applies production rules repeatedly starting from until a string of terminals is produced. In a leftmost derivation, the leftmost non-terminal is always expanded first; in a rightmost derivation, the rightmost non-terminal is expanded first. A parse tree is the graphical tree representation of a derivation whose root is , interior nodes are non-terminals, and leaves are terminals.
A grammar is ambiguous if there exists at least one valid sentence that has two or more distinct parse trees (equivalently, two distinct leftmost derivations). Ambiguity is dangerous in compilers because it yields conflicting operator precedence or dangling-else interpretations. Ambiguous expression grammars are rewritten into unambiguous stratified levels (e.g., separating expr, term, and factor).
17.3 Top-Down vs. Bottom-Up Parsing
- Top-Down Parsing (e.g., Recursive Descent, LL(1)): Builds the parse tree from the root downward to the leaves, matching a leftmost derivation. Requires eliminating left recursion () and applying left factoring so the parser can predict the correct rule from a single lookahead token.
- Bottom-Up Parsing (e.g., Shift-Reduce, LR(1), LALR): Builds the parse tree from the terminal leaves upward to , tracing a rightmost derivation in reverse. Handles a strictly larger class of grammars than LL(1), including left-recursive rules, and powers standard parser generators such as Yacc and Bison.
Chapter 18: Practical Assembler Implementation (Lab Exercises)
18.1 Lab 1: Implementing Pass 1 of a Two-Pass Assembler
Pass 1 reads the SIC source file, maintains LOCCTR, validates mnemonics against OPTAB, populates SYMTAB, and writes the intermediate file with byte addresses. Below is a complete, runnable C-style implementation of Pass 1 logic.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char label[20], opcode[20], operand[20];
char code[20], mnemonic[20];
int locctr = 0, start = 0, length = 0;
FILE *fp1 = fopen("input.txt", "r");
FILE *fp2 = fopen("optab.txt", "r");
FILE *fp3 = fopen("symtab.txt", "w");
FILE *fp4 = fopen("intermediate.txt", "w");
fscanf(fp1, "%s %s %s", label, opcode, operand);
if (strcmp(opcode, "START") == 0) {
start = (int)strtol(operand, NULL, 16);
locctr = start;
fprintf(fp4, "%04X\t%s\t%s\t%s\n", locctr, label, opcode, operand);
fscanf(fp1, "%s %s %s", label, opcode, operand);
}
while (strcmp(opcode, "END") != 0) {
fprintf(fp4, "%04X\t%s\t%s\t%s\n", locctr, label, opcode, operand);
if (strcmp(label, "**") != 0)
fprintf(fp3, "%s\t%04X\n", label, locctr);
rewind(fp2);
int found = 0;
while (fscanf(fp2, "%s %s", code, mnemonic) != EOF) {
if (strcmp(opcode, code) == 0) { locctr += 3; found = 1; break; }
}
if (!found) {
if (strcmp(opcode, "WORD") == 0) locctr += 3;
else if (strcmp(opcode, "RESW") == 0) locctr += 3 * atoi(operand);
else if (strcmp(opcode, "RESB") == 0) locctr += atoi(operand);
else if (strcmp(opcode, "BYTE") == 0)
locctr += (operand[0] == 'C') ? (strlen(operand) - 3) : ((strlen(operand) - 3) / 2);
}
fscanf(fp1, "%s %s %s", label, opcode, operand);
}
fprintf(fp4, "%04X\t%s\t%s\t%s\n", locctr, label, opcode, operand);
length = locctr - start;
printf("Program length: %X\n", length);
fclose(fp1); fclose(fp2); fclose(fp3); fclose(fp4);
return 0;
}18.2 Lab 2: Implementing Pass 2 of a Two-Pass Assembler
Pass 2 reads intermediate.txt, resolves opcodes from OPTAB and operand addresses from SYMTAB, converts WORD and BYTE constants to hexadecimal object code, and emits the Header, Text, and End records.
// Inside Pass 2 loop reading (addr, label, opcode, operand) from intermediate.txt:
if (found_in_optab) {
// Look up operand in SYMTAB -> sym_addr (hex)
sprintf(objcode, "%s%04X", machine_opcode, sym_addr);
} else if (strcmp(opcode, "WORD") == 0) {
sprintf(objcode, "%06X", atoi(operand));
} else if (strcmp(opcode, "BYTE") == 0) {
if (operand[0] == 'C') {
for (int i = 2; i < (int)strlen(operand) - 1; i++)
sprintf(objcode + strlen(objcode), "%02X", operand[i]);
} else if (operand[0] == 'X') {
strncpy(objcode, operand + 2, strlen(operand) - 3);
}
}
// Append objcode to current Text record (flush when length reaches 30 bytes)18.3 Lab 3: Implementing a Single-Pass Assembler
A single-pass assembler processes the source file once. Each symbol entry in SYMTAB stores an integer address (initialized to -1 when referenced before definition) and a linked list of forward-reference locations. Whenever a symbol is defined, the assembler traverses its forward-reference list and emits patch records (or updates memory directly in load-and-go mode), eliminating the need for an intermediate file or second scan.
#include <stdio.h>
#include <string.h>
typedef struct RefNode {
int addr;
struct RefNode *next;
} RefNode;
typedef struct {
char name[20];
int addr; // -1 if not yet defined
RefNode *refs; // linked list of forward references
} SymEntry;
// When a forward reference at 'loc' to symbol 'sym' is encountered:
// Add 'loc + 1' (the 2-byte address field offset) to sym.refs, emit 0000.
// When 'sym' is later defined at 'current_loc':
// sym.addr = current_loc;
// For each node in sym.refs: emit patch Text record T <node.addr> 02 <current_loc>18.4 Worked Example: Converting a Regular Expression to DFA
Consider the regular expression , which matches any string over ending in abb. Using Thompson's Construction, we build an NFA with -transitions for alternation, concatenation, and Kleene star. Next, using Subset Construction, we compute as DFA start state A, then repeatedly compute move(T, a) and move(T, b) followed by to discover DFA states B, C, D, E. State E (which contains the NFA accepting state) becomes the DFA accepting state. The resulting 5-state DFA recognizes any matching lexeme in a single left-to-right pass with zero backtracking.
18.5 Eliminating Left Recursion and Left Factoring in CFGs
Top-down predictive parsers (such as LL(1) recursive descent) enter an infinite loop on left-recursive rules of the form . To make the grammar suitable for top-down parsing, every immediate left-recursive production is transformed into right-recursive form:
Similarly, when two productions for the same non-terminal share a common prefix—such as —a 1-token lookahead parser cannot decide which rule to choose. Left factoring extracts the common prefix into a new non-terminal:
else token is inspected.18.6 Compiler Optimization Techniques and Register Allocation
The Code Optimization phase improves intermediate representation without altering program semantics. Common machine-independent optimizations include:
- Constant Folding and Propagation: Evaluating constant expressions (e.g.,
3600 * 24) at compile time and substituting known constant values into downstream uses. - Dead Code Elimination: Removing instructions whose computed results are never used on any reachable execution path, or branches guarded by always-false predicates.
- Common Subexpression Elimination (CSE): Computing an expression such as
a + bonce into a temporary variable and reusing it rather than recomputing it. - Loop-Invariant Code Motion: Moving computations whose operands do not change inside a loop (such as array stride calculations) to the loop pre-header so they execute once instead of on every iteration.
Finally, the Code Generation phase maps intermediate temporaries onto physical CPU registers using graph coloring (representing live-range interferences as graph edges and assigning registers as graph colors) and emits target assembly instructions.
18.7 Compiler vs. Interpreter: Operational Comparison
Both compilers and interpreters translate high-level languages, yet they differ sharply in execution model, performance, and diagnostics:
| Dimension | Compiler | Interpreter |
|---|---|---|
| Translation Granularity | Translates the entire source program into machine code before execution. | Translates and executes source statements one line or bytecode instruction at a time. |
| Execution Speed | Very fast; runs directly as native hardware instructions. | Slower; incurs per-statement parsing/dispatch overhead at runtime. |
| Memory Overhead | Compiler is not needed in memory at runtime. | Interpreter runtime must remain resident in memory during execution. |
| Error Reporting | Reports all syntax and type errors across the entire file together. | Stops immediately at the first runtime or syntax error encountered. |
18.8 Deterministic vs. Non-Deterministic Finite Automata
Although NFA and DFA recognize the exact same class of languages (the regular languages), their structural properties and execution characteristics differ significantly:
| Property | NFA (Non-Deterministic) | DFA (Deterministic) |
|---|---|---|
| Transition Function | (set of next states). | (at most one unique next state). |
| -Transitions | Permitted; state may change without reading input. | Strictly prohibited. |
| State Count | Compact; typically states for regex length . | May require up to states in the worst case. |
| Simulation Speed | Slower () because a set of active states must be tracked. | Fastest (); one table lookup per input character. |
18.9 Bottom-Up Shift-Reduce Parsing Trace
To illustrate how a bottom-up parser constructs a parse tree from tokens upward, consider the unambiguous expression grammar , , parsing the input id + id * id $. At each step, the parser either shifts the next input token onto the stack or reduces a handle at the top of the stack using a grammar production:
| Step | Stack | Remaining Input | Action |
|---|---|---|---|
| 1 | $ |
id + id * id $ |
Shift id |
| 2 | $ id |
+ id * id $ |
Reduce , then , then |
| 3 | $ E |
+ id * id $ |
Shift + |
| 4 | $ E + |
id * id $ |
Shift id |
| 5 | $ E + id |
* id $ |
Reduce , then (do not reduce to due to * lookahead!) |
| 6 | $ E + T |
* id $ |
Shift * |
| 7 | $ E + T * |
id $ |
Shift id |
| 8 | $ E + T * id |
$ |
Reduce , then , then |
| 9 | $ E |
$ |
Accept |
18.10 Intermediate Code Representations: Quadruples, Triples, and Indirect Triples
In the Synthesis front-to-back boundary, Three-Address Code (TAC) instructions such as t1 = -c, t2 = b * t1, t3 = t2 + a are stored in memory using one of three tabular representations:
- Quadruples: Four-field records
(op, arg1, arg2, result). Explicit temporary names (t1, t2) allow easy code motion during optimization without renumbering indices. - Triples: Three-field records
(op, arg1, arg2). Instead of naming temporaries, instructions reference earlier instructions by their table index (e.g.,(0),(1)), saving memory but complicating instruction reordering. - Indirect Triples: Combine a compact Triple table with a separate array of instruction pointers. Optimizers reorder only the pointer array without modifying the triples themselves.
18.11 Complete Lab Sample Trace: Input, SYMTAB, and Object Program
When testing Labs 1, 2, and 3 in the System Software laboratory, a standard SIC test program validates Pass 1 address calculation, Pass 2 object code emission, and single-pass forward-reference patching:
// --- input.txt --- COPY START 1000 ** LDA ALPHA ** ADD ONE ** STA BETA ALPHA WORD 5 ONE WORD 1 BETA RESW 1 ** END 1000 // --- symtab.txt produced by Pass 1 --- ALPHA 1009 ONE 100C BETA 100F // --- Object Program produced by Pass 2 --- H^COPY ^001000^000012 T^001000^0F^001009^18100C^0C100F^000005^000001 E^001000
In Listing 5.4, notice how COPY starts at 1000, the three 3-byte instructions occupy 1000–1008, ALPHA is assigned 1009, ONE is assigned 100C, and BETA (RESW 1) is assigned 100F, giving total program length 1012 - 1000 = 0012 (18 bytes). Pass 2 emits the Header record, a single Text record containing the 15 bytes of machine code and constants (RESW 1 emits no object code), and the End record pointing to 001000.
18.12 Chomsky Hierarchy of Grammars and System Software
Formal language theory classifies grammars into four nested levels known as the Chomsky Hierarchy. Two of these levels form the theoretical backbone of compiler front-ends:
| Grammar Type | Production Form | Recognizing Automaton | Compiler Application |
|---|---|---|---|
| Type 3: Regular Grammar | Finite Automaton (DFA / NFA) | Lexical Analysis (recognizing tokens, identifiers, numbers). | |
| Type 2: Context-Free Grammar | () | Pushdown Automaton (PDA) | Syntax Analysis (parsing expressions, blocks, nested statements). |
| Type 1: Context-Sensitive | Linear Bounded Automaton | Semantic constraints (declaration-before-use, type checking). | |
| Type 0: Unrestricted | () | Turing Machine | General computable transformations and macro/template expansion. |
18.13 Error Recovery Strategies in Lexical and Syntax Analyzers
A compiler should never abort on the very first syntax or lexical error; instead, it should recover cleanly and continue scanning to report as many genuine errors as possible in a single compilation pass:
- Panic-Mode Recovery: Upon encountering an unexpected token, the parser discards input tokens until a designated synchronizing token (such as a semicolon
;or closing brace}) is found, then resumes parsing at the next statement boundary. - Phrase-Level Recovery: The parser performs local repair on the remaining input—such as inserting a missing semicolon or deleting an extraneous comma—and continues.
- Error Productions: Common programmer mistakes (such as writing
=instead of==or missing parentheses) are explicitly added as grammar rules that emit targeted diagnostic messages.
18.14 Symbol Table Management and Error Handler Across Phases
Although the six compilation phases are drawn sequentially, the Symbol Table Manager and Error Handler interact with every phase. Lexical analysis inserts newly scanned identifiers into the symbol table; syntax and semantic analysis attach type signatures, array bounds, and lexical scope depths; intermediate code generation queries offsets; and code generation reads register or stack-frame assignments. Hash tables with chained scope stacks allow lookup while supporting nested block scopes cleanly.
18.15 Worked Example: Top-Down Recursive Descent Parsing
To see how a Context-Free Grammar translates directly into executable parser code, consider the left-recursion-eliminated grammar for arithmetic expressions: , , , , . Each non-terminal becomes a recursive C function that inspects the global lookahead token and calls match(token) to advance the scanner:
void E() { T(); E_prime(); }
void E_prime() {
if (lookahead == '+') { match('+'); T(); E_prime(); }
// else epsilon production: do nothing and return
}
void T() { F(); T_prime(); }
void T_prime() {
if (lookahead == '*') { match('*'); F(); T_prime(); }
}
void F() {
if (lookahead == '(') { match('('); E(); match(')'); }
else if (lookahead == ID) { match(ID); }
else report_syntax_error();
}Because every production begins with a distinct terminal or nullable branch, E(), T(), and F() parse any valid arithmetic expression in linear time with zero backtracking.
18.16 Target Code Generation: Register Allocation and Instruction Selection
The final phase of compilation—Code Generation—maps optimized Three-Address Code into target machine instructions (such as SIC/XE or x86-64). Two core problems dominate this phase:
- Instruction Selection: Choosing the shortest, fastest target instruction sequence for each intermediate operation. On SIC/XE, loading a small constant uses immediate Format 3 (
LDA #5) rather than allocating a memory word, and register-to-register arithmetic uses 2-byte Format 2 (ADDR S,A) instead of 3-byte memory instructions. - Register Allocation and Assignment: Determining which program variables reside in fast CPU registers (
A, S, T, F) at each program point. Modern compilers construct an Interference Graph where nodes represent temporary variables and an edge connects two variables that are simultaneously live. If the graph is -colorable (for available registers), every variable stays in a register; otherwise, a low-frequency variable is spilled to main memory.
18.17 Complete End-to-End Compilation Summary
From the initial character stream in a text editor through lexical tokenization (DFA), hierarchical parsing (CFG), semantic type checking, intermediate code optimization, target code generation, assembly (Pass 1 and Pass 2), static or dynamic linking, and OS loading, every layer of system software cooperates to transform human ideas into deterministic machine execution.
University of Kerala FYUGP Academic Framework
Syllabus details for BCA Semester 3 under official University of Kerala regulations.
Assessment comprises a 70-mark End-Semester Examination (2.5 Hours) and 30-mark Continuous Internal Evaluation.
About System Software (University of Kerala BCA Sem 3)
System Software (UK3DSCCAP205 • 4 Credits • 60 Hours (4 Hrs/Week)) is a DSC offering under the Bachelor of Computer Applications (BCA) Four-Year Undergraduate Programme (UoK FYUGP Regulations 2024 / 2025) at the University of Kerala. Structured across five sequentially integrated instructional modules, the course builds solid theoretical foundations and hands-on technical proficiency in system software. Students engage with core computing principles, structured problem-solving, implementation techniques, and modern industry practices aligned with Kerala State Higher Education Council outcome-based education standards.
System Software Module-by-Module Curriculum Breakdown
Official syllabus unit modules prescribed by the University of Kerala FYUGP framework:
Types of Software & Machine Architecture
Modern computing hardware consists of electronic circuits, registers, arithmetic-logic units, memory arrays, and peripheral controllers that execute binary machine instructions. Because raw hardware interfaces are intricate and unforgiving, software layers are organized to bridge the gap between physical circuitry and human problem-solving. At the broadest level, computer programs are divided into two major categories: application software and system software.
Assemblers
An assembler translates symbolic assembly language programs into binary machine code ready for loading and execution. To accomplish this, an assembler must perform three fundamental tasks: Unlike machine instructions, assembler directives (also called pseudo-instructions) are not translated into machine opcodes. Instead, they instruct the assembler how to organize memory, define constants, or mark program boundaries:
Linkers and Loaders
An object program produced by an assembler or compiler resides on secondary storage (disk) and cannot execute until its binary instructions and data are placed into main memory. Three fundamental operations must occur before execution begins: Loading copies the finalized executable bytes into memory and transfers CPU control to the entry point. Depending on system complexity, these tasks may be handled by a simple absolute loader, a relocating loader, a linking loader, or a separate linkage editor.
Macroprocessor and System Software Tools
Assembly programmers frequently encounter short sequences of instructions that must be repeated at multiple points in a program with slight variations in registers or operands. Using a subroutine ( JSUB / RSUB ) for a 3-instruction sequence introduces call-and-return overhead, linkage register saving, and parameter-passing instructions that may exceed the work of the routine itself. A macro provides an alternative: it is a named, parameterized abbreviation for a sequence of source statements.
Compilers, Automata, Grammars & Assembler Labs
A compiler is a system program that reads a complete source program written in a high-level language (such as C, Java, or Pascal) and translates it into an equivalent target program in assembly language or binary machine code. Unlike an interpreter, which executes source statements directly, a compiler separates translation time from execution time, enabling aggressive optimization and producing standalone executables that run at native hardware speed.
Core Curriculum & Key Topics
- Foundations of System Software and Application Software
- 1 Nature and Role of System Software
- 2 Detailed Comparison: System Software vs. Application Software
- 3 Taxonomy of System Software Components
- System Software and Machine Architecture
- 1 Why Architecture Governs System Software
- 2 The Simplified Instructional Computer (SIC) Standard Model
- The SIC/XE Extended Architecture
Learning Outcomes
- Demonstrate authoritative comprehension of the foundational concepts, architectures, and principles of system software.
- Apply algorithmic, programming, or analytical techniques to design and evaluate practical computing solutions.
- Analyze system trade-offs, security considerations, and industry standards relevant to modern software and IT environments.
- Implement, test, and document structured technical workflows aligned with professional computing practices.
- Achieve exam-ready mastery of University of Kerala FYUGP BCA question patterns across short concepts, technical comparisons, and comprehensive essays.
University of Kerala Examination Scheme for System Software
The evaluation framework for System Software (UK3DSCCAP205) under University of Kerala FYUGP regulations combines Continuous Internal Evaluation (30 Marks) with the university End-Semester Examination (70 Marks) for a total of 100 Marks (2.5 Hours duration):
10 Questions × 3 Marks (Maximum ceiling 24 Marks). Short definitional and conceptual questions covering all 5 syllabus modules.
8 Questions × 6 Marks (Maximum ceiling 36 Marks). Paragraph questions, comparative evaluations, and analytical problems.
2 Questions × 10 Marks (Answer any 1 for 10 Marks). Long-form essay or comprehensive numerical workout problem.
Exam Preparation Strategy:
To score top marks in the University of Kerala UK3DSCCAP205 (System Software) examination: 1. Sketch Layered Architectures & Protocol Flows: Draw neat block diagrams for OSI/TCP-IP layers, OS process state transitions, CPU scheduling Gantt charts, or cryptographic handshakes. 2. Solve Numerical & Scheduling Workouts Cleanly: Show step-by-step calculations for FCFS/SJF/Round Robin waiting times, subnetting, or cipher key transformations. 3. Cite Standards, Protocols & Statutes Accurately: Reference exact protocol numbers, IT Act provisions, or cloud service models (IaaS, PaaS, SaaS) clearly. 4. Balance All 5 Modules: University of Kerala question papers sample definitions, protocol comparisons, and architecture essays across every module.
Exam Preparation & Study Guides — System Software
What is the key distinction in System Software vs. Application Software?
System software consists of low-level, machine-dependent programs that manage hardware resources and provide an execution environment, whereas application software consists of machine-independent programs designed to solve specific end-user domain problems.
What are the core elements of Basic Assembler Functions in System Software?
An assembler translates symbolic assembly programs into binary object code by converting mnemonics to opcodes, replacing symbolic labels with memory addresses, converting data constants, and formatting object records.
What is One-Pass and Multi-Pass Assemblers and why is it important in System Software?
Alternative assembler architectures eliminate intermediate files or resolve chained forward symbol definitions.
What is Linkage Editors, Dynamic Linking, and Bootstrap Loaders and why is it important in System Software?
Advanced binding strategies optimize repeated execution, memory sharing, and system startup.
What are the core elements of Introduction to Compilers and Six Phases of Compilation in System Software?
A compiler translates an entire high-level program into target machine or assembly code through an Analysis Front-End and Synthesis Back-End, supported by a Symbol Table Manager and Error Handler.
What is the official course code and credit structure for System Software at University of Kerala?
System Software carries the official course code UK3DSCCAP205 under the University of Kerala FYUGP BCA framework. It is awarded 4 credits (60 Hours (4 Hrs/Week)), evaluated through 30 marks Continuous Internal Evaluation (CIE) and 70 marks End-Semester Examination (ESE).
Where can students download free PDF notes for System Software?
Students can read all 5 module notes online and download verified chapter-wise PDFs, combined exam notes, and quick revision sheets for System Software (UK3DSCCAP205) directly from DegreeLive (degreelive.in) with zero paywalls or sign-ups.
Course outlines and study notes follow official University of Kerala curricula. Curated by Anoop (Thiruvananthapuram).
For feedback or corrections, contact [email protected].
Related Study Resources & Student Support
Related Semester 3 Subjects
Browse study notes for other courses in BCA Sem 3:
Financial Aid & Grants 2026-27
Check eligibility criteria and deadlines for Kerala government and merit scholarships (e-Grantz 3.0, KSHEC, DCE).
Request Notes
Can't find what you're looking for? Let us know which subject notes you need.