SlideShare une entreprise Scribd logo
1  sur  22
Télécharger pour lire hors ligne
Fun with bytecode
1 / 21
Who the hell are you?
Programmer
Entrepeneur
CTO of import.io
Geek
Ex-mathematician
Long-suffering Java user (yay, lambdas!)
Proud father of two :)
2 / 21
So what's the plan?
1. What?
2. Why?
3. How?
4. Codez
5. Q&A
6. Beer!
3 / 21
Some JVM internals
Do you know how the JVM does its magic?
4 / 21
Per JVM
Heap for objects
PermGen/Metaspace
Per Thread
PC (Program Counter) tracks instruction position in a register
Stack (as in trace) of Frames (method invocations)
Native stack
Per frame
Local variable 32bit array ([0]=this)
Operand 32bit stack
Constant pool reference for the class
5 / 21
Operand stack
The Java stack is a last-in, first-out stack of 32-bit slots. Because each slot in the
stack occupies 32 bits, all stack variables occupy at least 32 bits - even a byte.
Longs/Doubles take 2 slots.
"We chose a stack organization so that it would be easy to emulate the
machine efficiently on machines with few or irregular registers such
as the Intel 486."
Local variable array
Zero-indexed, 32 bit slots.
6 / 21
Bytecode
"Understanding bytecode and what bytecode is likely to be generated
by a Java compiler helps the Java programmer in the same way that
knowledge of assembly helps the C or C++ programmer."
When a JVM loads a class file, it gets a stream of bytecodes that represent the
logic for each method that are interpreted or JIT compiled.
One byte opcode (mnemonics, action) and its operands.
7 / 21
Disassembling bytecode
publicstaticintfactorial(intx){
inty=1;
for(intz=2;z<=x;z++)y*=z;
returny;
}
PC keeps track of current position...
0iconst_1 [1] [x]
1istore_1 [] [x,1]
2iconst_2 [2] [x,1]
3istore_2 [] [x,1,2]
4iload_2 [2] [x,1,2]
5iload_0 [x,2][x,1,2]
6if_icmpgt19(+13) [] [x,1,2]
9iload_1 [1] [x,1,2]
10iload_2 [2,1]
11imul [2] [x,1,2]
12istore_1 [] [x,2,2]
13iinc2by1 [] [x,2,3]
16goto4(-12) [] [x,2,3]
19iload_1 [y] [x,y,z]
20ireturn [] [x,y,z]
8 / 21
Method signatures
V-void
B–byte
C–char
D–double
F–float
I–int
J–long
S–short
V–void
Z–boolean
[–arrayofthethingfollowingthebracket
L[classname];–instanceofthisclass,withdotsbecomingslashes
([args])[returntype]–methodsignature
For example:
publicintfoo(Stringbar,long[][]baz)
becomes
(Ljava/lang/String;[[J)I
9 / 21
What is bytecode weaving?
Changing byte code for a class either up front or dynamically at run-time.
10 / 21
Why should I want to weave bytecode?
Proxy creation
Aspect-orientated programming
Logging
Sandboxing
Code coverage
Adding in features like co-routines
Anything else you can dream up :)
11 / 21
How to weave
WTF is a Java agent?
An agent is just an interceptor in front of your main method,
executed in the same JVM and loaded by the same system classloader,
and governed by the same security policy and context.
Need a class with a premainmethod:
publicstaticvoidpremain(StringagentArgs,Instrumentationinst);
... and some special MANIFEST.MF lines:
Manifest-Version:1.0
Premain-Class:my.package.MyJavaAgent
Boot-Class-Path:some-dependency.jar
... a command line option:
-javaagent:<jarpath>[=<options>]
loadJavaprogramminglanguageagent,seejava.lang.instrument
... to hook into the Instrumentationclass
12 / 21
Getting funky with Instrumentation
Lets you hook in ClassFileTransformerinstances - which are what they sound
like.
byte[]
transform( ClassLoader loader,
String className,
Class classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] classfileBuffer)
throwsIllegalClassFormatException;
But what's in the byte arrays?
13 / 21
Class structure
14 / 21
How do you modify the bytes?
Manually (Super scary)
Javassist
ASM
Other libraries may be available... :)
15 / 21
Javassist: a quick aside
It'll parse Java source strings - no bytecode required.
publicbyte[]transform(ClassLoaderloader,StringclassName,ClassclassBeingRedefined,
ProtectionDomainprotectionDomain,byte[]classfileBuffer)throwsIllegalClassFormatException{
pool.insertClassPath(newByteArrayClassPath(className,classfileBuffer));
CtClasscclass=pool.get(className.replaceAll("/","."));
if(cclass.isFrozen()){
returnnull;//useuninstrumentedclass,alreadyprocessed
}
for(CtMethodcurrentMethod:cclass.getDeclaredMethods()){
currentMethod.insertBefore("System.err.println('foo');");
}
returncclass.toBytecode();
}
Easy, but not the quickest.
Not so good as a learning exercise either :)
16 / 21
ASM: total control, but like writing
assembler.
Event model, similar to SAX.
Extend abstract class:
classClassVisitor{
voidvisit(intversion,intaccess,Stringname,Stringsignature,StringsuperName,
String[]interfaces)
voidvisitSource(Stringsource,Stringdebug)
voidvisitOuterClass(Stringowner,Stringname,Stringdesc)
AnnotationVisitorvisitAnnotation(Stringdesc,booleanvisible)
AnnotationVisitorvisitTypeAnnotation(inttypeRef,TypePathtypePath,Stringdesc,
booleanvisible)
voidvisitAttribute(Attributeattr)
voidvisitInnerClass(Stringname,StringouterName,StringinnerName,intaccess)
FieldVisitorvisitField(intaccess,Stringname,Stringdesc,Stringsignature,
Objectvalue)
MethodVisitorvisitMethod(intaccess,Stringname,Stringdesc,Stringsignature,
String[]exceptions)
voidvisitEnd()
}
17 / 21
and hook in
to your ClassFileTransformer
publicbyte[]transform(ClassLoaderloader,StringclassName,
ClassclassBeingRedefined,ProtectionDomainprotectionDomain,
byte[]classfileBuffer)throwsIllegalClassFormatException{
ClassReadercr=newClassReader(classfileBuffer);
ClassWritercw=newClassWriter(cr,ClassWriter.COMPUTE_FRAMES);
cr.accept(cw,0);
returncw.toByteArray();
}
Easy!
18 / 21
sio2box
A memory sandbox that counts allocations.
Add annotations to classes (SiO2Class) and methods (SiO2Method) to limit the
total amount of memory allocated by untrusted code.
Don't take GC into account, interested in memory churn - could use
ReferenceQueueif we were.
Tracks:
Array.newInstance
type[].clone
Object instantiation
new type[] - ANEWARRAY, NEWARRAY, MULTIANEWARRAY
Object.clone
ArrayList.clone (TODO)
19 / 21
Quick example
Pass through a MemoryStoreobject as the first argument (this is a convention).
MemoryStorememoryStore=newMemoryStore(maxMemory);
myMethod(memoryStore,arg0,arg1);
Annotate the class and method:
@SiO2Class
publicclassMyClass{
@SiO2Method
publicvoidmyMethod(MemoryStorem,Stringarg0,Objectarg1){
...
}
}
If more memory is allocated than you specify, a MemoryExceededException
exception is thrown.
20 / 21
Code!
Let's checkout github...
21 / 21
Fun with bytecode weaving

