SlideShare a Scribd company logo
1 of 42
Byte code manipulation and
instrumentalization in Java
Alex Moskvin
CEO/CTO @ Plexteq
About myself
• CEO/CTO Plexteq OÜ
• Ph.D in information technology area
• Interests
• Software architecture
• High loaded systems
• Everything under the hood
• AI/ML + BigData
• Knowledge sharing ;)
• Follow me
• https://twitter.com/amoskvin
• https://www.facebook.com/moskvin.aleksey
Agenda
1. What is bytecode
2. How to manipulate byte code
3. Why would we need manipulate byte code
4. Let’s have some fun
1. Java agent
2. Expose java agent metrics via JMX
3. Use Java agent with regular Spring boot application
Disclaimer ;)
This talk is based on personal experience.
Use at your own risk.
Bytecode
Java bytecode is the result of the compilation of a Java program, an
intermediate representation of that program which is machine
independent.
The Java bytecode gets processed by the Java virtual machine (JVM)
instead of the processor. It is the job of the JVM to make the necessary
resource calls to the processor in order to run the bytecode.
Bytecode
Bytecode
“A Java programmer does not need to be aware of or understand Java
bytecode at all.”
- Wikipedia
Bytecode
Bytecode
Bytecode
$ javac HelloWorldA.java
$ file HelloWorldA.class
$ cat -v HelloWorldA.class
$ hexdump HelloWorldA.class
Bytecode
$ javac HelloWorldA.java
$ file HelloWorldA.class
$ cat -v HelloWorldA.class
$ hexdump HelloWorldA.class
Bytecode
• Magic Number: 0xCAFEBABE
• Version of Class File Format: the minor and major versions of the class file
• Constant Pool: Pool of constants for the class
• Access Flags: for example whether the class is abstract, static, etc.
• This Class: The name of the current class
• Super Class: The name of the super class
• Interfaces: Any interfaces in the class
• Fields: Any fields in the class
• Methods: Any methods in the class
• Attributes: Any attributes of the class (for example the name of the
sourcefile, etc.)
Bytecode
It’s javap time
https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html
Bytecode
Bytecode
JVM added constructor for us
Bytecode
JVM thread stack
Frame
Operand stack
Each thread of execution that stores frames
that represent method invocations
Each frame holds data, partial results, method return values and
performs dynamic linking
Each frame contains stack, known as Operand stack which holds
the operand values of JVM types
Bytecode
Java bytecodes instructions fall into these major categories:
• Load and store
• Method invocation and return
• Control transfer
• Arithmetical operation
• Type conversion
• Object manipulation
• Operand stack management
Bytecode
Call to super()
System.out.println(“Hello world”);
• Get System.out value out of a static field (i.e. PrintStream o = java.lang.System.in;)
• Put “Hello world” to operand stack
• Invoke java.io.PrintStream.println method on operant stack
Bytecode
More advanced case 
Bytecode
Bytecode
Compiler time optimization
• “new” allocates StringBuilder object on heap
• “dup” duplicates the value on top of the stack
• “invokevirtual” invokes constructor
Bytecode
Happy disassembling!
https://en.wikipedia.org/wiki/Java_bytecode_instruction_listings
Bytecode manipulation
• Bytecode is just an array of bytes
• Bytecode of a class represents method declarations with instructions
set
• Java class loading mechanisms allow to load bytecode from
everywhere
• Byte code could be generated at the runtime
• Byte code of application could be changed at runtime using Agents
Bytecode manipulation
Bytecode manipulation
Bytecode manipulation :: Javaassist
• How do we modify bytes using Javassist?
Bytecode manipulation :: Javaassist
Bytecode manipulation :: Javaassist
• Prerequisites
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.23.0-GA</version>
</dependency>
• Limitations
• No syntatic sugar (i.e foreach, full class names)
• No generics support
Bytecode manipulation
Let’s code!
Bytecode manipulation
Why would we need manipulate byte code?
Bytecode manipulation
• Program analysis:
• find bugs in your application
• examine code complexity
• find classes with a specific annotation
• Class generation:
• lazy load data from a database using proxies
• Security:
• restrict access to certain APIs
• code obfuscation
• Transforming classes without the Java source code:
• code profiling / instrumentalization
• code optimization
Bytecode manipulation
Bytecode manipulation :: Java agent
• We can use a core Java feature introduced in 1.5 to manipulate the
bytecode. This feature is called a Java agent.
Bytecode manipulation :: Java agent
Bytecode manipulation :: Java agent
Bytecode manipulation :: Java agent
public class JavassistAgent
{
public static void premain(String agentArgs, Instrumentation inst) {
System.out.println("Starting the agent");
inst.addTransformer(new ImportantLogClassTransformer());
}
}
public class ImportantLogClassTransformer implements ClassFileTransformer
{
public byte[] transform(ClassLoader loader, String className,
Class classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] classfileBuffer) throws IllegalClassFormatException {
// manipulate the bytes here
return modified bytes;
}
}
Bytecode manipulation :: Java agent
manifest.mf
Manifest-Version: 1.0
PreMain-Class: com.example.Agent007
Fun
Let’s have some fun!
Good point to start with:
https://github.com/tomsquest/java-agent-asm-javassist-sample
Fun
Specifically:
1. Let’s code a Java Agent that gathers invocations to MongoDB Java
driver (insert, update, find) operations
2. Expose stats using JMX
3. Try agent with real Spring boot app
Fun :: JMX
Java Management Extensions (JMX) is a Java technology that supplies
tools for managing and monitoring applications, system objects,
devices (such as printers) and service-oriented networks.
Covered by JSR 160
Cool and simple implementation:
https://github.com/j256/simplejmx
Questions?
We are hiring!

