SlideShare a Scribd company logo
JDK Power Tools
an overview of fun and useful tools
the JDK already provides you with
Tobias Lindaaker
Software Developer @ Neo Technology
twitter:! @thobe / @neo4j / #neo4j
email:! tobias@neotechnology.com
web:! http://neo4j.org/
web:! http://thobe.org/
The Tools
๏java.lang.instrument
๏Java agents
๏Java Debugging Interface
๏JVMTI heap introspection
๏JVMTI frame introspection
2
java.lang.instrument
3
java.lang.instrument.Instrumentation
๏The “missing” sizeof() operation:
•long getObjectSize( Object )
๏Inspecting loaded classes:
•Class[] getAllLoadedClasses()
•Class[] getInitiatedClasses( ClassLoader )
๏Transforming classes:
•redefineClasses( ClassDefinition(Class, byte[])... )
•addTransformer( ClassFileTransformer )
‣byte[] transform( ClassLoader, name, Class, byte[] )
•retransformClasses(Class...)
•setNativeMethodPrefix( ClassFileTransformer, String ) 4
public static void premain(
String agentArgs, Instrumentation inst)
5
๏java ... -javaagent:<jarfile>[=options]
๏Instrumentation parameter is optional in the signature
๏META-INF/MANIFEST.MF:
•Premain-Class [required; qualified classname of premain class]
•Boot-Class-Path [optional; class path]
•Can-Redefine-Classes [optional; true/false - request capability]
•Can-Retransform-Classes [optional; true/false - request capability]
•Can-Set-Native-Method-Prefix [optional; true/false - request capability]
Java agents
6
public static void agentmain(
String agentArgs, Instrumentation inst)
7
๏Executed when the agent attaches to an already running JVM
๏Instrumentation parameter is optional in the signature
๏META-INF/MANIFEST.MF:
•Agentmain-Class
+the same optional parameters as for premain():
+Boot-Class-Path
+Can-Redefine-Classes
+Can-Retransform-Classes
+Can-Set-Native-Method-Prefix
๏Requires support for loading agents in the JVM
๏Allows to add code to the JVM after-the-fact
The Use Case: add code live
๏Provide statically accessible entry point into your app
๏From here extend the app with the code loaded by the agent
๏Used by the JDK, when attaching with jconsole through PID
8
com.sun.tools.attach
๏com.sun.tools.attach.VirtualMachine
•Represents a JVM process
•static methods providing entry points for:
‣attaching to a JVM by process id
‣listing all running JVM processes (like jps)
๏Example (from the docs, simplified from jconsole source code):
// attach to target VM
VirtualMachine vm = VirtualMachine.attach( "1337" );
// get system properties in target VM
Properties props = vm.getSystemProperties();
// construct path to management agent
String agent = props.getProperty( "java.home" )
+ File.separator + "lib"
+ File.separator + "management-agent.jar";
// load agent into target VM, spcifying parameters for the agent
vm.loadAgent( agent, "com.sun.management.jmxremote.port=5000" );
// done - detach
vm.detach(); 9
Tricks: Registry-less RMI
๏RMI Registry just provides serialized objects specifying:
•Implemented Remote interfaces
•How to reach the actual object (host+port+id)
๏You can serialize the object yourself and pass it as the string
parameter to an agent
๏Now your agent has a talkback channel to the process that
spawned it
10
code.sample();
11
http://github.com/thobe/java-agent
Java Debugging Interface
12
Building an interactive
debugger is HARD, but
that isn’t the only thing
you can do with the JDI.
A Scriptable debugger is
much easier to build.
SubprocessTestRunner
13
๏Runs a JUnit test case in a sub process
๏Host process connects to the sub process with JDI
๏Define breakpoints for the code under test
๏Useful for triggering certain ordering between threads
•Triggering race conditions
๏Used at Neo Technology for Concurrency Regression Tests
•Prefer refactoring to allow testing concurrency,
but that isn’t always the appropriate short term solution
Simple example
@RunWith(SubprocessTestRunner.class)
public class SampleTest {
@Debugger.Using(BreakPoints.class)
@Test public void shouldHandleRaceCondition() {
new Sample().entryPoint();
}
static class BreakPoints extends Debugger {
List<Integer> loopVariables = new ArrayList<Integer>();
{ enable( "handle_someMethod" ); }
@Handler(on=ENTRY,type=Sample.class,method="someMethod")
void handle_someMethod() {
enable( "handle_loopBody" );
}
@Handler(on=ENTRY,type=Sample.class,method="loopBody")
void handle_loopBody(){
loopVariables.add( frame( 1 ).getInt( "i" ) );
}
@Override protected void finish() {
assertEquals( asList( 1, 2, 3, 4 ), loopVariables );
}
}
} 14
Simple example
@RunWith(SubprocessTestRunner.class)
public class SampleTest {
@Debugger.Using(BreakPoints.class)
@Test public void shouldHandleRaceCondition() {
new Sample().entryPoint();
}
static class BreakPoints extends Debugger {
List<Integer> loopVariables = new ArrayList<Integer>();
{ enable( "handle_someMethod" ); }
@Handler(on=ENTRY,type=Sample.class,method="someMethod")
void handle_someMethod() {
enable( "handle_loopBody" );
}
@Handler(on=ENTRY,type=Sample.class,method="loopBody")
void handle_loopBody(){
loopVariables.add( frame( 1 ).getInt( "i" ) );
}
@Override protected void finish() {
assertEquals( asList( 1, 2, 3, 4 ), loopVariables );
}
}
} 14
public class Sample {
public void entryPoint() {
for ( int i = 0; i < 5; i++ ) {
loopBody();
someMethod();
}
}
private void someMethod() { /* do nothing */ }
private void loopBody() { /* do nothing */ }
}
Simple example
@RunWith(SubprocessTestRunner.class)
public class SampleTest {
@Debugger.Using(BreakPoints.class)
@Test public void shouldHandleRaceCondition() {
new Sample().entryPoint();
}
static class BreakPoints extends Debugger {
List<Integer> loopVariables = new ArrayList<Integer>();
{ enable( "handle_someMethod" ); }
@Handler(on=ENTRY,type=Sample.class,method="someMethod")
void handle_someMethod() {
enable( "handle_loopBody" );
}
@Handler(on=ENTRY,type=Sample.class,method="loopBody")
void handle_loopBody(){
loopVariables.add( frame( 1 ).getInt( "i" ) );
}
@Override protected void finish() {
assertEquals( asList( 1, 2, 3, 4 ), loopVariables );
}
}
} 14
{ enable( "handle_someMethod" ); }
Simple example
@RunWith(SubprocessTestRunner.class)
public class SampleTest {
@Debugger.Using(BreakPoints.class)
@Test public void shouldHandleRaceCondition() {
new Sample().entryPoint();
}
static class BreakPoints extends Debugger {
List<Integer> loopVariables = new ArrayList<Integer>();
{ enable( "handle_someMethod" ); }
@Handler(on=ENTRY,type=Sample.class,method="someMethod")
void handle_someMethod() {
enable( "handle_loopBody" );
}
@Handler(on=ENTRY,type=Sample.class,method="loopBody")
void handle_loopBody(){
loopVariables.add( frame( 1 ).getInt( "i" ) );
}
@Override protected void finish() {
assertEquals( asList( 1, 2, 3, 4 ), loopVariables );
}
}
} 14
@Handler(on=ENTRY,type=Sample.class,method="someMethod")
void handle_someMethod() {
enable( "handle_loopBody" );
}
Simple example
@RunWith(SubprocessTestRunner.class)
public class SampleTest {
@Debugger.Using(BreakPoints.class)
@Test public void shouldHandleRaceCondition() {
new Sample().entryPoint();
}
static class BreakPoints extends Debugger {
List<Integer> loopVariables = new ArrayList<Integer>();
{ enable( "handle_someMethod" ); }
@Handler(on=ENTRY,type=Sample.class,method="someMethod")
void handle_someMethod() {
enable( "handle_loopBody" );
}
@Handler(on=ENTRY,type=Sample.class,method="loopBody")
void handle_loopBody(){
loopVariables.add( frame( 1 ).getInt( "i" ) );
}
@Override protected void finish() {
assertEquals( asList( 1, 2, 3, 4 ), loopVariables );
}
}
} 14
@Handler(on=ENTRY,type=Sample.class,method="loopBody")
void handle_loopBody(){
loopVariables.add( frame( 1 ).getInt( "i" ) );
}
Simple example
@RunWith(SubprocessTestRunner.class)
public class SampleTest {
@Debugger.Using(BreakPoints.class)
@Test public void shouldHandleRaceCondition() {
new Sample().entryPoint();
}
static class BreakPoints extends Debugger {
List<Integer> loopVariables = new ArrayList<Integer>();
{ enable( "handle_someMethod" ); }
@Handler(on=ENTRY,type=Sample.class,method="someMethod")
void handle_someMethod() {
enable( "handle_loopBody" );
}
@Handler(on=ENTRY,type=Sample.class,method="loopBody")
void handle_loopBody(){
loopVariables.add( frame( 1 ).getInt( "i" ) );
}
@Override protected void finish() {
assertEquals( asList( 1, 2, 3, 4 ), loopVariables );
}
}
} 14
@Override protected void finish() {
assertEquals( asList( 1, 2, 3, 4 ), loopVariables );
}
Simple example
@RunWith(SubprocessTestRunner.class)
public class SampleTest {
@Debugger.Using(BreakPoints.class)
@Test public void shouldHandleRaceCondition() {
new Sample().entryPoint();
}
static class BreakPoints extends Debugger {
List<Integer> loopVariables = new ArrayList<Integer>();
{ enable( "handle_someMethod" ); }
@Handler(on=ENTRY,type=Sample.class,method="someMethod")
void handle_someMethod() {
enable( "handle_loopBody" );
}
@Handler(on=ENTRY,type=Sample.class,method="loopBody")
void handle_loopBody(){
loopVariables.add( frame( 1 ).getInt( "i" ) );
}
@Override protected void finish() {
assertEquals( asList( 1, 2, 3, 4 ), loopVariables );
}
}
} 14
code.samples();
15
https://github.com/thobe/subprocess-testing
JVMTI frame introspection
16
Frame introspection
๏Native interface (JVMTI)
๏Abilities:
•Get method and instruction offset for each element on stack
•Force early return from method
•Pop frame and re-run method
•Get local variable from call stack
•Get notification when frame is popped (method is exited)
(Forcing a frame to be popped does not trigger the event)
17
Dynamic access to local variables
public @Test void sampleOfAccessingLiveCallFrame() {
int anInt = 4; // random number - by dice
String aString = "some string value";
18
Dynamic access to local variables
public @Test void sampleOfAccessingLiveCallFrame() {
int anInt = 4; // random number - by dice
String aString = "some string value";
// get the tool
ToolingInterface tools =
ToolingInterface.getToolingInterface();
18
Dynamic access to local variables
public @Test void sampleOfAccessingLiveCallFrame() {
int anInt = 4; // random number - by dice
String aString = "some string value";
// get the tool
ToolingInterface tools =
ToolingInterface.getToolingInterface();
// get the frame
CallFrame myFrame = tools.getCallFrame( 0 );
18
Dynamic access to local variables
public @Test void sampleOfAccessingLiveCallFrame() {
int anInt = 4; // random number - by dice
String aString = "some string value";
// get the tool
ToolingInterface tools =
ToolingInterface.getToolingInterface();
// get the frame
CallFrame myFrame = tools.getCallFrame( 0 );
// get local
assertEquals( anInt, frame.getLocal( "anInt" ) );
18
Dynamic access to local variables
public @Test void sampleOfAccessingLiveCallFrame() {
int anInt = 4; // random number - by dice
String aString = "some string value";
// get the tool
ToolingInterface tools =
ToolingInterface.getToolingInterface();
// get the frame
CallFrame myFrame = tools.getCallFrame( 0 );
// get local
assertEquals( anInt, frame.getLocal( "anInt" ) );
// update local
anInt = 17; // most random number - proven!
assertEquals( anInt, frame.getLocal( "anInt" ) );
18
Dynamic access to local variables
public @Test void sampleOfAccessingLiveCallFrame() {
int anInt = 4; // random number - by dice
String aString = "some string value";
// get the tool
ToolingInterface tools =
ToolingInterface.getToolingInterface();
// get the frame
CallFrame myFrame = tools.getCallFrame( 0 );
// get local
assertEquals( anInt, frame.getLocal( "anInt" ) );
// update local
anInt = 17; // most random number - proven!
assertEquals( anInt, frame.getLocal( "anInt" ) );
// fancy get
assertSame( aString
((CallFrame)myFrame.getLocal( "myFrame" ))
.getLocal( "aString" ) );
18
Dynamic access to local variables
public @Test void sampleOfAccessingLiveCallFrame() {
int anInt = 4; // random number - by dice
String aString = "some string value";
// get the tool
ToolingInterface tools =
ToolingInterface.getToolingInterface();
// get the frame
CallFrame myFrame = tools.getCallFrame( 0 );
// get local
assertEquals( anInt, frame.getLocal( "anInt" ) );
// update local
anInt = 17; // most random number - proven!
assertEquals( anInt, frame.getLocal( "anInt" ) );
// fancy get
assertSame( aString
((CallFrame)myFrame.getLocal( "myFrame" ))
.getLocal( "aString" ) );
// convenient this
assertSame( this, frame.getThis() );
}
18
code.samples();
19
http://github.com/thobe/java-tooling
JVMTI heap introspection
20
Heap introspection
๏Native interface (JVMTI)
๏Abilities:
•Following references
•Tagging objects and classes
•Getting tagged objects
•Transitive reachability traversal
•Iterating through all reachable objects
•Iterating through all objects (reachable and not)
•Iterating through all instances of a class
•Getting object size
•Getting object monitor usage 21
code.sample();
22
http://github.com/thobe/java-tooling
Putting it all together:
Live introspection
23
code.demo();
24
http://github.com/thobe/introscript
Finding out more
25
Web resources
26
๏Java Debug Interface (JDI):
http://docs.oracle.com/javase/7/docs/jdk/api/jpda/jdi/
๏JVM Tooling Interface:
http://docs.oracle.com/javase/7/docs/platform/jvmti/jvmti.html
๏JNI - JVMTI is an “extension” of JNI:
http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/jniTOC.html
๏Overview of JDK tools:
http://docs.oracle.com/javase/7/docs/technotes/tools/index.html
๏JVM Attach API:
http://docs.oracle.com/javase/7/docs/jdk/api/attach/spec/
Code samples
๏http://github.com/thobe/java-tooling, contains:
•Library for building tools in java
‣Soon: cross compiled native binaries for Mac OS X,Windows, Linux
•Code examples showing how to use these tools
๏https://github.com/thobe/subprocess-testing, contains:
•JDI-based JUnit TestRunner
๏http://github.com/thobe/java-agent, contains:
•Java agent code injection
๏http://github.com/thobe/introscript, contains:
•javax.script.ScriptEngine that attaches to other process
and introspects it with above tools
27
http://neotechnology.com

More Related Content

What's hot

The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agents
Rafael Winterhalter
 
Server1
Server1Server1
Server1
FahriIrawan3
 
How to build an AOP framework in ActionScript
How to build an AOP framework in ActionScriptHow to build an AOP framework in ActionScript
How to build an AOP framework in ActionScriptChristophe Herreman
 
Unit testing concurrent code
Unit testing concurrent codeUnit testing concurrent code
Unit testing concurrent code
Rafael Winterhalter
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
Rafael Winterhalter
 
The zen of async: Best practices for best performance
The zen of async: Best practices for best performanceThe zen of async: Best practices for best performance
The zen of async: Best practices for best performance
Microsoft Developer Network (MSDN) - Belgium and Luxembourg
 
Live Updating Swift Code
Live Updating Swift CodeLive Updating Swift Code
Live Updating Swift Code
Bartosz Polaczyk
 
Enterprise js pratices
Enterprise js praticesEnterprise js pratices
Enterprise js pratices
Marjan Nikolovski
 
Java 10, Java 11 and beyond
Java 10, Java 11 and beyondJava 10, Java 11 and beyond
Java 10, Java 11 and beyond
Rafael Winterhalter
 
Building a java tracer
Building a java tracerBuilding a java tracer
Building a java tracerrahulrevo
 
Object Oriented Exploitation: New techniques in Windows mitigation bypass
Object Oriented Exploitation: New techniques in Windows mitigation bypassObject Oriented Exploitation: New techniques in Windows mitigation bypass
Object Oriented Exploitation: New techniques in Windows mitigation bypass
Sam Thomas
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
Iram Ramrajkar
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
Iram Ramrajkar
 
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
epamspb
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
Ankit Rastogi
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - Praticals
Fahad Shaikh
 
Java Bytecode For Discriminating Developers - GeeCON 2011
Java Bytecode For Discriminating Developers - GeeCON 2011Java Bytecode For Discriminating Developers - GeeCON 2011
Java Bytecode For Discriminating Developers - GeeCON 2011Anton Arhipov
 
Byte code field report
Byte code field reportByte code field report
Byte code field report
Rafael Winterhalter
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with Javassist
Anton Arhipov
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 

What's hot (20)

The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agents
 
Server1
Server1Server1
Server1
 
How to build an AOP framework in ActionScript
How to build an AOP framework in ActionScriptHow to build an AOP framework in ActionScript
How to build an AOP framework in ActionScript
 
Unit testing concurrent code
Unit testing concurrent codeUnit testing concurrent code
Unit testing concurrent code
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
The zen of async: Best practices for best performance
The zen of async: Best practices for best performanceThe zen of async: Best practices for best performance
The zen of async: Best practices for best performance
 
Live Updating Swift Code
Live Updating Swift CodeLive Updating Swift Code
Live Updating Swift Code
 
Enterprise js pratices
Enterprise js praticesEnterprise js pratices
Enterprise js pratices
 
Java 10, Java 11 and beyond
Java 10, Java 11 and beyondJava 10, Java 11 and beyond
Java 10, Java 11 and beyond
 
Building a java tracer
Building a java tracerBuilding a java tracer
Building a java tracer
 
Object Oriented Exploitation: New techniques in Windows mitigation bypass
Object Oriented Exploitation: New techniques in Windows mitigation bypassObject Oriented Exploitation: New techniques in Windows mitigation bypass
Object Oriented Exploitation: New techniques in Windows mitigation bypass
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - Praticals
 
Java Bytecode For Discriminating Developers - GeeCON 2011
Java Bytecode For Discriminating Developers - GeeCON 2011Java Bytecode For Discriminating Developers - GeeCON 2011
Java Bytecode For Discriminating Developers - GeeCON 2011
 
Byte code field report
Byte code field reportByte code field report
Byte code field report
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with Javassist
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 

Viewers also liked

Exploiting Concurrency with Dynamic Languages
Exploiting Concurrency with Dynamic LanguagesExploiting Concurrency with Dynamic Languages
Exploiting Concurrency with Dynamic Languages
Tobias Lindaaker
 
A Better Python for the JVM
A Better Python for the JVMA Better Python for the JVM
A Better Python for the JVM
Tobias Lindaaker
 
[JavaOne 2011] Models for Concurrent Programming
[JavaOne 2011] Models for Concurrent Programming[JavaOne 2011] Models for Concurrent Programming
[JavaOne 2011] Models for Concurrent ProgrammingTobias Lindaaker
 
A Better Python for the JVM
A Better Python for the JVMA Better Python for the JVM
A Better Python for the JVM
Tobias Lindaaker
 
Choosing the right NOSQL database
Choosing the right NOSQL databaseChoosing the right NOSQL database
Choosing the right NOSQL database
Tobias Lindaaker
 
Persistent graphs in Python with Neo4j
Persistent graphs in Python with Neo4jPersistent graphs in Python with Neo4j
Persistent graphs in Python with Neo4j
Tobias Lindaaker
 
Building Applications with a Graph Database
Building Applications with a Graph DatabaseBuilding Applications with a Graph Database
Building Applications with a Graph Database
Tobias Lindaaker
 
NOSQL Overview
NOSQL OverviewNOSQL Overview
NOSQL Overview
Tobias Lindaaker
 
The Graph Traversal Programming Pattern
The Graph Traversal Programming PatternThe Graph Traversal Programming Pattern
The Graph Traversal Programming Pattern
Marko Rodriguez
 
An overview of Neo4j Internals
An overview of Neo4j InternalsAn overview of Neo4j Internals
An overview of Neo4j InternalsTobias Lindaaker
 
Mixing Python and Java
Mixing Python and JavaMixing Python and Java
Mixing Python and Java
Andreas Schreiber
 
Introduction to NoSQL Databases
Introduction to NoSQL DatabasesIntroduction to NoSQL Databases
Introduction to NoSQL DatabasesDerek Stainer
 

Viewers also liked (12)

Exploiting Concurrency with Dynamic Languages
Exploiting Concurrency with Dynamic LanguagesExploiting Concurrency with Dynamic Languages
Exploiting Concurrency with Dynamic Languages
 
A Better Python for the JVM
A Better Python for the JVMA Better Python for the JVM
A Better Python for the JVM
 
[JavaOne 2011] Models for Concurrent Programming
[JavaOne 2011] Models for Concurrent Programming[JavaOne 2011] Models for Concurrent Programming
[JavaOne 2011] Models for Concurrent Programming
 
A Better Python for the JVM
A Better Python for the JVMA Better Python for the JVM
A Better Python for the JVM
 
Choosing the right NOSQL database
Choosing the right NOSQL databaseChoosing the right NOSQL database
Choosing the right NOSQL database
 
Persistent graphs in Python with Neo4j
Persistent graphs in Python with Neo4jPersistent graphs in Python with Neo4j
Persistent graphs in Python with Neo4j
 
Building Applications with a Graph Database
Building Applications with a Graph DatabaseBuilding Applications with a Graph Database
Building Applications with a Graph Database
 
NOSQL Overview
NOSQL OverviewNOSQL Overview
NOSQL Overview
 
The Graph Traversal Programming Pattern
The Graph Traversal Programming PatternThe Graph Traversal Programming Pattern
The Graph Traversal Programming Pattern
 
An overview of Neo4j Internals
An overview of Neo4j InternalsAn overview of Neo4j Internals
An overview of Neo4j Internals
 
Mixing Python and Java
Mixing Python and JavaMixing Python and Java
Mixing Python and Java
 
Introduction to NoSQL Databases
Introduction to NoSQL DatabasesIntroduction to NoSQL Databases
Introduction to NoSQL Databases
 

Similar to JDK Power Tools

meet.js - QooXDoo
meet.js - QooXDoomeet.js - QooXDoo
meet.js - QooXDoo
Radek Benkel
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Jiayun Zhou
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
Doug Hawkins
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
Android Automated Testing
Android Automated TestingAndroid Automated Testing
Android Automated Testing
roisagiv
 
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24  tricky stuff in java grammar and javacJug trojmiasto 2014.04.24  tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
Anna Brzezińska
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
Ian Robertson
 
JUnit 5
JUnit 5JUnit 5
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
Thierry Wasylczenko
 
Nantes Jug - Java 7
Nantes Jug - Java 7Nantes Jug - Java 7
Nantes Jug - Java 7
Sébastien Prunier
 
10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems10 Typical Enterprise Java Problems
10 Typical Enterprise Java ProblemsEberhard Wolff
 
Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrity
Washington Botelho
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
Azul Systems, Inc.
 
Java tutorial PPT
Java tutorial  PPTJava tutorial  PPT
Java tutorial PPT
Intelligo Technologies
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
Intelligo Technologies
 
Java tut1
Java tut1Java tut1
Java tut1
Ajmal Khan
 

Similar to JDK Power Tools (20)

meet.js - QooXDoo
meet.js - QooXDoomeet.js - QooXDoo
meet.js - QooXDoo
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Android Automated Testing
Android Automated TestingAndroid Automated Testing
Android Automated Testing
 
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24  tricky stuff in java grammar and javacJug trojmiasto 2014.04.24  tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
Nantes Jug - Java 7
Nantes Jug - Java 7Nantes Jug - Java 7
Nantes Jug - Java 7
 
10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems
 
Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrity
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Java tutorial PPT
Java tutorial  PPTJava tutorial  PPT
Java tutorial PPT
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Java tut1
Java tut1Java tut1
Java tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 

Recently uploaded

Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 

Recently uploaded (20)

Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 

JDK Power Tools

  • 1. JDK Power Tools an overview of fun and useful tools the JDK already provides you with Tobias Lindaaker Software Developer @ Neo Technology twitter:! @thobe / @neo4j / #neo4j email:! tobias@neotechnology.com web:! http://neo4j.org/ web:! http://thobe.org/
  • 2. The Tools ๏java.lang.instrument ๏Java agents ๏Java Debugging Interface ๏JVMTI heap introspection ๏JVMTI frame introspection 2
  • 4. java.lang.instrument.Instrumentation ๏The “missing” sizeof() operation: •long getObjectSize( Object ) ๏Inspecting loaded classes: •Class[] getAllLoadedClasses() •Class[] getInitiatedClasses( ClassLoader ) ๏Transforming classes: •redefineClasses( ClassDefinition(Class, byte[])... ) •addTransformer( ClassFileTransformer ) ‣byte[] transform( ClassLoader, name, Class, byte[] ) •retransformClasses(Class...) •setNativeMethodPrefix( ClassFileTransformer, String ) 4
  • 5. public static void premain( String agentArgs, Instrumentation inst) 5 ๏java ... -javaagent:<jarfile>[=options] ๏Instrumentation parameter is optional in the signature ๏META-INF/MANIFEST.MF: •Premain-Class [required; qualified classname of premain class] •Boot-Class-Path [optional; class path] •Can-Redefine-Classes [optional; true/false - request capability] •Can-Retransform-Classes [optional; true/false - request capability] •Can-Set-Native-Method-Prefix [optional; true/false - request capability]
  • 7. public static void agentmain( String agentArgs, Instrumentation inst) 7 ๏Executed when the agent attaches to an already running JVM ๏Instrumentation parameter is optional in the signature ๏META-INF/MANIFEST.MF: •Agentmain-Class +the same optional parameters as for premain(): +Boot-Class-Path +Can-Redefine-Classes +Can-Retransform-Classes +Can-Set-Native-Method-Prefix ๏Requires support for loading agents in the JVM ๏Allows to add code to the JVM after-the-fact
  • 8. The Use Case: add code live ๏Provide statically accessible entry point into your app ๏From here extend the app with the code loaded by the agent ๏Used by the JDK, when attaching with jconsole through PID 8
  • 9. com.sun.tools.attach ๏com.sun.tools.attach.VirtualMachine •Represents a JVM process •static methods providing entry points for: ‣attaching to a JVM by process id ‣listing all running JVM processes (like jps) ๏Example (from the docs, simplified from jconsole source code): // attach to target VM VirtualMachine vm = VirtualMachine.attach( "1337" ); // get system properties in target VM Properties props = vm.getSystemProperties(); // construct path to management agent String agent = props.getProperty( "java.home" ) + File.separator + "lib" + File.separator + "management-agent.jar"; // load agent into target VM, spcifying parameters for the agent vm.loadAgent( agent, "com.sun.management.jmxremote.port=5000" ); // done - detach vm.detach(); 9
  • 10. Tricks: Registry-less RMI ๏RMI Registry just provides serialized objects specifying: •Implemented Remote interfaces •How to reach the actual object (host+port+id) ๏You can serialize the object yourself and pass it as the string parameter to an agent ๏Now your agent has a talkback channel to the process that spawned it 10
  • 12. Java Debugging Interface 12 Building an interactive debugger is HARD, but that isn’t the only thing you can do with the JDI. A Scriptable debugger is much easier to build.
  • 13. SubprocessTestRunner 13 ๏Runs a JUnit test case in a sub process ๏Host process connects to the sub process with JDI ๏Define breakpoints for the code under test ๏Useful for triggering certain ordering between threads •Triggering race conditions ๏Used at Neo Technology for Concurrency Regression Tests •Prefer refactoring to allow testing concurrency, but that isn’t always the appropriate short term solution
  • 14. Simple example @RunWith(SubprocessTestRunner.class) public class SampleTest { @Debugger.Using(BreakPoints.class) @Test public void shouldHandleRaceCondition() { new Sample().entryPoint(); } static class BreakPoints extends Debugger { List<Integer> loopVariables = new ArrayList<Integer>(); { enable( "handle_someMethod" ); } @Handler(on=ENTRY,type=Sample.class,method="someMethod") void handle_someMethod() { enable( "handle_loopBody" ); } @Handler(on=ENTRY,type=Sample.class,method="loopBody") void handle_loopBody(){ loopVariables.add( frame( 1 ).getInt( "i" ) ); } @Override protected void finish() { assertEquals( asList( 1, 2, 3, 4 ), loopVariables ); } } } 14
  • 15. Simple example @RunWith(SubprocessTestRunner.class) public class SampleTest { @Debugger.Using(BreakPoints.class) @Test public void shouldHandleRaceCondition() { new Sample().entryPoint(); } static class BreakPoints extends Debugger { List<Integer> loopVariables = new ArrayList<Integer>(); { enable( "handle_someMethod" ); } @Handler(on=ENTRY,type=Sample.class,method="someMethod") void handle_someMethod() { enable( "handle_loopBody" ); } @Handler(on=ENTRY,type=Sample.class,method="loopBody") void handle_loopBody(){ loopVariables.add( frame( 1 ).getInt( "i" ) ); } @Override protected void finish() { assertEquals( asList( 1, 2, 3, 4 ), loopVariables ); } } } 14 public class Sample { public void entryPoint() { for ( int i = 0; i < 5; i++ ) { loopBody(); someMethod(); } } private void someMethod() { /* do nothing */ } private void loopBody() { /* do nothing */ } }
  • 16. Simple example @RunWith(SubprocessTestRunner.class) public class SampleTest { @Debugger.Using(BreakPoints.class) @Test public void shouldHandleRaceCondition() { new Sample().entryPoint(); } static class BreakPoints extends Debugger { List<Integer> loopVariables = new ArrayList<Integer>(); { enable( "handle_someMethod" ); } @Handler(on=ENTRY,type=Sample.class,method="someMethod") void handle_someMethod() { enable( "handle_loopBody" ); } @Handler(on=ENTRY,type=Sample.class,method="loopBody") void handle_loopBody(){ loopVariables.add( frame( 1 ).getInt( "i" ) ); } @Override protected void finish() { assertEquals( asList( 1, 2, 3, 4 ), loopVariables ); } } } 14 { enable( "handle_someMethod" ); }
  • 17. Simple example @RunWith(SubprocessTestRunner.class) public class SampleTest { @Debugger.Using(BreakPoints.class) @Test public void shouldHandleRaceCondition() { new Sample().entryPoint(); } static class BreakPoints extends Debugger { List<Integer> loopVariables = new ArrayList<Integer>(); { enable( "handle_someMethod" ); } @Handler(on=ENTRY,type=Sample.class,method="someMethod") void handle_someMethod() { enable( "handle_loopBody" ); } @Handler(on=ENTRY,type=Sample.class,method="loopBody") void handle_loopBody(){ loopVariables.add( frame( 1 ).getInt( "i" ) ); } @Override protected void finish() { assertEquals( asList( 1, 2, 3, 4 ), loopVariables ); } } } 14 @Handler(on=ENTRY,type=Sample.class,method="someMethod") void handle_someMethod() { enable( "handle_loopBody" ); }
  • 18. Simple example @RunWith(SubprocessTestRunner.class) public class SampleTest { @Debugger.Using(BreakPoints.class) @Test public void shouldHandleRaceCondition() { new Sample().entryPoint(); } static class BreakPoints extends Debugger { List<Integer> loopVariables = new ArrayList<Integer>(); { enable( "handle_someMethod" ); } @Handler(on=ENTRY,type=Sample.class,method="someMethod") void handle_someMethod() { enable( "handle_loopBody" ); } @Handler(on=ENTRY,type=Sample.class,method="loopBody") void handle_loopBody(){ loopVariables.add( frame( 1 ).getInt( "i" ) ); } @Override protected void finish() { assertEquals( asList( 1, 2, 3, 4 ), loopVariables ); } } } 14 @Handler(on=ENTRY,type=Sample.class,method="loopBody") void handle_loopBody(){ loopVariables.add( frame( 1 ).getInt( "i" ) ); }
  • 19. Simple example @RunWith(SubprocessTestRunner.class) public class SampleTest { @Debugger.Using(BreakPoints.class) @Test public void shouldHandleRaceCondition() { new Sample().entryPoint(); } static class BreakPoints extends Debugger { List<Integer> loopVariables = new ArrayList<Integer>(); { enable( "handle_someMethod" ); } @Handler(on=ENTRY,type=Sample.class,method="someMethod") void handle_someMethod() { enable( "handle_loopBody" ); } @Handler(on=ENTRY,type=Sample.class,method="loopBody") void handle_loopBody(){ loopVariables.add( frame( 1 ).getInt( "i" ) ); } @Override protected void finish() { assertEquals( asList( 1, 2, 3, 4 ), loopVariables ); } } } 14 @Override protected void finish() { assertEquals( asList( 1, 2, 3, 4 ), loopVariables ); }
  • 20. Simple example @RunWith(SubprocessTestRunner.class) public class SampleTest { @Debugger.Using(BreakPoints.class) @Test public void shouldHandleRaceCondition() { new Sample().entryPoint(); } static class BreakPoints extends Debugger { List<Integer> loopVariables = new ArrayList<Integer>(); { enable( "handle_someMethod" ); } @Handler(on=ENTRY,type=Sample.class,method="someMethod") void handle_someMethod() { enable( "handle_loopBody" ); } @Handler(on=ENTRY,type=Sample.class,method="loopBody") void handle_loopBody(){ loopVariables.add( frame( 1 ).getInt( "i" ) ); } @Override protected void finish() { assertEquals( asList( 1, 2, 3, 4 ), loopVariables ); } } } 14
  • 23. Frame introspection ๏Native interface (JVMTI) ๏Abilities: •Get method and instruction offset for each element on stack •Force early return from method •Pop frame and re-run method •Get local variable from call stack •Get notification when frame is popped (method is exited) (Forcing a frame to be popped does not trigger the event) 17
  • 24. Dynamic access to local variables public @Test void sampleOfAccessingLiveCallFrame() { int anInt = 4; // random number - by dice String aString = "some string value"; 18
  • 25. Dynamic access to local variables public @Test void sampleOfAccessingLiveCallFrame() { int anInt = 4; // random number - by dice String aString = "some string value"; // get the tool ToolingInterface tools = ToolingInterface.getToolingInterface(); 18
  • 26. Dynamic access to local variables public @Test void sampleOfAccessingLiveCallFrame() { int anInt = 4; // random number - by dice String aString = "some string value"; // get the tool ToolingInterface tools = ToolingInterface.getToolingInterface(); // get the frame CallFrame myFrame = tools.getCallFrame( 0 ); 18
  • 27. Dynamic access to local variables public @Test void sampleOfAccessingLiveCallFrame() { int anInt = 4; // random number - by dice String aString = "some string value"; // get the tool ToolingInterface tools = ToolingInterface.getToolingInterface(); // get the frame CallFrame myFrame = tools.getCallFrame( 0 ); // get local assertEquals( anInt, frame.getLocal( "anInt" ) ); 18
  • 28. Dynamic access to local variables public @Test void sampleOfAccessingLiveCallFrame() { int anInt = 4; // random number - by dice String aString = "some string value"; // get the tool ToolingInterface tools = ToolingInterface.getToolingInterface(); // get the frame CallFrame myFrame = tools.getCallFrame( 0 ); // get local assertEquals( anInt, frame.getLocal( "anInt" ) ); // update local anInt = 17; // most random number - proven! assertEquals( anInt, frame.getLocal( "anInt" ) ); 18
  • 29. Dynamic access to local variables public @Test void sampleOfAccessingLiveCallFrame() { int anInt = 4; // random number - by dice String aString = "some string value"; // get the tool ToolingInterface tools = ToolingInterface.getToolingInterface(); // get the frame CallFrame myFrame = tools.getCallFrame( 0 ); // get local assertEquals( anInt, frame.getLocal( "anInt" ) ); // update local anInt = 17; // most random number - proven! assertEquals( anInt, frame.getLocal( "anInt" ) ); // fancy get assertSame( aString ((CallFrame)myFrame.getLocal( "myFrame" )) .getLocal( "aString" ) ); 18
  • 30. Dynamic access to local variables public @Test void sampleOfAccessingLiveCallFrame() { int anInt = 4; // random number - by dice String aString = "some string value"; // get the tool ToolingInterface tools = ToolingInterface.getToolingInterface(); // get the frame CallFrame myFrame = tools.getCallFrame( 0 ); // get local assertEquals( anInt, frame.getLocal( "anInt" ) ); // update local anInt = 17; // most random number - proven! assertEquals( anInt, frame.getLocal( "anInt" ) ); // fancy get assertSame( aString ((CallFrame)myFrame.getLocal( "myFrame" )) .getLocal( "aString" ) ); // convenient this assertSame( this, frame.getThis() ); } 18
  • 33. Heap introspection ๏Native interface (JVMTI) ๏Abilities: •Following references •Tagging objects and classes •Getting tagged objects •Transitive reachability traversal •Iterating through all reachable objects •Iterating through all objects (reachable and not) •Iterating through all instances of a class •Getting object size •Getting object monitor usage 21
  • 35. Putting it all together: Live introspection 23
  • 38. Web resources 26 ๏Java Debug Interface (JDI): http://docs.oracle.com/javase/7/docs/jdk/api/jpda/jdi/ ๏JVM Tooling Interface: http://docs.oracle.com/javase/7/docs/platform/jvmti/jvmti.html ๏JNI - JVMTI is an “extension” of JNI: http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/jniTOC.html ๏Overview of JDK tools: http://docs.oracle.com/javase/7/docs/technotes/tools/index.html ๏JVM Attach API: http://docs.oracle.com/javase/7/docs/jdk/api/attach/spec/
  • 39. Code samples ๏http://github.com/thobe/java-tooling, contains: •Library for building tools in java ‣Soon: cross compiled native binaries for Mac OS X,Windows, Linux •Code examples showing how to use these tools ๏https://github.com/thobe/subprocess-testing, contains: •JDI-based JUnit TestRunner ๏http://github.com/thobe/java-agent, contains: •Java agent code injection ๏http://github.com/thobe/introscript, contains: •javax.script.ScriptEngine that attaches to other process and introspects it with above tools 27