Contenu connexe

Tendances

Java bytecode and classes
Java bytecode and classesJava bytecode and classes
Java bytecode and classesyoavwix
 
Inside The Java Virtual Machine
Inside The Java Virtual MachineInside The Java Virtual Machine
Inside The Java Virtual Machineelliando dias
 
Java virtual machine
Java virtual machineJava virtual machine
Java virtual machineNikhil Sharma
 
Java Virtual Machine - Internal Architecture
Java Virtual Machine - Internal ArchitectureJava Virtual Machine - Internal Architecture
Java Virtual Machine - Internal Architecturesubnesh
 
Introduction to the Java bytecode - So@t - 20130924
Introduction to the Java bytecode - So@t - 20130924Introduction to the Java bytecode - So@t - 20130924
Introduction to the Java bytecode - So@t - 20130924yohanbeschi
 
Java byte code presentation
Java byte code presentationJava byte code presentation
Java byte code presentationMahnoor Hashmi
 
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIsCS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIsKwangshin Oh
 
Java byte code & virtual machine
Java byte code & virtual machineJava byte code & virtual machine
Java byte code & virtual machineLaxman Puri
 
Introduction of jvm|Java Training In Jaipur | Java Training Jaipur | Java Tra...
Introduction of jvm|Java Training In Jaipur | Java Training Jaipur | Java Tra...Introduction of jvm|Java Training In Jaipur | Java Training Jaipur | Java Tra...
Introduction of jvm|Java Training In Jaipur | Java Training Jaipur | Java Tra...Rhythm Suiwal
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz SAurabh PRajapati
 

Tendances (20)

