SlideShare ist ein Scribd-Unternehmen logo
1 von 81
Downloaden Sie, um offline zu lesen
Instrumentierung
Instrumentierung
— Das Werkzeug der Werkzeugmacher —
Bernd M¨uller
Ostfalia
Hochschule Braunschweig/Wolfenb¨uttel
Bernd M¨uller 1/46
Instrumentierung
Agenda
Instrumentierung und Agenten
Redefinition und Retransformation
Beispiele
Bernd M¨uller 2/46
Instrumentierung
Referent
Vorstellung Referent
Prof. Informatik (Ostfalia, HS Braunschweig/Wolfenb¨uttel)
Buchautor (JSF, Seam, JPA, ...)
Mitglied EGs JSR 344 (JSF 2.2) und JSR 338 (JPA 2.1)
Gesch¨aftsf¨uhrer PMST GmbH
. . .
bernd.mueller@ostfalia.de
@berndmuller
Bernd M¨uller 3/46
Instrumentierung
Instrumentierung und Agenten
Instrumentierung und Agenten
oder
Alt, m¨achtig, aber unbekannt . . .
Bernd M¨uller 4/46
Instrumentierung
Instrumentierung und Agenten
Instrumentierung in Java 5
Das Package java.lang.instrument
Das Package java.lang.instrument wurde mit Java 5
eingef¨uhrt
Bernd M¨uller 5/46
Instrumentierung
Instrumentierung und Agenten
Instrumentierung in Java 5
Das Package java.lang.instrument
Das Package java.lang.instrument wurde mit Java 5
eingef¨uhrt
Java-Doc:
”
. . . Provides services that allow Java programming language
agents to instrument programs running on the JVM. The
mechanism for instrumentation is modification of the
byte-codes of methods. . . .“
Bernd M¨uller 5/46
Instrumentierung
Instrumentierung und Agenten
Instrumentierung in Java 5
Das Package java.lang.instrument
Das Package java.lang.instrument wurde mit Java 5
eingef¨uhrt
Java-Doc:
”
. . . Provides services that allow Java programming language
agents to instrument programs running on the JVM. The
mechanism for instrumentation is modification of the
byte-codes of methods. . . .“
Verwendungsm¨oglichkeiten: Monitoring, JPA-Provider,
Code-Coverage, . . .
Bernd M¨uller 5/46
Instrumentierung
Instrumentierung und Agenten
Instrumentierung in Java 5
Das Package java.lang.instrument
Das Package java.lang.instrument wurde mit Java 5
eingef¨uhrt
Java-Doc:
”
. . . Provides services that allow Java programming language
agents to instrument programs running on the JVM. The
mechanism for instrumentation is modification of the
byte-codes of methods. . . .“
Verwendungsm¨oglichkeiten: Monitoring, JPA-Provider,
Code-Coverage, . . .
Allgemein: Sinnvolles Verhalten, das nicht im Code steht,
nachtr¨aglich und nur bei Bedarf einbauen
Bernd M¨uller 5/46
Instrumentierung
Instrumentierung und Agenten
Instrumentierung in Java 5
Agenten
Deployed als Jar-File
Bernd M¨uller 6/46
Instrumentierung
Instrumentierung und Agenten
Instrumentierung in Java 5
Agenten
Deployed als Jar-File
Attribut im Manifest definiert die Agenten-Klasse
Bernd M¨uller 6/46
Instrumentierung
Instrumentierung und Agenten
Instrumentierung in Java 5
Agenten
Deployed als Jar-File
Attribut im Manifest definiert die Agenten-Klasse
Alternativen, um Agent zu starten
Bernd M¨uller 6/46
Instrumentierung
Instrumentierung und Agenten
Instrumentierung in Java 5
Agenten
Deployed als Jar-File
Attribut im Manifest definiert die Agenten-Klasse
Alternativen, um Agent zu starten
Auf Kommandozeile bei VM-Start (zwingend erforderlich f¨ur
Kommandozeilenimplementierungen)
Bernd M¨uller 6/46
Instrumentierung
Instrumentierung und Agenten
Instrumentierung in Java 5
Agenten
Deployed als Jar-File
Attribut im Manifest definiert die Agenten-Klasse
Alternativen, um Agent zu starten
Auf Kommandozeile bei VM-Start (zwingend erforderlich f¨ur
Kommandozeilenimplementierungen)
Nach VM-Start, z.B. durch nicht n¨aher spezifiziertes Binden
(optional und implementation dependent)
Bernd M¨uller 6/46
Instrumentierung
Instrumentierung und Agenten
Instrumentierung in Java 5
Agenten
Deployed als Jar-File
Attribut im Manifest definiert die Agenten-Klasse
Alternativen, um Agent zu starten
Auf Kommandozeile bei VM-Start (zwingend erforderlich f¨ur
Kommandozeilenimplementierungen)
Nach VM-Start, z.B. durch nicht n¨aher spezifiziertes Binden
(optional und implementation dependent)
Artikel Java Magazin 3/2015: James Bond l¨asst gr¨ußen -
Geheimagenten (oder geheime Agenten) bei ihrer Arbeit
Bernd M¨uller 6/46
Instrumentierung
Instrumentierung und Agenten
Pre-Main
Pre-Main
oder
Gibt es ein Leben vor main() ?
Bernd M¨uller 7/46
Instrumentierung
Instrumentierung und Agenten
Pre-Main
Agentenstart ¨uber Kommandozeile
Syntax: -javaagent:jarpath[=options]
Bernd M¨uller 8/46
Instrumentierung
Instrumentierung und Agenten
Pre-Main
Agentenstart ¨uber Kommandozeile
Syntax: -javaagent:jarpath[=options]
Option mehrfach verwendbar, damit mehrere Agenten
Bernd M¨uller 8/46
Instrumentierung
Instrumentierung und Agenten
Pre-Main
Agentenstart ¨uber Kommandozeile
Syntax: -javaagent:jarpath[=options]
Option mehrfach verwendbar, damit mehrere Agenten
Manifest des Agenten-Jars muss Attribut Premain-Class
enthalten
Bernd M¨uller 8/46
Instrumentierung
Instrumentierung und Agenten
Pre-Main
Agentenstart ¨uber Kommandozeile
Syntax: -javaagent:jarpath[=options]
Option mehrfach verwendbar, damit mehrere Agenten
Manifest des Agenten-Jars muss Attribut Premain-Class
enthalten
Diese Agentenklasse muss premain()-Methode enthalten
Bernd M¨uller 8/46
Instrumentierung
Instrumentierung und Agenten
Pre-Main
Agentenstart ¨uber Kommandozeile
Syntax: -javaagent:jarpath[=options]
Option mehrfach verwendbar, damit mehrere Agenten
Manifest des Agenten-Jars muss Attribut Premain-Class
enthalten
Diese Agentenklasse muss premain()-Methode enthalten
Nachdem VM initialisiert ist, werden alle
premain()-Methoden in der Reihenfolge der Optionen
aufgerufen, dann die main()-Methode
Bernd M¨uller 8/46
Instrumentierung
Instrumentierung und Agenten
Pre-Main
Agentenstart ¨uber Kommandozeile
Syntax: -javaagent:jarpath[=options]
Option mehrfach verwendbar, damit mehrere Agenten
Manifest des Agenten-Jars muss Attribut Premain-Class
enthalten
Diese Agentenklasse muss premain()-Methode enthalten
Nachdem VM initialisiert ist, werden alle
premain()-Methoden in der Reihenfolge der Optionen
aufgerufen, dann die main()-Methode
Zwei m¨ogliche Signaturen:
public static void premain(String agentArgs ,
Instrumentation inst );
public static void premain(String agentArgs );
Aufruf der zweiten Alternative nur, falls erste nicht existiert
Bernd M¨uller 8/46
Instrumentierung
Instrumentierung und Agenten
Pre-Main
Agentenstart ¨uber Kommandozeile
Optional agentmain()-Methode zur Verwendung nach
VM-Start
Bernd M¨uller 9/46
Instrumentierung
Instrumentierung und Agenten
Pre-Main
Agentenstart ¨uber Kommandozeile
Optional agentmain()-Methode zur Verwendung nach
VM-Start
Falls Start ¨uber Kommandozeile, wird agentmain() nicht
aufgerufen
Bernd M¨uller 9/46
Instrumentierung
Instrumentierung und Agenten
Pre-Main
Agentenstart ¨uber Kommandozeile
Optional agentmain()-Methode zur Verwendung nach
VM-Start
Falls Start ¨uber Kommandozeile, wird agentmain() nicht
aufgerufen
Agent wird ¨uber System-Class-Loader geladen
Bernd M¨uller 9/46
Instrumentierung
Instrumentierung und Agenten
Pre-Main
Agentenstart ¨uber Kommandozeile
Optional agentmain()-Methode zur Verwendung nach
VM-Start
Falls Start ¨uber Kommandozeile, wird agentmain() nicht
aufgerufen
Agent wird ¨uber System-Class-Loader geladen
Jeder Agent bekommt seine Parameter ¨uber
agentArgs-Parameter als ein String, d.h. Agent muss selbst
parsen
Bernd M¨uller 9/46
Instrumentierung
Instrumentierung und Agenten
Pre-Main
Agentenstart ¨uber Kommandozeile
Optional agentmain()-Methode zur Verwendung nach
VM-Start
Falls Start ¨uber Kommandozeile, wird agentmain() nicht
aufgerufen
Agent wird ¨uber System-Class-Loader geladen
Jeder Agent bekommt seine Parameter ¨uber
agentArgs-Parameter als ein String, d.h. Agent muss selbst
parsen
Falls Agent nicht geladen werden kann oder
premain()-Methode nicht existert, wird VM beendet
Bernd M¨uller 9/46
Instrumentierung
Instrumentierung und Agenten
Pre-Main
Agentenstart ¨uber Kommandozeile
Optional agentmain()-Methode zur Verwendung nach
VM-Start
Falls Start ¨uber Kommandozeile, wird agentmain() nicht
aufgerufen
Agent wird ¨uber System-Class-Loader geladen
Jeder Agent bekommt seine Parameter ¨uber
agentArgs-Parameter als ein String, d.h. Agent muss selbst
parsen
Falls Agent nicht geladen werden kann oder
premain()-Methode nicht existert, wird VM beendet
Exceptions der premain()-Methode f¨uhren ebenfalls zum
Beenden der VM
Bernd M¨uller 9/46
Instrumentierung
Instrumentierung und Agenten
Attach-API
Das Attach-API
oder
Wie rede ich mit einer VM ?
Bernd M¨uller 10/46
Instrumentierung
Instrumentierung und Agenten
Attach-API
Instrumentation-Package
”
. . . Implementations may also support a mechanism to start
agents some time after the VM has started. For example, an
implementation may provide a mechanism that allows a tool to
attach to a running application, and initiate the loading of the
tool’s agent into the running application. The details as to how the
load is initiated, is implementation dependent.“
Bernd M¨uller 11/46
Instrumentierung
Instrumentierung und Agenten
Attach-API
Instrumentation-Package
”
. . . Implementations may also support a mechanism to start
agents some time after the VM has started. For example, an
implementation may provide a mechanism that allows a tool to
attach to a running application, and initiate the loading of the
tool’s agent into the running application. The details as to how the
load is initiated, is implementation dependent.“
Achtung: implementierungsabh¨angig
Aber: in HotSpot, JRockit, IBM, SAP vorhanden
Schnittstelle ist die abstrakte Klasse VirtualMachine im
Package com.sun.tools.attach, enthalten in tools.jar
Bernd M¨uller 11/46
Instrumentierung
Instrumentierung und Agenten
Attach-API
Java-Doc Klasse VirtualMachine
”
A VirtualMachine represents a Java virtual machine to which this
Java virtual machine has attached. The Java virtual machine to
which it is attached is sometimes called the target virtual machine,
or target VM. An application (typically a tool such as a
managemet console or profiler) uses a VirtualMachine to load an
agent into the target VM. “
Bernd M¨uller 12/46
Instrumentierung
Instrumentierung und Agenten
Attach-API
Java-Doc Klasse VirtualMachine
”
A VirtualMachine represents a Java virtual machine to which this
Java virtual machine has attached. The Java virtual machine to
which it is attached is sometimes called the target virtual machine,
or target VM. An application (typically a tool such as a
managemet console or profiler) uses a VirtualMachine to load an
agent into the target VM. “
Methode attach(<pid>)
Fabrikmethode, um angebundene Instanz zu bekommen
Methode loadAgent(<agent>,<args>)
um Agent zu laden und zu starten (Methode agentmain())
Bernd M¨uller 12/46
Instrumentierung
Instrumentierung und Agenten
Attach-API
Agent mit agentmain()
Der Agent
public static void agentmain(String agentArgs ,
Instrumentation inst );
public static void agentmain(String agentArgs );
Im Manifest Attribut Agent-Class auf Klassennamen des
Agenten setzten
Bernd M¨uller 13/46
Instrumentierung
Retransformation und Redefinition
Retransformation und Redefinition
oder
¨Andern oder neu machen ?
Bernd M¨uller 14/46
Instrumentierung
Retransformation und Redefinition
Retransformation und Redefinition
M¨oglichkeit, bereits geladene Klassen ganz oder teilweise zu
ersetzen
Bernd M¨uller 15/46
Instrumentierung
Retransformation und Redefinition
Retransformation und Redefinition
M¨oglichkeit, bereits geladene Klassen ganz oder teilweise zu
ersetzen
Beides optionale VM-Funktionen
Bernd M¨uller 15/46
Instrumentierung
Retransformation und Redefinition
Retransformation und Redefinition
M¨oglichkeit, bereits geladene Klassen ganz oder teilweise zu
ersetzen
Beides optionale VM-Funktionen
void redefineClasses(ClassDefinition... defs)
”
Redefine the supplied set of classes using the supplied class
files. This method is used to replace the definition of a class
without reference to the existing class file bytes, as one might
do when recompiling from source for fix-and-continue
debugging.“
Bernd M¨uller 15/46
Instrumentierung
Retransformation und Redefinition
Retransformation und Redefinition
M¨oglichkeit, bereits geladene Klassen ganz oder teilweise zu
ersetzen
Beides optionale VM-Funktionen
void redefineClasses(ClassDefinition... defs)
”
Redefine the supplied set of classes using the supplied class
files. This method is used to replace the definition of a class
without reference to the existing class file bytes, as one might
do when recompiling from source for fix-and-continue
debugging.“
void retransformClasses(Class<?>... classes)
”
Retransform the supplied set of classes. This function
facilitates the instrumentation of already loaded classes.“
Bernd M¨uller 15/46
Instrumentierung
Retransformation und Redefinition
Retransformation
Retransformation
Attribut Can-Retransform-Classes im Manifest auf true
setzen
Bernd M¨uller 16/46
Instrumentierung
Retransformation und Redefinition
Retransformation
Retransformation
Attribut Can-Retransform-Classes im Manifest auf true
setzen
Transformer registrieren:
Instrumentation.addTransformer(ClassFileTransformer
transformer)
Bernd M¨uller 16/46
Instrumentierung
Retransformation und Redefinition
Retransformation
Retransformation
Attribut Can-Retransform-Classes im Manifest auf true
setzen
Transformer registrieren:
Instrumentation.addTransformer(ClassFileTransformer
transformer)
Entsprechende Methode aufrufen:
Instrumentation.retransformClasses(Class<?>...
classes)
Bernd M¨uller 16/46
Instrumentierung
Retransformation und Redefinition
Redefinition
Redefinition
Attribut Can-Redefine-Classes im Manifest auf true
setzen
Bernd M¨uller 17/46
Instrumentierung
Retransformation und Redefinition
Redefinition
Redefinition
Attribut Can-Redefine-Classes im Manifest auf true
setzen
Entsprechende Methode aufrufen:
Instrumentation.redefineClasses(Class<?>...
classes)
Bernd M¨uller 17/46
Instrumentierung
Retransformation und Redefinition
Redefinition
Auszug aus Java-Doc f¨ur redefineClasses()
If a redefined method has active stack frames, those active
frames continue to run the bytecodes of the original method.
The redefined method will be used on new invokes.
Bernd M¨uller 18/46
Instrumentierung
Retransformation und Redefinition
Redefinition
Auszug aus Java-Doc f¨ur redefineClasses()
If a redefined method has active stack frames, those active
frames continue to run the bytecodes of the original method.
The redefined method will be used on new invokes.
This method does not cause any initialization except that
which would occur under the customary JVM semantics. In
other words, redefining a class does not cause its initializers to
be run. The values of static variables will remain as they were
prior to the call.
Bernd M¨uller 18/46
Instrumentierung
Retransformation und Redefinition
Redefinition
Auszug aus Java-Doc f¨ur redefineClasses()
If a redefined method has active stack frames, those active
frames continue to run the bytecodes of the original method.
The redefined method will be used on new invokes.
This method does not cause any initialization except that
which would occur under the customary JVM semantics. In
other words, redefining a class does not cause its initializers to
be run. The values of static variables will remain as they were
prior to the call.
Instances of the redefined class are not affected.
Bernd M¨uller 18/46
Instrumentierung
Retransformation und Redefinition
Redefinition
Auszug aus Java-Doc f¨ur redefineClasses() (cont’d)
The redefinition may change method bodies, the constant
pool and attributes. The redefinition must not add, remove or
rename fields or methods, change the signatures of methods,
or change inheritance. These restrictions maybe be lifted in
future versions.
Bernd M¨uller 19/46
Instrumentierung
Retransformation und Redefinition
Redefinition
Auszug aus Java-Doc f¨ur redefineClasses() (cont’d)
The redefinition may change method bodies, the constant
pool and attributes. The redefinition must not add, remove or
rename fields or methods, change the signatures of methods,
or change inheritance. These restrictions maybe be lifted in
future versions.
The class file bytes are not checked, verified and installed until
after the transformations have been applied, if the resultant
bytes are in error this method will throw an exception.
Bernd M¨uller 19/46
Instrumentierung
Beispiele
Beispiele
Bernd M¨uller 20/46
Instrumentierung
Beispiele
Beispiel: Monitoring
Beispiel: Monitoring
Bernd M¨uller 21/46
Instrumentierung
Beispiele
Beispiel: Monitoring
Beispiel Monitoring: Aufrufh¨aufigkeit der Methode
public class ClassToMonitor {
public void foo() {
// beliebig
}
}
Aufrufh¨aufigkeit der Methode foo() soll (auf einfache Art)
gez¨ahlt werden
Bernd M¨uller 22/46
Instrumentierung
Beispiele
Beispiel: Monitoring
Beispiel Monitoring: Z¨ahler und Main
public class Monitor {
public static int counter = 0;
}
public class Main {
public static void main(String [] args)
throws Exception {
System.out.println("Zaehler vor Schleife: "
+ Monitor.counter );
ClassToMonitor classToMonitor = new ClassToMonitor ();
for (int i = 0; i < 1000; i++) {
classToMonitor.foo ();
}
System.out.println("Zaehler nach Schleife: "
+ Monitor.counter );
}
}
Bernd M¨uller 23/46
Instrumentierung
Beispiele
Beispiel: Monitoring
Beispiel Monitoring: Der Agent
public class MonitorAgent {
public static void premain(String agentArgs ,
Instrumentation instrumentation ) {
instrumentation
.addTransformer (new MonitorTransformer ());
}
}
Und die MANIFEST.MF
Premain -Class: de.pdbm.MonitorAgent
Bernd M¨uller 24/46
Beispiel Monitoring: Instrumentierung mit Javassist
public class MonitorTransformer
implements ClassFileTransformer {
public byte [] transform(ClassLoader loader , String classNa
Class <?> classBeingRedefined , ProtectionDomain protect
byte [] classfileBuffer) throws IllegalClassFormatExcep
if (className.equals("de/pdbm/ ClassToMonitor")) {
ClassPool pool = ClassPool.getDefault ();
try {
CtClass cc = pool.get("de.pdbm. ClassToMonitor");
CtMethod method = cc. getDeclaredMethod ("foo");
method.insertBefore("de.pdbm.Monitor.counter ++;");
return cc.toBytecode ();
} catch ( NotFoundException | CannotCompileException |
...
}
}
return classfileBuffer ; // andere Klassen unveraendert
}
}
Instrumentierung
Beispiele
Beispiel: Klasse neu laden
Beispiel: Klasse neu laden
Bernd M¨uller 26/46
Instrumentierung
Beispiele
Beispiel: Klasse neu laden
Beispiel ¨Andern einer Methode und Neuladen
public class ClassToBeRedefined {
public void saySomething () {
System.out.println("foo");
// System.out.println ("bar ");
}
}
Bernd M¨uller 27/46
Instrumentierung
Beispiele
Beispiel: Klasse neu laden
Beispiel ¨Andern einer Methode und Neuladen (cont’d)
public class Agent {
private static Instrumentation instrumentation = null;
public static void agentmain(String agentArgument ,
Instrumentation instrumentation ) {
Agent. instrumentation = instrumentation ;
}
public static void redefineClasses ( ClassDefinition ...
definitions) throws Exc
if (Agent.instrumentation == null) {
throw new RuntimeException ("Agent nicht gestartet. Ins
}
Agent. instrumentation . redefineClasses (definitions );
}
}Bernd M¨uller 28/46
Instrumentierung
Beispiele
Beispiel: Klasse neu laden
Beispiel ¨Andern einer Methode und Neuladen (cont’d)
public class Main {
public static void main(String [] args) throws Exception {
ClassToBeRedefined ctbr = new ClassToBeRedefined ();
ctbr.saySomething ();
InputStream is = ctbr.getClass (). getClassLoader ()
// class ClassToBeRedefined
. getResourceAsStream ("dummy");
byte [] classBytes = classInputStreamToByteArray (is);
ClassDefinition classDefinition =
new ClassDefinition (ctbr.getClass (), classBytes );
loadAgent ();
Agent. redefineClasses ( classDefinition );
ctbr.saySomething ();
}
...
Bernd M¨uller 29/46
Instrumentierung
Beispiele
Beispiel: Klasse neu laden
Beispiel ¨Andern einer Methode und Neuladen (cont’d)
...
private static void loadAgent () {
String nameOfRunningVM = ManagementFactory
. getRuntimeMXBean (). getName ();
int p = nameOfRunningVM .indexOf(’@’);
String pid = nameOfRunningVM .substring (0, p);
try {
VirtualMachine vm = VirtualMachine.attach(pid);
vm.loadAgent(JAR_FILE_PATH , "");
vm.detach ();
} catch (Exception e) {
throw new RuntimeException (e);
}
}
}
Bernd M¨uller 30/46
Instrumentierung
Beispiele
Beispiel: Klasse neu laden
Seeing is believing . . .
Demo
Bernd M¨uller 31/46
Instrumentierung
Beispiele
Beispiel: Unit-Tests
Beispiel: Alle Unit-Tests bestehen ;-)
Bernd M¨uller 32/46
Instrumentierung
Beispiele
Beispiel: Unit-Tests
Beispiel
”
Alle JUnit-Tests bestehen“
public class ClassToTest {
public String getTheCanonicalClassName () {
return "Falscher Name";
// return this.getClass (). getCanonicalName ();
}
public int add(int a, int b) {
return a * b;
// return a + b;
}
}
Bernd M¨uller 33/46
Instrumentierung
Beispiele
Beispiel: Unit-Tests
Die JUnit-Tests
public class JunitTests {
@Test
public void testClassName () {
ClassToTest ctt = new ClassToTest ();
Assert.assertEquals("Falscher Klassenname",
ClassToTest.class. getCanonicalName (),
ctt. getTheCanonicalClassName ());
}
@Test
public void testAdd () {
ClassToTest ctt = new ClassToTest ();
Assert.assertEquals("Falsche Summe", (3 + 4),
ctt.add(3, 4));
}
}
Bernd M¨uller 34/46
Instrumentierung
Beispiele
Beispiel: Unit-Tests
Der Transformer
public class JunitTransformer implements ClassFileTransforme
@Override
public byte [] transform(ClassLoader loader , String classNa
Class <?> classBeingRedefined , ProtectionDomain protectionD
byte [] classfileBuffer) throws IllegalClassFormatException
if (className.equals("org/junit/Assert")) {
return transformAssert (); // ohne Exception -Handling
}
// alle anderen Klassen unveraendert zurueckgeben
return classfileBuffer ;
}
...
}
Bernd M¨uller 35/46
Instrumentierung
Beispiele
Beispiel: Unit-Tests
Der Transformer
private byte [] transformAssert () throws Exception {
ClassPool pool = ClassPool.getDefault ();
CtClass cc = pool.get("org.junit.Assert");
for (CtMethod ctMethod : cc.getMethods ()) {
if (ctMethod.getName (). startsWith("assert")) {
ctMethod.setBody("return;");
} else {
// die anderen (equals (), clone (), wait(), ...)
}
}
return cc.toBytecode ();
}
Bernd M¨uller 36/46
Instrumentierung
Beispiele
Beispiel: Unit-Tests
Der Agent
public class TransformerAgent {
public static void agentmain(String agentArgs , Instrumenta
instrumentation . addTransformer(new JunitTransformer (), t
Class <?>[] classes = instrumentation . getAllLoadedClasses
for (Class <?> c : classes) {
if (c.getName (). equals("org.junit.Assert")) {
try {
instrumentation . retransformClasses (c);
} catch ( UnmodifiableClassException e) {
e. printStackTrace ();
System.err.println(c + " laesst sich nicht modifiz
}
}
}
}
}Bernd M¨uller 37/46
Instrumentierung
Beispiele
Beispiel: Unit-Tests
Und wie besteht man alle Unit-Tests?
public class ClassToTest {
static {
AgentLoader.loadAgent ();
}
public String getTheCanonicalClassName () {
return "Falscher Name";
// return this.getClass (). getCanonicalName ();
}
public int add(int a, int b) {
return a * b;
// return a + b;
}
}
Bernd M¨uller 38/46
Instrumentierung
Beispiele
Beispiel: Unit-Tests
Seeing is believing . . .
Demo
Bernd M¨uller 39/46
Instrumentierung
Beispiele
Beispiel: Build your own JRebel Look-Alike
Beispiel: Build your own JRebel Look-Alike
Bernd M¨uller 40/46
Instrumentierung
Beispiele
Beispiel: Build your own JRebel Look-Alike
Was man dazu ben¨otigt . . .
File-System-Watcher! Gibt’s seit Java 7 im JDK
(Interface java.nio.file.WatchService)
Bernd M¨uller 41/46
Instrumentierung
Beispiele
Beispiel: Build your own JRebel Look-Alike
Was man dazu ben¨otigt . . .
File-System-Watcher! Gibt’s seit Java 7 im JDK
(Interface java.nio.file.WatchService)
Immer wenn *.class-Datei ge¨andert wird, diese neu laden
Bernd M¨uller 41/46
Instrumentierung
Beispiele
Beispiel: Build your own JRebel Look-Alike
Was man dazu ben¨otigt . . .
File-System-Watcher! Gibt’s seit Java 7 im JDK
(Interface java.nio.file.WatchService)
Immer wenn *.class-Datei ge¨andert wird, diese neu laden
Das wars schon !
Bernd M¨uller 41/46
Instrumentierung
Beispiele
Beispiel: Build your own JRebel Look-Alike
Seeing is believing . . .
Demo
Bernd M¨uller 42/46
Instrumentierung
Beispiele
Beispiel: App-Server Logging
Beispiel: App-Server Logging
Bernd M¨uller 43/46
Instrumentierung
Beispiele
Beispiel: App-Server Logging
JBoss’ Byteman (byteman.jboss.org)
Byteman is a tool which makes it easy to trace, monitor and
test the behaviour of Java application and JDK runtime code.
It injects Java code into your application methods or into
Java runtime methods without the need for you to recompile,
repackage or even redeploy your application.
Injection can be performed at JVM startup or after startup
while the application is still running.
Injected code can access any of your data and call any
application methods, including where they are private. You
can inject code almost anywhere you want and there is no
need to prepare the original source code in advance.
You can even remove injected code and reinstall different
changes while the application continues to execute.
Bernd M¨uller 44/46
Instrumentierung
Beispiele
Beispiel: App-Server Logging
JBoss’ Byteman (byteman.jboss.org)
Byteman is a tool which makes it easy to trace, monitor and
test the behaviour of Java application and JDK runtime code.
It injects Java code into your application methods or into
Java runtime methods without the need for you to recompile,
repackage or even redeploy your application.
Injection can be performed at JVM startup or after startup
while the application is still running.
Injected code can access any of your data and call any
application methods, including where they are private. You
can inject code almost anywhere you want and there is no
need to prepare the original source code in advance.
You can even remove injected code and reinstall different
changes while the application continues to execute.
Bernd M¨uller 44/46
Instrumentierung
Beispiele
Beispiel: App-Server Logging
JBoss’ Byteman (byteman.jboss.org)
Byteman is a tool which makes it easy to trace, monitor and
test the behaviour of Java application and JDK runtime code.
It injects Java code into your application methods or into
Java runtime methods without the need for you to recompile,
repackage or even redeploy your application.
Injection can be performed at JVM startup or after startup
while the application is still running.
Injected code can access any of your data and call any
application methods, including where they are private. You
can inject code almost anywhere you want and there is no
need to prepare the original source code in advance.
You can even remove injected code and reinstall different
changes while the application continues to execute.
Bernd M¨uller 44/46
Instrumentierung
Beispiele
Beispiel: App-Server Logging
JBoss’ Byteman (byteman.jboss.org)
Byteman is a tool which makes it easy to trace, monitor and
test the behaviour of Java application and JDK runtime code.
It injects Java code into your application methods or into
Java runtime methods without the need for you to recompile,
repackage or even redeploy your application.
Injection can be performed at JVM startup or after startup
while the application is still running.
Injected code can access any of your data and call any
application methods, including where they are private. You
can inject code almost anywhere you want and there is no
need to prepare the original source code in advance.
You can even remove injected code and reinstall different
changes while the application continues to execute.
Bernd M¨uller 44/46
Instrumentierung
Beispiele
Beispiel: App-Server Logging
JBoss’ Byteman (byteman.jboss.org)
Byteman is a tool which makes it easy to trace, monitor and
test the behaviour of Java application and JDK runtime code.
It injects Java code into your application methods or into
Java runtime methods without the need for you to recompile,
repackage or even redeploy your application.
Injection can be performed at JVM startup or after startup
while the application is still running.
Injected code can access any of your data and call any
application methods, including where they are private. You
can inject code almost anywhere you want and there is no
need to prepare the original source code in advance.
You can even remove injected code and reinstall different
changes while the application continues to execute.
Bernd M¨uller 44/46
Instrumentierung
Beispiele
Beispiel: App-Server Logging
Seeing is believing . . .
Demo
Bernd M¨uller 45/46
Instrumentierung
Fragen und Anmerkungen
Fragen und Anmerkungen
Bernd M¨uller 46/46

Weitere ähnliche Inhalte

Empfohlen

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Empfohlen (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Instrumentierung - Das Werkzeug der Werkzeugmacher -

  • 1. Instrumentierung Instrumentierung — Das Werkzeug der Werkzeugmacher — Bernd M¨uller Ostfalia Hochschule Braunschweig/Wolfenb¨uttel Bernd M¨uller 1/46
  • 2. Instrumentierung Agenda Instrumentierung und Agenten Redefinition und Retransformation Beispiele Bernd M¨uller 2/46
  • 3. Instrumentierung Referent Vorstellung Referent Prof. Informatik (Ostfalia, HS Braunschweig/Wolfenb¨uttel) Buchautor (JSF, Seam, JPA, ...) Mitglied EGs JSR 344 (JSF 2.2) und JSR 338 (JPA 2.1) Gesch¨aftsf¨uhrer PMST GmbH . . . bernd.mueller@ostfalia.de @berndmuller Bernd M¨uller 3/46
  • 4. Instrumentierung Instrumentierung und Agenten Instrumentierung und Agenten oder Alt, m¨achtig, aber unbekannt . . . Bernd M¨uller 4/46
  • 5. Instrumentierung Instrumentierung und Agenten Instrumentierung in Java 5 Das Package java.lang.instrument Das Package java.lang.instrument wurde mit Java 5 eingef¨uhrt Bernd M¨uller 5/46
  • 6. Instrumentierung Instrumentierung und Agenten Instrumentierung in Java 5 Das Package java.lang.instrument Das Package java.lang.instrument wurde mit Java 5 eingef¨uhrt Java-Doc: ” . . . Provides services that allow Java programming language agents to instrument programs running on the JVM. The mechanism for instrumentation is modification of the byte-codes of methods. . . .“ Bernd M¨uller 5/46
  • 7. Instrumentierung Instrumentierung und Agenten Instrumentierung in Java 5 Das Package java.lang.instrument Das Package java.lang.instrument wurde mit Java 5 eingef¨uhrt Java-Doc: ” . . . Provides services that allow Java programming language agents to instrument programs running on the JVM. The mechanism for instrumentation is modification of the byte-codes of methods. . . .“ Verwendungsm¨oglichkeiten: Monitoring, JPA-Provider, Code-Coverage, . . . Bernd M¨uller 5/46
  • 8. Instrumentierung Instrumentierung und Agenten Instrumentierung in Java 5 Das Package java.lang.instrument Das Package java.lang.instrument wurde mit Java 5 eingef¨uhrt Java-Doc: ” . . . Provides services that allow Java programming language agents to instrument programs running on the JVM. The mechanism for instrumentation is modification of the byte-codes of methods. . . .“ Verwendungsm¨oglichkeiten: Monitoring, JPA-Provider, Code-Coverage, . . . Allgemein: Sinnvolles Verhalten, das nicht im Code steht, nachtr¨aglich und nur bei Bedarf einbauen Bernd M¨uller 5/46
  • 9. Instrumentierung Instrumentierung und Agenten Instrumentierung in Java 5 Agenten Deployed als Jar-File Bernd M¨uller 6/46
  • 10. Instrumentierung Instrumentierung und Agenten Instrumentierung in Java 5 Agenten Deployed als Jar-File Attribut im Manifest definiert die Agenten-Klasse Bernd M¨uller 6/46
  • 11. Instrumentierung Instrumentierung und Agenten Instrumentierung in Java 5 Agenten Deployed als Jar-File Attribut im Manifest definiert die Agenten-Klasse Alternativen, um Agent zu starten Bernd M¨uller 6/46
  • 12. Instrumentierung Instrumentierung und Agenten Instrumentierung in Java 5 Agenten Deployed als Jar-File Attribut im Manifest definiert die Agenten-Klasse Alternativen, um Agent zu starten Auf Kommandozeile bei VM-Start (zwingend erforderlich f¨ur Kommandozeilenimplementierungen) Bernd M¨uller 6/46
  • 13. Instrumentierung Instrumentierung und Agenten Instrumentierung in Java 5 Agenten Deployed als Jar-File Attribut im Manifest definiert die Agenten-Klasse Alternativen, um Agent zu starten Auf Kommandozeile bei VM-Start (zwingend erforderlich f¨ur Kommandozeilenimplementierungen) Nach VM-Start, z.B. durch nicht n¨aher spezifiziertes Binden (optional und implementation dependent) Bernd M¨uller 6/46
  • 14. Instrumentierung Instrumentierung und Agenten Instrumentierung in Java 5 Agenten Deployed als Jar-File Attribut im Manifest definiert die Agenten-Klasse Alternativen, um Agent zu starten Auf Kommandozeile bei VM-Start (zwingend erforderlich f¨ur Kommandozeilenimplementierungen) Nach VM-Start, z.B. durch nicht n¨aher spezifiziertes Binden (optional und implementation dependent) Artikel Java Magazin 3/2015: James Bond l¨asst gr¨ußen - Geheimagenten (oder geheime Agenten) bei ihrer Arbeit Bernd M¨uller 6/46
  • 15. Instrumentierung Instrumentierung und Agenten Pre-Main Pre-Main oder Gibt es ein Leben vor main() ? Bernd M¨uller 7/46
  • 16. Instrumentierung Instrumentierung und Agenten Pre-Main Agentenstart ¨uber Kommandozeile Syntax: -javaagent:jarpath[=options] Bernd M¨uller 8/46
  • 17. Instrumentierung Instrumentierung und Agenten Pre-Main Agentenstart ¨uber Kommandozeile Syntax: -javaagent:jarpath[=options] Option mehrfach verwendbar, damit mehrere Agenten Bernd M¨uller 8/46
  • 18. Instrumentierung Instrumentierung und Agenten Pre-Main Agentenstart ¨uber Kommandozeile Syntax: -javaagent:jarpath[=options] Option mehrfach verwendbar, damit mehrere Agenten Manifest des Agenten-Jars muss Attribut Premain-Class enthalten Bernd M¨uller 8/46
  • 19. Instrumentierung Instrumentierung und Agenten Pre-Main Agentenstart ¨uber Kommandozeile Syntax: -javaagent:jarpath[=options] Option mehrfach verwendbar, damit mehrere Agenten Manifest des Agenten-Jars muss Attribut Premain-Class enthalten Diese Agentenklasse muss premain()-Methode enthalten Bernd M¨uller 8/46
  • 20. Instrumentierung Instrumentierung und Agenten Pre-Main Agentenstart ¨uber Kommandozeile Syntax: -javaagent:jarpath[=options] Option mehrfach verwendbar, damit mehrere Agenten Manifest des Agenten-Jars muss Attribut Premain-Class enthalten Diese Agentenklasse muss premain()-Methode enthalten Nachdem VM initialisiert ist, werden alle premain()-Methoden in der Reihenfolge der Optionen aufgerufen, dann die main()-Methode Bernd M¨uller 8/46
  • 21. Instrumentierung Instrumentierung und Agenten Pre-Main Agentenstart ¨uber Kommandozeile Syntax: -javaagent:jarpath[=options] Option mehrfach verwendbar, damit mehrere Agenten Manifest des Agenten-Jars muss Attribut Premain-Class enthalten Diese Agentenklasse muss premain()-Methode enthalten Nachdem VM initialisiert ist, werden alle premain()-Methoden in der Reihenfolge der Optionen aufgerufen, dann die main()-Methode Zwei m¨ogliche Signaturen: public static void premain(String agentArgs , Instrumentation inst ); public static void premain(String agentArgs ); Aufruf der zweiten Alternative nur, falls erste nicht existiert Bernd M¨uller 8/46
  • 22. Instrumentierung Instrumentierung und Agenten Pre-Main Agentenstart ¨uber Kommandozeile Optional agentmain()-Methode zur Verwendung nach VM-Start Bernd M¨uller 9/46
  • 23. Instrumentierung Instrumentierung und Agenten Pre-Main Agentenstart ¨uber Kommandozeile Optional agentmain()-Methode zur Verwendung nach VM-Start Falls Start ¨uber Kommandozeile, wird agentmain() nicht aufgerufen Bernd M¨uller 9/46
  • 24. Instrumentierung Instrumentierung und Agenten Pre-Main Agentenstart ¨uber Kommandozeile Optional agentmain()-Methode zur Verwendung nach VM-Start Falls Start ¨uber Kommandozeile, wird agentmain() nicht aufgerufen Agent wird ¨uber System-Class-Loader geladen Bernd M¨uller 9/46
  • 25. Instrumentierung Instrumentierung und Agenten Pre-Main Agentenstart ¨uber Kommandozeile Optional agentmain()-Methode zur Verwendung nach VM-Start Falls Start ¨uber Kommandozeile, wird agentmain() nicht aufgerufen Agent wird ¨uber System-Class-Loader geladen Jeder Agent bekommt seine Parameter ¨uber agentArgs-Parameter als ein String, d.h. Agent muss selbst parsen Bernd M¨uller 9/46
  • 26. Instrumentierung Instrumentierung und Agenten Pre-Main Agentenstart ¨uber Kommandozeile Optional agentmain()-Methode zur Verwendung nach VM-Start Falls Start ¨uber Kommandozeile, wird agentmain() nicht aufgerufen Agent wird ¨uber System-Class-Loader geladen Jeder Agent bekommt seine Parameter ¨uber agentArgs-Parameter als ein String, d.h. Agent muss selbst parsen Falls Agent nicht geladen werden kann oder premain()-Methode nicht existert, wird VM beendet Bernd M¨uller 9/46
  • 27. Instrumentierung Instrumentierung und Agenten Pre-Main Agentenstart ¨uber Kommandozeile Optional agentmain()-Methode zur Verwendung nach VM-Start Falls Start ¨uber Kommandozeile, wird agentmain() nicht aufgerufen Agent wird ¨uber System-Class-Loader geladen Jeder Agent bekommt seine Parameter ¨uber agentArgs-Parameter als ein String, d.h. Agent muss selbst parsen Falls Agent nicht geladen werden kann oder premain()-Methode nicht existert, wird VM beendet Exceptions der premain()-Methode f¨uhren ebenfalls zum Beenden der VM Bernd M¨uller 9/46
  • 28. Instrumentierung Instrumentierung und Agenten Attach-API Das Attach-API oder Wie rede ich mit einer VM ? Bernd M¨uller 10/46
  • 29. Instrumentierung Instrumentierung und Agenten Attach-API Instrumentation-Package ” . . . Implementations may also support a mechanism to start agents some time after the VM has started. For example, an implementation may provide a mechanism that allows a tool to attach to a running application, and initiate the loading of the tool’s agent into the running application. The details as to how the load is initiated, is implementation dependent.“ Bernd M¨uller 11/46
  • 30. Instrumentierung Instrumentierung und Agenten Attach-API Instrumentation-Package ” . . . Implementations may also support a mechanism to start agents some time after the VM has started. For example, an implementation may provide a mechanism that allows a tool to attach to a running application, and initiate the loading of the tool’s agent into the running application. The details as to how the load is initiated, is implementation dependent.“ Achtung: implementierungsabh¨angig Aber: in HotSpot, JRockit, IBM, SAP vorhanden Schnittstelle ist die abstrakte Klasse VirtualMachine im Package com.sun.tools.attach, enthalten in tools.jar Bernd M¨uller 11/46
  • 31. Instrumentierung Instrumentierung und Agenten Attach-API Java-Doc Klasse VirtualMachine ” A VirtualMachine represents a Java virtual machine to which this Java virtual machine has attached. The Java virtual machine to which it is attached is sometimes called the target virtual machine, or target VM. An application (typically a tool such as a managemet console or profiler) uses a VirtualMachine to load an agent into the target VM. “ Bernd M¨uller 12/46
  • 32. Instrumentierung Instrumentierung und Agenten Attach-API Java-Doc Klasse VirtualMachine ” A VirtualMachine represents a Java virtual machine to which this Java virtual machine has attached. The Java virtual machine to which it is attached is sometimes called the target virtual machine, or target VM. An application (typically a tool such as a managemet console or profiler) uses a VirtualMachine to load an agent into the target VM. “ Methode attach(<pid>) Fabrikmethode, um angebundene Instanz zu bekommen Methode loadAgent(<agent>,<args>) um Agent zu laden und zu starten (Methode agentmain()) Bernd M¨uller 12/46
  • 33. Instrumentierung Instrumentierung und Agenten Attach-API Agent mit agentmain() Der Agent public static void agentmain(String agentArgs , Instrumentation inst ); public static void agentmain(String agentArgs ); Im Manifest Attribut Agent-Class auf Klassennamen des Agenten setzten Bernd M¨uller 13/46
  • 34. Instrumentierung Retransformation und Redefinition Retransformation und Redefinition oder ¨Andern oder neu machen ? Bernd M¨uller 14/46
  • 35. Instrumentierung Retransformation und Redefinition Retransformation und Redefinition M¨oglichkeit, bereits geladene Klassen ganz oder teilweise zu ersetzen Bernd M¨uller 15/46
  • 36. Instrumentierung Retransformation und Redefinition Retransformation und Redefinition M¨oglichkeit, bereits geladene Klassen ganz oder teilweise zu ersetzen Beides optionale VM-Funktionen Bernd M¨uller 15/46
  • 37. Instrumentierung Retransformation und Redefinition Retransformation und Redefinition M¨oglichkeit, bereits geladene Klassen ganz oder teilweise zu ersetzen Beides optionale VM-Funktionen void redefineClasses(ClassDefinition... defs) ” Redefine the supplied set of classes using the supplied class files. This method is used to replace the definition of a class without reference to the existing class file bytes, as one might do when recompiling from source for fix-and-continue debugging.“ Bernd M¨uller 15/46
  • 38. Instrumentierung Retransformation und Redefinition Retransformation und Redefinition M¨oglichkeit, bereits geladene Klassen ganz oder teilweise zu ersetzen Beides optionale VM-Funktionen void redefineClasses(ClassDefinition... defs) ” Redefine the supplied set of classes using the supplied class files. This method is used to replace the definition of a class without reference to the existing class file bytes, as one might do when recompiling from source for fix-and-continue debugging.“ void retransformClasses(Class<?>... classes) ” Retransform the supplied set of classes. This function facilitates the instrumentation of already loaded classes.“ Bernd M¨uller 15/46
  • 39. Instrumentierung Retransformation und Redefinition Retransformation Retransformation Attribut Can-Retransform-Classes im Manifest auf true setzen Bernd M¨uller 16/46
  • 40. Instrumentierung Retransformation und Redefinition Retransformation Retransformation Attribut Can-Retransform-Classes im Manifest auf true setzen Transformer registrieren: Instrumentation.addTransformer(ClassFileTransformer transformer) Bernd M¨uller 16/46
  • 41. Instrumentierung Retransformation und Redefinition Retransformation Retransformation Attribut Can-Retransform-Classes im Manifest auf true setzen Transformer registrieren: Instrumentation.addTransformer(ClassFileTransformer transformer) Entsprechende Methode aufrufen: Instrumentation.retransformClasses(Class<?>... classes) Bernd M¨uller 16/46
  • 42. Instrumentierung Retransformation und Redefinition Redefinition Redefinition Attribut Can-Redefine-Classes im Manifest auf true setzen Bernd M¨uller 17/46
  • 43. Instrumentierung Retransformation und Redefinition Redefinition Redefinition Attribut Can-Redefine-Classes im Manifest auf true setzen Entsprechende Methode aufrufen: Instrumentation.redefineClasses(Class<?>... classes) Bernd M¨uller 17/46
  • 44. Instrumentierung Retransformation und Redefinition Redefinition Auszug aus Java-Doc f¨ur redefineClasses() If a redefined method has active stack frames, those active frames continue to run the bytecodes of the original method. The redefined method will be used on new invokes. Bernd M¨uller 18/46
  • 45. Instrumentierung Retransformation und Redefinition Redefinition Auszug aus Java-Doc f¨ur redefineClasses() If a redefined method has active stack frames, those active frames continue to run the bytecodes of the original method. The redefined method will be used on new invokes. This method does not cause any initialization except that which would occur under the customary JVM semantics. In other words, redefining a class does not cause its initializers to be run. The values of static variables will remain as they were prior to the call. Bernd M¨uller 18/46
  • 46. Instrumentierung Retransformation und Redefinition Redefinition Auszug aus Java-Doc f¨ur redefineClasses() If a redefined method has active stack frames, those active frames continue to run the bytecodes of the original method. The redefined method will be used on new invokes. This method does not cause any initialization except that which would occur under the customary JVM semantics. In other words, redefining a class does not cause its initializers to be run. The values of static variables will remain as they were prior to the call. Instances of the redefined class are not affected. Bernd M¨uller 18/46
  • 47. Instrumentierung Retransformation und Redefinition Redefinition Auszug aus Java-Doc f¨ur redefineClasses() (cont’d) The redefinition may change method bodies, the constant pool and attributes. The redefinition must not add, remove or rename fields or methods, change the signatures of methods, or change inheritance. These restrictions maybe be lifted in future versions. Bernd M¨uller 19/46
  • 48. Instrumentierung Retransformation und Redefinition Redefinition Auszug aus Java-Doc f¨ur redefineClasses() (cont’d) The redefinition may change method bodies, the constant pool and attributes. The redefinition must not add, remove or rename fields or methods, change the signatures of methods, or change inheritance. These restrictions maybe be lifted in future versions. The class file bytes are not checked, verified and installed until after the transformations have been applied, if the resultant bytes are in error this method will throw an exception. Bernd M¨uller 19/46
  • 51. Instrumentierung Beispiele Beispiel: Monitoring Beispiel Monitoring: Aufrufh¨aufigkeit der Methode public class ClassToMonitor { public void foo() { // beliebig } } Aufrufh¨aufigkeit der Methode foo() soll (auf einfache Art) gez¨ahlt werden Bernd M¨uller 22/46
  • 52. Instrumentierung Beispiele Beispiel: Monitoring Beispiel Monitoring: Z¨ahler und Main public class Monitor { public static int counter = 0; } public class Main { public static void main(String [] args) throws Exception { System.out.println("Zaehler vor Schleife: " + Monitor.counter ); ClassToMonitor classToMonitor = new ClassToMonitor (); for (int i = 0; i < 1000; i++) { classToMonitor.foo (); } System.out.println("Zaehler nach Schleife: " + Monitor.counter ); } } Bernd M¨uller 23/46
  • 53. Instrumentierung Beispiele Beispiel: Monitoring Beispiel Monitoring: Der Agent public class MonitorAgent { public static void premain(String agentArgs , Instrumentation instrumentation ) { instrumentation .addTransformer (new MonitorTransformer ()); } } Und die MANIFEST.MF Premain -Class: de.pdbm.MonitorAgent Bernd M¨uller 24/46
  • 54. Beispiel Monitoring: Instrumentierung mit Javassist public class MonitorTransformer implements ClassFileTransformer { public byte [] transform(ClassLoader loader , String classNa Class <?> classBeingRedefined , ProtectionDomain protect byte [] classfileBuffer) throws IllegalClassFormatExcep if (className.equals("de/pdbm/ ClassToMonitor")) { ClassPool pool = ClassPool.getDefault (); try { CtClass cc = pool.get("de.pdbm. ClassToMonitor"); CtMethod method = cc. getDeclaredMethod ("foo"); method.insertBefore("de.pdbm.Monitor.counter ++;"); return cc.toBytecode (); } catch ( NotFoundException | CannotCompileException | ... } } return classfileBuffer ; // andere Klassen unveraendert } }
  • 55. Instrumentierung Beispiele Beispiel: Klasse neu laden Beispiel: Klasse neu laden Bernd M¨uller 26/46
  • 56. Instrumentierung Beispiele Beispiel: Klasse neu laden Beispiel ¨Andern einer Methode und Neuladen public class ClassToBeRedefined { public void saySomething () { System.out.println("foo"); // System.out.println ("bar "); } } Bernd M¨uller 27/46
  • 57. Instrumentierung Beispiele Beispiel: Klasse neu laden Beispiel ¨Andern einer Methode und Neuladen (cont’d) public class Agent { private static Instrumentation instrumentation = null; public static void agentmain(String agentArgument , Instrumentation instrumentation ) { Agent. instrumentation = instrumentation ; } public static void redefineClasses ( ClassDefinition ... definitions) throws Exc if (Agent.instrumentation == null) { throw new RuntimeException ("Agent nicht gestartet. Ins } Agent. instrumentation . redefineClasses (definitions ); } }Bernd M¨uller 28/46
  • 58. Instrumentierung Beispiele Beispiel: Klasse neu laden Beispiel ¨Andern einer Methode und Neuladen (cont’d) public class Main { public static void main(String [] args) throws Exception { ClassToBeRedefined ctbr = new ClassToBeRedefined (); ctbr.saySomething (); InputStream is = ctbr.getClass (). getClassLoader () // class ClassToBeRedefined . getResourceAsStream ("dummy"); byte [] classBytes = classInputStreamToByteArray (is); ClassDefinition classDefinition = new ClassDefinition (ctbr.getClass (), classBytes ); loadAgent (); Agent. redefineClasses ( classDefinition ); ctbr.saySomething (); } ... Bernd M¨uller 29/46
  • 59. Instrumentierung Beispiele Beispiel: Klasse neu laden Beispiel ¨Andern einer Methode und Neuladen (cont’d) ... private static void loadAgent () { String nameOfRunningVM = ManagementFactory . getRuntimeMXBean (). getName (); int p = nameOfRunningVM .indexOf(’@’); String pid = nameOfRunningVM .substring (0, p); try { VirtualMachine vm = VirtualMachine.attach(pid); vm.loadAgent(JAR_FILE_PATH , ""); vm.detach (); } catch (Exception e) { throw new RuntimeException (e); } } } Bernd M¨uller 30/46
  • 60. Instrumentierung Beispiele Beispiel: Klasse neu laden Seeing is believing . . . Demo Bernd M¨uller 31/46
  • 61. Instrumentierung Beispiele Beispiel: Unit-Tests Beispiel: Alle Unit-Tests bestehen ;-) Bernd M¨uller 32/46
  • 62. Instrumentierung Beispiele Beispiel: Unit-Tests Beispiel ” Alle JUnit-Tests bestehen“ public class ClassToTest { public String getTheCanonicalClassName () { return "Falscher Name"; // return this.getClass (). getCanonicalName (); } public int add(int a, int b) { return a * b; // return a + b; } } Bernd M¨uller 33/46
  • 63. Instrumentierung Beispiele Beispiel: Unit-Tests Die JUnit-Tests public class JunitTests { @Test public void testClassName () { ClassToTest ctt = new ClassToTest (); Assert.assertEquals("Falscher Klassenname", ClassToTest.class. getCanonicalName (), ctt. getTheCanonicalClassName ()); } @Test public void testAdd () { ClassToTest ctt = new ClassToTest (); Assert.assertEquals("Falsche Summe", (3 + 4), ctt.add(3, 4)); } } Bernd M¨uller 34/46
  • 64. Instrumentierung Beispiele Beispiel: Unit-Tests Der Transformer public class JunitTransformer implements ClassFileTransforme @Override public byte [] transform(ClassLoader loader , String classNa Class <?> classBeingRedefined , ProtectionDomain protectionD byte [] classfileBuffer) throws IllegalClassFormatException if (className.equals("org/junit/Assert")) { return transformAssert (); // ohne Exception -Handling } // alle anderen Klassen unveraendert zurueckgeben return classfileBuffer ; } ... } Bernd M¨uller 35/46
  • 65. Instrumentierung Beispiele Beispiel: Unit-Tests Der Transformer private byte [] transformAssert () throws Exception { ClassPool pool = ClassPool.getDefault (); CtClass cc = pool.get("org.junit.Assert"); for (CtMethod ctMethod : cc.getMethods ()) { if (ctMethod.getName (). startsWith("assert")) { ctMethod.setBody("return;"); } else { // die anderen (equals (), clone (), wait(), ...) } } return cc.toBytecode (); } Bernd M¨uller 36/46
  • 66. Instrumentierung Beispiele Beispiel: Unit-Tests Der Agent public class TransformerAgent { public static void agentmain(String agentArgs , Instrumenta instrumentation . addTransformer(new JunitTransformer (), t Class <?>[] classes = instrumentation . getAllLoadedClasses for (Class <?> c : classes) { if (c.getName (). equals("org.junit.Assert")) { try { instrumentation . retransformClasses (c); } catch ( UnmodifiableClassException e) { e. printStackTrace (); System.err.println(c + " laesst sich nicht modifiz } } } } }Bernd M¨uller 37/46
  • 67. Instrumentierung Beispiele Beispiel: Unit-Tests Und wie besteht man alle Unit-Tests? public class ClassToTest { static { AgentLoader.loadAgent (); } public String getTheCanonicalClassName () { return "Falscher Name"; // return this.getClass (). getCanonicalName (); } public int add(int a, int b) { return a * b; // return a + b; } } Bernd M¨uller 38/46
  • 68. Instrumentierung Beispiele Beispiel: Unit-Tests Seeing is believing . . . Demo Bernd M¨uller 39/46
  • 69. Instrumentierung Beispiele Beispiel: Build your own JRebel Look-Alike Beispiel: Build your own JRebel Look-Alike Bernd M¨uller 40/46
  • 70. Instrumentierung Beispiele Beispiel: Build your own JRebel Look-Alike Was man dazu ben¨otigt . . . File-System-Watcher! Gibt’s seit Java 7 im JDK (Interface java.nio.file.WatchService) Bernd M¨uller 41/46
  • 71. Instrumentierung Beispiele Beispiel: Build your own JRebel Look-Alike Was man dazu ben¨otigt . . . File-System-Watcher! Gibt’s seit Java 7 im JDK (Interface java.nio.file.WatchService) Immer wenn *.class-Datei ge¨andert wird, diese neu laden Bernd M¨uller 41/46
  • 72. Instrumentierung Beispiele Beispiel: Build your own JRebel Look-Alike Was man dazu ben¨otigt . . . File-System-Watcher! Gibt’s seit Java 7 im JDK (Interface java.nio.file.WatchService) Immer wenn *.class-Datei ge¨andert wird, diese neu laden Das wars schon ! Bernd M¨uller 41/46
  • 73. Instrumentierung Beispiele Beispiel: Build your own JRebel Look-Alike Seeing is believing . . . Demo Bernd M¨uller 42/46
  • 74. Instrumentierung Beispiele Beispiel: App-Server Logging Beispiel: App-Server Logging Bernd M¨uller 43/46
  • 75. Instrumentierung Beispiele Beispiel: App-Server Logging JBoss’ Byteman (byteman.jboss.org) Byteman is a tool which makes it easy to trace, monitor and test the behaviour of Java application and JDK runtime code. It injects Java code into your application methods or into Java runtime methods without the need for you to recompile, repackage or even redeploy your application. Injection can be performed at JVM startup or after startup while the application is still running. Injected code can access any of your data and call any application methods, including where they are private. You can inject code almost anywhere you want and there is no need to prepare the original source code in advance. You can even remove injected code and reinstall different changes while the application continues to execute. Bernd M¨uller 44/46
  • 76. Instrumentierung Beispiele Beispiel: App-Server Logging JBoss’ Byteman (byteman.jboss.org) Byteman is a tool which makes it easy to trace, monitor and test the behaviour of Java application and JDK runtime code. It injects Java code into your application methods or into Java runtime methods without the need for you to recompile, repackage or even redeploy your application. Injection can be performed at JVM startup or after startup while the application is still running. Injected code can access any of your data and call any application methods, including where they are private. You can inject code almost anywhere you want and there is no need to prepare the original source code in advance. You can even remove injected code and reinstall different changes while the application continues to execute. Bernd M¨uller 44/46
  • 77. Instrumentierung Beispiele Beispiel: App-Server Logging JBoss’ Byteman (byteman.jboss.org) Byteman is a tool which makes it easy to trace, monitor and test the behaviour of Java application and JDK runtime code. It injects Java code into your application methods or into Java runtime methods without the need for you to recompile, repackage or even redeploy your application. Injection can be performed at JVM startup or after startup while the application is still running. Injected code can access any of your data and call any application methods, including where they are private. You can inject code almost anywhere you want and there is no need to prepare the original source code in advance. You can even remove injected code and reinstall different changes while the application continues to execute. Bernd M¨uller 44/46
  • 78. Instrumentierung Beispiele Beispiel: App-Server Logging JBoss’ Byteman (byteman.jboss.org) Byteman is a tool which makes it easy to trace, monitor and test the behaviour of Java application and JDK runtime code. It injects Java code into your application methods or into Java runtime methods without the need for you to recompile, repackage or even redeploy your application. Injection can be performed at JVM startup or after startup while the application is still running. Injected code can access any of your data and call any application methods, including where they are private. You can inject code almost anywhere you want and there is no need to prepare the original source code in advance. You can even remove injected code and reinstall different changes while the application continues to execute. Bernd M¨uller 44/46
  • 79. Instrumentierung Beispiele Beispiel: App-Server Logging JBoss’ Byteman (byteman.jboss.org) Byteman is a tool which makes it easy to trace, monitor and test the behaviour of Java application and JDK runtime code. It injects Java code into your application methods or into Java runtime methods without the need for you to recompile, repackage or even redeploy your application. Injection can be performed at JVM startup or after startup while the application is still running. Injected code can access any of your data and call any application methods, including where they are private. You can inject code almost anywhere you want and there is no need to prepare the original source code in advance. You can even remove injected code and reinstall different changes while the application continues to execute. Bernd M¨uller 44/46
  • 80. Instrumentierung Beispiele Beispiel: App-Server Logging Seeing is believing . . . Demo Bernd M¨uller 45/46
  • 81. Instrumentierung Fragen und Anmerkungen Fragen und Anmerkungen Bernd M¨uller 46/46