CPU Emulator Tutorial - Goucher College

Transcription

CPU Emulator TutorialThis program is part of the software suitethat accompaniesThe Elements of Computing Systemsby Noam Nisan and Shimon SchockenMIT Presswww.nand2tetris.orgThis software was developed by students at theEfi Arazi School of Computer Science at IDCChief Software Architect: Yaron UkrainitzCPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 1/40

BackgroundThe Elements of Computing Systems evolves aroundthe construction of a complete computer system,done in the framework of a 1- or 2-semester course.In the first part of the book/course, we build thehardware platform of a simple yet powerfulcomputer, called Hack. In the second part, we buildthe computer’s software hierarchy, consisting of anassembler, a virtual machine, a simple Java-likelanguage called Jack, a compiler for it, and a minioperating system, written in Jack.The book/course is completely self-contained,requiring only programming as a pre-requisite.The book’s web site includes some 200 testprograms, test scripts, and all the softwaretools necessary for doing all the projects.CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 2/40

The book’s software suite(All the supplied tools are dual-platform: Xxx.bat startsXxx in Windows, and Xxx.sh starts it in Unix)Simulators(HardwareSimulator, CPUEmulator, VMEmulator):This tutorial isabout theCPU emulator. Used to build hardware platforms andexecute programs; Supplied by us.Translators (Assembler, JackCompiler): Used to translate from high-level to low-level; Developed by the students, using the book’sspecs; Executable solutions supplied by us.Other Bin: simulators and translators software; builtIn: executable versions of all the logicgates and chips mentioned in the book; OS: executable version of the Jack OS; TextComparer: a text comparison utility.CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 3/40

Tutorial ObjectiveLearn how to use theCPU Emulatorfor simulating theexecution of machinelanguage programs onthe Hack computerCPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 4/40

The Hack computerThis CPU emulator simulates theoperations of the Hack computer,built in chapters 1-5 of the book.Hack -- a 16-bit computer equippedwith a screen and a keyboard -resembles hand-held computerslike game machines, PDA’s, andcellular telephones.Before such devices are actuallybuilt in hardware, they are plannedand simulated in software.The CPU emulator is one ofthe software tools used forthis purpose.CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 5/40

CPU Emulator TutorialI.Basic PlatformII. I/O devicesIII. Interactive simulationIV. Script-based simulationV. DebuggingRelevant reading (from “The Elements of Computing Systems”): Chapter 4:Machine Language Chapter 5:Computer Architecture Appendix B: Test Scripting LanguageCPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 6/40

CPU Emulator TutorialPart I:Basic PlatformCPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 7/40

The Hack Computer Platform (simulated)Travel Advice:This tutorial includes some examplesof programs written in the Hackmachine language (chapter 4).There is no need however tounderstand either the language or theprograms in order to learn how to usethe CPU emulator.Rather, it is only important to grasp thegeneral logic of these programs,as explained (when relevant)in the tutorial.CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 8/40

The Hack Computer memoryALUregistersCPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 9/40

Instruction memoryThe loaded code can be viewedeither in binary, or in symbolicnotation (present view)Instruction memory(32K): Holds a machinelanguage programNext instructionis highlightedProgram counter (PC) (16-bit):Selects the next instruction.CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 10/40

Data memory (RAM)Data memory (32K RAM), used for: General-purpose data storage(variables, arrays, objects, etc.) Screen memory map Keyboard memory mapAddress (A) register, used to: Select the current RAM locationOR Set the Program Counter (PC) forjumps (relevant only if the currentinstruction includes a jump directive).CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 11/40

RegistersRegisters (all 16-bit): D: Data register A: Address register M: Stands for the memory registerwhose address is the currentvalue of the Address registerM ( RAM[A])DACPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 12/40

