SlideShare une entreprise Scribd logo
1  sur  41
S.Ducasse 1
QuickTime™ and aTIFF (Uncompressed) decompressorare needed to see this picture.
Marcus Denker
denker@iam.unibe.ch
Working with
Bytecodes: IRBuilder and
InstructionStream
S.Ducasse 2
License: CC-Attribution-ShareAlike 2.0
http://creativecommons.org/licenses/by-sa/2.0/
S.Ducasse 3
Reasons for working with Bytecode
• Generating Bytecode
• Implementing compilers for other languages
• Experimentation with new language features
• Parsing and Interpretation:
• Analysis
• Decompilation (for systems without source)
• Pretty printing
• Interpretation: Debugger, Profiler
S.Ducasse 4
Overview
• Squeak Bytecodes
• Examples: Generating Bytecode
• with IRBuilder
• Decoding Bytecodes
• Bytecode Execution
S.Ducasse 5
The SqueakVirtual Machine
• Virtual machine provides a virtual processor
• Bytecode:The ‘machinecode’ of the virtual machine
• Smalltalk (like Java): Stack machine
• easy to implement interpreters for different processors
• most hardware processors are register machines
• SqueakVM: Implemented in Slang
• Slang: Subset of Smalltalk. (”C with Smalltalk Syntax”)
• Translated to C
S.Ducasse 6
Bytecode in the CompiledMethod
• CompiledMethods format:
Header
Literals
Bytecode
Trailer
Pointer to
Source
Array of all
Literal Objects
Number of
temps, literals...
(Number>>#asInteger)inspect
S.Ducasse 7
Bytecodes: Single or multibyte
• Different forms of bytecodes:
• Single bytecodes:
• Example: 120: push self
• Groups of similar bytecodes
• 16: push temp 1
• 17: push temp 2
• up to 31
• Multibyte bytecodes
• Problem: 4bit offset may be too small
• Solution: Use the following byte as offset
• Example: Jumps need to encode large jump offsets
OffsetType
4bits 4bits
S.Ducasse 8
Example: Number>>asInteger
• Smalltalk code:
• Symbolic Bytecode
Number>>asInteger
"Answer an Integer nearest the receiver toward zero."
^self truncated
9 <70> self
10 <D0> send: truncated
11 <7C> returnTop
S.Ducasse 9
Example: Step by Step
• 9 <70> self
• The receiver (self) is pushed on the stack
• 10 <D0> send: truncated
• Bytecode 208: send litereral selector 1
• Get the selector from the first literal
• start message lookup in the class of the object
that is top of the stack
• result is pushed on the stack
• 11 <7C> returnTop
• return the object on top of the stack to the
calling method
S.Ducasse 10
Squeak Bytecodes
• 256 Bytecodes, four groups:
• Stack Bytecodes
• Stack manipulation: push / pop / dup
• Send Bytecodes
• Invoke Methods
• Return Bytecodes
• Return to caller
• Jump Bytecodes
• Control flow inside a method
S.Ducasse 11
Stack Bytecodes
• push and store, e.g. temps, instVars, literals
• e.g: 16 - 31: push instance variable
• Push Constants (False/True/Nil/1/0/2/-1)
• Push self, thisContext
• duplicate top of stack
• pop
S.Ducasse 12
Sends and Returns
• Sends: receiver is on top of stack
• Normal send
• Super Sends
• Hard-coded sends for efficiency, e.g. +, -
• Returns
• Return top of stack to the sender
• Return from a block
• Special bytecodes for return self, nil, true, false
(for efficiency)
S.Ducasse 13
Jump Bytecodes
• Control Flow inside one method
• Used to implement control-flow efficiently
• Example:
9 <76> pushConstant: 1
10 <77> pushConstant: 2
11 <B2> send: <
12 <99> jumpFalse: 15
13 <20> pushConstant: 'true'
14 <90> jumpTo: 16
15 <73> pushConstant: nil
16 <7C> returnTop
^ 1<2 ifTrue: ['true']
S.Ducasse 14
What you should have learned...
• ... dealing with bytecodes directly is possible, but very
boring.
• We want reusable abstractions that hide the details
(e.g. the different send bytecodes)
• We would like to have frameworks for
• Generating bytecode easily
• Parsing bytecode
• Evaluating bytecode
S.Ducasse 15
Generating Bytecodes
• IRBuilder
• Part of the new compiler (on SqueakMap)
• Like an Assembler for Squeak
S.Ducasse 16
IRBuilder: Simple Example
• Number>>asInteger
iRMethod := IRBuilder new
rargs: #(self); "receiver and args"
pushTemp: #self;
send: #truncated;
returnTop;
ir.
aCompiledMethod := iRMethod compiledMethod.
aCompiledMethod valueWithReceiver:3.5
arguments: #()
S.Ducasse 17
IRBuilder: Stack Manipulation
• popTop - remove the top of stack
• pushDup - push top of stack on the stack
• pushLiteral:
• pushReceiver - push self
• pushThisContext
S.Ducasse 18
IRBuilder: Symbolic Jumps
• Jump targets are resolved:
• Example: false ifTrue: [’true’] ifFalse: [’false’]
iRMethod := IRBuilder new
rargs: #(self); "receiver and args"
pushLiteral: false;
jumpAheadTo: #false if: false;
pushLiteral: 'true'; "ifTrue: ['true']"
jumpAheadTo: #end;
jumpAheadTarget: #false;
pushLiteral: 'false'; "ifFalse: ['false']"
jumpAheadTarget: #end;
returnTop;
ir.
S.Ducasse 19
IRBuiler: InstanceVariables
• Access by offset
• Read: getField:
• receiver on top of stack
• Write: setField:
• receiver and value on stack
• Example: set the first instance variable to 2
iRMethod := IRBuilder new
rargs: #(self); "receiver and args declarations"
pushLiteral: 2;
pushTemp: #self;
setField: 1;
pushTemp: #self;
returnTop;
ir.
aCompiledMethod := iRMethod compiledMethod.
aCompiledMethod valueWithReceiver: 1@2 arguments: #()
S.Ducasse 20
IRBuilder:TemporaryVariables
• Accessed by name
• Define with addTemp: / addTemps:
• Read with pushTemp:
• Write with storeTemp:
• Examle: set variables a and b, return value of a
iRMethod := IRBuilder new
rargs: #(self); "receiver and args"
addTemps: #(a b);
pushLiteral: 1;
storeTemp: #a;
pushLiteral: 2;
storeTemp: #b;
pushTemp: #a;
returnTop;
ir.
S.Ducasse 21
IRBuilder: Sends
• normal send
• super send
• The second parameter specifies the class were the
lookup starts.
....
builder send: #selector toSuperOf: aClass;
builder pushLiteral: ‘hello’
builder send: #size;
S.Ducasse 22
IRBuilder: Lessons learned
• IRBuilder: Easy bytecode generation
• Not part of Squeak yet
• Will be added to Squeak 3.9 or 4.0
• Next: Decoding bytecode
S.Ducasse 23
Parsing and Interpretation
• First step: Parse bytecode
• enough for easy analysis, pretty printing, decompilation
• Second step: Interpretation
• needed for simulation, complex analyis (e.g., profiling)
• Squeak provides frameworks for both:
• InstructionStream/InstructionClient (parsing)
• ContextPart (Interpretation)
S.Ducasse 24
The InstructionStream Hierarchy
InstructionStream
ContextPart
BlockContext
MethodContext
Decompiler
InstructionPrinter
InstVarRefLocator
BytecodeDecompiler
S.Ducasse 25
InstructionStream
• Parses the byte-encoded instructions
• State:
• pc: programm counter
• sender: the method (bad name!)
Object subclass: #InstructionStream
instanceVariableNames: 'sender pc'
classVariableNames: 'SpecialConstants'
poolDictionaries: ''
category: 'Kernel-Methods'
S.Ducasse 26
Usage
• Generate an instance:
• Now we can step through the bytecode with
• calls methods on a client object for the type of
bytecode, e.g.
• pushReceiver
• pushConstant: value
• pushReceiverVariable: offset
instrStream := IntructionStream on: aMethod
instrStream interpretNextInstructionFor: client
S.Ducasse 27
InstructionClient
• Abstract superclass
• Defines empty methods for all methods that
InstructionStream calls on a client
• For convienience:
• Client don’t need to inherit from this
Object subclass: #InstructionClient
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Kernel-Methods'
S.Ducasse 28
Example:A test
InstructionClientTest>>testInstructions
"just interpret all of methods of Object"
| methods client scanner|
methods := Object methodDict values.
client := InstructionClient new.
methods do: [:method |
scanner := (InstructionStream on: method).
[scanner pc <= method endPC] whileTrue: [
self shouldnt: [scanner interpretNextInstructionFor: client] raise:
Error.
].
].
S.Ducasse 29
Example: Printing Bytecodes
• InstructionPrinter: Print the bytecodes as human
readable text
• Example: print the bytecode of Number>>asInteger:
String streamContents: [:str |
(InstructionPrinter on: Number>>#asInteger)
printInstructionsOn: str
]
result:
'9 <70> self
10 <D0> send: truncated
11 <7C> returnTop
'
S.Ducasse 30
InstructionPrinter
• Class Definition:
InstructionClient subclass: #InstructionPrinter
instanceVariableNames: 'method scanner
stream oldPC indent'
classVariableNames: ''
poolDictionaries: ''
category: 'Kernel-Methods'
S.Ducasse 31
InstructionPrinter
• Main Loop:
InstructionPrinter>>printInstructionsOn: aStream
"Append to the stream, aStream, a description of each
bytecode in the instruction stream."
| end |
stream := aStream.
scanner := InstructionStream on: method.
end := method endPC.
oldPC := scanner pc.
[scanner pc <= end]
whileTrue: [scanner interpretNextInstructionFor: self]
S.Ducasse 32
InstructionPrinter
• Overwrites methods form InstructionClient to print
the bytecodes as text
• e.g. the method for pushReceiver:
InstructionPrinter>>pushReceiver
"Print the Push Active Context's Receiver
on Top Of Stack bytecode."
self print: 'self'
S.Ducasse 33
Example: InstVarRefLocator
InstructionClient subclass: #InstVarRefLocator
instanceVariableNames: 'bingo'
....
interpretNextInstructionUsing: aScanner
bingo := false.
aScanner interpretNextInstructionFor: self.
^bingo
popIntoReceiverVariable: offset
bingo := true
pushReceiverVariable: offset
bingo := true
storeIntoReceiverVariable: offset
bingo := true
S.Ducasse 34
InstVarRefLocator
• CompiledMethod>>#hasInstVarRef
hasInstVarRef
"Answer whether the receiver references an instance variable."
| scanner end printer |
scanner := InstructionStream on: self.
printer := InstVarRefLocator new.
end := self endPC.
[scanner pc <= end] whileTrue: [
(printer interpretNextInstructionUsing: scanner) ifTrue: [^true].
].
^false
S.Ducasse 35
InstVarRefLocator
• Example for a simple bytecode analyzer
• Usage:
aMethod hasInstVarRef
(TestCase>>#debug) hasInstVarRef
true
(Integer>>#+) hasInstVarRef
false
S.Ducasse 36
Example: Decompiling to IR
• BytecodeDecompiler
• Usage:
InstructionStream subclass: #BytecodeDecompiler
instanceVariableNames: 'irBuilder blockFlag'
classVariableNames: ''
poolDictionaries: ''
category: 'Compiler-Bytecodes'
BytecodeDecompiler new decompile: (Number>>#asInteger)
S.Ducasse 37
Decompiling
• uses IRBuilder for building IR
• e.g. code for the bytecode pushReceiver:
BytecodeDecompiler>>pushReceiver
irBuilder pushReceiver
S.Ducasse 38
ContextPart: Execution Semantics
• Sometimes we need more than parsing
• “stepping” in the debugger
• system simulation for profiling
InstructionStream subclass: #ContextPart
instanceVariableNames: 'stackp'
classVariableNames: 'PrimitiveFailToken QuickStep'
poolDictionaries: ''
category: 'Kernel-Methods'
S.Ducasse 39
Simulation
• Provides a complete Bytecode interpreter
• Run a block with the simulator:
(ContextPart runSimulated: [3 factorial])
S.Ducasse 40
Profiling: MesageTally
• Usage:
• Other example:
MessageTally tallySends: [3 factorial]
This simulation took 0.0 seconds.
**Tree**
1 SmallInteger(Integer)>>factorial
1 SmallInteger(Integer)>>factorial
1 SmallInteger(Integer)>>factorial
1 SmallInteger(Integer)>>factorial
MessageTally tallySends: [’3’ + 1]
**Leaves**
4 SmallInteger(Integer)>>factorial
3 SmallInteger(Integer)>>factorial
1 BlockContext>>DoIt
S.Ducasse 41

Contenu connexe

Tendances

Dennis Benkert & Matthias Lübken - Patterns in a containerized world? - code....
Dennis Benkert & Matthias Lübken - Patterns in a containerized world? - code....Dennis Benkert & Matthias Lübken - Patterns in a containerized world? - code....
Dennis Benkert & Matthias Lübken - Patterns in a containerized world? - code....AboutYouGmbH
 
An Introduction to Twisted
An Introduction to TwistedAn Introduction to Twisted
An Introduction to Twistedsdsern
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?Kyle Oba
 
06 - Qt Communication
06 - Qt Communication06 - Qt Communication
06 - Qt CommunicationAndreas Jakl
 
Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Max Kleiner
 
Patterns for JVM languages JokerConf
Patterns for JVM languages JokerConfPatterns for JVM languages JokerConf
Patterns for JVM languages JokerConfJaroslaw Palka
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The ApproachHaci Murat Yaman
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPrashant Rane
 
Other Approaches (Concurrency)
Other Approaches (Concurrency)Other Approaches (Concurrency)
Other Approaches (Concurrency)Sri Prasanna
 
network programing lab file ,
network programing lab file ,network programing lab file ,
network programing lab file ,AAlha PaiKra
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance TuningMinh Hoang
 
Python twisted
Python twistedPython twisted
Python twistedMahendra M
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals ThreadsNeera Mital
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchMatteo Battaglio
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrencyfeng lee
 
C++ process new
C++ process newC++ process new
C++ process new敬倫 林
 

Tendances (20)

Runtime
RuntimeRuntime
Runtime
 
Dennis Benkert & Matthias Lübken - Patterns in a containerized world? - code....
Dennis Benkert & Matthias Lübken - Patterns in a containerized world? - code....Dennis Benkert & Matthias Lübken - Patterns in a containerized world? - code....
Dennis Benkert & Matthias Lübken - Patterns in a containerized world? - code....
 
8 - OOP - Syntax & Messages
8 - OOP - Syntax & Messages8 - OOP - Syntax & Messages
8 - OOP - Syntax & Messages
 
An Introduction to Twisted
An Introduction to TwistedAn Introduction to Twisted
An Introduction to Twisted
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?
 
NodeJS: an Introduction
NodeJS: an IntroductionNodeJS: an Introduction
NodeJS: an Introduction
 
06 - Qt Communication
06 - Qt Communication06 - Qt Communication
06 - Qt Communication
 
Cp7 rpc
Cp7 rpcCp7 rpc
Cp7 rpc
 
Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475
 
Patterns for JVM languages JokerConf
Patterns for JVM languages JokerConfPatterns for JVM languages JokerConf
Patterns for JVM languages JokerConf
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCD
 
Other Approaches (Concurrency)
Other Approaches (Concurrency)Other Approaches (Concurrency)
Other Approaches (Concurrency)
 
network programing lab file ,
network programing lab file ,network programing lab file ,
network programing lab file ,
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 
Python twisted
Python twistedPython twisted
Python twisted
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals Threads
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central Dispatch
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
C++ process new
C++ process newC++ process new
C++ process new
 

En vedette (20)

Stoop 439-decorator
Stoop 439-decoratorStoop 439-decorator
Stoop 439-decorator
 
Stoop 436-strategy
Stoop 436-strategyStoop 436-strategy
Stoop 436-strategy
 
12 virtualmachine
12 virtualmachine12 virtualmachine
12 virtualmachine
 
Stoop 423-smalltalk idioms
Stoop 423-smalltalk idiomsStoop 423-smalltalk idioms
Stoop 423-smalltalk idioms
 
10 reflection
10 reflection10 reflection
10 reflection
 
05 seaside
05 seaside05 seaside
05 seaside
 
Stoop 413-abstract classes
Stoop 413-abstract classesStoop 413-abstract classes
Stoop 413-abstract classes
 
Stoop ed-class forreuse
Stoop ed-class forreuseStoop ed-class forreuse
Stoop ed-class forreuse
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
5 - OOP - Smalltalk in a Nutshell (c)
5 - OOP - Smalltalk in a Nutshell (c)5 - OOP - Smalltalk in a Nutshell (c)
5 - OOP - Smalltalk in a Nutshell (c)
 
14 - Exceptions
14 - Exceptions14 - Exceptions
14 - Exceptions
 
Stoop 437-proxy
Stoop 437-proxyStoop 437-proxy
Stoop 437-proxy
 
11 bytecode
11 bytecode11 bytecode
11 bytecode
 
Stoop 301-internal objectstructureinvw
Stoop 301-internal objectstructureinvwStoop 301-internal objectstructureinvw
Stoop 301-internal objectstructureinvw
 
Stoop ed-inheritance composition
Stoop ed-inheritance compositionStoop ed-inheritance composition
Stoop ed-inheritance composition
 
Stoop 303-advanced blocks
Stoop 303-advanced blocksStoop 303-advanced blocks
Stoop 303-advanced blocks
 
Stoop 422-naming idioms
Stoop 422-naming idiomsStoop 422-naming idioms
Stoop 422-naming idioms
 
Stoop ed-subtyping subclassing
Stoop ed-subtyping subclassingStoop ed-subtyping subclassing
Stoop ed-subtyping subclassing
 
Stoop ed-lod
Stoop ed-lodStoop ed-lod
Stoop ed-lod
 
01 intro
01 intro01 intro
01 intro
 

Similaire à Stoop 390-instruction stream

Working with Bytecode
Working with BytecodeWorking with Bytecode
Working with BytecodeMarcus Denker
 
Vlsi lab manual exp:2
Vlsi lab manual exp:2Vlsi lab manual exp:2
Vlsi lab manual exp:2komala vani
 
Friend this-new&delete
Friend this-new&deleteFriend this-new&delete
Friend this-new&deleteShehzad Rizwan
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxAshrithaRokkam
 
Testing: ¿what, how, why?
Testing: ¿what, how, why?Testing: ¿what, how, why?
Testing: ¿what, how, why?David Rodenas
 
Checking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xChecking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xAndrey Karpov
 
AntiVirus Evasion Techniques Use of Crypters 2k14 at MundoHackerDay
AntiVirus Evasion Techniques Use of Crypters 2k14 at MundoHackerDayAntiVirus Evasion Techniques Use of Crypters 2k14 at MundoHackerDay
AntiVirus Evasion Techniques Use of Crypters 2k14 at MundoHackerDayINCIDE
 
Blazing Performance with Flame Graphs
Blazing Performance with Flame GraphsBlazing Performance with Flame Graphs
Blazing Performance with Flame GraphsBrendan Gregg
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#ANURAG SINGH
 
Workshop Infrastructure as Code - Suestra
Workshop Infrastructure as Code - SuestraWorkshop Infrastructure as Code - Suestra
Workshop Infrastructure as Code - SuestraMario IC
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 developmentFisnik Doko
 
Reactive Design Patterns: a talk by Typesafe's Dr. Roland Kuhn
Reactive Design Patterns: a talk by Typesafe's Dr. Roland KuhnReactive Design Patterns: a talk by Typesafe's Dr. Roland Kuhn
Reactive Design Patterns: a talk by Typesafe's Dr. Roland KuhnZalando Technology
 
Test-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpec
Test-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpecTest-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpec
Test-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpecMartin Etmajer
 
Pdf tech deep dive 42 paris
Pdf tech deep dive 42 parisPdf tech deep dive 42 paris
Pdf tech deep dive 42 parisLaure Vergeron
 
C# What's next? (7.x and 8.0)
C# What's next? (7.x and 8.0)C# What's next? (7.x and 8.0)
C# What's next? (7.x and 8.0)Christian Nagel
 

Similaire à Stoop 390-instruction stream (20)

Working with Bytecode
Working with BytecodeWorking with Bytecode
Working with Bytecode
 
Vlsi lab manual exp:2
Vlsi lab manual exp:2Vlsi lab manual exp:2
Vlsi lab manual exp:2
 
Friend this-new&delete
Friend this-new&deleteFriend this-new&delete
Friend this-new&delete
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
Return of c++
Return of c++Return of c++
Return of c++
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
 
Testing: ¿what, how, why?
Testing: ¿what, how, why?Testing: ¿what, how, why?
Testing: ¿what, how, why?
 
Checking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xChecking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-x
 
2-Functions.pdf
2-Functions.pdf2-Functions.pdf
2-Functions.pdf
 
AntiVirus Evasion Techniques Use of Crypters 2k14 at MundoHackerDay
AntiVirus Evasion Techniques Use of Crypters 2k14 at MundoHackerDayAntiVirus Evasion Techniques Use of Crypters 2k14 at MundoHackerDay
AntiVirus Evasion Techniques Use of Crypters 2k14 at MundoHackerDay
 
Stoop 300-block optimizationinvw
Stoop 300-block optimizationinvwStoop 300-block optimizationinvw
Stoop 300-block optimizationinvw
 
Blazing Performance with Flame Graphs
Blazing Performance with Flame GraphsBlazing Performance with Flame Graphs
Blazing Performance with Flame Graphs
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
 
Workshop Infrastructure as Code - Suestra
Workshop Infrastructure as Code - SuestraWorkshop Infrastructure as Code - Suestra
Workshop Infrastructure as Code - Suestra
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 development
 
Reactive Design Patterns: a talk by Typesafe's Dr. Roland Kuhn
Reactive Design Patterns: a talk by Typesafe's Dr. Roland KuhnReactive Design Patterns: a talk by Typesafe's Dr. Roland Kuhn
Reactive Design Patterns: a talk by Typesafe's Dr. Roland Kuhn
 
Test-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpec
Test-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpecTest-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpec
Test-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpec
 
linq with Exampls
linq with Examplslinq with Exampls
linq with Exampls
 
Pdf tech deep dive 42 paris
Pdf tech deep dive 42 parisPdf tech deep dive 42 paris
Pdf tech deep dive 42 paris
 
C# What's next? (7.x and 8.0)
C# What's next? (7.x and 8.0)C# What's next? (7.x and 8.0)
C# What's next? (7.x and 8.0)
 

Plus de The World of Smalltalk (20)

05 seaside canvas
05 seaside canvas05 seaside canvas
05 seaside canvas
 
99 questions
99 questions99 questions
99 questions
 
13 traits
13 traits13 traits
13 traits
 
09 metaclasses
09 metaclasses09 metaclasses
09 metaclasses
 
08 refactoring
08 refactoring08 refactoring
08 refactoring
 
07 bestpractice
07 bestpractice07 bestpractice
07 bestpractice
 
06 debugging
06 debugging06 debugging
06 debugging
 
04 idioms
04 idioms04 idioms
04 idioms
 
03 standardclasses
03 standardclasses03 standardclasses
03 standardclasses
 
02 basics
02 basics02 basics
02 basics
 
Stoop sed-smells
Stoop sed-smellsStoop sed-smells
Stoop sed-smells
 
Stoop sed-sharing ornot
Stoop sed-sharing ornotStoop sed-sharing ornot
Stoop sed-sharing ornot
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
Stoop metaclasses
Stoop metaclassesStoop metaclasses
Stoop metaclasses
 
Stoop ed-unit ofreuse
Stoop ed-unit ofreuseStoop ed-unit ofreuse
Stoop ed-unit ofreuse
 
Stoop ed-some principles
Stoop ed-some principlesStoop ed-some principles
Stoop ed-some principles
 
Stoop ed-frameworks
Stoop ed-frameworksStoop ed-frameworks
Stoop ed-frameworks
 
Stoop ed-dual interface
Stoop ed-dual interfaceStoop ed-dual interface
Stoop ed-dual interface
 
Stoop 450-s unit
Stoop 450-s unitStoop 450-s unit
Stoop 450-s unit
 
Stoop 440-adaptor
Stoop 440-adaptorStoop 440-adaptor
Stoop 440-adaptor
 

Dernier

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
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 WorkerThousandEyes
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
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...apidays
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Dernier (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Stoop 390-instruction stream

  • 1. S.Ducasse 1 QuickTime™ and aTIFF (Uncompressed) decompressorare needed to see this picture. Marcus Denker denker@iam.unibe.ch Working with Bytecodes: IRBuilder and InstructionStream
  • 2. S.Ducasse 2 License: CC-Attribution-ShareAlike 2.0 http://creativecommons.org/licenses/by-sa/2.0/
  • 3. S.Ducasse 3 Reasons for working with Bytecode • Generating Bytecode • Implementing compilers for other languages • Experimentation with new language features • Parsing and Interpretation: • Analysis • Decompilation (for systems without source) • Pretty printing • Interpretation: Debugger, Profiler
  • 4. S.Ducasse 4 Overview • Squeak Bytecodes • Examples: Generating Bytecode • with IRBuilder • Decoding Bytecodes • Bytecode Execution
  • 5. S.Ducasse 5 The SqueakVirtual Machine • Virtual machine provides a virtual processor • Bytecode:The ‘machinecode’ of the virtual machine • Smalltalk (like Java): Stack machine • easy to implement interpreters for different processors • most hardware processors are register machines • SqueakVM: Implemented in Slang • Slang: Subset of Smalltalk. (”C with Smalltalk Syntax”) • Translated to C
  • 6. S.Ducasse 6 Bytecode in the CompiledMethod • CompiledMethods format: Header Literals Bytecode Trailer Pointer to Source Array of all Literal Objects Number of temps, literals... (Number>>#asInteger)inspect
  • 7. S.Ducasse 7 Bytecodes: Single or multibyte • Different forms of bytecodes: • Single bytecodes: • Example: 120: push self • Groups of similar bytecodes • 16: push temp 1 • 17: push temp 2 • up to 31 • Multibyte bytecodes • Problem: 4bit offset may be too small • Solution: Use the following byte as offset • Example: Jumps need to encode large jump offsets OffsetType 4bits 4bits
  • 8. S.Ducasse 8 Example: Number>>asInteger • Smalltalk code: • Symbolic Bytecode Number>>asInteger "Answer an Integer nearest the receiver toward zero." ^self truncated 9 <70> self 10 <D0> send: truncated 11 <7C> returnTop
  • 9. S.Ducasse 9 Example: Step by Step • 9 <70> self • The receiver (self) is pushed on the stack • 10 <D0> send: truncated • Bytecode 208: send litereral selector 1 • Get the selector from the first literal • start message lookup in the class of the object that is top of the stack • result is pushed on the stack • 11 <7C> returnTop • return the object on top of the stack to the calling method
  • 10. S.Ducasse 10 Squeak Bytecodes • 256 Bytecodes, four groups: • Stack Bytecodes • Stack manipulation: push / pop / dup • Send Bytecodes • Invoke Methods • Return Bytecodes • Return to caller • Jump Bytecodes • Control flow inside a method
  • 11. S.Ducasse 11 Stack Bytecodes • push and store, e.g. temps, instVars, literals • e.g: 16 - 31: push instance variable • Push Constants (False/True/Nil/1/0/2/-1) • Push self, thisContext • duplicate top of stack • pop
  • 12. S.Ducasse 12 Sends and Returns • Sends: receiver is on top of stack • Normal send • Super Sends • Hard-coded sends for efficiency, e.g. +, - • Returns • Return top of stack to the sender • Return from a block • Special bytecodes for return self, nil, true, false (for efficiency)
  • 13. S.Ducasse 13 Jump Bytecodes • Control Flow inside one method • Used to implement control-flow efficiently • Example: 9 <76> pushConstant: 1 10 <77> pushConstant: 2 11 <B2> send: < 12 <99> jumpFalse: 15 13 <20> pushConstant: 'true' 14 <90> jumpTo: 16 15 <73> pushConstant: nil 16 <7C> returnTop ^ 1<2 ifTrue: ['true']
  • 14. S.Ducasse 14 What you should have learned... • ... dealing with bytecodes directly is possible, but very boring. • We want reusable abstractions that hide the details (e.g. the different send bytecodes) • We would like to have frameworks for • Generating bytecode easily • Parsing bytecode • Evaluating bytecode
  • 15. S.Ducasse 15 Generating Bytecodes • IRBuilder • Part of the new compiler (on SqueakMap) • Like an Assembler for Squeak
  • 16. S.Ducasse 16 IRBuilder: Simple Example • Number>>asInteger iRMethod := IRBuilder new rargs: #(self); "receiver and args" pushTemp: #self; send: #truncated; returnTop; ir. aCompiledMethod := iRMethod compiledMethod. aCompiledMethod valueWithReceiver:3.5 arguments: #()
  • 17. S.Ducasse 17 IRBuilder: Stack Manipulation • popTop - remove the top of stack • pushDup - push top of stack on the stack • pushLiteral: • pushReceiver - push self • pushThisContext
  • 18. S.Ducasse 18 IRBuilder: Symbolic Jumps • Jump targets are resolved: • Example: false ifTrue: [’true’] ifFalse: [’false’] iRMethod := IRBuilder new rargs: #(self); "receiver and args" pushLiteral: false; jumpAheadTo: #false if: false; pushLiteral: 'true'; "ifTrue: ['true']" jumpAheadTo: #end; jumpAheadTarget: #false; pushLiteral: 'false'; "ifFalse: ['false']" jumpAheadTarget: #end; returnTop; ir.
  • 19. S.Ducasse 19 IRBuiler: InstanceVariables • Access by offset • Read: getField: • receiver on top of stack • Write: setField: • receiver and value on stack • Example: set the first instance variable to 2 iRMethod := IRBuilder new rargs: #(self); "receiver and args declarations" pushLiteral: 2; pushTemp: #self; setField: 1; pushTemp: #self; returnTop; ir. aCompiledMethod := iRMethod compiledMethod. aCompiledMethod valueWithReceiver: 1@2 arguments: #()
  • 20. S.Ducasse 20 IRBuilder:TemporaryVariables • Accessed by name • Define with addTemp: / addTemps: • Read with pushTemp: • Write with storeTemp: • Examle: set variables a and b, return value of a iRMethod := IRBuilder new rargs: #(self); "receiver and args" addTemps: #(a b); pushLiteral: 1; storeTemp: #a; pushLiteral: 2; storeTemp: #b; pushTemp: #a; returnTop; ir.
  • 21. S.Ducasse 21 IRBuilder: Sends • normal send • super send • The second parameter specifies the class were the lookup starts. .... builder send: #selector toSuperOf: aClass; builder pushLiteral: ‘hello’ builder send: #size;
  • 22. S.Ducasse 22 IRBuilder: Lessons learned • IRBuilder: Easy bytecode generation • Not part of Squeak yet • Will be added to Squeak 3.9 or 4.0 • Next: Decoding bytecode
  • 23. S.Ducasse 23 Parsing and Interpretation • First step: Parse bytecode • enough for easy analysis, pretty printing, decompilation • Second step: Interpretation • needed for simulation, complex analyis (e.g., profiling) • Squeak provides frameworks for both: • InstructionStream/InstructionClient (parsing) • ContextPart (Interpretation)
  • 24. S.Ducasse 24 The InstructionStream Hierarchy InstructionStream ContextPart BlockContext MethodContext Decompiler InstructionPrinter InstVarRefLocator BytecodeDecompiler
  • 25. S.Ducasse 25 InstructionStream • Parses the byte-encoded instructions • State: • pc: programm counter • sender: the method (bad name!) Object subclass: #InstructionStream instanceVariableNames: 'sender pc' classVariableNames: 'SpecialConstants' poolDictionaries: '' category: 'Kernel-Methods'
  • 26. S.Ducasse 26 Usage • Generate an instance: • Now we can step through the bytecode with • calls methods on a client object for the type of bytecode, e.g. • pushReceiver • pushConstant: value • pushReceiverVariable: offset instrStream := IntructionStream on: aMethod instrStream interpretNextInstructionFor: client
  • 27. S.Ducasse 27 InstructionClient • Abstract superclass • Defines empty methods for all methods that InstructionStream calls on a client • For convienience: • Client don’t need to inherit from this Object subclass: #InstructionClient instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Methods'
  • 28. S.Ducasse 28 Example:A test InstructionClientTest>>testInstructions "just interpret all of methods of Object" | methods client scanner| methods := Object methodDict values. client := InstructionClient new. methods do: [:method | scanner := (InstructionStream on: method). [scanner pc <= method endPC] whileTrue: [ self shouldnt: [scanner interpretNextInstructionFor: client] raise: Error. ]. ].
  • 29. S.Ducasse 29 Example: Printing Bytecodes • InstructionPrinter: Print the bytecodes as human readable text • Example: print the bytecode of Number>>asInteger: String streamContents: [:str | (InstructionPrinter on: Number>>#asInteger) printInstructionsOn: str ] result: '9 <70> self 10 <D0> send: truncated 11 <7C> returnTop '
  • 30. S.Ducasse 30 InstructionPrinter • Class Definition: InstructionClient subclass: #InstructionPrinter instanceVariableNames: 'method scanner stream oldPC indent' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Methods'
  • 31. S.Ducasse 31 InstructionPrinter • Main Loop: InstructionPrinter>>printInstructionsOn: aStream "Append to the stream, aStream, a description of each bytecode in the instruction stream." | end | stream := aStream. scanner := InstructionStream on: method. end := method endPC. oldPC := scanner pc. [scanner pc <= end] whileTrue: [scanner interpretNextInstructionFor: self]
  • 32. S.Ducasse 32 InstructionPrinter • Overwrites methods form InstructionClient to print the bytecodes as text • e.g. the method for pushReceiver: InstructionPrinter>>pushReceiver "Print the Push Active Context's Receiver on Top Of Stack bytecode." self print: 'self'
  • 33. S.Ducasse 33 Example: InstVarRefLocator InstructionClient subclass: #InstVarRefLocator instanceVariableNames: 'bingo' .... interpretNextInstructionUsing: aScanner bingo := false. aScanner interpretNextInstructionFor: self. ^bingo popIntoReceiverVariable: offset bingo := true pushReceiverVariable: offset bingo := true storeIntoReceiverVariable: offset bingo := true
  • 34. S.Ducasse 34 InstVarRefLocator • CompiledMethod>>#hasInstVarRef hasInstVarRef "Answer whether the receiver references an instance variable." | scanner end printer | scanner := InstructionStream on: self. printer := InstVarRefLocator new. end := self endPC. [scanner pc <= end] whileTrue: [ (printer interpretNextInstructionUsing: scanner) ifTrue: [^true]. ]. ^false
  • 35. S.Ducasse 35 InstVarRefLocator • Example for a simple bytecode analyzer • Usage: aMethod hasInstVarRef (TestCase>>#debug) hasInstVarRef true (Integer>>#+) hasInstVarRef false
  • 36. S.Ducasse 36 Example: Decompiling to IR • BytecodeDecompiler • Usage: InstructionStream subclass: #BytecodeDecompiler instanceVariableNames: 'irBuilder blockFlag' classVariableNames: '' poolDictionaries: '' category: 'Compiler-Bytecodes' BytecodeDecompiler new decompile: (Number>>#asInteger)
  • 37. S.Ducasse 37 Decompiling • uses IRBuilder for building IR • e.g. code for the bytecode pushReceiver: BytecodeDecompiler>>pushReceiver irBuilder pushReceiver
  • 38. S.Ducasse 38 ContextPart: Execution Semantics • Sometimes we need more than parsing • “stepping” in the debugger • system simulation for profiling InstructionStream subclass: #ContextPart instanceVariableNames: 'stackp' classVariableNames: 'PrimitiveFailToken QuickStep' poolDictionaries: '' category: 'Kernel-Methods'
  • 39. S.Ducasse 39 Simulation • Provides a complete Bytecode interpreter • Run a block with the simulator: (ContextPart runSimulated: [3 factorial])
  • 40. S.Ducasse 40 Profiling: MesageTally • Usage: • Other example: MessageTally tallySends: [3 factorial] This simulation took 0.0 seconds. **Tree** 1 SmallInteger(Integer)>>factorial 1 SmallInteger(Integer)>>factorial 1 SmallInteger(Integer)>>factorial 1 SmallInteger(Integer)>>factorial MessageTally tallySends: [’3’ + 1] **Leaves** 4 SmallInteger(Integer)>>factorial 3 SmallInteger(Integer)>>factorial 1 BlockContext>>DoIt