virtual machines as an aid in teaching computer concepts

5
Virtual Machines as an Aid in Teaching Computer Concepts Ola Ågren Department of Computing Science Umeå University SE-901 87 Umeå, SWEDEN E-mail: [email protected] Abstract A debugger containing a set of virtual assemblers and a virtual machine are used as teaching tools in order to teach students differences and similarities between architectural styles of computer processors. Programs written by the stu- dents in the virtual assemblers are compiled and executed in this environment so that the students can follow the exe- cution of the programs step by step or at full speed. 1 Introduction The course in Computer Architecture is one of the most popular courses in Computing Science at Umeå University. It is a graduate level course, mandatory for students of the MSC/E program and optional for students of the MSC and BSC/E programs. The main text of the course is the very popular textbook by Patterson and Hennessy [4]. 1.1 Problem The course has grown over the years and had two years ago an enrollment of over 100 students, which meant that the assignments had to be changed because of resource lim- itations. The first assignment has been to build an instruc- tion tracer that executed other programs while collecting vital statistics about it (i.e., size of data used in the opera- tions, register usage, length of basic blocks and calls, bits used in instructions, etc.). This assignment unfortunately required that all students had to have access to machines with MIPS processors. This assignment had to be scrapped since there are only a total of 28 SGI workstations and two SGI servers available and test runs of the assignment led to an unacceptably high load level on the machines running it. Since the author wanted to highlight the issue of differ- ent architectural styles a new assignment was planned. A virtual machine [5] running on all Unix platforms available (SGI Irix, Sun Solaris and IBM AIX) was created together with virtual assemblers that converted assembler code of the different architectural styles to the virtual target machine assembler. Unfortunately, some of the students complained that the terminal based interface was outdated and wanted a graph- ical user interface instead. Since we had already planned to use the same type of assignment last fall (with an en- rollment of over 120), we felt a need to supply one. The choices available at the time were to either set up a “wrap- per” around the older programs 1 or create a new program from scratch. 1.2 Goals There were three goals for the new assignment: 1. It should still provide a deeper understanding of how different computer architectures behave, 2. it had to be easy to understand and use, and 3. it had to be portable to all platforms available at the department (including Windows-based PCs). All of the goals were deemed imperative for the actual im- plementation to be successful. 2 Solution New hardware is expensive both to acquire and main- tain, especially if it makes the machine park heterogeneous. Moreover, very few machines with unorthodox system ar- chitectures are currently in production; especially accumu- lator and stack machines have become very rare lately. This indicated that another route had to be followed: The Virtual Machine. The basis of virtual machinery is the actual hardware that is supposed to build up a machine. This is constructed in such a way that it “executes” the given program in the same way as an actual machine would do, but in software. Virtual machines have been used for a multitude of reasons. One use of virtual machines has been to test hardware systems 1 In the same way that ddd is a wrapper for gdb.

Upload: others

Post on 07-Dec-2021

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Virtual Machines as an Aid in Teaching Computer Concepts

Virtual Machinesasan Aid in TeachingComputer Concepts

OlaÅgrenDepartmentof ComputingScience

UmeåUniversitySE-90187Umeå,SWEDEN

E-mail: [email protected] u.s e

AbstractA debuggercontaininga setof virtual assemblersanda

virtual machineareusedasteachingtoolsin orderto teachstudentsdifferencesandsimilaritiesbetweenarchitecturalstylesof computerprocessors.Programswrittenby thestu-dentsin the virtual assemblersarecompiledandexecutedin this environmentsothatthestudentscanfollow theexe-cutionof theprogramsstepby stepor at full speed.

1 Intr oductionThecoursein ComputerArchitectureis oneof themost

popularcoursesin ComputingScienceatUmeåUniversity.It is a graduatelevel course,mandatoryfor studentsof theMSC/Eprogramandoptionalfor studentsof theMSC andBSC/Eprograms.The main text of the courseis the verypopulartextbookby PattersonandHennessy[4].

1.1 ProblemThecoursehasgrown over theyearsandhadtwo years