More Related Content

What's hot

Advanced java
Advanced java Advanced java
Advanced java NA
 
Session 42 - Struts 2 Hibernate Integration
Session 42 - Struts 2 Hibernate IntegrationSession 42 - Struts 2 Hibernate Integration
Session 42 - Struts 2 Hibernate IntegrationPawanMM
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introductionSagar Verma
 
Java Development Kit (jdk)
Java Development Kit (jdk)Java Development Kit (jdk)
Java Development Kit (jdk)Jadavsejal
 
Session 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOPSession 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOPPawanMM
 
Александр Пашинский "Reinventing Design Patterns with Java 8"
Александр Пашинский "Reinventing Design Patterns with Java 8"Александр Пашинский "Reinventing Design Patterns with Java 8"
Александр Пашинский "Reinventing Design Patterns with Java 8"Anna Shymchenko
 
Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1PawanMM
 
Struts 2 - Introduction
Struts 2 - Introduction Struts 2 - Introduction
Struts 2 - Introduction Hitesh-Java
 
Grails 4 and Micronaut at Devnexus 2019
Grails 4 and Micronaut at Devnexus 2019Grails 4 and Micronaut at Devnexus 2019
Grails 4 and Micronaut at Devnexus 2019graemerocher
 
Java introduction
Java introductionJava introduction
Java introductionSagar Verma
 
Pj01 2-install java and write first java program
Pj01 2-install java and write first java programPj01 2-install java and write first java program
Pj01 2-install java and write first java programSasidharaRaoMarrapu
 
Basic difference between jdk,jre,jvm in advance java course
Basic difference between jdk,jre,jvm in advance java courseBasic difference between jdk,jre,jvm in advance java course
Basic difference between jdk,jre,jvm in advance java coursePreeti Agarwal
 

What's hot (20)

Advanced java
Advanced java Advanced java
Advanced java
 
Session 42 - Struts 2 Hibernate Integration
Session 42 - Struts 2 Hibernate IntegrationSession 42 - Struts 2 Hibernate Integration
Session 42 - Struts 2 Hibernate Integration
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
 
JDK,JRE,JVM
JDK,JRE,JVMJDK,JRE,JVM
JDK,JRE,JVM
 
Java Development Kit (jdk)
Java Development Kit (jdk)Java Development Kit (jdk)
Java Development Kit (jdk)
 
Session 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOPSession 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOP
 
Александр Пашинский "Reinventing Design Patterns with Java 8"
Александр Пашинский "Reinventing Design Patterns with Java 8"Александр Пашинский "Reinventing Design Patterns with Java 8"
Александр Пашинский "Reinventing Design Patterns with Java 8"
 
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
 
Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1
 
Struts 2 - Introduction
Struts 2 - Introduction Struts 2 - Introduction
Struts 2 - Introduction
 
JVM
JVMJVM
JVM
 
JVM
JVMJVM
JVM
 
Grails 4 and Micronaut at Devnexus 2019
Grails 4 and Micronaut at Devnexus 2019Grails 4 and Micronaut at Devnexus 2019
Grails 4 and Micronaut at Devnexus 2019
 
Java introduction
Java introductionJava introduction
Java introduction
 
Pj01 2-install java and write first java program
Pj01 2-install java and write first java programPj01 2-install java and write first java program
Pj01 2-install java and write first java program
 
Java and the JVM
Java and the JVMJava and the JVM
Java and the JVM
 
Java virtual machine
Java virtual machineJava virtual machine
Java virtual machine
 
Basic difference between jdk,jre,jvm in advance java course
Basic difference between jdk,jre,jvm in advance java courseBasic difference between jdk,jre,jvm in advance java course
Basic difference between jdk,jre,jvm in advance java course
 
History of java'
History of java'History of java'
History of java'
 

Similar to Byte code manipulation and instrumentalization in Java

1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introductionjyoti_lakhani
 
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...Malin Weiss
 
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...Speedment, Inc.
 