Arithmetic/Logic UnitArithmetic logic unit (ALU)CurrentinstructionM ( RAM[A]) The ALU can compute various arithmeticand logical functions (let’s call them f) onsubsets of the three registers {M,A,D} All ALU instructions are of the form{M,A,D} f ({M,A,D})(e.g. M M-1, MD D A , A 0, etc.) The ALU operation (LHS destination,function, RHS operands) is specified bythe current instruction.DACPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 13/40

CPU Emulator TutorialPart II:I/O DevicesCPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 14/40

I/O devices: screen and keyboardSimulated screen: 256 columns by512 rows, black & white memorymapped device. The pixels arecontinuously refreshed from respectivebits in an 8K memory-map, located atRAM[16384] - RAM[24575].Simulated keyboard:One click on this button causes theCPU emulator to intercept all thekeys subsequently pressed on thereal computer’s keyboard; anotherclick disengages the real keyboardfrom the emulator.CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 15/40

Screen action demoPerspective: That’s how computerprograms put images (text, pictures,video) on the screen: they write bits intosome display-oriented memory device.This is rather hard to do in machinelanguage programming, but quite easyin high-level languages that write to thescreen indirectly, using OS routines likeprintString or drawCircle, as wewill see in chapters 9 and 12.3. Built-in Refresh action:The emulator draws thecorresponding pixels on thescreen. In this case, 16 blackpixels, one for each binary 1.Since all high level programs and OSroutines are eventually translated intomachine language, they all end updoing something like this example.1. Select a word in the RAM regionthat serves as the screen memorymap, e.g. address 16384 (the firstword in the screen memory map).2. Enter a value, say –1(1111111111111111 in binary)CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 16/40

Keyboard action demo1. Click the keyboard enabler2. Press some key on thereal keyboard, say “S”3. Watch here:Keyboard memorymap(a single 16-bitmemory location)CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 17/40

Keyboard action demoPerspective: That’s how computerprograms read from the keyboard: theypeek some keyboard-oriented memorydevice, one character at a time.Visual echoAsGUIlong a key(convenientpressed,effect, not ispartof thehardware platform)This is rather tedious in machinelanguage programming, but quite easy inhigh-level languages that handle thekeyboard indirectly, using OS routineslike readLine or readInt, as we will seein Chapters 9 and 12.Since all high level programs and OSroutines are eventually translated intomachine language, they all end up doingsomething like this example.Keyboard memorymap(a single 16-bitmemory location)CPU Emulator Tutorial, www.nand2tetris.orgThe emulator displaysIts character code in thekeyboard memory mapTutorial IndexSlide 18/40

CPU Emulator TutorialPart III:InteractiveSimulationCPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 19/40

Loading a programNavigate to adirectory and selecta .hack or .asm file.CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 20/40

Loading a programCan switchfrom binary tosymbolicrepresentationCPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 21/40

Running a program4. Watchhere2. Click the“run” button.1. Enter anumber,say 50.3. To speed upexecution,use the speedcontrol sliderProgram’s description: Draws a rectangle at thetop left corner of the screen. The rectangle’s widthis 16 pixels, and its length is determined by thecurrent contents of RAM[0].Note: There is no need to understand the program’scode in order to understand what’s going on.CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 22/40

Running a program4. Watchhere2. Click the“run” button.1. Enter anumber,say 50.3. To speed upexecution,use the speedcontrol sliderProgram’s description: Draws a rectangle at thetop left corner of the screen. The rectangle’s widthis 16 pixels, and its length is determined by thecurrent contents of RAM[0].Note: There is no need to understand the program’scode in order to understand what’s going on.CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 23/40

Hack programming at a glance (optional)Next instruction is M -1.Since presently A 17536, the next ALUinstruction will effect RAM[17536] 1111111111111111. The 17536 address,which falls in the screen memory map,corresponds to the row just below therectangle’s current bottom. In the next screenrefresh, a new row of 16 black pixels will bedrawn there.Program action:Since RAM[0] happens to be 50,the program draws a 16X50rectangle. In this example theuser paused execution whenthere are 14 more rows to draw.Program’s description: Draws a rectangle at thetop left corner of the screen. The rectangle’s widthis 16 pixels, and its length is determined by thecurrent contents of RAM[0].Note: There is no need to understand the program’scode in order to understand what’s going on.CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 24/40

