What does it take to write an emulator in Java? Vineel Kovvuri

Similar documents
Chip-8 Design Specification

CHAPTER 1 Introduction to Computers and Java

Lecture 2 Microcomputer Organization: Fig.1.1 Basic Components of Microcomputer

Chapter 1: Introduction to Computers and Java

8/23/2014. Chapter Topics. Introduction. Java History. Why Program? Java Applications and Applets. Chapter 1: Introduction to Computers and Java

Introduction. Lecture 1 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

538 Lecture Notes Week 1

The CPU and Memory. How does a computer work? How does a computer interact with data? How are instructions performed? Recall schematic diagram:

Java and Software Design

The x86 Microprocessors. Introduction. The 80x86 Microprocessors. 1.1 Assembly Language

Microprocessors I MICROCOMPUTERS AND MICROPROCESSORS

! Learn how to think like a computer scientist. ! Learn problem solving. ! Read and write code. ! Understand object oriented programming

LAB C Translating Utility Classes

Topics. Hardware and Software. Introduction. Main Memory. The CPU 9/21/2014. Introduction to Computers and Programming

Chapter 1. Introduction to Computers and Programming. M hiwa ahmad aziz

Microcomputer Architecture and Programming

Last 2 Classes: Introduction to Operating Systems & C++ tutorial. Today: OS and Computer Architecture

G52PGP. Lecture oo3 Java (A real object oriented language)

NOTE: ESCAPE is not always being checked for when the Monitor is performing a selected function,

NEW CEIBO DEBUGGER. Menus and Commands

Chapter 2 Lecture 1 Computer Systems Organization

Chapter 5. A Closer Look at Instruction Set Architectures. Chapter 5 Objectives. 5.1 Introduction. 5.2 Instruction Formats

Microprocessor Architecture. mywbut.com 1

Chapter 5. A Closer Look at Instruction Set Architectures

C H A P T E R 1. Introduction to Computers and Programming

ENE 334 Microprocessors

EE2007 Microprocessor systems.

How does breakpoints work in debuggers? Vineel Kumar Reddy Kovvuri

Digital System Design Using Verilog. - Processing Unit Design

Description of the Simulator

Microprocessors/Microcontrollers

Introduction: From Nand to Tetris

static String usersname; public static int numberofplayers; private static double velocity, time;

Programming Languages and Techniques (CIS120)

Notos: Efficient Emulation of Wireless Sensor Networks with Binary-to-Source Translation

Virtual Machine. Part I: Stack Arithmetic. Building a Modern Computer From First Principles.

Chapter 1 Getting Started

IWKS 3300: NAND to Tetris Spring John K. Bennett. Assembler

Object-oriented programming in Java (2)

Microprocessors and rpeanut. Eric McCreath

What the CPU Sees Basic Flow Control Conditional Flow Control Structured Flow Control Functions and Scope. C Flow Control.

Software Programming Objectives

Microprocessors. Microprocessors and rpeanut. Memory. Eric McCreath

OPERATING SYSTEMS. Goals of the Course. This lecture will cover: This Lecture will also cover:

CC411: Introduction To Microprocessors

CHAPTER 4 MARIE: An Introduction to a Simple Computer

Processes. CS 416: Operating Systems Design, Spring 2011 Department of Computer Science Rutgers University

Character Stream : It provides a convenient means for handling input and output of characters.

Lecture1: introduction. Outline: History overview Central processing unite Register set Special purpose address registers Datapath Control unit

Introduction to MiniSim A Simple von Neumann Machine

EC6504 MICROPROCESSOR AND MICROCONTROLLER

PROGRAMMING FUNDAMENTALS

UNIT 2. OPERATING SYSTEM STRUCTURES

Memory Map for the MCU320 board:

Building a Java First-Person Shooter

Introduction: Hello, World Below

Chapter 5. A Closer Look at Instruction Set Architectures