Jvm Architecture
Jvm ArchitectureJvm Architecture
Jvm Architecture
 
Java bytecode and classes
Java bytecode and classesJava bytecode and classes
Java bytecode and classes
 
What is-java
What is-javaWhat is-java
What is-java
 
What's Inside a JVM?
What's Inside a JVM?What's Inside a JVM?
What's Inside a JVM?
 
Inside The Java Virtual Machine
Inside The Java Virtual MachineInside The Java Virtual Machine
Inside The Java Virtual Machine
 
Java virtual machine
Java virtual machineJava virtual machine
Java virtual machine
 
Java virtual machine
Java virtual machineJava virtual machine
Java virtual machine
 
Java-java virtual machine
Java-java virtual machineJava-java virtual machine
Java-java virtual machine
 
Java Virtual Machine - Internal Architecture
Java Virtual Machine - Internal ArchitectureJava Virtual Machine - Internal Architecture
Java Virtual Machine - Internal Architecture
 
Introduction to the Java bytecode - So@t - 20130924
Introduction to the Java bytecode - So@t - 20130924Introduction to the Java bytecode - So@t - 20130924
Introduction to the Java bytecode - So@t - 20130924
 
Java byte code presentation
Java byte code presentationJava byte code presentation
Java byte code presentation
 
Java 2
Java 2Java 2
Java 2
 
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIsCS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
 
Java byte code & virtual machine
Java byte code & virtual machineJava byte code & virtual machine
Java byte code & virtual machine
 
QSpiders - Memory (JVM architecture)
QSpiders - Memory (JVM architecture)QSpiders - Memory (JVM architecture)
QSpiders - Memory (JVM architecture)
 
Java architecture
Java architectureJava architecture
Java architecture
 
Introduction of jvm|Java Training In Jaipur | Java Training Jaipur | Java Tra...
Introduction of jvm|Java Training In Jaipur | Java Training Jaipur | Java Tra...Introduction of jvm|Java Training In Jaipur | Java Training Jaipur | Java Tra...
Introduction of jvm|Java Training In Jaipur | Java Training Jaipur | Java Tra...
 
Java virtual machine
Java virtual machineJava virtual machine
Java virtual machine
 
Matlab isim link
Matlab isim linkMatlab isim link
Matlab isim link
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
 

En vedette

Voice of the CALA-sponsored Emerging Leaders
Voice of the CALA-sponsored Emerging LeadersVoice of the CALA-sponsored Emerging Leaders
Voice of the CALA-sponsored Emerging LeadersNing Zou
 
market-review-2014-15
market-review-2014-15market-review-2014-15
market-review-2014-15Andrew Ranson
 
Company Profile Finint
Company Profile FinintCompany Profile Finint
Company Profile FinintEleonora Riva
 
AACUpresentationfeb24draft
AACUpresentationfeb24draftAACUpresentationfeb24draft
AACUpresentationfeb24draftNing Zou
 
Neural nets: How regular expressions brought about deep learning
Neural nets: How regular expressions brought about deep learningNeural nets: How regular expressions brought about deep learning
Neural nets: How regular expressions brought about deep learningMatthew
 

En vedette (7)

Voice of the CALA-sponsored Emerging Leaders
Voice of the CALA-sponsored Emerging LeadersVoice of the CALA-sponsored Emerging Leaders
Voice of the CALA-sponsored Emerging Leaders
 
market-review-2014-15
market-review-2014-15market-review-2014-15
market-review-2014-15
 
Company Profile Finint
Company Profile FinintCompany Profile Finint
Company Profile Finint
 
AACUpresentationfeb24draft
AACUpresentationfeb24draftAACUpresentationfeb24draft
AACUpresentationfeb24draft
 
Pembahasan
PembahasanPembahasan
Pembahasan
 
Neural nets: How regular expressions brought about deep learning
Neural nets: How regular expressions brought about deep learningNeural nets: How regular expressions brought about deep learning
Neural nets: How regular expressions brought about deep learning
 
patelchodu
patelchodupatelchodu
patelchodu
 

Similaire à Fun with bytecode weaving

An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeOmar Bashir
 
Ijaprr vol1-2-13-60-64tejinder
Ijaprr vol1-2-13-60-64tejinderIjaprr vol1-2-13-60-64tejinder
Ijaprr vol1-2-13-60-64tejinderijaprr_editor
 
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpotВладимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpotVolha Banadyseva
 
It pro dev_birbilis_20101127_en
It pro dev_birbilis_20101127_enIt pro dev_birbilis_20101127_en
It pro dev_birbilis_20101127_enGeorge Birbilis
 