Animation optionsControls execution(and animation)speed.Animation control: Program flow (default): highlights thecurrent instruction in the instruction memoryand the currently selected RAM location Program & data flow: animates allprogram and data flow in the computer No animation: disables all animationThe simulator cananimate both programflow and data flowCPU Emulator Tutorial, www.nand2tetris.orgUsage tip: To execute any non-trivial programquickly, select no animation.Tutorial IndexSlide 25/40

CPU Emulator TutorialPart IV:Script-BasedSimulationCPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 26/40

Interactive VS Script-Based SimulationA program can be executed and debugged: Interactively, by ad-hoc playing with the emulator’s GUI(as we have done so far in this tutorial) Batch-ly, by running a pre-planned set of tests, specified in a script.Script-based simulation enables planning and using tests that are: Pro-active Documented Replicable Complete (as much as possible)Test scripts: Are written in a Test Description Language (described in Appendix B) Can cause the emulator to do anything that can be done interactively,and quite a few things that cannot be done interactively.CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 27/40

The basic settingtest scripttested programCPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 28/40

Example: Max.asmNote: For now, it is not necessary to understand either the Hackmachine language or the Max program. It is only important tograsp the program’s logic. But if you’re interested, we give alanguage overview on the right.Hack language at a glance: (label) // defines a label//// ComputesComputes M[2] max(M[0],M[1])M[2] max(M[0],M[1]) wherewhere MM standsstands forfor RAMRAM@0@0D M//D M// DD M[0]M[0]@1@1D D-M//D D-M// DD DD -- M[1]M[1]@FIRST IS GREATER@FIRST IS GREATERD;JGT//D;JGT// IfIf D 0D 0 gotogoto FIRST IS GREATERFIRST IS GREATER@1@1D M//D M// DD M[1]M[1]@SECOND IS GREATER@SECOND IS GREATER0;JMP//0;JMP// GotoGoto SECOND IS GREATERSECOND IS GREATER(FIRST IS GREATER)(FIRST IS GREATER)@0@0D M//D M// D firstD first numbernumber(SECOND IS GREATER)(SECOND IS GREATER)@2@2M D//M D// M[2] DM[2] D (greater(greater number)number)(INFINITE LOOP)(INFINITE LOOP)@INFINITE LOOP@INFINITE LOOP //// InfiniteInfinite looploop (our(our standardstandard0;JMP//0;JMP// wayway toto terminateterminate programs).programs).CPU Emulator Tutorial, www.nand2tetris.orgTutorial Index @xxx// sets the A register// to xxx’s value The other commands are selfexplanatory; Jump directiveslike JGT and JMP mean “Jumpto the address currently storedin the A register” Before any command involvinga RAM location (M), the Aregister must be set to thedesired RAM address(@address) Before any command involvinga jump, the A register must beset to the desired ROMaddress (@label).Slide 29/40

Sample test script: Max.tst//// LoadLoad thethe programprogram andand setset up:up:loadMax.asm,load Max.asm,output-fileoutput-file Max.out,Max.out,compare-toMax.cmp,compare-to Max.cmp,output-listoutput-list .2RAM[2]%D2.6.2;RAM[2]%D2.6.2;//// TestTest 1:1: max(15,32)max(15,32)setRAM[0]15,set RAM[0] 15,setset RAM[1]RAM[1] 32;32;repeat14{repeat 14 {ticktock;ticktock;}}output;output; //// toto thethe Max.outMax.out filefile//// TestTest 2:2: max(47,22)max(47,22)setPC0,//set PC 0, // ResetReset prog.prog. countercountersetRAM[0]47,set RAM[0] 47,setset RAM[1]RAM[1] 22;22;repeat14{repeat 14 {ticktock;ticktock;}}output;output;The scripting languagehas commands for: Loading programsSetting up output and compare filesWriting values into RAM locationsWriting values into registersExecuting the next command (“ticktack”)Looping (“repeat”)And more (see Appendix B).Notes: As it turns out, the Max program requires 14cycles to complete its execution All relevant files (.asm,.tst,.cmp) mustbe present in the same directory.Output RAM[0]RAM[0] RAM[1]RAM[1] RAM[2]RAM[2] 15323215 32 32 47224747 22 47 //// testtest 3:3: max(12,12)max(12,12)//Etc.// Etc.CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 30/40