agoan enrollmentof over 100 students,which meantthattheassignmentshadto bechangedbecauseof resourcelim-itations. Thefirst assignmenthasbeento build an instruc-tion tracer that executedother programswhile collectingvital statisticsaboutit (i.e., sizeof datausedin theopera-tions, registerusage,lengthof basicblocksandcalls,bitsusedin instructions,etc.). This assignmentunfortunatelyrequiredthat all studentshad to have accessto machineswith MIPSprocessors.Thisassignmenthadto bescrappedsincethereareonly a total of 28 SGI workstationsandtwoSGIserversavailableandtestrunsof theassignmentled toanunacceptablyhigh loadlevel on themachinesrunningit.

Sincethe authorwantedto highlight the issueof differ-ent architecturalstylesa new assignmentwasplanned.Avirtual machine[5] runningonall Unix platformsavailable(SGI Irix, SunSolarisandIBM AIX) wascreatedtogetherwith virtualassemblersthatconvertedassemblercodeof thedifferent architecturalstylesto the virtual target machine

assembler.Unfortunately, someof thestudentscomplainedthat the

terminalbasedinterfacewasoutdatedandwanteda graph-ical userinterfaceinstead. Sincewe hadalreadyplannedto usethe sametype of assignmentlast fall (with an en-rollment of over 120), we felt a needto supplyone. Thechoicesavailableat thetime wereto eithersetup a “wrap-per” aroundthe older programs1 or createa new programfrom scratch.

1.2 GoalsTherewerethreegoalsfor thenew assignment:

1. It shouldstill provide a deeperunderstandingof howdifferentcomputerarchitecturesbehave,

2. it hadto beeasyto understandanduse,and

3. it had to be portableto all platformsavailable at thedepartment(includingWindows-basedPCs).

All of thegoalsweredeemedimperative for theactualim-plementationto besuccessful.

2 SolutionNew hardware is expensive both to acquireand main-

tain,especiallyif it makesthemachineparkheterogeneous.Moreover, very few machineswith unorthodoxsystemar-chitecturesarecurrentlyin production;especiallyaccumu-latorandstackmachineshavebecomeveryrarelately. Thisindicatedthatanotherroutehadto befollowed:TheVirtualMachine.

Thebasisof virtual machineryis theactualhardwarethatis supposedto build up a machine.This is constructedinsuchawaythatit “executes”thegivenprogramin thesamewayasanactualmachinewoulddo,but in software.Virtualmachineshave beenusedfor a multitudeof reasons.Oneuseof virtual machineshasbeento testhardwaresystems

1In thesameway thatddd is awrapperfor gdb .

Page 2: Virtual Machines as an Aid in Teaching Computer Concepts

prior to their actualconstruction(often in VHDL or Ver-ilog). Anotheruseis to give systemdevelopersthe avail-ability of theirown machinewithoutblockingit for all oth-ers(providing theuserwith thesameinterfaceastheunder-lying hardware)[5].

3 The Different Typesof Virtual Machines

Therearefour basictypesof architectures([4, 1]): Accu-mulator, Stack,Memory-MemoryandLoad-Store.In addi-tion to thesefour we addeda fifth, an Index Machine. In-steadof developinga virtual machine(with userinterface)for eachstyle we optedfor a debuggercontainingall fivevirtual assemblersasautonomoussystems.

The virtual assemblerswerecreatedwith small instruc-tion sets(between20 and35 for eachmachine)to empha-sizethemainprinciplesasclearlyaspossible.Thediffer-ent assemblerlanguageshadsomepartsthat weresimilar(e.g.,nameof the normaloperations)andsomethat werenot (i.e., branching/jumping,how to createvariables,andarchitecture-specificinstructions).Schematicsfor the vir-tualmachinesarefoundin AppendixA.

3.1 Accumulator

The accumulatormachineis oneof the mostbasicpro-cessorarchitecturescreated.This typeof machinehasoneregister(calledthe accumulator)that is implicitly usedasoneof theoperandsin all instructionsandis thedestinationof all calculations.It is thetargetof all loadsandthesourcefor all stores.

3.2 Index

This is basicallyan accumulatormachinewith the ad-dition of two index registersthat can be usedas tempo-rary storageand/oroffsetregisterin loadandstoreinstruc-tions. Theseextra operationsmake themachinemoresuit-able for implementationof high-level languagesand dataconstructs,e.g.vectoroperations.