CS 231 Data Structures and Algorithms, Fall 2016

CS 11 java track: lecture 1

Chapter 5. A Closer Look at Instruction Set Architectures. Chapter 5 Objectives. 5.1 Introduction. 5.2 Instruction Formats

CHAPTER 3 JUMP, LOOP, AND CALL INSTRUCTIONS

An Introduction to Computers and Java CSC 121 Spring 2015 Howard Rosenthal

VARDHAMAN COLLEGE OF ENGINEERING (AUTONOMOUS) Shamshabad, Hyderabad

Computer Hardware and Software Introduction. Mr. Smith AP Computer Science A

BASIC INTERFACING CONCEPTS

Chapter. Focus of the Course. Object-Oriented Software Development. program design, implementation, and testing

Multiple Choice Type Questions

MARIE: An Introduction to a Simple Computer

8051 Microcontroller

Java Basic Programming Constructs

Computer Architecture Review CS 595

Lecture 1 - Introduction (Class Notes)

MSMF GATE CENTRE. Sub: MICROPROCESSORS. Time: 50min Date: Marks:33

Q1. Describe C.P.U and its subunits with the help of diagram?

Java Basics Lecture: January 26, 2012 (On-line Lecture 1)

CHAPTER ASSEMBLY LANGUAGE PROGRAMMING

Graphical User Interface (GUI)

Programming. Syntax and Semantics

CG2007 Microprocessor systems.

Unit - II. Computer Concepts and C Programming 06CCP13. Unit II

Virtual Machine Where we are at: Part I: Stack Arithmetic. Motivation. Compilation models. direct compilation:... 2-tier compilation:

Processor design - MIPS

William Stallings Computer Organization and Architecture. Chapter 11 CPU Structure and Function

FIFTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLOGY-MARCH 2014 EMBEDDED SYSTEMS (Common for CT,CM) [Time: 3 hours] (Maximum marks : 100)

QUESTION BANK CS2252 MICROPROCESSOR AND MICROCONTROLLERS

CP122 CS I. Abstract Interfaces, Graphical User Interfaces, Inheritance

Accumulator and memory instructions 1. Loads, stores, and transfers 2. Arithmetic operations 3. Multiply and divide 4. Logical operations 5. Data test

Chapter 2: Operating-System Structures

Computer Processors. Part 2. Components of a Processor. Execution Unit The ALU. Execution Unit. The Brains of the Box. Processors. Execution Unit (EU)

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

CPU Structure and Function

Darrell Bethea May 10, MTWRF 9:45-11:15 AM Sitterson 011

MICROCONTROLLERS 8051

COE 205: Computer Organization & Assembly Language Introductory Experiment-B By Louai Al-Awami

Understand the factors involved in instruction set

CSE 1223: Introduction to Computer Programming in Java Chapter 1 Computer Basics

2. List the five interrupt pins available in INTR, TRAP, RST 7.5, RST 6.5, RST 5.5.

Dispatch techniques and closure representations

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

Five classic components

Transcription:

What does it take to write an emulator in Java? Vineel Kovvuri http://vineelkovvuri.com

Contents 1 Introduction 2 2 What is Chip 8? 2 3 How does a CPU work? 2 4 Emulation 3 5 Cpu 4 6 Memory 5 7 Display 5 8 Keyboard 5 9 Main 6 10 Output 6 1

