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.


Recommended