Wehavemodeledtheseoperationsafterthe6502proces-sor, sincethatprocessorusedto bequitepopularandhasauserfriendly instructionset.

3.3 Stack

A strictstackmachinedoesnothaveany generalpurposeregistersat all. All data is handledin a last-in, first-outstack.Operationstaketheiroperandsfrom thestackandtheresultis pushedbackonto thestack,exceptfor operationsthatmovedatafrom memoryto stackor viceversa.

3.4 Memory-MemoryA strict memory-memorymachinedoesnot have any

generalpurposeregisters.Themaindifferencewith respectto stackmachinesis that operationsin a memory-memorymachineusethevaluesin memorycellsasoperandsandtheresultis storedin amemorycell.

3.5 Load-StoreThe load-storemachinehasa fixed numberof registers

(in our case32) thatareusedasoperandsandthedestina-tion of the resultfor operations,exceptfor operationsthattransferdatabetweenregistersandmemoryor viceversa.

4 ImplementationIn orderto gettherequiredportabilityevenin thegraphi-

caluserinterface(therebyruling outC andX11) Java2 waschosenastheimplementationlanguage.Anotherbenefitofthis choicewas that someof the codewritten in C couldbeusedwith few changes.Thebasicstructureof both thevirtual machineand most of the virtual assemblerscouldberetained,therebyincreasingtheprobabilitythatthenewsystemwouldwork in muchthesamewayastheold.

The programusesthe suffix of the input files to decidewhich virtual assemblerto usewhen parsingthe file (i.e.ac , ix , st , mmandls , respectively).

4.1 Implementation-SpecificBugThevirtual assemblerfor thememory-memorymachine

usedto beimplementedpartlyusingyacc,andjava_cup(byScottHudson,FrankFlanneryandC. ScottAnanian)wasusedasa substitutefor yacc. The two programpackagesareunfortunatelynot plug-and-playreplacementsfor eachother, so thereis a differencein behavior in theendprod-uct. The main differenceis that reductionsareperformedeagerly(assoonasa projectionis fulfilled) [2, 3] in yacc,but requireyet anothertoken in java_cup.This meantthatif a codecontainedan “end fct” (indicatingthat fct is thelabel to startexecutionat) at the end,executionwould inthe java_cupversionstartat thefirst valid operationin thefile evenif fct wasfurtherdown in thesourcefile.

5 AssignmentsWe have now usedthis assignmentfor two yearsrun-

ning, with somesmallerchanges.During the first coursewe let thestudentsdecidefor themselveswhichmathemat-ical function to implementin the four virtual assemblers,disallowing factorialfunctionsin themark-upassignments.During the secondcoursethe studentshad to choosetwo

2Java is a trademarkof SunMicrosystems,Inc.

Page 3: Virtual Machines as an Aid in Teaching Computer Concepts

functionsto implementin all five availablevirtual assem-blers,of which onehadto bea fifth degreepolynomial(toshow thestrengthsof thestackmachine).

6 SampleScreenshotThescreenshot(Figure6) in AppendixB shows thevir-

tualmachine/debuggerin operation.It is currentlyprocess-ing astackmachineprogramthatcalculatesthefactorialof10,andis justaboutto multiply thetoptwo numbersonthestack.

7 AvailabilityThe virtual machine is together with some exam-

ple assembler files available for download throughhttp://www.cs.u mu.s e/ ˜ol a/ Dark / . Currentdocumentationis unfortunatelyin Swedish,but a full tech-nical reportin Englishwill beavailablethisautumn.

8 ConclusionsThe studentshave found it much easierto understand

how different architecturalstyles affect code (generality,parameterpassing,layout, execution, porting, etc.) afterthisassignmentwasaddedto thecurriculum.Sincethiswasoneof themaingoalsfor theassignmentit canberegardedasa successsofar.

The systemappearsto be easyto use,therebyfulfillingthe secondgoal. So far, only a few bugs turnedout toexist andthosewill be correctedbeforenext course. Thegraphicaluser interface was seenas a boostby most ofthestudentsbut someusedtheolderscriptsinstead.Somestudentsmaderequestsfor minor changes,mainly in errorpresentationanddefault behavior of certaincharactercom-binations.