Con-FESS 2015 - Having Fun With Javassist
Con-FESS 2015 - Having Fun With JavassistCon-FESS 2015 - Having Fun With Javassist
Con-FESS 2015 - Having Fun With JavassistAnton Arhipov
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction AKR Education
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Mr. Akaash
 
Java programming basics
Java programming basicsJava programming basics
Java programming basicsHamid Ghorbani
 
Sybsc cs sem 3 core java
Sybsc cs sem 3 core javaSybsc cs sem 3 core java
Sybsc cs sem 3 core javaWE-IT TUTORIALS
 

Similaire à Fun with bytecode weaving (20)

An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and Runtime
 
Ijaprr vol1-2-13-60-64tejinder
Ijaprr vol1-2-13-60-64tejinderIjaprr vol1-2-13-60-64tejinder
Ijaprr vol1-2-13-60-64tejinder
 
Introduction java programming
Introduction java programmingIntroduction java programming
Introduction java programming
 
Java Basic PART I
Java Basic PART IJava Basic PART I
Java Basic PART I
 
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpotВладимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
 
basic_java.ppt
basic_java.pptbasic_java.ppt
basic_java.ppt
 
It pro dev_birbilis_20101127_en
It pro dev_birbilis_20101127_enIt pro dev_birbilis_20101127_en
It pro dev_birbilis_20101127_en
 
Con-FESS 2015 - Having Fun With Javassist
Con-FESS 2015 - Having Fun With JavassistCon-FESS 2015 - Having Fun With Javassist
Con-FESS 2015 - Having Fun With Javassist
 
Java basic
Java basicJava basic
Java basic
 
JAVA for Every one
JAVA for Every oneJAVA for Every one
JAVA for Every one
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...
 
Java introduction
Java introductionJava introduction
Java introduction
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Sybsc cs sem 3 core java
Sybsc cs sem 3 core javaSybsc cs sem 3 core java
Sybsc cs sem 3 core java
 
JVM.pptx
JVM.pptxJVM.pptx
JVM.pptx
 
Understanding the Dalvik Virtual Machine
Understanding the Dalvik Virtual MachineUnderstanding the Dalvik Virtual Machine
Understanding the Dalvik Virtual Machine
 
Basic Java I
Basic Java IBasic Java I
Basic Java I
 
Mpl 1
Mpl 1Mpl 1
Mpl 1
 

Dernier

Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 

Dernier (20)

Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 