Micronaut Deep Dive - Devoxx Belgium 2019
Micronaut Deep Dive - Devoxx Belgium 2019Micronaut Deep Dive - Devoxx Belgium 2019
Micronaut Deep Dive - Devoxx Belgium 2019graemerocher
 
Micronaut: Evolving Java for the Microservices and Serverless Era
Micronaut: Evolving Java for the Microservices and Serverless EraMicronaut: Evolving Java for the Microservices and Serverless Era
Micronaut: Evolving Java for the Microservices and Serverless Eragraemerocher
 
Typesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and PlayTypesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and PlayLuka Zakrajšek
 
How to generate customized java 8 code from your database
How to generate customized java 8 code from your databaseHow to generate customized java 8 code from your database
How to generate customized java 8 code from your databaseSpeedment, Inc.
 
Silicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your databaseSilicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your databaseSpeedment, Inc.
 
Oracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningOracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningMichel Schildmeijer
 
Introduction to java
Introduction to java Introduction to java
Introduction to java Java Lover
 
Java Programming and J2ME: The Basics
Java Programming and J2ME: The BasicsJava Programming and J2ME: The Basics
Java Programming and J2ME: The Basicstosine
 
Advanced Production Debugging
Advanced Production DebuggingAdvanced Production Debugging
Advanced Production DebuggingTakipi
 
Object Oriented Programming-JAVA
Object Oriented Programming-JAVAObject Oriented Programming-JAVA
Object Oriented Programming-JAVAHome
 
JDK Tools For Performance Diagnostics
JDK Tools For Performance DiagnosticsJDK Tools For Performance Diagnostics
JDK Tools For Performance DiagnosticsBaruch Sadogursky
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionMazenetsolution
 
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf10322210023
 

Similar to Byte code manipulation and instrumentalization in Java (20)

1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
 
oop unit1.pptx
oop unit1.pptxoop unit1.pptx
oop unit1.pptx
 
CS8392 OOP
CS8392 OOPCS8392 OOP
CS8392 OOP
 
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
 
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...
 
Micronaut Deep Dive - Devoxx Belgium 2019
Micronaut Deep Dive - Devoxx Belgium 2019Micronaut Deep Dive - Devoxx Belgium 2019
Micronaut Deep Dive - Devoxx Belgium 2019
 
Micronaut: Evolving Java for the Microservices and Serverless Era
Micronaut: Evolving Java for the Microservices and Serverless EraMicronaut: Evolving Java for the Microservices and Serverless Era
Micronaut: Evolving Java for the Microservices and Serverless Era
 
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptxJAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
 
Typesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and PlayTypesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and Play
 
How to generate customized java 8 code from your database
How to generate customized java 8 code from your databaseHow to generate customized java 8 code from your database
How to generate customized java 8 code from your database
 
Silicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your databaseSilicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your database
 
Oracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningOracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuning
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Java Programming and J2ME: The Basics
Java Programming and J2ME: The BasicsJava Programming and J2ME: The Basics
Java Programming and J2ME: The Basics
 
Advanced Production Debugging
Advanced Production DebuggingAdvanced Production Debugging
Advanced Production Debugging
 
Object Oriented Programming-JAVA
Object Oriented Programming-JAVAObject Oriented Programming-JAVA
Object Oriented Programming-JAVA
 
06.1 .Net memory management
06.1 .Net memory management06.1 .Net memory management
06.1 .Net memory management
 
JDK Tools For Performance Diagnostics
JDK Tools For Performance DiagnosticsJDK Tools For Performance Diagnostics
JDK Tools For Performance Diagnostics
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
 
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
 

Recently uploaded

Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
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
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
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
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
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.
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
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
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
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
 
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
 
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
 

Recently uploaded (20)

Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
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
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
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
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
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...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
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
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
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
 
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...
 
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...
 

