SlideShare a Scribd company logo
Agents are watching your
bytecode.
Roman Tsypuk
Agenda
• WebGoat
• Xrebel
• Javasist (basics, demo method timing calculation)
• How to create and pack your own JavaAgent
• Demo create Agents (agent calculates loaded classes)
• (agent shows obj size)
• (agent traces the methods call chain)
• (agent time machine)
Java agents are watching your ByteCode
Java agents are watching your ByteCode
Software Engineering Economics by Barry Boehm
Java agents are watching your ByteCode
Class
Loading
Instrumentaion
ClassFileTransformer
ClassFileTransformer
ClassFileTransformer
Javassist
CtField
CtMethod
CtConst
insertBefore
insertAfter
instrument
CtPool CtClass CtMethod
CtClass
CtClass
CtClass


import java.lang.instrument.ClassFileTransformer;

import java.lang.instrument.Instrumentation;



public class Agent {

public static premain(String args, Instrumentation instr) throws Exception {

instr.addTransformer(new ClassFileTransformer() {

///////////////////

});

}

}

META-INF/MANIFEST.MF
Premain-Class: Agent
https://docs.oracle.com/javase/8/docs/api/java/lang/instrument/package-summary.html
-javaagent:jarpath[=options]
new ClassFileTransformer() {

@Override

public byte[] transform(ClassLoader loader, 

String className, 

Class<?> classBeingRedefined, 

ProtectionDomain protectionDomain, 

byte[] classfileBuffer)

throws IllegalClassFormatException {

ClassPool cp = ClassPool.getDefault();

CtClass ct = cp.makeClass(new ByteArrayInputStream(classfileBuffer));



// ct transformation



return ct.toByteCode();



}

}
public class ClassTransformer implements ClassFileTransformer {
public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined,
ProtectionDomain protectionDomain, byte[] classfileBuffer)
throws IllegalClassFormatException {
if(className.startsWith("tt")) return null;
try {
ClassPool pool = ClassPool.getDefault();
CtClass s1 = pool.get("java.lang.System");
CtMethod m11 = s1.getDeclaredMethod("currentTimeMillis");
CtClass s2 = pool.get("tt.MySystem");
CtMethod m21 = s2.getDeclaredMethod("currentTimeMillis");
CodeConverter cc = new CodeConverter();
cc.redirectMethodCall(m11, m21);
CtClass cl = pool.makeClass(new ByteArrayInputStream(classfileBuffer), false);
if(cl.isFrozen()) return null;
CtConstructor[] constructors = cl.getConstructors();
for(CtConstructor constructor : constructors) {
constructor.instrument(cc);
}
CtMethod[] methods = cl.getDeclaredMethods();
for(CtMethod method : methods) {
method.instrument(cc);
}
classfileBuffer = cl.toBytecode();
} catch (Exception ex) {
System.out.println("Exception: " + ex);
ex.printStackTrace();
}
return classfileBuffer;
}
}
public class MySystem {
public static long currentTimeMillis() {
return 1234567890L;
}
}
public class TimeMachine {
public static void main(String[] args) {
System.out.println(System.currentTimeMillis());
}
}
public class TraceTransformer implements ClassFileTransformer {
private static StringBuilder space = new StringBuilder(" |___");
@Override
public byte[] transform(ClassLoader loader,
String className,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] classfileBuffer) {
try {
if (!className.startsWith("jav/smart")) {
return classfileBuffer;
}
ClassPool cp = ClassPool.getDefault();
CtClass ct = cp.makeClass(new ByteArrayInputStream(classfileBuffer));
CtMethod[] methods = ct.getDeclaredMethods();
for (CtMethod method : methods) {
space.insert(0, " ");
String methodBody = "{System.out.println(""+ space.toString() + className + "." + method.getName() +" ");}";
method.insertBefore(methodBody);
}
return ct.toBytecode();
} catch (Exception e) {
e.printStackTrace();
}
return classfileBuffer;
}
}
public class ClassTransformer implements ClassFileTransformer {
private static int count = 0;
@Override
public byte[] transform(ClassLoader loader,
String className,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] classfileBuffer) {
System.out.println(String.format("%d. Loading class: %s ",++count, className.replaceAll("/", ".")));
return classfileBuffer;
}
}
Questions?
USA HQ

Toll Free: 866-687-3588 

Tel: +1-512-516-8880
Ukraine HQ

Tel: +380-32-240-9090
Bulgaria 

Tel: +359-2-902-3760
Thank you!

More Related Content