1 Introduction I am proud, This weekend I did some productive work. I was able to code Chip 8 emulator in Java over a night I have always been fascinated by them and finally I was able to get the damn thing to work! For those of you who are not familiar with software emulator, It is a software which can emulate the functionality of other hardware or software components. Notable examples are video game emulators(dosbox/nes Emulator), general purpose software emulators(qemu) 2 What is Chip 8? It was the software used in some of earlier 8 bit microprocessors. Which provided portability across multiple computer models. Think of it as the JVM of 1970. Similar to JVM byte codes, it has an instruction set. Any program written in this instruction set can be interpreted by the Chip 8 interpreter(which will be preloaded in to memory @ 0x0). Over the weekend, I was trying to write an emulator for this instruction set. Fortunately, I tried and succeeded in do it. In this article I would like to share my thoughts about how to write an emulator in its most basic form. More info of chip 8 can be found here. 3 How does a CPU work? Lets quickly go back to computer organization 101 class. In its most basic form, Every CPU need two inputs. 1. Data 2. Instructions To store and retrieve these, CPU also needs a storage location, we call this as RAM. Along with this we may also need couple more input/output devices. The simplest of these are keyboard and display. Now lets see how all of these interact with one another. Every CPU when powered on will have to read its first instruction to execute. The location of this very first instruction in RAM is usually hard coded to a predefined location by convention. This is when CPU starts interacting with RAM for the first time. Once it fetches the instruction from RAM. It tries to decode it, meaning, it tries to understand want it should do with it. After that, it will execute the operation. As part of this execution any new results will be saved backed to RAM. This process repeats forever. This is the classic Fetch-Decode-Execute cycle. In the process CPU may also interact with keyboard and display. Below illustration explains the process. 2

Figure 1 4 Emulation In general, for any processor to emulate other hardware or software components it has to essentially emulate all the above modules and any associated peripherals. First, we need to get familiar with the Chip 8 Technical Reference found here. This reference covers pretty much every thing we need. Enough theory, Now lets get to the meat of the show, THE CODE. Technically, an emulator can be written in any language. I have chosen Java for its included batteries/libraries. I have organized the source code of my implementation into below 5 Objects. 1. CPU(Chip8Cpu.java) - This is the core module which implements the instruction set of Chip 8 and its decode logic 2. Memory(Chip8Memory.java) - This emulates the RAM and associated constraint to interact with Chip 8 CPU 3. Display(Chip8Display.java) - This emulates the Dxyn - DRW Vx, Vy, nibble 3

4. instruction to capture the output on to the display 5. Keyboard(Chip8Keyboard.java) - This emulates the keyboard input 6. Main(Main.java) - The main driver program which sets up the system 5 Cpu The bulk of the decode processing logic is implemented in the run() method and each instruction is first fetched using Memory objects getword() method(every opcode in of Chip 8 is of 2 bytes). Then decode the instruction and appropriately run the respective executable code. For the majority of time, execution mainly results in moving data around. //Below Is The Trimmed Version Of Original Source Code Found At //https://github.com/vineelkovvuri/chip8emulator/blob/master/src/main/java/com/vineelkumarreddy/chip public class Chip8CPU { private int V[] = new int[16]; //8bit each private int I; //16bit private int DT; //8bit private int ST; //8bit private int PC; //16bit program counter private int SP; //8bit stack pointer private int stack[] = new int[16]; //16bit each private final Chip8Display display; private final Chip8Keyboard keyboard; private final Chip8Memory ram; private final int DT_FREQUENCY = 60; //60 hz private final int ST_FREQUENCY = 60; //60 hz private final int HZ = 1000; // 60hz => 60 times in 1sec or in 1000 milliseconds public void run() { while (true) { //FETCH int instruction = ram.getword(pc); incrementpc(); //fetched the instruction so move on //DECODE int opcode = (instruction >> 12) & 0xf; switch (opcode) { case 0: decode0(instruction); printinstructiondecodecycle(0); break; // Trimmed for brevity private void incrementpc() {... private void decode0(int instruction) { int opcodeargs = instruction & 0xfff; switch (opcodeargs & 0xff) { case 0xEE: // 00EE - RET //EXECUTE PC = stack[--sp]; break; 4

