SlideShare una empresa de Scribd logo
1 de 24
Understanding
Java byte code
and the class file format
0xCAFEBABE
source code
byte code
JVM
javac scalac groovyc jrubyc
JIT compilerinterpreter
class loader
creates
reads
runs
source code byte code
void foo() {
}
RETURNreturn; 0xB1
source code byte code
int foo() {
return 1 + 2;
}
ICONST_1
ICONST_2
IADD
operand stack 1
2
13
IRETURN
0x04
0x05
0x60
0xAC
source code byte code
ICONST_2
IADD
IRETURN
BIPUSH
int foo() {
return 11 + 2;
}
operand stack 11
2
1113
0x05
0x60
0xAC
0x10 110x0B
source code byte code
int foo(int i) {
return i + 1;
}
ILOAD_1
ICONST_1
IADD
IRETURN
operand stack
local variable array
1 : i
0 : this
i
1
ii + 1
0x1B
0x04
0x60
0xAC
source code byte code
ILOAD_1
ICONST_1
IADD
operand stack
local variable array
1 : i
0 : this
1
i
int foo(int i) {
int i2 = i + 1;
return i2;
}
ISTORE_2
ILOAD_2
IRETURN
2 : i + 1
ii + 1
2 :2 : i + 1
0x1B
0x04
0x60
0x3D
0x1C
0xAC
source code byte code
long foo(long i) {
return i + 1L;
}
LLOAD_1
LCONST_1
LADD
LRETURN
operand stack
local variable array
2 : i (cn.)
1 : i
0 : this
i (cn.)
i
0x1F
0x0A
0x61
0xAD
i (cn.)
i
1L
1L (cn.)
i + 1L
i + 1L (cn.)
source code byte code
short foo(short i) {
return (short) (i + 1);
}
ILOAD_1
ICONST_1
IADD
I2S
IRETURN
operand stack
local variable array
1 : i
0 : this
1
iii + 1
0x1B
0x04
0x60
0x93
0xAC
Java type JVM type (non-array) JVM descriptor stack slots
boolean
I
Z 1
byte B 1
short S 1
char C 1
int I 1
long L J 2
float F F 1
double D D 2
void - V 0
java.lang.Object A Ljava/lang/Object; 1
source code byte code
pkg/Bar.class
void foo() {
return;
}
RETURN
package pkg;
class Bar {
}
constant pool (i.a. UTF-8)
0x0000
0x0000: foo
0x0001: ()V
0x0002: pkg/Bar
0xB1
0x0000 0x0000foo ()V()V0x0001
0x00000 1 10x0001
operand stack /////////////////
local variable array 0 : this
source code byte code
package pkg;
class Bar {
public static void foo() {
return;
}
}
RETURN
0x0009
operand stack /////////////////
local variable array /////////////////
0 0
Modifier Value
static 0x0008
public 0x0001
0x0009
constant pool
0xB1
0x0000 0x0000
0x0000 0x0001foo ()V
source code byte code
package pkg;
class Bar {
int foo(int i) {
return foo(i + 1);
}
}
ILOAD_1
ICONST_1
IADD
INVOKEVIRTUAL pkg/Bar foo (I)I
ALOAD_0
IRETURN
operand stack
local variable array
1 : i
0 : this
this
i
1
this
ii + 1
foo(i + 1)
0x2A
0x1B
0x04
0x60
0xAC
0xB6
constant pool
0x0002 0x0000 0x0001
source code byte code
package pkg;
class Bar {
static int foo(int i) {
return foo(i + 1);
}
}
ILOAD_0
ICONST_1
IADD
INVOKESTATIC pkg/Bar foo (I)I
IRETURN
operand stack
local variable array 0 : i
i
1
ii + 1foo(i + 1)
0x1A
0x04
0x60
0xB8 0x0002 0x0001 0x0000
0xAC
constant pool
source code byte code
package pkg;
class Bar {
@Override
public String toString() {
return super.toString();
}
}
ALOAD_0
INVOKESPECIAL java/lang/Object
toString
()Ljava/lang/String;
ARETURN
operand stack
local variable array 0 : this
thistoString()
0x1A
0xB7 0x0004
0x0005
0x0006
0xAC
constant pool
INVOKESPECIAL
INVOKEVIRTUAL
INVOKESTATIC
INVOKEINTERFACE
INVOKEDYNAMIC
Invokes a static method.
pkg/Bar foo ()V
pkg/Bar foo ()V
Invokes the most-specific version of an inherited method on a non-interface class.
pkg/Bar foo ()V
Invokes a super class‘s version of an inherited method.
Invokes a “constructor method”.
Invokes a private method.
Invokes an interface default method (Java 8).
pkg/Bar foo ()V
Invokes an interface method.
(Similar to INVOKEVIRTUAL but without virtual method table index optimization.)
foo ()V bootstrap
Queries the given bootstrap method for locating a method implementation at runtime.
(MethodHandle: Combines a specific method and an INVOKE* instruction.)
void foo() {
???(); // invokedynamic
}
foo() ? qux()
bootstrap()
bar()
void foo() {
bar();
}
In theory, this could be achieved by using reflection. However, using invokedynamic
offers a more native approach. This is especially important when dealing with
primitive types (double boxing).
Used to implement lambda expressions, more important for dynamic languages.
source code byte code
0x1A
0x06
0xA4
0x03
0xAC
0x1A
0x04
0x60
0xB8 0x0002 0x0000 0x0001
0xAC
package pkg;
class Bar {
static int foo(int i) {
if (i > 3) {
return 0;
} else {
return foo(i + 1);
}
}
}
ILOAD_0
ICONST_3
IF_ICMPLE
ICONST_0
IRETURN
ILOAD_0
ICONST_1
IADD
INVOKESTATIC
IRETURN
pkg/Bar foo (I)I
X
X:
operand stack
local variable array 0 : i
i
3
i
1
i + 1foo(i + 1)
constant pool
0x0008
0008:
java.lang.VerifyError: Inconsistent stackmap frames at branch
target XXX in method pkg.Bar.foo(I)I
at offset YYY
type inferencing
(until Java 5, failover for Java 6)
Follow any possible path of jump
instructions: Assert the consistency of the
contents of the operand stack and local
variable array for any possible path.
Inference might require several iterations
over a method‘s byte code.
Legacy: -XX:-UseSplitVerifier
type checking
(from Java 6)
The verifier rejects malformed class files and byte code:
• compliance to class file format
• type safety
• access violations
Require the otherwise infered information
about the contents of the operand stack
and the local variable array to be
embedded in the code as stack map frames
at any target of a jump instruction.
Checking requires exactly one iteration over
a method‘s byte code.
source code byte code
int foo() {
try {
return 1;
} catch (Exception e) {
return 0;
}
}
ICONST_1
IRETURN
ICONST_0
IRETURN
exception table:
0000:
0001:
0002:
0003:
<from> <to> <catch> java/lang/Exception0x0000 0x0001 0x0002
constant pool
0x0005
0x04
0xAC
0x03
0xAC
source code byte code
package pkg;
class Bar {
void foo() {
return;
}
}
RETURN
0x0000 foo ()V
0 1
foo
()V
pkg/Bar
java/lang/Object
0x0000
pkg/Bar
java/lang/Object
[]
[]
0xCAFEBABE
0x0052
0000:
0001:
0002:
0003:
0x0000
0x0002
0x0003
0x0000
0x0000
0x0000 0x0000 0x0001
0xB1
0x0000 0x0001
UTF-8[foo]
UTF-8[()V]
UTF-8[pkg/Bar]
UTF-8[java/lang/Object]
0x0004
class Service {
@Secured(user = "ADMIN")
void deleteEverything() {
if(!"ADMIN".equals(UserHolder.user)) {
throw new IllegalStateException("Wrong user");
}
// delete everything...
}
}
redefine class
(build time, agent)
create subclass
(Liskov substitution)
class SecuredService extends Service {
@Override
void deleteEverything() {
if(!"ADMIN".equals(UserHolder.user)) {
throw new IllegalStateException("Wrong user");
}
super.deleteEverything();
}
}
class Service {
@Secured(user = "ADMIN")
void deleteEverything() {
// delete everything...
}
}
Class<?> dynamicType = new ByteBuddy()
.subclass(Object.class)
.method(named("toString"))
.intercept(value("Hello World!"))
.make()
.load(getClass().getClassLoader(),
ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
assertThat(dynamicType.newInstance().toString(),
is("Hello World!"));
http://rafael.codes
@rafaelcodes
http://documents4j.com
https://github.com/documents4j/documents4j
http://bytebuddy.net
https://github.com/raphw/byte-buddy

Más contenido relacionado

La actualidad más candente

Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introductioncaswenson
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and UtilitiesPramod Kumar
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple ProgramsUpender Upr
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Nishan Barot
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesGanesh Samarthyam
 
Easy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEEasy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEUehara Junji
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java DevelopersChristoph Pickl
 

La actualidad más candente (19)

Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 
Initial Java Core Concept
Initial Java Core ConceptInitial Java Core Concept
Initial Java Core Concept
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Java Programming - 03 java control flow
Java Programming - 03 java control flowJava Programming - 03 java control flow
Java Programming - 03 java control flow
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Easy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEEasy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVE
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java Developers
 
Java programs
Java programsJava programs
Java programs
 
Java generics final
Java generics finalJava generics final
Java generics final
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 

Destacado

Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languagesRafael Winterhalter
 
How to Change Permissions and Install a Module in Drupal - Musings of a Drupa...
How to Change Permissions and Install a Module in Drupal - Musings of a Drupa...How to Change Permissions and Install a Module in Drupal - Musings of a Drupa...
How to Change Permissions and Install a Module in Drupal - Musings of a Drupa...OlinData
 
The power of information - easy read version
The power of information - easy read versionThe power of information - easy read version
The power of information - easy read versionDepartment of Health
 
XML Schema Difference Analysis
XML Schema Difference AnalysisXML Schema Difference Analysis
XML Schema Difference Analysisartcolman
 
EclipseLink: Beyond Relational and NoSQL to Polyglot and HTML5
EclipseLink: Beyond Relational and NoSQL to Polyglot and HTML5EclipseLink: Beyond Relational and NoSQL to Polyglot and HTML5
EclipseLink: Beyond Relational and NoSQL to Polyglot and HTML5Shaun Smith
 
An introductory guide to the United Nations Convention on the Rights of Perso...
An introductory guide to the United Nations Convention on the Rights of Perso...An introductory guide to the United Nations Convention on the Rights of Perso...
An introductory guide to the United Nations Convention on the Rights of Perso...NUDORRwanda
 
PRINCE2 Foundation Training Manual by Frank Turley
PRINCE2 Foundation Training Manual by Frank TurleyPRINCE2 Foundation Training Manual by Frank Turley
PRINCE2 Foundation Training Manual by Frank TurleyFrank Turley
 
National Care Standards - Easy Read Version
National Care Standards - Easy Read VersionNational Care Standards - Easy Read Version
National Care Standards - Easy Read VersionChristian Storstein
 
Making Great Presentations
Making Great PresentationsMaking Great Presentations
Making Great PresentationsIan Lurie
 
4 great public speaking tips effective presentation skills training
4 great public speaking tips effective presentation skills training4 great public speaking tips effective presentation skills training
4 great public speaking tips effective presentation skills trainingAkash Karia
 
Scientific Method Variables (Teach)
Scientific Method Variables (Teach)Scientific Method Variables (Teach)
Scientific Method Variables (Teach)Moira Whitehouse
 
Going to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGoing to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGuillaume Laforge
 
4. heredity and evolution
4. heredity and evolution4. heredity and evolution
4. heredity and evolutionAbhay Goyal
 

Destacado (16)

Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
 
How to Change Permissions and Install a Module in Drupal - Musings of a Drupa...
How to Change Permissions and Install a Module in Drupal - Musings of a Drupa...How to Change Permissions and Install a Module in Drupal - Musings of a Drupa...
How to Change Permissions and Install a Module in Drupal - Musings of a Drupa...
 
The power of information - easy read version
The power of information - easy read versionThe power of information - easy read version
The power of information - easy read version
 
XML Schema Difference Analysis
XML Schema Difference AnalysisXML Schema Difference Analysis
XML Schema Difference Analysis
 
EclipseLink: Beyond Relational and NoSQL to Polyglot and HTML5
EclipseLink: Beyond Relational and NoSQL to Polyglot and HTML5EclipseLink: Beyond Relational and NoSQL to Polyglot and HTML5
EclipseLink: Beyond Relational and NoSQL to Polyglot and HTML5
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
 
An introductory guide to the United Nations Convention on the Rights of Perso...
An introductory guide to the United Nations Convention on the Rights of Perso...An introductory guide to the United Nations Convention on the Rights of Perso...
An introductory guide to the United Nations Convention on the Rights of Perso...
 
Responsive Typography II
Responsive Typography IIResponsive Typography II
Responsive Typography II
 
PRINCE2 Foundation Training Manual by Frank Turley
PRINCE2 Foundation Training Manual by Frank TurleyPRINCE2 Foundation Training Manual by Frank Turley
PRINCE2 Foundation Training Manual by Frank Turley
 
National Care Standards - Easy Read Version
National Care Standards - Easy Read VersionNational Care Standards - Easy Read Version
National Care Standards - Easy Read Version
 
Making Great Presentations
Making Great PresentationsMaking Great Presentations
Making Great Presentations
 
4 great public speaking tips effective presentation skills training
4 great public speaking tips effective presentation skills training4 great public speaking tips effective presentation skills training
4 great public speaking tips effective presentation skills training
 
Formal & informal organisational
Formal & informal organisationalFormal & informal organisational
Formal & informal organisational
 
Scientific Method Variables (Teach)
Scientific Method Variables (Teach)Scientific Method Variables (Teach)
Scientific Method Variables (Teach)
 
Going to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGoing to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific Languages
 
4. heredity and evolution
4. heredity and evolution4. heredity and evolution
4. heredity and evolution
 

Similar a Understanding Java byte code and the class file format

Arithmatic logic unit using VHDL (gates)
Arithmatic logic unit using VHDL (gates)Arithmatic logic unit using VHDL (gates)
Arithmatic logic unit using VHDL (gates)TakashiSuoh
 
Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performanceDuoyi Wu
 
JVM bytecode - The secret language behind Java and Scala
JVM bytecode - The secret language behind Java and ScalaJVM bytecode - The secret language behind Java and Scala
JVM bytecode - The secret language behind Java and ScalaTakipi
 
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016Codemotion
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Andrey Breslav
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Charles Nutter
 
StackOverflow
StackOverflowStackOverflow
StackOverflowSusam Pal
 
sizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may mattersizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may matterDawid Weiss
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performanceintelliyole
 
Reverse Engineering Dojo: Enhancing Assembly Reading Skills
Reverse Engineering Dojo: Enhancing Assembly Reading SkillsReverse Engineering Dojo: Enhancing Assembly Reading Skills
Reverse Engineering Dojo: Enhancing Assembly Reading SkillsAsuka Nakajima
 
Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019
Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019
Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019corehard_by
 
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...Muhammad Ulhaque
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesCharles Nutter
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engineDuoyi Wu
 
Денис Лебедев, Swift
Денис Лебедев, SwiftДенис Лебедев, Swift
Денис Лебедев, SwiftYandex
 

Similar a Understanding Java byte code and the class file format (20)

Arithmatic logic unit using VHDL (gates)
Arithmatic logic unit using VHDL (gates)Arithmatic logic unit using VHDL (gates)
Arithmatic logic unit using VHDL (gates)
 
Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performance
 
JVM bytecode - The secret language behind Java and Scala
JVM bytecode - The secret language behind Java and ScalaJVM bytecode - The secret language behind Java and Scala
JVM bytecode - The secret language behind Java and Scala
 
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
 
Kotlin @ Devoxx 2011
Kotlin @ Devoxx 2011Kotlin @ Devoxx 2011
Kotlin @ Devoxx 2011
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
 
StackOverflow
StackOverflowStackOverflow
StackOverflow
 
sizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may mattersizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may matter
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
 
Faster Python, FOSDEM
Faster Python, FOSDEMFaster Python, FOSDEM
Faster Python, FOSDEM
 
Reverse Engineering Dojo: Enhancing Assembly Reading Skills
Reverse Engineering Dojo: Enhancing Assembly Reading SkillsReverse Engineering Dojo: Enhancing Assembly Reading Skills
Reverse Engineering Dojo: Enhancing Assembly Reading Skills
 
Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019
Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019
Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019
 
Why Learn Python?
Why Learn Python?Why Learn Python?
Why Learn Python?
 
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
 
Computer hw1
Computer hw1Computer hw1
Computer hw1
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
CORE JAVA-1
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engine
 
Денис Лебедев, Swift
Денис Лебедев, SwiftДенис Лебедев, Swift
Денис Лебедев, Swift
 

Más de Rafael Winterhalter

Java and OpenJDK: disecting the ecosystem
Java and OpenJDK: disecting the ecosystemJava and OpenJDK: disecting the ecosystem
Java and OpenJDK: disecting the ecosystemRafael Winterhalter
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agentsRafael Winterhalter
 
Event-Sourcing Microservices on the JVM
Event-Sourcing Microservices on the JVMEvent-Sourcing Microservices on the JVM
Event-Sourcing Microservices on the JVMRafael Winterhalter
 
Getting started with Java 9 modules
Getting started with Java 9 modulesGetting started with Java 9 modules
Getting started with Java 9 modulesRafael Winterhalter
 
Monitoring distributed (micro-)services
Monitoring distributed (micro-)servicesMonitoring distributed (micro-)services
Monitoring distributed (micro-)servicesRafael Winterhalter
 

Más de Rafael Winterhalter (8)

Java and OpenJDK: disecting the ecosystem
Java and OpenJDK: disecting the ecosystemJava and OpenJDK: disecting the ecosystem
Java and OpenJDK: disecting the ecosystem
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agents
 
Byte code field report
Byte code field reportByte code field report
Byte code field report
 
Event-Sourcing Microservices on the JVM
Event-Sourcing Microservices on the JVMEvent-Sourcing Microservices on the JVM
Event-Sourcing Microservices on the JVM
 
Java 10, Java 11 and beyond
Java 10, Java 11 and beyondJava 10, Java 11 and beyond
Java 10, Java 11 and beyond
 
Getting started with Java 9 modules
Getting started with Java 9 modulesGetting started with Java 9 modules
Getting started with Java 9 modules
 
Monitoring distributed (micro-)services
Monitoring distributed (micro-)servicesMonitoring distributed (micro-)services
Monitoring distributed (micro-)services
 
An Overview of Project Jigsaw
An Overview of Project JigsawAn Overview of Project Jigsaw
An Overview of Project Jigsaw
 

Último

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 

Último (20)

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 

Understanding Java byte code and the class file format

  • 1. Understanding Java byte code and the class file format
  • 2. 0xCAFEBABE source code byte code JVM javac scalac groovyc jrubyc JIT compilerinterpreter class loader creates reads runs
  • 3. source code byte code void foo() { } RETURNreturn; 0xB1
  • 4. source code byte code int foo() { return 1 + 2; } ICONST_1 ICONST_2 IADD operand stack 1 2 13 IRETURN 0x04 0x05 0x60 0xAC
  • 5. source code byte code ICONST_2 IADD IRETURN BIPUSH int foo() { return 11 + 2; } operand stack 11 2 1113 0x05 0x60 0xAC 0x10 110x0B
  • 6. source code byte code int foo(int i) { return i + 1; } ILOAD_1 ICONST_1 IADD IRETURN operand stack local variable array 1 : i 0 : this i 1 ii + 1 0x1B 0x04 0x60 0xAC
  • 7. source code byte code ILOAD_1 ICONST_1 IADD operand stack local variable array 1 : i 0 : this 1 i int foo(int i) { int i2 = i + 1; return i2; } ISTORE_2 ILOAD_2 IRETURN 2 : i + 1 ii + 1 2 :2 : i + 1 0x1B 0x04 0x60 0x3D 0x1C 0xAC
  • 8. source code byte code long foo(long i) { return i + 1L; } LLOAD_1 LCONST_1 LADD LRETURN operand stack local variable array 2 : i (cn.) 1 : i 0 : this i (cn.) i 0x1F 0x0A 0x61 0xAD i (cn.) i 1L 1L (cn.) i + 1L i + 1L (cn.)
  • 9. source code byte code short foo(short i) { return (short) (i + 1); } ILOAD_1 ICONST_1 IADD I2S IRETURN operand stack local variable array 1 : i 0 : this 1 iii + 1 0x1B 0x04 0x60 0x93 0xAC
  • 10. Java type JVM type (non-array) JVM descriptor stack slots boolean I Z 1 byte B 1 short S 1 char C 1 int I 1 long L J 2 float F F 1 double D D 2 void - V 0 java.lang.Object A Ljava/lang/Object; 1
  • 11. source code byte code pkg/Bar.class void foo() { return; } RETURN package pkg; class Bar { } constant pool (i.a. UTF-8) 0x0000 0x0000: foo 0x0001: ()V 0x0002: pkg/Bar 0xB1 0x0000 0x0000foo ()V()V0x0001 0x00000 1 10x0001 operand stack ///////////////// local variable array 0 : this
  • 12. source code byte code package pkg; class Bar { public static void foo() { return; } } RETURN 0x0009 operand stack ///////////////// local variable array ///////////////// 0 0 Modifier Value static 0x0008 public 0x0001 0x0009 constant pool 0xB1 0x0000 0x0000 0x0000 0x0001foo ()V
  • 13. source code byte code package pkg; class Bar { int foo(int i) { return foo(i + 1); } } ILOAD_1 ICONST_1 IADD INVOKEVIRTUAL pkg/Bar foo (I)I ALOAD_0 IRETURN operand stack local variable array 1 : i 0 : this this i 1 this ii + 1 foo(i + 1) 0x2A 0x1B 0x04 0x60 0xAC 0xB6 constant pool 0x0002 0x0000 0x0001
  • 14. source code byte code package pkg; class Bar { static int foo(int i) { return foo(i + 1); } } ILOAD_0 ICONST_1 IADD INVOKESTATIC pkg/Bar foo (I)I IRETURN operand stack local variable array 0 : i i 1 ii + 1foo(i + 1) 0x1A 0x04 0x60 0xB8 0x0002 0x0001 0x0000 0xAC constant pool
  • 15. source code byte code package pkg; class Bar { @Override public String toString() { return super.toString(); } } ALOAD_0 INVOKESPECIAL java/lang/Object toString ()Ljava/lang/String; ARETURN operand stack local variable array 0 : this thistoString() 0x1A 0xB7 0x0004 0x0005 0x0006 0xAC constant pool
  • 16. INVOKESPECIAL INVOKEVIRTUAL INVOKESTATIC INVOKEINTERFACE INVOKEDYNAMIC Invokes a static method. pkg/Bar foo ()V pkg/Bar foo ()V Invokes the most-specific version of an inherited method on a non-interface class. pkg/Bar foo ()V Invokes a super class‘s version of an inherited method. Invokes a “constructor method”. Invokes a private method. Invokes an interface default method (Java 8). pkg/Bar foo ()V Invokes an interface method. (Similar to INVOKEVIRTUAL but without virtual method table index optimization.) foo ()V bootstrap Queries the given bootstrap method for locating a method implementation at runtime. (MethodHandle: Combines a specific method and an INVOKE* instruction.)
  • 17. void foo() { ???(); // invokedynamic } foo() ? qux() bootstrap() bar() void foo() { bar(); } In theory, this could be achieved by using reflection. However, using invokedynamic offers a more native approach. This is especially important when dealing with primitive types (double boxing). Used to implement lambda expressions, more important for dynamic languages.
  • 18. source code byte code 0x1A 0x06 0xA4 0x03 0xAC 0x1A 0x04 0x60 0xB8 0x0002 0x0000 0x0001 0xAC package pkg; class Bar { static int foo(int i) { if (i > 3) { return 0; } else { return foo(i + 1); } } } ILOAD_0 ICONST_3 IF_ICMPLE ICONST_0 IRETURN ILOAD_0 ICONST_1 IADD INVOKESTATIC IRETURN pkg/Bar foo (I)I X X: operand stack local variable array 0 : i i 3 i 1 i + 1foo(i + 1) constant pool 0x0008 0008:
  • 19. java.lang.VerifyError: Inconsistent stackmap frames at branch target XXX in method pkg.Bar.foo(I)I at offset YYY type inferencing (until Java 5, failover for Java 6) Follow any possible path of jump instructions: Assert the consistency of the contents of the operand stack and local variable array for any possible path. Inference might require several iterations over a method‘s byte code. Legacy: -XX:-UseSplitVerifier type checking (from Java 6) The verifier rejects malformed class files and byte code: • compliance to class file format • type safety • access violations Require the otherwise infered information about the contents of the operand stack and the local variable array to be embedded in the code as stack map frames at any target of a jump instruction. Checking requires exactly one iteration over a method‘s byte code.
  • 20. source code byte code int foo() { try { return 1; } catch (Exception e) { return 0; } } ICONST_1 IRETURN ICONST_0 IRETURN exception table: 0000: 0001: 0002: 0003: <from> <to> <catch> java/lang/Exception0x0000 0x0001 0x0002 constant pool 0x0005 0x04 0xAC 0x03 0xAC
  • 21. source code byte code package pkg; class Bar { void foo() { return; } } RETURN 0x0000 foo ()V 0 1 foo ()V pkg/Bar java/lang/Object 0x0000 pkg/Bar java/lang/Object [] [] 0xCAFEBABE 0x0052 0000: 0001: 0002: 0003: 0x0000 0x0002 0x0003 0x0000 0x0000 0x0000 0x0000 0x0001 0xB1 0x0000 0x0001 UTF-8[foo] UTF-8[()V] UTF-8[pkg/Bar] UTF-8[java/lang/Object] 0x0004
  • 22. class Service { @Secured(user = "ADMIN") void deleteEverything() { if(!"ADMIN".equals(UserHolder.user)) { throw new IllegalStateException("Wrong user"); } // delete everything... } } redefine class (build time, agent) create subclass (Liskov substitution) class SecuredService extends Service { @Override void deleteEverything() { if(!"ADMIN".equals(UserHolder.user)) { throw new IllegalStateException("Wrong user"); } super.deleteEverything(); } } class Service { @Secured(user = "ADMIN") void deleteEverything() { // delete everything... } }
  • 23. Class<?> dynamicType = new ByteBuddy() .subclass(Object.class) .method(named("toString")) .intercept(value("Hello World!")) .make() .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) .getLoaded(); assertThat(dynamicType.newInstance().toString(), is("Hello World!"));