PPTX
Go Concurrency Patterns
PPTX
Go Concurrency Basics
DOCX
Overriding abstract in java
DOCX
WAP to implement inheritance and overloading methods in java
PDF
Rcpp11 useR2014
PDF
R/C++ talk at earl 2014
PPTX
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
PDF
A "Do-It-Yourself" Specification Language with BeepBeep 3 (Talk @ Dagstuhl 2017)
Go Concurrency Patterns
Go Concurrency Basics
Overriding abstract in java
WAP to implement inheritance and overloading methods in java
Rcpp11 useR2014
R/C++ talk at earl 2014
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
A "Do-It-Yourself" Specification Language with BeepBeep 3 (Talk @ Dagstuhl 2017)

What's hot (20)

PDF
Rcpp11 genentech
PDF
BeepBeep 3: A declarative event stream query engine (EDOC 2015)
PPT
20100712-OTcl Command -- Getting Started
PDF
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
PPTX
Chap2 class,objects contd
PPTX
Reacting with ReactiveUI
PDF
ECMAScript 2015 Tips & Traps
KEY
Inheritance patterns
PPT
Loops (1)
PDF
scala-gopher: async implementation of CSP for scala
PPTX
Binary Studio Academy: Concurrency in C# 5.0
PDF
RxJava applied [JavaDay Kyiv 2016]
PPT
NS2 Object Construction
PDF
When RV Meets CEP (RV 2016 Tutorial)
PDF
CL metaprogramming
PDF
RxJava on Android
PDF
Activity Recognition Through Complex Event Processing: First Findings
PPTX
Concurrency in Programming Languages
PDF
Intro to RxJava/RxAndroid - GDG Munich Android
PDF
Modern c++ Memory Management
Rcpp11 genentech
BeepBeep 3: A declarative event stream query engine (EDOC 2015)
20100712-OTcl Command -- Getting Started
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
Chap2 class,objects contd
Reacting with ReactiveUI
ECMAScript 2015 Tips & Traps
Inheritance patterns
Loops (1)
scala-gopher: async implementation of CSP for scala
Binary Studio Academy: Concurrency in C# 5.0
RxJava applied [JavaDay Kyiv 2016]
NS2 Object Construction
When RV Meets CEP (RV 2016 Tutorial)
CL metaprogramming
RxJava on Android
Activity Recognition Through Complex Event Processing: First Findings
Concurrency in Programming Languages
Intro to RxJava/RxAndroid - GDG Munich Android
Modern c++ Memory Management
Ad

Similar to Java agents are watching your ByteCode (20)

PPTX
Binary patching for fun and profit @ JUG.ru, 25.02.2012
PDF
Riga Dev Day 2016 - Having fun with Javassist
PDF
33rd Degree 2013, Bad Tests, Good Tests
PPT
2012 JDays Bad Tests Good Tests
PDF
JavaOne 2015 - Having fun with Javassist
PPTX
Anti patterns
PPTX
C# 6.0 Preview
ODP
Java Generics
PPTX
NetBeans Plugin Development: JRebel Experience Report
PDF
Taming Java Agents
PDF
BarcelonaJUG2016: walkmod: how to run and design code transformations
ODP
Jersey Guice AOP
PPTX
from java to c
PPTX
Story of static code analyzer development
PDF
Online Meetup: Why should container system / platform builders care about con...
PPTX
Rx workshop
PPT
Whats new in_csharp4
PPT
Hector v2: The Second Version of the Popular High-Level Java Client for Apach...
PPTX
Making Java more dynamic: runtime code generation for the JVM
ODP
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Binary patching for fun and profit @ JUG.ru, 25.02.2012
Riga Dev Day 2016 - Having fun with Javassist
33rd Degree 2013, Bad Tests, Good Tests
2012 JDays Bad Tests Good Tests
JavaOne 2015 - Having fun with Javassist
Anti patterns
C# 6.0 Preview
Java Generics
NetBeans Plugin Development: JRebel Experience Report
Taming Java Agents
BarcelonaJUG2016: walkmod: how to run and design code transformations
Jersey Guice AOP
from java to c
Story of static code analyzer development
Online Meetup: Why should container system / platform builders care about con...
Rx workshop
Whats new in_csharp4
Hector v2: The Second Version of the Popular High-Level Java Client for Apach...
Making Java more dynamic: runtime code generation for the JVM
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Ad

More from Roman Tsypuk (7)

PPTX
Amazon Alexa: How to talk with your Smart Home devices
PPTX
Voice control with Amazon Alexa(for pacemaker conf)
PDF
Web Security training for Lohika.
PDF
Effective Java. By materials of Josch Bloch's book
PDF
IoT. GPS in our cars.
PDF
Test Driven Documentation with Spring Rest Docs JEEConf2017
PDF
Test Driven Documentation with Spring Rest Docs
Amazon Alexa: How to talk with your Smart Home devices
Voice control with Amazon Alexa(for pacemaker conf)
Web Security training for Lohika.
Effective Java. By materials of Josch Bloch's book
IoT. GPS in our cars.
Test Driven Documentation with Spring Rest Docs JEEConf2017
Test Driven Documentation with Spring Rest Docs

