SlideShare uma empresa Scribd logo
1 de 11
How to Build a Virtual Machine
Terence Parr
University of San Francisco
May 13, 2014
Preliminaries
• What is a VM?
– A simulated computer that runs a simple instruction set
(bytecodes).
• And why do we want one?
– We can’t execute high-level languages like Java directly on
the computer
– Rather than compile to machine code, we generate
bytecodes for a VM; much easier
– We get code portability to anywhere with same VM
– But bytecodes are slower than raw machine code
– Ultimately VMs today compile by codes to machine code
on the fly
Goal: Simulate a simple computer
0600 A4 44 MEMCPY LDY CNT+0 ;Set Y = CNT.L
0602 D0 05 BNE LOOP ;If CNT.L > 0, then loop
0604 A5 45 LDA CNT+1 ;If CNT.H > 0,
0606 D0 01 BNE LOOP ; then loop
0608 60 RTS ;Return
0609 B1 40 LOOP LDA (SRC),Y ;Load A from ((SRC)+Y)
060B 91 42 STA (DST),Y ;Store A to ((DST)+Y)
060D 88 DEY ;Decr CNT.L
060E D0 F9 BNE LOOP ;if CNT.L > 0, then loop
0610 E6 41 INC SRC+1 ;Incr SRC += $0100
0612 E6 43 INC DST+1 ;Incr DST += $0100
0614 88 DEY ;Decr CNT.L
0615 C6 45 DEC CNT+1 ;Decr CNT.H
0617 D0 F0 BNE LOOP ;If CNT.H > 0, then loop
0619 60 RTS ;Return
061A END
Machine code Assembly code
address
Here is a real CPU block diagram and code
Programming our VM
• Our bytecodes will be very regular and higher
level than machine instructions
• Each bytecode does a tiny bit of work
• Print 1+2:
ICONST 1
ICONST 2
IADD
PRINT
0000: iconst 1 stack=[ 1 ]
0002: iconst 2 stack=[ 1 2 ]
0004: iadd stack=[ 3 ]
0005: print stack=[ ]
0006: halt stack=[ ]
Stack code Execution trace
Our instruction set
iadd integer add (pop 2 operands, add, push result)
isub
imul
ilt integer less than
ieq
br addr branch to address
brt addr branch if true
brf addr
iconst value push integer constant
load addr load local
gload addr load global variable
store addr
gstore addr
print
pop toss out the top of stack
call addr, numArgscall addr, expect numArgs
ret return from function, expected result on top of stack
halt
Instruction format
• Code memory is 32-bit word addressable
• Bytecodes stored as ints but they are bytes
• Data memory is 32-bit word addressable
• Addresses are just integer numbers
• Operands are 32-bit integers
bytecode
bytecode operand
bytecode operand1 operand2
+0
+1
+2
Sample bytecodes
0000 9 1 ICONST 1
0002 9 2 ICONST 2
0004 1 IADD
0005 14 PRINT
Address Bytecodes Assembly bytecode
Our little stack machine
data
memory
code
memory
...
stack
sp
fp
ip
registers
fetch
decode
execute
Fetch: opcode = code[ip]
Decode: switch (opcode) {…}
Execute: stack[++sp] = stack[sp--] + stack[sp--] (iadd instruction)
CPU: Fetch, decode, execute cycle
Sample implementations
case BR :
ip = code[ip++];
break;
case IADD:
b = stack[sp--]; // 2nd opnd at top of stack
a = stack[sp--]; // 1st opnd 1 below top
stack[++sp] = a + b; // push result
break;
Implementing functions
• f();
• g(int x,y) {
int z;
z = f(x,y);
...
• return 9;
call f, 0
pop
load x (fp-4)
load y (fp-3)
call f, 2
store z (fp+1)
...
iconst 9
ret

Mais conteúdo relacionado

Mais procurados

Mastering PostgreSQL Administration
Mastering PostgreSQL AdministrationMastering PostgreSQL Administration
Mastering PostgreSQL Administration
Command Prompt., Inc
 

Mais procurados (20)

Introduction to eBPF and XDP
Introduction to eBPF and XDPIntroduction to eBPF and XDP
Introduction to eBPF and XDP
 
Kernel Recipes 2017 - Understanding the Linux kernel via ftrace - Steven Rostedt
Kernel Recipes 2017 - Understanding the Linux kernel via ftrace - Steven RostedtKernel Recipes 2017 - Understanding the Linux kernel via ftrace - Steven Rostedt
Kernel Recipes 2017 - Understanding the Linux kernel via ftrace - Steven Rostedt
 
eBPF Basics
eBPF BasicseBPF Basics
eBPF Basics
 
How Functions Work
How Functions WorkHow Functions Work
How Functions Work
 
Heap exploitation
Heap exploitationHeap exploitation
Heap exploitation
 
Binary exploitation - AIS3
Binary exploitation - AIS3Binary exploitation - AIS3
Binary exploitation - AIS3
 
Pwning in c++ (basic)
Pwning in c++ (basic)Pwning in c++ (basic)
Pwning in c++ (basic)
 
New Ways to Find Latency in Linux Using Tracing
New Ways to Find Latency in Linux Using TracingNew Ways to Find Latency in Linux Using Tracing
New Ways to Find Latency in Linux Using Tracing
 
syzkaller: the next gen kernel fuzzer
syzkaller: the next gen kernel fuzzersyzkaller: the next gen kernel fuzzer
syzkaller: the next gen kernel fuzzer
 
Faster packet processing in Linux: XDP
Faster packet processing in Linux: XDPFaster packet processing in Linux: XDP
Faster packet processing in Linux: XDP
 
Vmlinux: anatomy of bzimage and how x86 64 processor is booted
Vmlinux: anatomy of bzimage and how x86 64 processor is bootedVmlinux: anatomy of bzimage and how x86 64 processor is booted
Vmlinux: anatomy of bzimage and how x86 64 processor is booted
 
Linux Instrumentation
Linux InstrumentationLinux Instrumentation
Linux Instrumentation
 
Continuous Go Profiling & Observability
Continuous Go Profiling & ObservabilityContinuous Go Profiling & Observability
Continuous Go Profiling & Observability
 
Alfresco y SOLR, presentación en español
Alfresco y SOLR, presentación en españolAlfresco y SOLR, presentación en español
Alfresco y SOLR, presentación en español
 
LLVM Instruction Selection
LLVM Instruction SelectionLLVM Instruction Selection
LLVM Instruction Selection
 
Reverse Mapping (rmap) in Linux Kernel
Reverse Mapping (rmap) in Linux KernelReverse Mapping (rmap) in Linux Kernel
Reverse Mapping (rmap) in Linux Kernel
 
Mastering PostgreSQL Administration
Mastering PostgreSQL AdministrationMastering PostgreSQL Administration
Mastering PostgreSQL Administration
 
Anatomy of the loadable kernel module (lkm)
Anatomy of the loadable kernel module (lkm)Anatomy of the loadable kernel module (lkm)
Anatomy of the loadable kernel module (lkm)
 
Linux Kernel Booting Process (1) - For NLKB
Linux Kernel Booting Process (1) - For NLKBLinux Kernel Booting Process (1) - For NLKB
Linux Kernel Booting Process (1) - For NLKB
 
Presto on Apache Spark: A Tale of Two Computation Engines
Presto on Apache Spark: A Tale of Two Computation EnginesPresto on Apache Spark: A Tale of Two Computation Engines
Presto on Apache Spark: A Tale of Two Computation Engines
 

Destaque

Antlr Conference Drools & Hibernate
Antlr Conference   Drools & HibernateAntlr Conference   Drools & Hibernate
Antlr Conference Drools & Hibernate
Alexandre Porcelli
 
Electric power transmission system engineering 2nd edition by turan gonen
Electric power transmission system engineering  2nd edition by turan gonenElectric power transmission system engineering  2nd edition by turan gonen
Electric power transmission system engineering 2nd edition by turan gonen
Ummi Robbania Mushthofa
 
Powerpoint presentation about lenz's law
Powerpoint presentation about lenz's lawPowerpoint presentation about lenz's law
Powerpoint presentation about lenz's law
rdelizoneyou
 

Destaque (19)

Static vs dynamic types
Static vs dynamic typesStatic vs dynamic types
Static vs dynamic types
 
Antlr Conference Drools & Hibernate
Antlr Conference   Drools & HibernateAntlr Conference   Drools & Hibernate
Antlr Conference Drools & Hibernate
 
How to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machineHow to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machine
 
From SIP to WebRTC and vice versa
From SIP to WebRTC and vice versaFrom SIP to WebRTC and vice versa
From SIP to WebRTC and vice versa
 
Dc machines electrical machines – i
Dc machines   electrical machines – iDc machines   electrical machines – i
Dc machines electrical machines – i
 
Understanding the Dalvik Virtual Machine
Understanding the Dalvik Virtual MachineUnderstanding the Dalvik Virtual Machine
Understanding the Dalvik Virtual Machine
 
Dynamic analysis of dc machine
Dynamic analysis of dc machineDynamic analysis of dc machine
Dynamic analysis of dc machine
 
Gas turbine-power-plant[1]
Gas turbine-power-plant[1]Gas turbine-power-plant[1]
Gas turbine-power-plant[1]
 
Basics of Electrical Machines
Basics of Electrical MachinesBasics of Electrical Machines
Basics of Electrical Machines
 
Distributed Generation
Distributed Generation Distributed Generation
Distributed Generation
 
Electrical Machines Notes
Electrical Machines NotesElectrical Machines Notes
Electrical Machines Notes
 
Electric machine
Electric machineElectric machine
Electric machine
 
power plant engineering
power plant engineeringpower plant engineering
power plant engineering
 
Electric power transmission system engineering 2nd edition by turan gonen
Electric power transmission system engineering  2nd edition by turan gonenElectric power transmission system engineering  2nd edition by turan gonen
Electric power transmission system engineering 2nd edition by turan gonen
 
Lecture 25 induction. faradays law. lenz law
Lecture 25   induction. faradays law. lenz lawLecture 25   induction. faradays law. lenz law
Lecture 25 induction. faradays law. lenz law
 
Power plant engineering complete five unit vtu notes pdf download
Power plant engineering complete five unit vtu notes pdf downloadPower plant engineering complete five unit vtu notes pdf download
Power plant engineering complete five unit vtu notes pdf download
 
12.1 - Lenz's law
12.1  - Lenz's law12.1  - Lenz's law
12.1 - Lenz's law
 
Powerpoint presentation about lenz's law
Powerpoint presentation about lenz's lawPowerpoint presentation about lenz's law
Powerpoint presentation about lenz's law
 
Data acquisition system (DAS)
Data acquisition system (DAS)Data acquisition system (DAS)
Data acquisition system (DAS)
 

Semelhante a How to build a virtual machine

Bits of Advice for the VM Writer, by Cliff Click @ Curry On 2015
Bits of Advice for the VM Writer, by Cliff Click @ Curry On 2015Bits of Advice for the VM Writer, by Cliff Click @ Curry On 2015
Bits of Advice for the VM Writer, by Cliff Click @ Curry On 2015
curryon
 
Vectorization on x86: all you need to know
Vectorization on x86: all you need to knowVectorization on x86: all you need to know
Vectorization on x86: all you need to know
Roberto Agostino Vitillo
 
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
Positive Hack Days
 
Chapter 1SyllabusCatalog Description Computer structu
Chapter 1SyllabusCatalog Description Computer structuChapter 1SyllabusCatalog Description Computer structu
Chapter 1SyllabusCatalog Description Computer structu
EstelaJeffery653
 
FPGA design with CλaSH
FPGA design with CλaSHFPGA design with CλaSH
FPGA design with CλaSH
Conrad Parker
 
LECTURE2 td 2 sue les theories de graphes
LECTURE2 td 2 sue les theories de graphesLECTURE2 td 2 sue les theories de graphes
LECTURE2 td 2 sue les theories de graphes
AhmedMahjoub15
 
EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5
PRADEEP
 

Semelhante a How to build a virtual machine (20)

Bits of Advice for the VM Writer, by Cliff Click @ Curry On 2015
Bits of Advice for the VM Writer, by Cliff Click @ Curry On 2015Bits of Advice for the VM Writer, by Cliff Click @ Curry On 2015
Bits of Advice for the VM Writer, by Cliff Click @ Curry On 2015
 
Arduino by yogesh t s'
Arduino by yogesh t s'Arduino by yogesh t s'
Arduino by yogesh t s'
 
Vectorization on x86: all you need to know
Vectorization on x86: all you need to knowVectorization on x86: all you need to know
Vectorization on x86: all you need to know
 
Rig nitc [autosaved] (copy)
Rig nitc [autosaved] (copy)Rig nitc [autosaved] (copy)
Rig nitc [autosaved] (copy)
 
Java Jit. Compilation and optimization by Andrey Kovalenko
Java Jit. Compilation and optimization by Andrey KovalenkoJava Jit. Compilation and optimization by Andrey Kovalenko
Java Jit. Compilation and optimization by Andrey Kovalenko
 
Using Python3 to Build a Cloud Computing Service for my Superboard II
Using Python3 to Build a Cloud Computing Service for my Superboard IIUsing Python3 to Build a Cloud Computing Service for my Superboard II
Using Python3 to Build a Cloud Computing Service for my Superboard II
 
Module_01.ppt
Module_01.pptModule_01.ppt
Module_01.ppt
 
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
 
Microcontroller part 4
Microcontroller part 4Microcontroller part 4
Microcontroller part 4
 
Semtex.c [CVE-2013-2094] - A Linux Privelege Escalation
Semtex.c [CVE-2013-2094] - A Linux Privelege EscalationSemtex.c [CVE-2013-2094] - A Linux Privelege Escalation
Semtex.c [CVE-2013-2094] - A Linux Privelege Escalation
 
arduinoedit.pptx
arduinoedit.pptxarduinoedit.pptx
arduinoedit.pptx
 
Programming arduino makeymakey
Programming arduino makeymakeyProgramming arduino makeymakey
Programming arduino makeymakey
 
Introduction to Microcontrollers
Introduction to MicrocontrollersIntroduction to Microcontrollers
Introduction to Microcontrollers
 
Chapter 1SyllabusCatalog Description Computer structu
Chapter 1SyllabusCatalog Description Computer structuChapter 1SyllabusCatalog Description Computer structu
Chapter 1SyllabusCatalog Description Computer structu
 
FPGA design with CλaSH
FPGA design with CλaSHFPGA design with CλaSH
FPGA design with CλaSH
 
LECTURE2 td 2 sue les theories de graphes
LECTURE2 td 2 sue les theories de graphesLECTURE2 td 2 sue les theories de graphes
LECTURE2 td 2 sue les theories de graphes
 
EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5
 
Instruction Set Architecture
Instruction Set ArchitectureInstruction Set Architecture
Instruction Set Architecture
 
ISA.pptx
ISA.pptxISA.pptx
ISA.pptx
 
Java on arm theory, applications, and workloads [dev5048]
Java on arm  theory, applications, and workloads [dev5048]Java on arm  theory, applications, and workloads [dev5048]
Java on arm theory, applications, and workloads [dev5048]
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

How to build a virtual machine

  • 1. How to Build a Virtual Machine Terence Parr University of San Francisco May 13, 2014
  • 2. Preliminaries • What is a VM? – A simulated computer that runs a simple instruction set (bytecodes). • And why do we want one? – We can’t execute high-level languages like Java directly on the computer – Rather than compile to machine code, we generate bytecodes for a VM; much easier – We get code portability to anywhere with same VM – But bytecodes are slower than raw machine code – Ultimately VMs today compile by codes to machine code on the fly
  • 3. Goal: Simulate a simple computer 0600 A4 44 MEMCPY LDY CNT+0 ;Set Y = CNT.L 0602 D0 05 BNE LOOP ;If CNT.L > 0, then loop 0604 A5 45 LDA CNT+1 ;If CNT.H > 0, 0606 D0 01 BNE LOOP ; then loop 0608 60 RTS ;Return 0609 B1 40 LOOP LDA (SRC),Y ;Load A from ((SRC)+Y) 060B 91 42 STA (DST),Y ;Store A to ((DST)+Y) 060D 88 DEY ;Decr CNT.L 060E D0 F9 BNE LOOP ;if CNT.L > 0, then loop 0610 E6 41 INC SRC+1 ;Incr SRC += $0100 0612 E6 43 INC DST+1 ;Incr DST += $0100 0614 88 DEY ;Decr CNT.L 0615 C6 45 DEC CNT+1 ;Decr CNT.H 0617 D0 F0 BNE LOOP ;If CNT.H > 0, then loop 0619 60 RTS ;Return 061A END Machine code Assembly code address Here is a real CPU block diagram and code
  • 4. Programming our VM • Our bytecodes will be very regular and higher level than machine instructions • Each bytecode does a tiny bit of work • Print 1+2: ICONST 1 ICONST 2 IADD PRINT 0000: iconst 1 stack=[ 1 ] 0002: iconst 2 stack=[ 1 2 ] 0004: iadd stack=[ 3 ] 0005: print stack=[ ] 0006: halt stack=[ ] Stack code Execution trace
  • 5. Our instruction set iadd integer add (pop 2 operands, add, push result) isub imul ilt integer less than ieq br addr branch to address brt addr branch if true brf addr iconst value push integer constant load addr load local gload addr load global variable store addr gstore addr print pop toss out the top of stack call addr, numArgscall addr, expect numArgs ret return from function, expected result on top of stack halt
  • 6. Instruction format • Code memory is 32-bit word addressable • Bytecodes stored as ints but they are bytes • Data memory is 32-bit word addressable • Addresses are just integer numbers • Operands are 32-bit integers bytecode bytecode operand bytecode operand1 operand2 +0 +1 +2
  • 7. Sample bytecodes 0000 9 1 ICONST 1 0002 9 2 ICONST 2 0004 1 IADD 0005 14 PRINT Address Bytecodes Assembly bytecode
  • 8. Our little stack machine data memory code memory ... stack sp fp ip registers fetch decode execute Fetch: opcode = code[ip] Decode: switch (opcode) {…} Execute: stack[++sp] = stack[sp--] + stack[sp--] (iadd instruction)
  • 9. CPU: Fetch, decode, execute cycle
  • 10. Sample implementations case BR : ip = code[ip++]; break; case IADD: b = stack[sp--]; // 2nd opnd at top of stack a = stack[sp--]; // 1st opnd 1 below top stack[++sp] = a + b; // push result break;
  • 11. Implementing functions • f(); • g(int x,y) { int z; z = f(x,y); ... • return 9; call f, 0 pop load x (fp-4) load y (fp-3) call f, 2 store z (fp+1) ... iconst 9 ret