Experience the inner workings of computing with this 16-bit CPU emulator in Kotlin. It includes a basic assembler and supports a comprehensive fetch-decode-execute cycle, making it an excellent educational tool for understanding CPU architecture and assembly language.
The kotlin-cpu project is a comprehensive 16-bit CPU emulator implemented in Kotlin, designed for educational purposes. This emulator models the essential components of a CPU including registers, RAM, and an execution loop, while also providing a simplistic assembler that transforms assembly code into machine-executable binary.
Key Features
-
CPU Architecture: The emulator features a fully functional 16-bit CPU core, which supports a resource configuration including:
- 64KB RAM
- 8 General-Purpose Registers (
R0toR7) - Program Counter (PC) and Stack Pointer (SP)
- Flags to indicate zero, carry, and negative states
-
Instruction Set Architecture (ISA): The implementation includes an ISA executor that decodes 16-bit instructions and executes various operations. The available instruction formats include:
- R-type, for arithmetic operations
- I-type, for immediate values
- J-type, for jumps and branches
-
Arithmetic Logic Unit (ALU): Implements a variety of operations encompassing arithmetic, bitwise, and shift functionalities. Example operations include addition, subtraction, logical AND, and more.
-
Assembler Pipeline: The assembler processes assembly files (.kasm) through several stages:
- KasmReader: Strips out comments and blank lines from the source code.
- KasmParser: Parses the input to resolve labels and instructions.
- KasmEncoder: Converts instructions into 16-bit encoded words.
- KasmLoader: Loads the encoded instructions into the emulated CPU memory.
Instruction Encoding Details
The instruction encoding is structured as a 16-bit layout with distinct opcodes and operand formats. Several types of operations (such as ADD, SUB, LOAD, etc.) are encoded into the instruction set, accompanied by immediate value processing that supports signed extensions.
Flags and State Management
The emulator effectively handles flags that impact the behavior of subsequent commands and maintain CPU state, enhancing its functionality in executing control flow instructions.
Example Programs
Several sample programs illustrate the capabilities of the emulator, showcasing:
- Arithmetic operations in
alu.kasm - Memory management in
memory.kasm - Conditional branches in
beq.kasmandbne.kasm - Call and return sequence in
call.kasm
Getting Started
The entry point for executing the emulator is found in src/main/kotlin/Main.kt. Users can modify the specified KASM file to run different sample programs, enabling a hands-on approach to learning about CPU operation and assembly language.
For further understanding of how the CPU operates, refer to an insightful series of blog posts:
No comments yet.
Sign in to be the first to comment.