Fun with bytecode weaving

  • 2. Who the hell are you? Programmer Entrepeneur CTO of import.io Geek Ex-mathematician Long-suffering Java user (yay, lambdas!) Proud father of two :) 2 / 21
  • 3. So what's the plan? 1. What? 2. Why? 3. How? 4. Codez 5. Q&A 6. Beer! 3 / 21
  • 4. Some JVM internals Do you know how the JVM does its magic? 4 / 21
  • 5. Per JVM Heap for objects PermGen/Metaspace Per Thread PC (Program Counter) tracks instruction position in a register Stack (as in trace) of Frames (method invocations) Native stack Per frame Local variable 32bit array ([0]=this) Operand 32bit stack Constant pool reference for the class 5 / 21
  • 6. Operand stack The Java stack is a last-in, first-out stack of 32-bit slots. Because each slot in the stack occupies 32 bits, all stack variables occupy at least 32 bits - even a byte. Longs/Doubles take 2 slots. "We chose a stack organization so that it would be easy to emulate the machine efficiently on machines with few or irregular registers such as the Intel 486." Local variable array Zero-indexed, 32 bit slots. 6 / 21
  • 7. Bytecode "Understanding bytecode and what bytecode is likely to be generated by a Java compiler helps the Java programmer in the same way that knowledge of assembly helps the C or C++ programmer." When a JVM loads a class file, it gets a stream of bytecodes that represent the logic for each method that are interpreted or JIT compiled. One byte opcode (mnemonics, action) and its operands. 7 / 21
  • 8. Disassembling bytecode publicstaticintfactorial(intx){ inty=1; for(intz=2;z<=x;z++)y*=z; returny; } PC keeps track of current position... 0iconst_1 [1] [x] 1istore_1 [] [x,1] 2iconst_2 [2] [x,1] 3istore_2 [] [x,1,2] 4iload_2 [2] [x,1,2] 5iload_0 [x,2][x,1,2] 6if_icmpgt19(+13) [] [x,1,2] 9iload_1 [1] [x,1,2] 10iload_2 [2,1] 11imul [2] [x,1,2] 12istore_1 [] [x,2,2] 13iinc2by1 [] [x,2,3] 16goto4(-12) [] [x,2,3] 19iload_1 [y] [x,y,z] 20ireturn [] [x,y,z] 8 / 21
  • 10. What is bytecode weaving? Changing byte code for a class either up front or dynamically at run-time. 10 / 21
  • 11. Why should I want to weave bytecode? Proxy creation Aspect-orientated programming Logging Sandboxing Code coverage Adding in features like co-routines Anything else you can dream up :) 11 / 21
  • 12. How to weave WTF is a Java agent? An agent is just an interceptor in front of your main method, executed in the same JVM and loaded by the same system classloader, and governed by the same security policy and context. Need a class with a premainmethod: publicstaticvoidpremain(StringagentArgs,Instrumentationinst); ... and some special MANIFEST.MF lines: Manifest-Version:1.0 Premain-Class:my.package.MyJavaAgent Boot-Class-Path:some-dependency.jar ... a command line option: -javaagent:<jarpath>[=<options>] loadJavaprogramminglanguageagent,seejava.lang.instrument ... to hook into the Instrumentationclass 12 / 21
  • 13. Getting funky with Instrumentation Lets you hook in ClassFileTransformerinstances - which are what they sound like. byte[] transform( ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throwsIllegalClassFormatException; But what's in the byte arrays? 13 / 21
  • 15. How do you modify the bytes? Manually (Super scary) Javassist ASM Other libraries may be available... :) 15 / 21
  • 16. Javassist: a quick aside It'll parse Java source strings - no bytecode required. publicbyte[]transform(ClassLoaderloader,StringclassName,ClassclassBeingRedefined, ProtectionDomainprotectionDomain,byte[]classfileBuffer)throwsIllegalClassFormatException{ pool.insertClassPath(newByteArrayClassPath(className,classfileBuffer)); CtClasscclass=pool.get(className.replaceAll("/",".")); if(cclass.isFrozen()){ returnnull;//useuninstrumentedclass,alreadyprocessed } for(CtMethodcurrentMethod:cclass.getDeclaredMethods()){ currentMethod.insertBefore("System.err.println('foo');"); } returncclass.toBytecode(); } Easy, but not the quickest. Not so good as a learning exercise either :) 16 / 21
  • 17. ASM: total control, but like writing assembler. Event model, similar to SAX. Extend abstract class: classClassVisitor{ voidvisit(intversion,intaccess,Stringname,Stringsignature,StringsuperName, String[]interfaces) voidvisitSource(Stringsource,Stringdebug) voidvisitOuterClass(Stringowner,Stringname,Stringdesc) AnnotationVisitorvisitAnnotation(Stringdesc,booleanvisible) AnnotationVisitorvisitTypeAnnotation(inttypeRef,TypePathtypePath,Stringdesc, booleanvisible) voidvisitAttribute(Attributeattr) voidvisitInnerClass(Stringname,StringouterName,StringinnerName,intaccess) FieldVisitorvisitField(intaccess,Stringname,Stringdesc,Stringsignature, Objectvalue) MethodVisitorvisitMethod(intaccess,Stringname,Stringdesc,Stringsignature, String[]exceptions) voidvisitEnd() } 17 / 21
  • 18. and hook in to your ClassFileTransformer publicbyte[]transform(ClassLoaderloader,StringclassName, ClassclassBeingRedefined,ProtectionDomainprotectionDomain, byte[]classfileBuffer)throwsIllegalClassFormatException{ ClassReadercr=newClassReader(classfileBuffer); ClassWritercw=newClassWriter(cr,ClassWriter.COMPUTE_FRAMES); cr.accept(cw,0); returncw.toByteArray(); } Easy! 18 / 21
  • 19. sio2box A memory sandbox that counts allocations. Add annotations to classes (SiO2Class) and methods (SiO2Method) to limit the total amount of memory allocated by untrusted code. Don't take GC into account, interested in memory churn - could use ReferenceQueueif we were. Tracks: Array.newInstance type[].clone Object instantiation new type[] - ANEWARRAY, NEWARRAY, MULTIANEWARRAY Object.clone ArrayList.clone (TODO) 19 / 21
  • 20. Quick example Pass through a MemoryStoreobject as the first argument (this is a convention). MemoryStorememoryStore=newMemoryStore(maxMemory); myMethod(memoryStore,arg0,arg1); Annotate the class and method: @SiO2Class publicclassMyClass{ @SiO2Method publicvoidmyMethod(MemoryStorem,Stringarg0,Objectarg1){ ... } } If more memory is allocated than you specify, a MemoryExceededException exception is thrown. 20 / 21