Using test scriptsLoad ascriptInteractive loading of the testedprogram itself (.asm or .hack file)is typically not necessary, sincetest scripts typically begin with a“load program” command.CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 31/40

Using test scriptsSpeedcontrolLoad ascriptScript a series ofsimulation steps, eachending with a semicolon;ResetImportantpoint: Whenever an assemblythe scriptprogram (.asm file) is loaded into theemulator, the program is assembled on thePausefly into themachine language code, and this issimulationthe code that actually gets loaded. In theprocess, all comments and white space areExecute stepafter from the code, and all symbolsremovedstep repeatedlyresolve to the numbers that they stand for.Execute the nextsimulation stepCPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 32/40

Using test scriptsView options: Script: Shows the current script; Output: Shows the generated output file; Compare: Shows the given comparison file; Screen: Shows the simulated screen.When the script terminates, thecomparison of the script outputand the compare file is reported.CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 33/40

The default script(and a deeper understanding of the CPU emulator logic)If you load a program file without firstloading a script file, the emulatorloads a default script (always). Thedefault script consists of a loop thatruns the computer clock infinitely.Note that these run/stop buttons don’tcontrol the program. They control thescript, which controls the computer’sclock, which causes the computerhardware to fetch and execute theprogram’s instructions, one instructionper clock cycle.CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 34/40

CPU Emulator TutorialPart V:DebuggingCPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 35/40

Breakpoints: a powerful debugging toolThe CPU emulator continuously keeps track of: A:value of the A registerD:value of the D register PC:value of the Program CounterRAM[i]: value of any RAM locationtime:number of elapsed machine cyclesBreakpoints: A breakpoint is a pair variable, value where variable is one of{A, D, PC, RAM[i], time} and i is between 0 and 32K. Breakpoints can be declared either interactively, or via script commands.For each declared breakpoint, when the variable reaches the value, theemulator pauses the program’s execution with a proper message.CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 36/40

Breakpoints declaration2. Previouslydeclaredbreakpoints1. Open thebreakpointspanel3. Add, delete,or updatebreakpointsCPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 37/40

Breakpoints declaration1. Select the systemvariable on which youwant to break2. Enter the valueat which the breakshould occurCPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 38/40

Breakpoints usage1. Newbreakpoint2. Run theprogram3. When the A register will be 2, orRAM[20] will be 5, or 12 time units(cycles) will elapse, or RAM[21] willbe 200, the emulator will pause theprogram’s execution with anappropriate message.A powerful debugging tool!CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 39/40

Postscript: Maurice Wilkes (computer pioneer) discovers debugging:As soon as we started programming, we found to oursurprise that it wasn't as easy to get programs rightas we had thought. Debugging had to be discovered. Ican remember the exact instant when I realized thata large part of my life from then on was going to bespent in finding mistakes in my own programs.(Maurice Wilkes, 1949).CPU Emulator Tutorial, www.nand2tetris.orgTutorial IndexSlide 40/40

CPU Emulator Tutorial, www.nand2tetris.org Tutorial Index Slide 16/40 Screen action demo 1. Select a word in the RAM region that serves as the screen memory map, e.g. address 16384 (the first word in the screen memory map). 2. Enter a value, say -1 (1111111111111111 in binary) 3. Built-in Refresh action: The emulator draws the corresponding .