Byte code manipulation and instrumentalization in Java

  • 1. Byte code manipulation and instrumentalization in Java Alex Moskvin CEO/CTO @ Plexteq
  • 2. About myself • CEO/CTO Plexteq OÜ • Ph.D in information technology area • Interests • Software architecture • High loaded systems • Everything under the hood • AI/ML + BigData • Knowledge sharing ;) • Follow me • https://twitter.com/amoskvin • https://www.facebook.com/moskvin.aleksey
  • 3. Agenda 1. What is bytecode 2. How to manipulate byte code 3. Why would we need manipulate byte code 4. Let’s have some fun 1. Java agent 2. Expose java agent metrics via JMX 3. Use Java agent with regular Spring boot application
  • 4. Disclaimer ;) This talk is based on personal experience. Use at your own risk.
  • 5. Bytecode Java bytecode is the result of the compilation of a Java program, an intermediate representation of that program which is machine independent. The Java bytecode gets processed by the Java virtual machine (JVM) instead of the processor. It is the job of the JVM to make the necessary resource calls to the processor in order to run the bytecode.
  • 7. Bytecode “A Java programmer does not need to be aware of or understand Java bytecode at all.” - Wikipedia
  • 10. Bytecode $ javac HelloWorldA.java $ file HelloWorldA.class $ cat -v HelloWorldA.class $ hexdump HelloWorldA.class
  • 11. Bytecode $ javac HelloWorldA.java $ file HelloWorldA.class $ cat -v HelloWorldA.class $ hexdump HelloWorldA.class
  • 12. Bytecode • Magic Number: 0xCAFEBABE • Version of Class File Format: the minor and major versions of the class file • Constant Pool: Pool of constants for the class • Access Flags: for example whether the class is abstract, static, etc. • This Class: The name of the current class • Super Class: The name of the super class • Interfaces: Any interfaces in the class • Fields: Any fields in the class • Methods: Any methods in the class • Attributes: Any attributes of the class (for example the name of the sourcefile, etc.)
  • 16. Bytecode JVM thread stack Frame Operand stack Each thread of execution that stores frames that represent method invocations Each frame holds data, partial results, method return values and performs dynamic linking Each frame contains stack, known as Operand stack which holds the operand values of JVM types
  • 17. Bytecode Java bytecodes instructions fall into these major categories: • Load and store • Method invocation and return • Control transfer • Arithmetical operation • Type conversion • Object manipulation • Operand stack management
  • 18. Bytecode Call to super() System.out.println(“Hello world”); • Get System.out value out of a static field (i.e. PrintStream o = java.lang.System.in;) • Put “Hello world” to operand stack • Invoke java.io.PrintStream.println method on operant stack
  • 21. Bytecode Compiler time optimization • “new” allocates StringBuilder object on heap • “dup” duplicates the value on top of the stack • “invokevirtual” invokes constructor
  • 23. Bytecode manipulation • Bytecode is just an array of bytes • Bytecode of a class represents method declarations with instructions set • Java class loading mechanisms allow to load bytecode from everywhere • Byte code could be generated at the runtime • Byte code of application could be changed at runtime using Agents
  • 26. Bytecode manipulation :: Javaassist • How do we modify bytes using Javassist?
  • 28. Bytecode manipulation :: Javaassist • Prerequisites <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.23.0-GA</version> </dependency> • Limitations • No syntatic sugar (i.e foreach, full class names) • No generics support
  • 30. Bytecode manipulation Why would we need manipulate byte code?
  • 31. Bytecode manipulation • Program analysis: • find bugs in your application • examine code complexity • find classes with a specific annotation • Class generation: • lazy load data from a database using proxies • Security: • restrict access to certain APIs • code obfuscation • Transforming classes without the Java source code: • code profiling / instrumentalization • code optimization
  • 33. Bytecode manipulation :: Java agent • We can use a core Java feature introduced in 1.5 to manipulate the bytecode. This feature is called a Java agent.
  • 36. Bytecode manipulation :: Java agent public class JavassistAgent { public static void premain(String agentArgs, Instrumentation inst) { System.out.println("Starting the agent"); inst.addTransformer(new ImportantLogClassTransformer()); } } public class ImportantLogClassTransformer implements ClassFileTransformer { public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { // manipulate the bytes here return modified bytes; } }
  • 37. Bytecode manipulation :: Java agent manifest.mf Manifest-Version: 1.0 PreMain-Class: com.example.Agent007
  • 38. Fun Let’s have some fun! Good point to start with: https://github.com/tomsquest/java-agent-asm-javassist-sample
  • 39. Fun Specifically: 1. Let’s code a Java Agent that gathers invocations to MongoDB Java driver (insert, update, find) operations 2. Expose stats using JMX 3. Try agent with real Spring boot app
  • 40. Fun :: JMX Java Management Extensions (JMX) is a Java technology that supplies tools for managing and monitoring applications, system objects, devices (such as printers) and service-oriented networks. Covered by JSR 160 Cool and simple implementation: https://github.com/j256/simplejmx

Editor's Notes

  1. Знания - nda
  2. Объект исследования
  3. javac -verbose
  4. javac -verbose
  5. javac -verbose
  6. javac -verbose
  7. javac -verbose
  8. javac -verbose
  9. javac -verbose
  10. javac -verbose
  11. javac -verbose
  12. javac -verbose
  13. The ClassPool is a container of CtClass objects implemented as a HashMap where the key is the name of the class and the value is the CtClass object representing the class CtClass object to represent a class The default ClassPool uses the same classpath as the underlying JVM.
  14. Question to present
  15. Funny case with lost source code and production patch release using bytecode manipulation with agents
  16. Who worked with MongoDB?
  17. Who worked with MongoDB?