Recently uploaded (20)

PDF
Digital Strategies for Manufacturing Companies
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PPTX
Operating system designcfffgfgggggggvggggggggg
PPTX
history of c programming in notes for students .pptx
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
How Creative Agencies Leverage Project Management Software.pdf
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
System and Network Administraation Chapter 3
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Digital Strategies for Manufacturing Companies
2025 Textile ERP Trends: SAP, Odoo & Oracle
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Understanding Forklifts - TECH EHS Solution
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Operating system designcfffgfgggggggvggggggggg
history of c programming in notes for students .pptx
VVF-Customer-Presentation2025-Ver1.9.pptx
How Creative Agencies Leverage Project Management Software.pdf
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Design an Analysis of Algorithms I-SECS-1021-03
Softaken Excel to vCard Converter Software.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Odoo POS Development Services by CandidRoot Solutions
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
System and Network Administraation Chapter 3
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...

Java agents are watching your ByteCode

  • 1. Agents are watching your bytecode. Roman Tsypuk
  • 2. Agenda • WebGoat • Xrebel • Javasist (basics, demo method timing calculation) • How to create and pack your own JavaAgent • Demo create Agents (agent calculates loaded classes) • (agent shows obj size) • (agent traces the methods call chain) • (agent time machine)
  • 9. 
 import java.lang.instrument.ClassFileTransformer;
 import java.lang.instrument.Instrumentation;
 
 public class Agent {
 public static premain(String args, Instrumentation instr) throws Exception {
 instr.addTransformer(new ClassFileTransformer() {
 ///////////////////
 });
 }
 }
 META-INF/MANIFEST.MF Premain-Class: Agent https://docs.oracle.com/javase/8/docs/api/java/lang/instrument/package-summary.html -javaagent:jarpath[=options]
  • 10. new ClassFileTransformer() {
 @Override
 public byte[] transform(ClassLoader loader, 
 String className, 
 Class<?> classBeingRedefined, 
 ProtectionDomain protectionDomain, 
 byte[] classfileBuffer)
 throws IllegalClassFormatException {
 ClassPool cp = ClassPool.getDefault();
 CtClass ct = cp.makeClass(new ByteArrayInputStream(classfileBuffer));
 
 // ct transformation
 
 return ct.toByteCode();
 
 }
 }
  • 11. public class ClassTransformer implements ClassFileTransformer { public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { if(className.startsWith("tt")) return null; try { ClassPool pool = ClassPool.getDefault(); CtClass s1 = pool.get("java.lang.System"); CtMethod m11 = s1.getDeclaredMethod("currentTimeMillis"); CtClass s2 = pool.get("tt.MySystem"); CtMethod m21 = s2.getDeclaredMethod("currentTimeMillis"); CodeConverter cc = new CodeConverter(); cc.redirectMethodCall(m11, m21); CtClass cl = pool.makeClass(new ByteArrayInputStream(classfileBuffer), false); if(cl.isFrozen()) return null; CtConstructor[] constructors = cl.getConstructors(); for(CtConstructor constructor : constructors) { constructor.instrument(cc); } CtMethod[] methods = cl.getDeclaredMethods(); for(CtMethod method : methods) { method.instrument(cc); } classfileBuffer = cl.toBytecode(); } catch (Exception ex) { System.out.println("Exception: " + ex); ex.printStackTrace(); } return classfileBuffer; } } public class MySystem { public static long currentTimeMillis() { return 1234567890L; } } public class TimeMachine { public static void main(String[] args) { System.out.println(System.currentTimeMillis()); } }
  • 12. public class TraceTransformer implements ClassFileTransformer { private static StringBuilder space = new StringBuilder(" |___"); @Override public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) { try { if (!className.startsWith("jav/smart")) { return classfileBuffer; } ClassPool cp = ClassPool.getDefault(); CtClass ct = cp.makeClass(new ByteArrayInputStream(classfileBuffer)); CtMethod[] methods = ct.getDeclaredMethods(); for (CtMethod method : methods) { space.insert(0, " "); String methodBody = "{System.out.println(""+ space.toString() + className + "." + method.getName() +" ");}"; method.insertBefore(methodBody); } return ct.toBytecode(); } catch (Exception e) { e.printStackTrace(); } return classfileBuffer; } }
  • 13. public class ClassTransformer implements ClassFileTransformer { private static int count = 0; @Override public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) { System.out.println(String.format("%d. Loading class: %s ",++count, className.replaceAll("/", "."))); return classfileBuffer; } }
  • 15. USA HQ
 Toll Free: 866-687-3588 
 Tel: +1-512-516-8880 Ukraine HQ
 Tel: +380-32-240-9090 Bulgaria 
 Tel: +359-2-902-3760 Thank you!