The third major goal of this assignmentwas that anyworkstationor server couldbeusedasa platform for pro-gramming and debugging of the students’assignments,therebyreducingtheburdenof theSGImachines.Thisgoalwasclearly achieved sincethe programcould be installedonany machinethatsupportsJava 1.1or higher.

9 Future Updatesand AdditionsTheknown bugswill beeliminated.Themajor thing to

changewill beto rewrite thememory-memoryassemblerina recursive-descentparserin Java, thuscorrectingthe dif-ferencein behavior betweenyaccandjava_cupdescribedin section4.1.

Thevirtual assemblerpartof thepreviousversionof thisassignmentwill beusedasafront-endin alaterassignment.Thestudentswill implementtheirown virtual machinethat

will berequiredto matchthevirtual assembler, therebyex-ecutingthecodethatthey wrotein theassignmentwith thevirtual machine.

References

[1] ÅGREN, O. TeachingComputerConceptsUsingVir-tualMachines.SIGCSE Bulletin 31, 2 (June1999).

[2] AHO, A. V., SETHI , R., AND ULLMAN, J. D. Compil-ers: principles, techniques and tools. Addison-Wesley,Reading,Massachusetts,1986.

[3] LEVINE, J. R., MASON, T., AND BROWN, D. lex &yacc, seconded. O’Reilly & Associates,Inc.,Sebasto-pol, California,1992.

[4] PATTERSON, D. A., AND HENNESSY, J. L. Computerorganization & design: the hardware/software inter-face, first ed. MorganKaufmannPublishers,Inc., SanFrancisco,California,1994.

[5] SILBERSCHATZ, A., AND GALVIN, P. B. OperatingSystem Concepts, fifth ed. Addison-Wesley, Reading,Massachusetts,1997.

Appendix A: Schematicsof the Virtual Machines

Figures1 to4showstheprogrammers’view of thevirtualmachinesschematics,while Figure 5 is the layout of thebasicvirtual machineactuallyexecutingthecode.

Bus

ALU

Program memory

Data memory

Accumulator

Return stack

Figure1: Schematicsof theaccumulatormachine.

Page 4: Virtual Machines as an Aid in Teaching Computer Concepts

ALU Bus

Stack pointer

Data memory and stack

Program memory

Return stack

Figure2: Schematicsof thestackmachine.

BusALU

Return stack

Data memory

Program memory

Figure3: Schematicsof thememory-memorymachine.

Appendix B: The User InterfaceThe different partsof the userinterfaceare (as can be

seenin Figure6):

� Menu bar: This givesaccessto the“File” pop-upmenuanda helpwindow. Thecommandsavailableare“Loadfile”, “Reloadfile”, “Print to file” and“Quit”;

� Top: Currentinformationanddebuggingcommands,i.e.nameof currentlyloadedfile, numberof assemblerlinesandinternalstepsexecuted,a“step” button(executesoneassemblercommand),and a “go” button (executecodeat full speeduntil a "stop"-instructionis executedor aninvalid memorylocationis reached);

� Left column: Sourceview of the currently loadedfile,with theline thatis justaboutto beexecutedhighlighted;

ALU

Bus

Return stack

Registers

Data memory and stack

Program memory

Figure4: Schematicsof theload-storemachine.

A

B

C

BusALU

Data memory and stack

Program memory

Return stack

Registers

Figure5: Schematicsof thevirtual machine.

� Upper right: The variablewindow. It shows the cur-rentvalueof all variablesdefinedin theprogram.Doubleclicking onavariablebringsupadialogueto setthevalueof thatvariable;

� Lower right: Themiscellaneouswindow. It will alwaysshow non-zeromemory locationsin the lower part ofmemory, but also informationthat dependson the typeof sourcecodethatis currentlyloaded:

– Accumulator: For accumulatorandindex machinecode;

– Index registers:For index machinecode;

– Stack: For stackandload-storemachinecode;

– Non-zero registers:For load-storemachinecode.

Page 5: Virtual Machines as an Aid in Teaching Computer Concepts

Figure6: Screenshotof theuserinterface.