6 Memory //Below Is The Trimmed Version Of Original Source Code Found At //https://github.com/vineelkovvuri/chip8emulator/blob/master/src/main/java/com/vineelkumarreddy/chip public class Chip8Memory { // Chip 8 can address up to 4K bytes private int ram[] = new int[0x1000]; private final int DEFAULT_LOAD_ADDRESS = 0x200; // Read from RAM public int getword(int index) {... public int getbyte(int index) {... // Write to RAM public void setbyte(int index, int value) {... // Load program public void loadprogram(path path) {... // Dump RAM for debug public void dumpram() {... The primary operations done by CPU with memory is reads and writes. These are implemented as getbyte() and setbyte() operations inside Memory object. These reads and writes are actually backed up by 4k integer array. This is the maximum memory addressable by Chip 8 instruction set. 7 Display //Below Is The Trimmed Version Of Original Source Code Found At //https://github.com/vineelkovvuri/chip8emulator/blob/master/src/main/java/com/vineelkumarreddy/chip public class Chip8Display extends JFrame { //Chip8 display size private final int displaywidth = 64, displayheight = 32; private JPanel display[][] = new JPanel[displayHeight][displayWidth]; public boolean setpixel(int x, int y) {... public void clear() {... The one and only instruction in the Chip 8 instruction set that interact with display is Dxyn - DRW Vx, Vy, nibble. When CPU has decoded this instruction, it interface with the Display object and calls setpixel() method to turn on/off a pixel. Display is interesting and it deserves some explanation. The way the instruction works is, given a starting pixel (Vx, Vy). CPU first reads nibble number of bytes from the memory location pointer by I register. Now each bit in each byte corresponds to one pixel starting from (Vx, Vy). For example if jth bit of ith byte is 1 then the pixel at display[vx + j][vy + i] XOR with its previous value. This mechanism is also called Stripping in the reference. The Display object simulates each pixel as a 1212 size JPanel. The entire display contains 6432 such pixels or JPanels. These JPanels are initially added to JFrame window and these will be set to black for off state and green for on state by setpixel() method. 8 Keyboard //Below Is The Trimmed Version Of Original Source Code Found At //https://github.com/vineelkovvuri/chip8emulator/blob/master/src/main/java/com/vineelkumarreddy/chip 5

//This listener is added to Chip8Display module to capture the events public class Chip8Keyboard implements KeyListener { // This keeps the state of the chip 8 keyboard's 15 keys private boolean keyspressed[] = new boolean[0x10]; public boolean ischip8keypressed(int key) {... public void keypressed(keyevent e) {... public void keyreleased(keyevent e) {... There are few instructions which interfaces with keyboard. This object is hooked as the keyboard listener on to the JFrame of Display. This is the only way that I know in Java to capture the keyboard events. Chip 8 has 15 keys starting with 0-9 and A-F. We maintain the state of these keys using an array of 16 integers and convert the A-F key events to their corresponding 10-15 indexes in to the above array. 9 Main public class Main { public static void main(string... args) { // Init peripherals Chip8Keyboard keyboard = new Chip8Keyboard(); Chip8Display display = new Chip8Display(keyboard); Chip8Memory ram = new Chip8Memory(); // Init CPU Chip8CPU cpu = new Chip8CPU(ram, display, keyboard); // Load program to RAM ram.loadprogram(paths.get("/home/vineel/downloads/chip8/chip8/games/invaders")); // Run CPU cpu.run(); Finally, this object is responsible for setting up all the modules and invoking the CPU run() method. Purposefully I kept this object very simple, especially by hard coding the file path to load. 10 Output Now in order to test this, we need some chip 8 programs/games, also called as ROM files. A simple google search will return good number of ROM files. Lets see the output of loading few of them. 6

Figure 2: Invaders 7

Figure 3: TicTac 8

Figure 4: Tetris 9

Figure 5: PingPong This one is for my wife, It is really not a game, but this ROM file exist beside other game files. I know we cannot play with them 10

Figure 6: IBM ROM for my wife ;) I recommened you to read the source code https://github.com/vineelkovvuri/chip8emulator. 11