Living in the Matrix with Bytecode Manipulation

Size: px
Start display at page:

Download "Living in the Matrix with Bytecode Manipulation"

Transcription

1 Living in the Matrix with Bytecode Manipulation QCon NY 2014

2 Ashley Puls Senior Software Engineer New Relic, Inc.

3 Follow Along

4 Outline What is bytecode? Why manipulate bytecode? What frameworks can be used to manipulate bytecode? Examine two frameworks in depth

5 What is Java bytecode?.java file Java compiler (javac).class file Java Virtual Machine Native OS Java Runtime System Bytecode Verifier Class Loader Source:

6 What is Java bytecode?.java file Java compiler (javac).class file Java Virtual Machine Native OS Java Runtime System Bytecode Verifier Class Loader Source:

7 What is Java bytecode? Instruction set of the Java Virtual Machine.java file Java compiler (javac).class file Java Virtual Machine Native OS Java Runtime System Bytecode Verifier Class Loader Source:

8 Why learn about Java bytecode manipulation frameworks?

9 Why learn about Java bytecode manipulation frameworks? A bytecode manipulation framework is likely already on your stack Spring Hibernate Groovy Clojure Eclipse JRuby

10 Why learn about Java bytecode manipulation frameworks? A bytecode manipulation framework is likely already on your stack Spring Hibernate Groovy Clojure Eclipse JRuby Its really fun!!!

11 Why learn about Java bytecode manipulation frameworks? program analysis find bugs in code examine code complexity generate classes proxies remove access to certain APIs compiler for another language like Scala transform classes without Java source code profilers optimization and obfuscation additional logging

12 Why learn about Java bytecode manipulation frameworks? program analysis find bugs in code examine code complexity generate classes proxies remove access to certain APIs compiler for another language like Scala transform classes without Java source code profilers optimization and obfuscation additional logging

13 Logging Source:

14 Logging Source:

15 Logging Source:

16 Logging Audit Log: a message should be logged every time an important method is called Source:

17 Logging Audit Log: a message should be logged every time an important method is called log important input parameters to the method Source:

18 Logging public class BankTransactions { public static void main(string[] args) { BankTransactions bank = new BankTransactions(); // login and add i dollars to account for (int i = 0; i < 100; i++) { String accountid = "account" + i; bank.login("password", accountid, "Ashley"); bank.unimportantprocessing(accountid); bank.finalizetransaction(accountid, Double.valueOf(i)); System.out.println( Transactions completed );

19 Logging public class BankTransactions { public static void main(string[] args) { BankTransactions bank = new BankTransactions(); // login and add i dollars to each account for (int i = 0; i < 100; i++) { String accountid = "account" + i; bank.login("password", accountid, "Ashley"); bank.unimportantprocessing(accountid); bank.finalizetransaction(accountid, Double.valueOf(i)); System.out.println( Transactions completed );

20 Logging /** * A method annotation which should be used to indicate important methods whose * invocations should be logged. * */ ImportantLog { /** * The method parameter indexes whose values should be logged. For example, * if we have the method hello(int parama, int paramb, int paramc), and we * wanted to log the values of parama and paramc, then fields would be ["0", * "2"]. If we only want to log the value of paramb, then fields would be * ["1"]. */ String[] fields();

21 Logging public void login(string password, String accountid, String username) { // login logic public void finalizetransaction(string accountid, Double moneytoadd) { // transaction logic

22 = { "1", "2" ) public void login(string password, String accountid, String username) { // login = { "0", "1" ) public void finalizetransaction(string accountid, Double moneytoadd) { // transaction logic

23 = { "1", "2" ) public void login(string password, String accountid, String username) { // login logic A call was made to method "login" on class "com/example/qcon/mains/banktransactions". Important params: Index 1 value: ${accountid Index 2 value: = { "0", "1" ) public void finalizetransaction(string accountid, Double moneytoadd) { // transaction logic

24 = { "1", "2" ) public void login(string password, String accountid, String username) { // login logic A call was made to method "login" on class "com/example/qcon/mains/banktransactions". Important params: Index 1 value: ${accountid Index 2 value: = { "0", "1" ) public void finalizetransaction(string accountid, Double moneytoadd) { // transaction logic A call was made to method "finalizetransaction" on class "com/example/qcon/ mains/banktransactions". Important params: Index 0 value: ${accountid Index 1 value: ${moneytoadd

25 Java Agent Ability to modify the bytecode without modifying the application source code Added in Java 1.5 Docs: java/lang/instrument/package-summary.html

26 Typical Java Process java com/example/qcon/mains/banktransactions JVM Classloader BankTransactions.class public static void main(string[] args) Transactions completed

27 Java Agent java -javaagent:/path/to/agent.jar com/example/qcon/mains/ BankTransactions Agent JVM

28 Java Agent java -javaagent:/path/to/agent.jar com/example/qcon/mains/ BankTransactions JVM

29 Java Agent java -javaagent:/path/to/agent.jar com/example/qcon/mains/ BankTransactions Agent JVM

30 Java Agent java -javaagent:/path/to/agent.jar com/example/qcon/mains/ BankTransactions Agent Agent.class void premain(string agentargs, Instrumentation inst) JVM 1. call Agent premain in manifest 2. JVM registers my transformer MyTransformer.class byte[] transform(..., byte[] banktransbytes)

31 Java Agent java -javaagent:/path/to/agent.jar com/example/qcon/mains/ BankTransactions Agent Agent.class void premain(string agentargs, Instrumentation inst) MyTransformer.class byte[] transform(..., byte[] banktransbytes) JVM 1. call Agent premain in manifest 2. JVM registers my transformer 3. Give BankTransactions bytes to MyTransformer 4. MyTransformer provides bytes to load

32 Java Agent java -javaagent:/path/to/agent.jar com/example/qcon/mains/ BankTransactions Agent Agent.class void premain(string agentargs, Instrumentation inst) MyTransformer.class byte[] transform(..., byte[] banktransbytes) JVM 1. call Agent premain in manifest 2. JVM registers my transformer 3. Give BankTransactions bytes to MyTransformer 4. MyTransformer provides bytes to load BankTransactions.class void main(string[] args) 5. BankTransactions loaded and main runs Transactions completed

33 lets code Manifest: Premain-Class: com.example.qcon.agent.agent

34 lets code Manifest: Premain-Class: com.example.qcon.agent.agent package com.example.qcon.agent; public class Agent { public static void premain(string agentargs, Instrumentation inst) { System.out.println("Starting the agent"); inst.addtransformer(new ImportantLogClassTransformer());

35 lets code Manifest: Premain-Class: com.example.qcon.agent.agent package com.example.qcon.agent; public class Agent { public static void premain(string agentargs, Instrumentation inst) { System.out.println("Starting the agent"); inst.addtransformer(new ImportantLogClassTransformer());

36 lets code package com.example.qcon.agent; import java.lang.instrument.classfiletransformer; import java.lang.instrument.illegalclassformatexception; public class ImportantLogClassTransformer implements ClassFileTransformer { public byte[] transform(classloader loader, String classname, Class classbeingredefined, ProtectionDomain protectiondomain, byte[] classfilebuffer) throws IllegalClassFormatException { //TODO return null;

37 lets code package com.example.qcon.agent; import java.lang.instrument.classfiletransformer; import java.lang.instrument.illegalclassformatexception; public class ImportantLogClassTransformer implements ClassFileTransformer { public byte[] transform(classloader loader, String classname, Class classbeingredefined, ProtectionDomain protectiondomain, byte[] classfilebuffer) throws IllegalClassFormatException { //TODO return null;

38 lets code package com.example.qcon.agent; import java.lang.instrument.classfiletransformer; import java.lang.instrument.illegalclassformatexception; public class ImportantLogClassTransformer implements ClassFileTransformer { public byte[] transform(classloader loader, String classname, Class classbeingredefined, ProtectionDomain protectiondomain, byte[] classfilebuffer) throws IllegalClassFormatException { System.out.println(" Loading class: " + classname); return null;

39 lets code Starting the agent Loading class: java/lang/invoke/methodhandleimpl Loading class: java/lang/invoke/membername$factory Loading class: java/lang/invoke/lambdaform$namedfunction Loading class: java/lang/invoke/methodtype$concurrentweakinternset Loading class: java/lang/invoke/methodhandlestatics Loading class: java/lang/invoke/methodhandlestatics$1 Loading class: java/lang/invoke/methodtypeform Loading class: java/lang/invoke/invokers Loading class: java/lang/invoke/methodtype$concurrentweakinternset$weakentry Loading class: java/lang/void Loading class: java/lang/illegalaccessexception Loading class: sun/misc/postvminithook Loading class: sun/launcher/launcherhelper Loading class: java/util/concurrent/concurrenthashmap$forwardingnode Loading class: sun/misc/urlclasspath$fileloader$1 Loading class: com/example/qcon/mains/banktransactions Loading class: sun/launcher/launcherhelper$fxhelper

40 lets code package com.example.qcon.agent; import java.lang.instrument.classfiletransformer; import java.lang.instrument.illegalclassformatexception; public class ImportantLogClassTransformer implements ClassFileTransformer { public byte[] transform(classloader loader, String classname, Class classbeingredefined, ProtectionDomain protectiondomain, byte[] classfilebuffer) throws IllegalClassFormatException { System.out.println(" Loading class: " + classname); return null;

41 lets code package com.example.qcon.agent; import java.lang.instrument.classfiletransformer; import java.lang.instrument.illegalclassformatexception; public class ImportantLogClassTransformer implements ClassFileTransformer { public byte[] transform(classloader loader, String classname, Class classbeingredefined, ProtectionDomain protectiondomain, byte[] classfilebuffer) throws IllegalClassFormatException { // manipulate the bytes here and then return them return null;

42 Bytecode Manipulation Frameworks ASM: BCEL: CGLib: Javassist: Serp: Cojen: Soot:

43 Bytecode Manipulation Frameworks ASM: BCEL: CGLib: Javassist: Serp: Cojen: Soot:

44 Javassist Java Programming Assistant Subproject of JBoss Actively updated Version released May 2014 Source code: javassist Documentation: ~chiba/javassist/tutorial/tutorial.html

45 Javassist CtClass: represents a compile time class ArrayList HashMap

46 Javassist CtClass: represents a compile time class ClassPool: container of CtClass objects ArrayList HashMap

47 Javassist CtClass: represents a compile time class ClassPool: container of CtClass objects ArrayList ArrayList HashMap HashMap

48 Javassist CtClass: represents a compile time class ClassPool: container of CtClass objects ArrayList ArrayList HashMap HashMap BankTrans

49 Javassist CtClass: represents a compile time class ClassPool: container of CtClass objects ByteArrayClassPath: converts a byte[] to a CtClass ArrayList ArrayList HashMap HashMap BankTrans

50 Javassist CtClass: represents a compile time class ClassPool: container of CtClass objects ByteArrayClassPath: converts a byte[] to a CtClass Classpool.getDefault().insertClassPath(new ByteArrayClassPath( BankTrans, classbytes); ArrayList ArrayList HashMap HashMap BankTrans

51 Javassist CtClass: represents a compile time class ClassPool: container of CtClass objects ByteArrayClassPath: converts a byte[] to a CtClass Classpool.getDefault().insertClassPath(new ByteArrayClassPath( BankTrans, classbytes); ArrayList ArrayList HashMap HashMap BankTrans BankTrans

52 Javassist CtClass: represents a compile time class ClassPool: container of CtClass objects ByteArrayClassPath: converts a byte[] to a CtClass Classpool.getDefault().insertClassPath(new ByteArrayClassPath( BankTrans, classbytes); CtClass bank = Classpool.getDefault().get( BankTrans ); ArrayList ArrayList HashMap HashMap BankTrans BankTrans

53 Javassist CtClass: represents a compile time class ClassPool: container of CtClass objects ByteArrayClassPath: converts a byte[] to a CtClass Classpool.getDefault().insertClassPath(new ByteArrayClassPath( BankTrans, classbytes); CtClass bank = Classpool.getDefault().get( BankTrans ); ArrayList ArrayList HashMap HashMap BankTrans BankTrans BankTrans

54 Javassist CtClass: represents a compile time class BankTrans

55 Javassist CtClass: represents a compile time class CtConstructor: represents a compile time constructor BankTrans init

56 Javassist CtClass: represents a compile time class CtConstructor: represents a compile time constructor CtMethod: represents a compile time class BankTrans init login process

57 Javassist CtClass: represents a compile time class CtConstructor: represents a compile time constructor CtMethod: represents a compile time method CtMethod loginmethod = loginctclass.getdeclaredmethod( login ); BankTrans init login process

58 Javassist CtClass: represents a compile time class CtConstructor: represents a compile time constructor CtMethod: represents a compile time method CtMethod loginmethod = loginctclass.getdeclaredmethod( login ); BankTrans init login process login

59 Javassist CtMethod: represents a compile time method login

60 Javassist CtMethod: represents a compile time method Modifications: login

61 Javassist CtMethod: represents a compile time method Modifications: putmethod.insertbefore( System.out.println(\ before method\ ); ); putmethod.insertafter( System.out.println(\ after method\ ); ); login

62 Javassist CtMethod: represents a compile time method Modifications: putmethod.insertbefore( System.out.println(\ before method\ ); ); putmethod.insertafter( System.out.println(\ after method\ ); ); login System.out.println( before method ); System.out.println( after method );

63 Javassist CtMethod: represents a compile time method Modifications: CtClass exceptiontype = classpool.get( java.io.ioexception ); putmethod.addcatch( {System.out.println($e); throw $e, exceptiontype); login

64 Javassist CtMethod: represents a compile time method Modifications: CtClass exceptiontype = classpool.get( java.io.ioexception ); putmethod.addcatch( {System.out.println($e); throw $e, exceptiontype); login System.out.println( exception ); throw exception;

65 Javassist CtMethod: represents a compile time method Modifications: putmethod.insertat(5, true, System.out.println(\ hello\ ); ); login

66 Javassist CtMethod: represents a compile time method Modifications: putmethod.insertat(5, true, System.out.println(\ hello\ ); ); login System.out.println( hello );

67 Javassist CtMethod: represents a compile time method Modifications: insertbefore insertafter insertat addcatch login System.out.println( before method ); System.out.println( hello ); System.out.println( exception ); throw exception; System.out.println( after method );

68 Javassist CtMethod: represents a compile time method Modifications: insertbefore insertafter insertat addcatch Freeze Class: login System.out.println( before method ); System.out.println( hello ); System.out.println( exception ); throw exception; System.out.println( after method );

69 Javassist CtMethod: represents a compile time method Modifications: insertbefore insertafter insertat addcatch Freeze Class: writefile() toclass() tobytecode() login System.out.println( before method ); System.out.println( hello ); System.out.println( exception ); throw exception; System.out.println( after method );

70 lets code

71 lets code package com.example.qcon.agent; import java.lang.instrument.classfiletransformer; import java.lang.instrument.illegalclassformatexception; public class ImportantLogClassTransformer implements ClassFileTransformer { public byte[] transform(classloader loader, String classname, Class classbeingredefined, ProtectionDomain protectiondomain, byte[] classfilebuffer) throws IllegalClassFormatException { //TODO return null;

72 lets code package com.example.qcon.agent; import java.lang.instrument.classfiletransformer; import java.lang.instrument.illegalclassformatexception; public class ImportantLogClassTransformer implements ClassFileTransformer { public byte[] transform(classloader loader, String classname, Class classbeingredefined, ProtectionDomain protectiondomain, byte[] classfilebuffer) throws IllegalClassFormatException { //TODO return null;

73 lets code public byte[] transform(classloader loader, String classname, Class classbeingredefined, ProtectionDomain protectiondomain, byte[] cfbuffer) throws IllegalClassFormatException { 1. convert byte array to a ct class object 2. check each method of ct class for 3. annotation present on method, then a. get important method parameter indexes b. add logging statement to beginning of the method return null;

74 lets code public byte[] transform(classloader loader, String classname, Class classbeingredefined, ProtectionDomain protectiondomain, byte[] cfbuffer) throws IllegalClassFormatException { pool.insertclasspath(new ByteArrayClassPath(className, classfilebuffer)); CtClass cclass = pool.get(classname.replaceall("/", ".")); 2. check each method of ct class for 3. annotation present on method, then a. get important method parameter indexes b. add logging statement to beginning of the method return null;

75 lets code public byte[] transform(classloader loader, String classname, Class classbeingredefined, ProtectionDomain protectiondomain, byte[] cfbuffer) throws IllegalClassFormatException { pool.insertclasspath(new ByteArrayClassPath(className, classfilebuffer)); CtClass cclass = pool.get(classname.replaceall("/", ".")); if (!cclass.isfrozen()) { for (CtMethod currentmethod : cclass.getdeclaredmethods()) { Annotation annotation = getannotation(currentmethod); 3. annotation present on method, then a. get important method parameter indexes b. add logging statement to beginning of the method return null;

76 lets code public byte[] transform(classloader loader, String classname, Class classbeingredefined, ProtectionDomain protectiondomain, byte[] cfbuffer) throws IllegalClassFormatException { pool.insertclasspath(new ByteArrayClassPath(className, classfilebuffer)); CtClass cclass = pool.get(classname.replaceall("/", ".")); if (!cclass.isfrozen()) { for (CtMethod currentmethod : cclass.getdeclaredmethods()) { Annotation annotation = getannotation(currentmethod); if (annotation!= null) { List<String> parameterindexes = getparamindexes(annotation); return null; b. add logging statement to beginning of the method

77 lets code public byte[] transform(classloader loader, String classname, Class classbeingredefined, ProtectionDomain protectiondomain, byte[] cfbuffer) throws IllegalClassFormatException { pool.insertclasspath(new ByteArrayClassPath(className, classfilebuffer)); CtClass cclass = pool.get(classname.replaceall("/", ".")); if (!cclass.isfrozen()) { for (CtMethod currentmethod : cclass.getdeclaredmethods()) { Annotation annotation = getannotation(currentmethod); if (annotation!= null) { List<String> parameterindexes = getparamindexes(annotation); currentmethod.insertbefore(createjavastring( currentmethod, classname, parameterindexes)); return cclass.tobytecode(); return null;

78 lets code public byte[] transform(classloader loader, String classname, Class classbeingredefined, ProtectionDomain protectiondomain, byte[] cfbuffer) throws IllegalClassFormatException { pool.insertclasspath(new ByteArrayClassPath(className, classfilebuffer)); CtClass cclass = pool.get(classname.replaceall("/", ".")); if (!cclass.isfrozen()) { for (CtMethod currentmethod : cclass.getdeclaredmethods()) { Annotation annotation = getannotation(currentmethod); if (annotation!= null) { List<String> parameterindexes = getparamindexes(annotation); currentmethod.insertbefore(createjavastring( currentmethod, classname, parameterindexes)); return cclass.tobytecode(); return null;

79 lets code private Annotation getannotation(ctmethod method) { MethodInfo minfo = method.getmethodinfo(); // the attribute we are looking for is a runtime invisible attribute // use Retention(RetentionPolicy.RUNTIME) on the annotation to make it // visible at runtime AnnotationsAttribute attinfo = (AnnotationsAttribute) minfo.getattribute(annotationsattribute.invisibletag); if (attinfo!= null) { // this is the type name meaning use dots instead of slashes return attinfo.getannotation("com.example.qcon.mains.importantlog"); return null;

80 lets code public byte[] transform(classloader loader, String classname, Class classbeingredefined, ProtectionDomain protectiondomain, byte[] cfbuffer) throws IllegalClassFormatException { pool.insertclasspath(new ByteArrayClassPath(className, classfilebuffer)); CtClass cclass = pool.get(classname.replaceall("/", ".")); if (!cclass.isfrozen()) { for (CtMethod currentmethod : cclass.getdeclaredmethods()) { Annotation annotation = getannotation(currentmethod); if (annotation!= null) { List<String> parameterindexes = getparamindexes(annotation); currentmethod.insertbefore(createjavastring( currentmethod, classname, parameterindexes)); return cclass.tobytecode(); return null;

81 lets code private List<String> getparamindexes(annotation annotation) { ArrayMemberValue fields = (ArrayMemberValue) annotation.getmembervalue( fields ); if (fields!= null) { MemberValue[] values = (MemberValue[]) fields.getvalue(); List<String> parameterindexes = new ArrayList<String>(); for (MemberValue val : values) { parameterindexes.add(((stringmembervalue) val).getvalue()); return parameterindexes; return Collections.emptyList();

82 lets code public byte[] transform(classloader loader, String classname, Class classbeingredefined, ProtectionDomain protectiondomain, byte[] cfbuffer) throws IllegalClassFormatException { pool.insertclasspath(new ByteArrayClassPath(className, classfilebuffer)); CtClass cclass = pool.get(classname.replaceall("/", ".")); if (!cclass.isfrozen()) { for (CtMethod currentmethod : cclass.getdeclaredmethods()) { Annotation annotation = getannotation(currentmethod); if (annotation!= null) { List<String> parameterindexes = getparamindexes(annotation); currentmethod.insertbefore(createjavastring( currentmethod, classname, parameterindexes)); return cclass.tobytecode(); return null;

83 lets code private String createjavastring(ctmethod currentmethod, String classname, List<String> indexparameters) { StringBuilder sb = new StringBuilder(); sb.append("{stringbuilder sb = new StringBuilder"); sb.append("(\"a call was made to method '\");"); sb.append("sb.append(\""); sb.append(currentmethod.getname()); sb.append("\");sb.append(\"' on class '\");"); sb.append("sb.append(\""); sb.append(classname); sb.append("\");sb.append(\"'.\");"); sb.append("sb.append(\"\\n Important params:\");");...

84 lets code private String createjavastring(ctmethod currentmethod, String classname, List<String> indexparameters) { StringBuilder sb = new StringBuilder(); sb.append("{stringbuilder sb = new StringBuilder"); sb.append("(\"a call was made to method '\");"); sb.append("sb.append(\""); sb.append(currentmethod.getname()); sb.append("\");sb.append(\"' on class '\");"); sb.append("sb.append(\""); sb.append(classname); sb.append("\");sb.append(\"'.\");"); sb.append("sb.append(\"\\n Important params:\");");... Put multiple statements inside brackets {

85 lets code private String createjavastring(ctmethod currentmethod, String classname, List<String> indexparameters) {... for (String index : indexparameters) { try { int localvar = Integer.parseInt(index) + 1; sb.append("sb.append(\"\\n Index: \");"); sb.append("sb.append(\""); sb.append(index); sb.append("\");sb.append(\" value: \");"); sb.append("sb.append($" + localvar + ");"); catch (NumberFormatException e) { e.printstacktrace(); sb.append("system.out.println(sb.tostring());"); return sb.tostring();

86 lets code private String createjavastring(ctmethod currentmethod, String classname, List<String> indexparameters) {... for (String index : indexparameters) { try { int localvar = Integer.parseInt(index) + 1; sb.append("sb.append(\"\\n Index: \");"); sb.append("sb.append(\""); sb.append(index); sb.append("\");sb.append(\" value: \");"); sb.append("sb.append($" + localvar + ");"); catch (NumberFormatException e) { e.printstacktrace(); sb.append("system.out.println(sb.tostring());"); return sb.tostring(); $0, $1, $2,... can be used to access this and the actual method parameters

87 lets code public byte[] transform(classloader loader, String classname, Class classbeingredefined, ProtectionDomain protectiondomain, byte[] cfbuffer) throws IllegalClassFormatException { pool.insertclasspath(new ByteArrayClassPath(className, classfilebuffer)); CtClass cclass = pool.get(classname.replaceall("/", ".")); if (!cclass.isfrozen()) { for (CtMethod currentmethod : cclass.getdeclaredmethods()) { Annotation annotation = getannotation(currentmethod); if (annotation!= null) { List<String> parameterindexes = getparamindexes(annotation); currentmethod.insertbefore(createjavastring( currentmethod, classname, parameterindexes)); return cclass.tobytecode(); return null;

88 Javassist Positives Simplicity Do not have to write actual bytecode Decent documentation Negatives Generally slower than ASM Less functionality

89 ASM Released in Open Source in 2002 Actively updated Version released May 2014 Two ASM libraries Event based (SAX like) Visitor design pattern Object based (DOM like) Documentation: asm/asm4-guide.pdf

90 ASM Source:

91 ASM Source:

92 ASM Source:

93 ASM ClassReader: given a byte[], parses a compiled class ClassReader: event producer ClassVisitor: event filter ClassWriter: event consumer BankTrans

94 ASM ClassReader: given a byte[], parses a compiled class ClassReader: event producer ClassVisitor: event filter ClassWriter: event consumer BankTrans visitfield visitmethod

95 ASM ClassReader: given a byte[], parses a compiled class ClassVisitor: delegates class events, event filter visitattribute visitfield visitmethod visitinnerclass visitend ClassReader: event producer ClassVisitor: event filter ClassWriter: event consumer BankTrans visitfield visitmethod

96 ASM ClassReader: given a byte[], parses a compiled class ClassVisitor: delegates class events, event filter visitattribute visitfield visitmethod visitinnerclass visitend ClassWriter: produces output byte[] ClassReader: event producer ClassVisitor: event filter ClassWriter: event consumer BankTrans visitfield BankTrans visitmethod

97 lets code package com.example.qcon.agent; import java.lang.instrument.instrumentation; public class Agent { public static void premain(string agentargs, Instrumentation inst) { System.out.println("Starting the agent"); inst.addtransformer(new ImportantLogClassTransformer());

98 lets code package com.example.qcon.agent; import java.lang.instrument.instrumentation; public class Agent { public static void premain(string agentargs, Instrumentation inst) { System.out.println("Starting the agent"); inst.addtransformer(new ImportantLogClassTransformer());

99 lets code package com.example.qcon.agent; import java.lang.instrument.classfiletransformer; import java.lang.instrument.illegalclassformatexception; public class ImportantLogClassTransformer implements ClassFileTransformer { public byte[] transform(classloader loader, String classname, Class classbeingredefined, ProtectionDomain protectiondomain, byte[] classfilebuffer) throws IllegalClassFormatException { //TODO return null;

100 lets code package com.example.qcon.agent; import java.lang.instrument.classfiletransformer; import java.lang.instrument.illegalclassformatexception; public class ImportantLogClassTransformer implements ClassFileTransformer { public byte[] transform(classloader loader, String classname, Class classbeingredefined, ProtectionDomain protectiondomain, byte[] classfilebuffer) throws IllegalClassFormatException { //TODO return null;

101 lets code public byte[] transform(classloader loader, String classname, Class<?> classbeingredefined, ProtectionDomain protectiondomain, byte[] classfilebuffer) throws IllegalClassFormatException { ClassReader cr = new ClassReader(classfileBuffer); ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_FRAMES); cr.accept(cw, 0); return cw.tobytearray();

102 lets code public byte[] transform(classloader loader, String classname, Class<?> classbeingredefined, ProtectionDomain protectiondomain, byte[] classfilebuffer) throws IllegalClassFormatException { ClassReader cr = new ClassReader(classfileBuffer); ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_FRAMES); ClassVisitor cv = new LogMethodClassVisitor(cw, classname); cr.accept(cv, 0); return cw.tobytearray();

103 ASM ClassReader: given a byte[], parses a compiled class ClassVisitor: delegates class events, event filter visitattribute visitfield visitmethod visitinnerclass visitend ClassWriter: produces output byte[] BankTrans ClassReader: event producer LogMethod ClassVisitor: event filter visitmethod ClassWriter: event consumer BankTrans

104 ASM Source:

105 lets code public class LogMethodClassVisitor extends ClassVisitor { private String classname; public LogMethodIfAnnotationVisitor(ClassVisitor cv, String pclassname) { super(opcodes.asm5, cv); classname = public MethodVisitor visitmethod(int access, String name, String desc, String signature, String[] exceptions) { // put our logic in here

106 lets code public class LogMethodClassVisitor extends ClassVisitor { private String classname; public LogMethodIfAnnotationVisitor(ClassVisitor cv, String pclassname) { super(opcodes.asm5, cv); classname = public MethodVisitor visitmethod(int access, String name, String desc, String signature, String[] exceptions) { // put our logic in here

107 ASM Source:

108 ASM Source:

109 ASM Source:

110 ASM MethodVisitor: method event filter visitannotation visitend visitcode visittrycatchblock MethodVisitor MethodVisitor login method visitor visitattribute visitcode login method visitor visitend

111 ASM Source:

112 lets code public class LogMethodClassVisitor extends ClassVisitor { private String classname; public LogMethodIfAnnotationVisitor(ClassVisitor cv, String pclassname) { super(opcodes.asm5, cv); classname = public MethodVisitor visitmethod(int access, String name, String desc, String signature, String[] exceptions) { MethodVisitor mv = super.visitmethod(access, name, desc, signature, exceptions); return new PrintMessageMethodVisitor(mv, name, classname);

113 lets code public class PrintMessageMethodVisitor extends MethodVisitor { private String methodname; private String classname; private boolean isannotationpresent; private List<String> parameterindexes; public PrintMessageMethodVisitor(MethodVisitor mv, String methodname, String classname) public AnnotationVisitor visitannotation(string desc, boolean visible) public void visitcode() {

114 lets code public class PrintMessageMethodVisitor extends MethodVisitor { private String methodname; private String classname; private boolean isannotationpresent; private List<String> parameterindexes; public PrintMessageMethodVisitor(MethodVisitor mv, String methodname, String classname) { // initialize instance public AnnotationVisitor visitannotation(string desc, boolean visible) { 1. check method for 2. if annotation present, then get important method param public void visitcode() { 3. if annotation present, add logging to beginning of the method

115 lets code public AnnotationVisitor visitannotation(string desc, boolean visible) { if ("Lcom/example/qcon/mains/ImportantLog;".equals(desc)) { isannotationpresent = true; return new AnnotationVisitor(Opcodes.ASM5, super.visitannotation(desc, visible)) { public AnnotationVisitor visitarray(string name) { if ( fields.equals(name)) { return new AnnotationVisitor(Opcodes.ASM5, super.visitarray(name)) { public void visit(string name, Object value) { parameterindexes.add((string) value); super.visit(name, value); ; else { return super.visitarray(name); ; return super.visitannotation(desc, visible);

116 lets code public class PrintMessageMethodVisitor extends MethodVisitor { private String methodname; private String classname; private boolean isannotationpresent; private List<String> parameterindexes; public PrintMessageMethodVisitor(MethodVisitor mv, String methodname, String classname) { // initialize instance public AnnotationVisitor visitannotation(string desc, boolean visible) { 1. check method for 2. if annotation present, then get important method param public void visitcode() { 3. if annotation present, add logging statement to beginning of the method

117 lets code public void visitcode() { if (isannotationpresent) { // create string builder mv.visitfieldinsn(opcodes.getstatic, "java/lang/system", "out", "Ljava/io/PrintStream;"); mv.visittypeinsn(opcodes.new, "java/lang/stringbuilder"); mv.visitinsn(opcodes.dup);... // add everything to the string builder mv.visitldcinsn("a call was made to method \""); mv.visitmethodinsn(opcodes.invokespecial, "java/lang/stringbuilder", "<init>", "(Ljava/lang/String;)V", false); mv.visitldcinsn(methodname); mv.visitmethodinsn(opcodes.invokevirtual, "java/lang/stringbuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false);

118 What is Java bytecode? use javap to examine the bytecode

119 What is Java bytecode? public class PrintMessage { private String methodname; private String classname; public PrintMessage(String mname, String cname) { methodname = mname; classname = cname; public void print() { StringBuilder sb = new StringBuilder(); sb.append("a call was made to method \""); sb.append(methodname); sb.append("\" on class \""); sb.append(classname); sb.append("\"."); System.out.println(sb.toString());

120 What is Java bytecode? javap -c bin/com/example/qcon/mains/printmessage

121 What is Java bytecode? javap -c bin/com/example/qcon/mains/printmessage public void print(); Code: 0: new #38 // class java/lang/stringbuilder 3: dup 4: invokespecial #40 // Method java/lang/ StringBuilder."<init>":()V 7: astore_1 8: aload_1 9: ldc #41 // String A call was made to method \" 11: invokevirtual #43 // Method java/lang/ StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 14: pop 15: aload_1 16: aload_0 17: getfield #14 // Field methodname:ljava/lang/string; 20: invokevirtual #43 // Method java/lang/ StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;...

122 What is Java bytecode? each line represents one JVM instruction public void print(); Code: 0: new #38 // class java/lang/stringbuilder 3: dup 4: invokespecial #40 // Method java/lang/ StringBuilder."<init>":()V 7: astore_1 8: aload_1 9: ldc #41 // String A call was made to method \" 11: invokevirtual #43 // Method java/lang/ StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 14: pop 15: aload_1 16: aload_0 17: getfield #14 // Field methodname:ljava/lang/string; 20: invokevirtual #43 // Method java/lang/ StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;...

123 What is Java bytecode? JVM instruction = 1 opcode with 0 or more operands public void print(); Code: 0: new #38 // class java/lang/stringbuilder 3: dup 4: invokespecial #40 // Method java/lang/ StringBuilder."<init>":()V 7: astore_1 8: aload_1 9: ldc #41 // String A call was made to method \" 11: invokevirtual #43 // Method java/lang/ StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 14: pop 15: aload_1 16: aload_0 17: getfield #14 // Field methodname:ljava/lang/string; 20: invokevirtual #43 // Method java/lang/ StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;...

124 What is Java bytecode? Opcode load store lcd return invokevirtual invokespecial Description load a reference onto the stack from a local variable iload, lload, fload, dload, aload stores a value from the stack into a local variable istore, lstore, fstore, dstore, astore push a constant from a constant pool onto the stack method return instruction ireturn, lreturn, freturn, dreturn, areturn, return invoke an instance method on an object invokes an instance method requiring special handling such as an initialization method See the spec for more info:

125 What is Java bytecode? Opcode invokestatic athrow new newarray if<cond> dup Description invoke a class (static) method on a named class throws an exception create a new class create a new array branch if int comparison with 0 succeeds ifeq, ifne, iflt, ifge, ifgt, ifle duplicate the top operand stack value See the spec for more info:

126 What is Java bytecode?

127 What is Java bytecode?

128 What is Java bytecode?

129 lets code public void visitcode() { if (isannotationpresent) { // create string builder mv.visitfieldinsn(opcodes.getstatic, "java/lang/system", "out", "Ljava/io/PrintStream;"); mv.visittypeinsn(opcodes.new, "java/lang/stringbuilder"); mv.visitinsn(opcodes.dup);... // add everything to the string builder mv.visitldcinsn("a call was made to method \""); mv.visitmethodinsn(opcodes.invokespecial, "java/lang/stringbuilder", "<init>", "(Ljava/lang/String;)V", false); mv.visitldcinsn(methodname); mv.visitmethodinsn(opcodes.invokevirtual, "java/lang/stringbuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false);

130 ASM Positives Speed and Size Decent documentation Depth of Functionality Number of people using framework Negatives Need to write actual byte code longer developer ramp-up

131 Why learn about Java bytecode manipulation frameworks? program analysis find bugs in code examine code complexity generate classes proxies remove access to certain APIs compiler for another language like Scala transform classes without Java source code profilers optimization and obfuscation additional logging

132 Bytecode Manipulation Frameworks ASM: BCEL: CGLib: Javassist: Serp: Cojen: Soot:

133 Make bytecode manipulation frameworks your friend. They might save your job one day. Source:

134

135 Questions? Source:

Program Dynamic Analysis. Overview

Program Dynamic Analysis. Overview Program Dynamic Analysis Overview Dynamic Analysis JVM & Java Bytecode [2] A Java bytecode engineering library: ASM [1] 2 1 What is dynamic analysis? [3] The investigation of the properties of a running

More information

3/15/18. Overview. Program Dynamic Analysis. What is dynamic analysis? [3] Why dynamic analysis? Why dynamic analysis? [3]

3/15/18. Overview. Program Dynamic Analysis. What is dynamic analysis? [3] Why dynamic analysis? Why dynamic analysis? [3] Overview Program Dynamic Analysis Dynamic Analysis JVM & Java Bytecode [2] A Java bytecode engineering library: ASM [1] 2 What is dynamic analysis? [3] The investigation of the properties of a running

More information

The Dark Sides of Integration. Anton Arhipov JRebel,

The Dark Sides of Integration. Anton Arhipov JRebel, The Dark Sides of Integration Anton Arhipov JRebel, ZeroTurnaround @antonarhipov Observe results Make a change Build, deploy, wait Where the time goes? Where the time goes? Build Container start Just don

More information

Bytecode Manipulation with a Java Agent and Byte Buddy. Koichi Sakata PONOS Corporation

Bytecode Manipulation with a Java Agent and Byte Buddy. Koichi Sakata PONOS Corporation Bytecode Manipulation with a Java Agent and Byte Buddy Koichi Sakata PONOS Corporation 2 About Me Koichi Sakata ( ) KanJava JUG Leader Java Champion PONOS Corporation 3 4 Intended Audience Those who want

More information

JVML Instruction Set. How to get more than 256 local variables! Method Calls. Example. Method Calls

JVML Instruction Set. How to get more than 256 local variables! Method Calls. Example. Method Calls CS6: Program and Data Representation University of Virginia Computer Science Spring 006 David Evans Lecture 8: Code Safety and Virtual Machines (Duke suicide picture by Gary McGraw) pushing constants JVML

More information

Course Overview. PART I: overview material. PART II: inside a compiler. PART III: conclusion

Course Overview. PART I: overview material. PART II: inside a compiler. PART III: conclusion Course Overview PART I: overview material 1 Introduction (today) 2 Language Processors (basic terminology, tombstone diagrams, bootstrapping) 3 The architecture of a Compiler PART II: inside a compiler

More information

JVM. What This Topic is About. Course Overview. Recap: Interpretive Compilers. Abstract Machines. Abstract Machines. Class Files and Class File Format

JVM. What This Topic is About. Course Overview. Recap: Interpretive Compilers. Abstract Machines. Abstract Machines. Class Files and Class File Format Course Overview What This Topic is About PART I: overview material 1 Introduction 2 Language processors (tombstone diagrams, bootstrapping) 3 Architecture of a compiler PART II: inside a compiler 4 Syntax

More information

The Java Virtual Machine. CSc 553. Principles of Compilation. 3 : The Java VM. Department of Computer Science University of Arizona

The Java Virtual Machine. CSc 553. Principles of Compilation. 3 : The Java VM. Department of Computer Science University of Arizona The Java Virtual Machine CSc 553 Principles of Compilation 3 : The Java VM Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2011 Christian Collberg The Java VM has gone

More information

Let s make some Marc R. Hoffmann Eclipse Summit Europe

Let s make some Marc R. Hoffmann Eclipse Summit Europe Let s make some Marc R. Hoffmann Eclipse Summit Europe 2012 24.10.2012 public class WhatIsFaster { int i; void inc1() { i = i + 1; } void inc2() { i += 1; } void inc3() { i++; } } Why? Compilers Scrip;ng

More information

Why GC is eating all my CPU? Aprof - Java Memory Allocation Profiler Roman Elizarov, Devexperts Joker Conference, St.

Why GC is eating all my CPU? Aprof - Java Memory Allocation Profiler Roman Elizarov, Devexperts Joker Conference, St. Why GC is eating all my CPU? Aprof - Java Memory Allocation Profiler Roman Elizarov, Devexperts Joker Conference, St. Petersburg, 2014 Java Memory Allocation Profiler Why it is needed? When to use it?

More information

Michael Rasmussen ZeroTurnaround

Michael Rasmussen ZeroTurnaround Michael Rasmussen ZeroTurnaround Terminology ASM basics Generating bytecode Simple examples Your examples? Lately I ve been, I ve been losing sleep, dreaming about the things that we could be Binary names

More information

Java Instrumentation for Dynamic Analysis

Java Instrumentation for Dynamic Analysis Java Instrumentation for Dynamic Analysis and Michael Ernst MIT CSAIL Page 1 Java Instrumentation Approaches Instrument source files Java Debug Interface (JDI) Instrument class files Page 2 Advantages

More information

Compiling Techniques

Compiling Techniques Lecture 10: Introduction to 10 November 2015 Coursework: Block and Procedure Table of contents Introduction 1 Introduction Overview Java Virtual Machine Frames and Function Call 2 JVM Types and Mnemonics

More information

Improving Java Code Performance. Make your Java/Dalvik VM happier

Improving Java Code Performance. Make your Java/Dalvik VM happier Improving Java Code Performance Make your Java/Dalvik VM happier Agenda - Who am I - Java vs optimizing compilers - Java & Dalvik - Examples - Do & dont's - Tooling Who am I? (Mobile) Software Engineering

More information

CS2110 Fall 2011 Lecture 25. Under the Hood: The Java Virtual Machine, Part II

CS2110 Fall 2011 Lecture 25. Under the Hood: The Java Virtual Machine, Part II CS2110 Fall 2011 Lecture 25 Under the Hood: The Java Virtual Machine, Part II 1 Java program last time Java compiler Java bytecode (.class files) Compile for platform with JIT Interpret with JVM run native

More information

Run-time Program Management. Hwansoo Han

Run-time Program Management. Hwansoo Han Run-time Program Management Hwansoo Han Run-time System Run-time system refers to Set of libraries needed for correct operation of language implementation Some parts obtain all the information from subroutine

More information

Java Class Loading and Bytecode Verification

Java Class Loading and Bytecode Verification Java Class Loading and Bytecode Verification Every object is a member of some class. The Class class: its members are the (definitions of) various classes that the JVM knows about. The classes can be dynamically

More information

Improving Java Performance

Improving Java Performance Improving Java Performance #perfmatters Raimon Ràfols ...or the mumbo-jumbo behind the java compiler Agenda - Disclaimer - Who am I? - Our friend the java compiler - Language additions & things to consider

More information

Compiler construction 2009

Compiler construction 2009 Compiler construction 2009 Lecture 2 Code generation 1: Generating Jasmin code JVM and Java bytecode Jasmin Naive code generation The Java Virtual Machine Data types Primitive types, including integer

More information

Programming Language Systems

Programming Language Systems Programming Language Systems Instructors: Taiichi Yuasa and Masahiro Yasugi Course Description (overview, purpose): The course provides an introduction to run-time mechanisms such as memory allocation,

More information

Taming the Java Virtual Machine. Li Haoyi, Chicago Scala Meetup, 19 Apr 2017

Taming the Java Virtual Machine. Li Haoyi, Chicago Scala Meetup, 19 Apr 2017 Taming the Java Virtual Machine Li Haoyi, Chicago Scala Meetup, 19 Apr 2017 Who Am I? Previously: Dropbox Engineering Currently: Bright Technology Services - Data Science, Scala consultancy Fluent Code

More information

Mnemonics Type-Safe Bytecode Generation in Scala

Mnemonics Type-Safe Bytecode Generation in Scala Mnemonics Type-Safe Bytecode Generation in Scala Johannes Rudolph CleverSoft GmbH, Munich Peter Thiemann Albert-Ludwigs-Universität Freiburg, Germany Scala Days 2010, Lausanne, 15.04.2010 Existing bytecode

More information

Bytecode Manipulation Techniques for Dynamic Applications for the Java Virtual Machine

Bytecode Manipulation Techniques for Dynamic Applications for the Java Virtual Machine Bytecode Manipulation Techniques for Dynamic Applications for the Java Virtual Machine Eugene Kuleshov, Terracotta Tim Eck, Terracotta Tom Ware, Oracle Corporation Charles Nutter, Sun Microsystems, Inc.

More information

CSE P 501 Compilers. Java Implementation JVMs, JITs &c Hal Perkins Winter /11/ Hal Perkins & UW CSE V-1

CSE P 501 Compilers. Java Implementation JVMs, JITs &c Hal Perkins Winter /11/ Hal Perkins & UW CSE V-1 CSE P 501 Compilers Java Implementation JVMs, JITs &c Hal Perkins Winter 2008 3/11/2008 2002-08 Hal Perkins & UW CSE V-1 Agenda Java virtual machine architecture.class files Class loading Execution engines

More information

Scala Benchmark: Invariant Verifier

Scala Benchmark: Invariant Verifier Scala Benchmark: Invariant Verifier Optional Semester Project Pamela Delgado ***** Supervisor: Aleksandar Prokopec Professor: Martin Odersky Programming Methods Laboratory LAMP, EPFL Lausanne, Switzerland

More information

Agenda. CSE P 501 Compilers. Java Implementation Overview. JVM Architecture. JVM Runtime Data Areas (1) JVM Data Types. CSE P 501 Su04 T-1

Agenda. CSE P 501 Compilers. Java Implementation Overview. JVM Architecture. JVM Runtime Data Areas (1) JVM Data Types. CSE P 501 Su04 T-1 Agenda CSE P 501 Compilers Java Implementation JVMs, JITs &c Hal Perkins Summer 2004 Java virtual machine architecture.class files Class loading Execution engines Interpreters & JITs various strategies

More information

Static Analysis of Dynamic Languages. Jennifer Strater

Static Analysis of Dynamic Languages. Jennifer Strater Static Analysis of Dynamic Languages Jennifer Strater 2017-06-01 Table of Contents Introduction............................................................................... 1 The Three Compiler Options...............................................................

More information

02 B The Java Virtual Machine

02 B The Java Virtual Machine 02 B The Java Virtual Machine CS1102S: Data Structures and Algorithms Martin Henz January 22, 2010 Generated on Friday 22 nd January, 2010, 09:46 CS1102S: Data Structures and Algorithms 02 B The Java Virtual

More information

How do you create a programming language for the JVM?

How do you create a programming language for the JVM? How do you create a programming language for the JVM? Federico Tomassetti.com Hi, I am Federico!Got a PhD in Language Engineering!Lived here and there Ora sono un Language En Progetto e co! Parser! Interpr!

More information

Java Code Coverage Mechanics

Java Code Coverage Mechanics at by Evgeny Mandrikov Java Code Coverage Mechanics #DevoxxFR Evgeny Mandrikov @_Godin_.com/Godin one of JaCoCo and Eclipse EclEmma Project Leads Disclaimer /* TODO don't forget to add huge disclaimer

More information

The Java Virtual Machine

The Java Virtual Machine Virtual Machines in Compilation Abstract Syntax Tree Compilation 2007 The compile Virtual Machine Code interpret compile Native Binary Code Michael I. Schwartzbach BRICS, University of Aarhus 2 Virtual

More information

Space Exploration EECS /25

Space Exploration EECS /25 1/25 Space Exploration EECS 4315 www.eecs.yorku.ca/course/4315/ Nondeterminism 2/25 Nondeterministic code is code that, even for the same input, can exhibit different behaviours on different runs, as opposed

More information

Implement detection of duplicate test coverage for Java applications

Implement detection of duplicate test coverage for Java applications Masaryk University Faculty of Informatics Implement detection of duplicate test coverage for Java applications Bachelor s Thesis Jakub Schwan Brno, Spring 2018 Replace this page with a copy of the official

More information

invokedynamic IN 45 MINUTES!!! Wednesday, February 6, 13

invokedynamic IN 45 MINUTES!!! Wednesday, February 6, 13 invokedynamic IN 45 MINUTES!!! Me Charles Oliver Nutter headius@headius.com, @headius blog.headius.com JRuby Guy at Sun, Engine Yard, Red Hat JVM enthusiast, educator, contributor Earliest adopter of invokedynamic

More information

Under the Hood: The Java Virtual Machine. Lecture 23 CS2110 Fall 2008

Under the Hood: The Java Virtual Machine. Lecture 23 CS2110 Fall 2008 Under the Hood: The Java Virtual Machine Lecture 23 CS2110 Fall 2008 Compiling for Different Platforms Program written in some high-level language (C, Fortran, ML,...) Compiled to intermediate form Optimized

More information

COMP3131/9102: Programming Languages and Compilers

COMP3131/9102: Programming Languages and Compilers COMP3131/9102: Programming Languages and Compilers Jingling Xue School of Computer Science and Engineering The University of New South Wales Sydney, NSW 2052, Australia http://www.cse.unsw.edu.au/~cs3131

More information

Java Code Coverage Mechanics. by Evgeny Mandrikov at EclipseCon Europe 2017

Java Code Coverage Mechanics. by Evgeny Mandrikov at EclipseCon Europe 2017 Java Code Coverage Mechanics by Evgeny Mandrikov at EclipseCon Europe 2017 Evgeny Mandrikov @_Godin_ Godin Marc Hoffmann @marcandsweep marchof JaCoCo and Eclipse EclEmma Project Leads /* TODO Don't forget

More information

Recap: Printing Trees into Bytecodes

Recap: Printing Trees into Bytecodes Recap: Printing Trees into Bytecodes To evaluate e 1 *e 2 interpreter evaluates e 1 evaluates e 2 combines the result using * Compiler for e 1 *e 2 emits: code for e 1 that leaves result on the stack,

More information

Java Code Coverage Mechanics Evgeny Mandrikov Marc Hoffmann #JokerConf 2017, Saint-Petersburg

Java Code Coverage Mechanics Evgeny Mandrikov Marc Hoffmann #JokerConf 2017, Saint-Petersburg Java Code Coverage Mechanics Evgeny Mandrikov Marc Hoffmann #JokerConf 2017, Saint-Petersburg Evgeny Mandrikov @_Godin_ Godin Marc Hoffmann @marcandsweep marchof JaCoCo and Eclipse EclEmma Project Leads

More information

Exercise 7 Bytecode Verification self-study exercise sheet

Exercise 7 Bytecode Verification self-study exercise sheet Concepts of ObjectOriented Programming AS 2018 Exercise 7 Bytecode Verification selfstudy exercise sheet NOTE: There will not be a regular exercise session on 9th of November, because you will take the

More information

Problem: Too Many Platforms!

Problem: Too Many Platforms! Compiling for Different Platforms 2 Program written in some high-level language (C, Fortran, ML,...) Compiled to intermediate form Optimized UNDE THE HOOD: THE JAVA VITUAL MACHINE Code generated for various

More information

Understand Every Line of Your Codebase

Understand Every Line of Your Codebase Understand Every Line of Your Codebase Victoria Gonda Boris Farber Speakers Victoria Developer at Collective Idea Android and Rails Boris Partner Engineer at Google Android Partnerships Android and Java

More information

The Java Language Implementation

The Java Language Implementation CS 242 2012 The Java Language Implementation Reading Chapter 13, sections 13.4 and 13.5 Optimizing Dynamically-Typed Object-Oriented Languages With Polymorphic Inline Caches, pages 1 5. Outline Java virtual

More information

Java Security. Compiler. Compiler. Hardware. Interpreter. The virtual machine principle: Abstract Machine Code. Source Code

Java Security. Compiler. Compiler. Hardware. Interpreter. The virtual machine principle: Abstract Machine Code. Source Code Java Security The virtual machine principle: Source Code Compiler Abstract Machine Code Abstract Machine Code Compiler Concrete Machine Code Input Hardware Input Interpreter Output 236 Java programs: definitions

More information

Under the Hood: The Java Virtual Machine. Problem: Too Many Platforms! Compiling for Different Platforms. Compiling for Different Platforms

Under the Hood: The Java Virtual Machine. Problem: Too Many Platforms! Compiling for Different Platforms. Compiling for Different Platforms Compiling for Different Platforms Under the Hood: The Java Virtual Machine Program written in some high-level language (C, Fortran, ML, ) Compiled to intermediate form Optimized Code generated for various

More information

CSc 372 Comparative Programming Languages. Getting started... Getting started. B: Java Bytecode BCEL

CSc 372 Comparative Programming Languages. Getting started... Getting started. B: Java Bytecode BCEL BCEL CSc 372 Comparative Programming Languages B: Java Bytecode BCEL BCEL (formerly JavaClass) allows you to load a class, iterate through the methods and fields, change methods, add new methods and fields,

More information

Over-view. CSc Java programs. Java programs. Logging on, and logging o. Slides by Michael Weeks Copyright Unix basics. javac.

Over-view. CSc Java programs. Java programs. Logging on, and logging o. Slides by Michael Weeks Copyright Unix basics. javac. Over-view CSc 3210 Slides by Michael Weeks Copyright 2015 Unix basics javac java.j files javap 1 2 jasmin converting from javap to jasmin classfile structure calling methods adding line numbers Java programs

More information

CS263: Runtime Systems Lecture: High-level language virtual machines. Part 1 of 2. Chandra Krintz UCSB Computer Science Department

CS263: Runtime Systems Lecture: High-level language virtual machines. Part 1 of 2. Chandra Krintz UCSB Computer Science Department CS263: Runtime Systems Lecture: High-level language virtual machines Part 1 of 2 Chandra Krintz UCSB Computer Science Department Portable, Mobile, OO Execution Model Execution model embodied by recent

More information

CSc 620 Debugging, Profiling, Tracing, and Visualizing Programs. Getting started... Getting started. 2 : Java Bytecode BCEL

CSc 620 Debugging, Profiling, Tracing, and Visualizing Programs. Getting started... Getting started. 2 : Java Bytecode BCEL BCEL CSc 620 Debugging, Profiling, Tracing, and Visualizing Programs 2 : Java Bytecode BCEL BCEL (formerly JavaClass) allows you to load a class, iterate through the methods and fields, change methods,

More information

CSc 620 Debugging, Profiling, Tracing, and Visualizing Programs

CSc 620 Debugging, Profiling, Tracing, and Visualizing Programs CSc 620 Debugging, Profiling, Tracing, and Visualizing Programs 2 : Java Bytecode BCEL Christian Collberg Department of Computer Science University of Arizona collberg+620@gmail.com Copyright c 2005Christian

More information

Java byte code verification

Java byte code verification Java byte code verification SOS Master Science Informatique U. Rennes 1 Thomas Jensen SOS Java byte code verification 1 / 26 Java security architecture Java: programming applications with code from different

More information

Compiling for Different Platforms. Problem: Too Many Platforms! Dream: Platform Independence. Java Platform 5/3/2011

Compiling for Different Platforms. Problem: Too Many Platforms! Dream: Platform Independence. Java Platform 5/3/2011 CS/ENGD 2110 Object-Oriented Programming and Data Structures Spring 2011 Thorsten Joachims Lecture 24: Java Virtual Machine Compiling for Different Platforms Program written in some high-level language

More information

Today. Instance Method Dispatch. Instance Method Dispatch. Instance Method Dispatch 11/29/11. today. last time

Today. Instance Method Dispatch. Instance Method Dispatch. Instance Method Dispatch 11/29/11. today. last time CS2110 Fall 2011 Lecture 25 Java program last time Java compiler Java bytecode (.class files) Compile for platform with JIT Interpret with JVM Under the Hood: The Java Virtual Machine, Part II 1 run native

More information

SOFTWARE ARCHITECTURE 7. JAVA VIRTUAL MACHINE

SOFTWARE ARCHITECTURE 7. JAVA VIRTUAL MACHINE 1 SOFTWARE ARCHITECTURE 7. JAVA VIRTUAL MACHINE Tatsuya Hagino hagino@sfc.keio.ac.jp slides URL https://vu5.sfc.keio.ac.jp/sa/ Java Programming Language Java Introduced in 1995 Object-oriented programming

More information

Tutorial 3: Code Generation

Tutorial 3: Code Generation S C I E N C E P A S S I O N T E C H N O L O G Y Tutorial 3: Code Generation Univ.-Prof. Dr. Franz Wotawa, DI Roxane Koitz, Stephan Frühwirt, Christopher Liebmann, Martin Zimmermann Institute for Software

More information

Java and C II. CSE 351 Spring Instructor: Ruth Anderson

Java and C II. CSE 351 Spring Instructor: Ruth Anderson Java and C II CSE 351 Spring 2017 Instructor: Ruth Anderson Teaching Assistants: Dylan Johnson Kevin Bi Linxing Preston Jiang Cody Ohlsen Yufang Sun Joshua Curtis Administrivia Lab 5 Due TONIGHT! Fri 6/2

More information

CSE 431S Final Review. Washington University Spring 2013

CSE 431S Final Review. Washington University Spring 2013 CSE 431S Final Review Washington University Spring 2013 What You Should Know The six stages of a compiler and what each stage does. The input to and output of each compilation stage (especially the back-end).

More information

Java 1.6 Annotations ACCU Tony Barrett-Powell

Java 1.6 Annotations ACCU Tony Barrett-Powell Java 1.6 Annotations ACCU 2007 Tony Barrett-Powell tony.barrett-powell@oracle.com Introduction An exploration of Java annotations Concepts what are annotations? Java 1.6 changes related to annotations

More information

CSC 4181 Handout : JVM

CSC 4181 Handout : JVM CSC 4181 Handout : JVM Note: This handout provides you with the basic information about JVM. Although we tried to be accurate about the description, there may be errors. Feel free to check your compiler

More information

Advanced Programming Introduction

Advanced Programming Introduction Advanced Programming Introduction Course Description The Goal The Motivation Lectures and Assignments Programming Platform Resources Evaluation Lab: problems, projects, essays easy Exam: written test hard

More information

JSR 292 backport. (Rémi Forax) University Paris East

JSR 292 backport. (Rémi Forax) University Paris East JSR 292 backport (Rémi Forax) University Paris East Interactive talk Ask your question when you want Just remember : Use only verbs understandable by a 4 year old kid Use any technical words you want A

More information

Advances in Programming Languages: Generics, interoperability and implementation

Advances in Programming Languages: Generics, interoperability and implementation Advances in Programming Languages: Generics, interoperability and implementation Stephen Gilmore The University of Edinburgh February 1, 2007 Understanding generic code Generic Java extends Java with generic

More information

Run-time Performance Testing in Java

Run-time Performance Testing in Java Charles University in Prague Faculty of Mathematics and Physics MASTER THESIS Jaroslav Kotrč Run-time Performance Testing in Java Department of Distributed and Dependable Systems Supervisor of the master

More information

JAM 16: The Instruction Set & Sample Programs

JAM 16: The Instruction Set & Sample Programs JAM 16: The Instruction Set & Sample Programs Copyright Peter M. Kogge CSE Dept. Univ. of Notre Dame Jan. 8, 1999, modified 4/4/01 Revised to 16 bits: Dec. 5, 2007 JAM 16: 1 Java Terms Java: A simple,

More information

CSc 620 Debugging, Profiling, Tracing, and Visualizing Programs. Compiling Java. The Java Class File Format 1 : JVM

CSc 620 Debugging, Profiling, Tracing, and Visualizing Programs. Compiling Java. The Java Class File Format 1 : JVM Attributes Execute The Java Virtual Machine CSc 620 Debugging, Profiling, Tracing, and Visualizing Programs 1 : JVM Christian Collberg collberg+620@gmail.com The Java VM has gone the many complex instructions/large

More information

javac 29: pop 30: iconst_0 31: istore_3 32: jsr [label_51]

javac 29: pop 30: iconst_0 31: istore_3 32: jsr [label_51] Analyzing Control Flow in Java Bytecode Jianjun Zhao Department of Computer Science and Engineering Fukuoka Institute of Technology 3-10-1 Wajiro-Higashi, Higashi-ku, Fukuoka 811-02, Japan zhao@cs.t.ac.jp

More information

Chapter 5. A Closer Look at Instruction Set Architectures. Chapter 5 Objectives. 5.1 Introduction. 5.2 Instruction Formats

Chapter 5. A Closer Look at Instruction Set Architectures. Chapter 5 Objectives. 5.1 Introduction. 5.2 Instruction Formats Chapter 5 Objectives Understand the factors involved in instruction set architecture design. Chapter 5 A Closer Look at Instruction Set Architectures Gain familiarity with memory addressing modes. Understand

More information

301AA - Advanced Programming [AP-2017]

301AA - Advanced Programming [AP-2017] 301AA - Advanced Programming [AP-2017] Lecturer: Andrea Corradini andrea@di.unipi.it Tutor: Lillo GalleBa galleba@di.unipi.it Department of Computer Science, Pisa Academic Year 2017/18 AP-2017-05: The

More information

Chapter 5. A Closer Look at Instruction Set Architectures

Chapter 5. A Closer Look at Instruction Set Architectures Chapter 5 A Closer Look at Instruction Set Architectures Chapter 5 Objectives Understand the factors involved in instruction set architecture design. Gain familiarity with memory addressing modes. Understand

More information

COMP3131/9102: Programming Languages and Compilers

COMP3131/9102: Programming Languages and Compilers COMP3131/9102: Programming Languages and Compilers Jingling Xue School of Computer Science and Engineering The University of New South Wales Sydney, NSW 2052, Australia http://www.cse.unsw.edu.au/~cs3131

More information

Building a Compiler with. JoeQ. Outline of this lecture. Building a compiler: what pieces we need? AKA, how to solve Homework 2

Building a Compiler with. JoeQ. Outline of this lecture. Building a compiler: what pieces we need? AKA, how to solve Homework 2 Building a Compiler with JoeQ AKA, how to solve Homework 2 Outline of this lecture Building a compiler: what pieces we need? An effective IR for Java joeq Homework hints How to Build a Compiler 1. Choose

More information

Joeq Analysis Framework. CS 243, Winter

Joeq Analysis Framework. CS 243, Winter Joeq Analysis Framework CS 243, Winter 2009-2010 Joeq Background Compiler backend for analyzing and optimizing Java bytecode Developed by John Whaley and others Implemented in Java Research project infrastructure:

More information

Compiling Faster, Compiling Better with Falcon. Iván

Compiling Faster, Compiling Better with Falcon. Iván Compiling Faster, Compiling Better with Falcon Iván Krȳlov @JohnWings Compiling Faster, Compiling Better with Falcon Overview of 3 technologies Falcon compiler ReadyNow & Compile Stashing Challenges (largely

More information

LINGI2252 PROF. KIM MENS REFLECTION (IN JAVA)*

LINGI2252 PROF. KIM MENS REFLECTION (IN JAVA)* LINGI2252 PROF. KIM MENS REFLECTION (IN JAVA)* * These slides are part of the course LINGI2252 Software Maintenance and Evolution, given by Prof. Kim Mens at UCL, Belgium Lecture 10 a Basics of Reflection

More information

Introduction Basic elements of Java

Introduction Basic elements of Java Software and Programming I Introduction Basic elements of Java Roman Kontchakov / Carsten Fuhs Birkbeck, University of London Module Information Time: Thursdays in the Spring term Lectures: MAL B04: 2

More information

An Introduction to Multicodes. Ben Stephenson Department of Computer Science University of Western Ontario

An Introduction to Multicodes. Ben Stephenson Department of Computer Science University of Western Ontario An Introduction to Multicodes Ben Stephenson Department of Computer Science University of Western Ontario ben@csd csd.uwo.ca Outline Java Virtual Machine Background The Current State of the Multicode Art

More information

The Future of Code Coverage for Eclipse

The Future of Code Coverage for Eclipse Marc R. Hoffmann EclipseCon 2010 2010-03-25 2010 by Marc R. Hoffmann made available under the EPL v1.0 2010-03-25 Outline Code Coverage EclEmma EMMA JaCoCo Sorry, no robots Code Coverage Legacy Code is

More information

COMP 520 Fall 2009 Virtual machines (1) Virtual machines

COMP 520 Fall 2009 Virtual machines (1) Virtual machines COMP 520 Fall 2009 Virtual machines (1) Virtual machines COMP 520 Fall 2009 Virtual machines (2) Compilation and execution modes of Virtual machines: Abstract syntax trees Interpreter AOT-compile Virtual

More information

JoeQ Framework CS243, Winter 20156

JoeQ Framework CS243, Winter 20156 Overview Java Intermediate representation JoeQ Framework CS243, Winter 20156 Bytecode JoeQ Framework Quads: Instruction set used in JoeQ JoeQ constructs Writing analysis in JoeQ HW 2 Typical Compiler Infrastructure

More information

Compilation 2012 Code Generation

Compilation 2012 Code Generation Compilation 2012 Jan Midtgaard Michael I. Schwartzbach Aarhus University Phases Computing resources, such as: layout of data structures offsets register allocation Generating an internal representation

More information

Roadmap. Java: Assembly language: OS: Machine code: Computer system:

Roadmap. Java: Assembly language: OS: Machine code: Computer system: Roadmap C: car *c = malloc(sizeof(car)); c->miles = 100; c->gals = 17; float mpg = get_mpg(c); free(c); Assembly language: Machine code: Computer system: get_mpg: pushq movq... popq ret %rbp %rsp, %rbp

More information

Java: framework overview and in-the-small features

Java: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO)

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO) Outline stacks stack ADT method signatures array stack implementation linked stack implementation stack applications infix, prefix, and postfix expressions 1 Stacks stacks of dishes or trays in a cafeteria

More information

CSCE 314 Programming Languages

CSCE 314 Programming Languages CSCE 314 Programming Languages! JVM Dr. Hyunyoung Lee 1 Java Virtual Machine and Java The Java Virtual Machine (JVM) is a stack-based abstract computing machine. JVM was designed to support Java -- Some

More information

JSR 292 Cookbook: Fresh Recipes with New Ingredients

JSR 292 Cookbook: Fresh Recipes with New Ingredients JSR 292 Cookbook: Fresh Recipes with New Ingredients John Rose Christian Thalinger Sun Microsystems Overview Got a language cooking on the JVM? JSR 292, a set of major changes to the JVM architecture,

More information

Selected Questions from by Nageshwara Rao

Selected Questions from  by Nageshwara Rao Selected Questions from http://way2java.com by Nageshwara Rao Swaminathan J Amrita University swaminathanj@am.amrita.edu November 24, 2016 Swaminathan J (Amrita University) way2java.com (Nageshwara Rao)

More information

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline Java Intro 3 9/7/2007 1 Java Intro 3 Outline Java API Packages Access Rules, Class Visibility Strings as Objects Wrapper classes Static Attributes & Methods Hello World details 9/7/2007 2 Class Libraries

More information

Copyright 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 16

Copyright 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 16 1 Copyright 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 16 Towards JVM Dynamic Languages Toolchain Insert Picture Here Attila

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

Chapter 5. A Closer Look at Instruction Set Architectures. Chapter 5 Objectives. 5.1 Introduction. 5.2 Instruction Formats

Chapter 5. A Closer Look at Instruction Set Architectures. Chapter 5 Objectives. 5.1 Introduction. 5.2 Instruction Formats Chapter 5 Objectives Chapter 5 A Closer Look at Instruction Set Architectures Understand the factors involved in instruction set architecture design. Gain familiarity with memory addressing modes. Understand

More information

Chapter 5. A Closer Look at Instruction Set Architectures

Chapter 5. A Closer Look at Instruction Set Architectures Chapter 5 A Closer Look at Instruction Set Architectures Chapter 5 Objectives Understand the factors involved in instruction set architecture design. Gain familiarity with memory addressing modes. Understand

More information

Class, Variable, Constructor, Object, Method Questions

Class, Variable, Constructor, Object, Method Questions Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx

More information

/* Copyright 2012 Robert C. Ilardi

/* Copyright 2012 Robert C. Ilardi / Copyright 2012 Robert C. Ilardi Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

Bugs in software. Using Static Analysis to Find Bugs. David Hovemeyer

Bugs in software. Using Static Analysis to Find Bugs. David Hovemeyer Bugs in software Programmers are smart people We have good techniques for finding bugs early: Unit testing, pair programming, code inspections So, most bugs should be subtle, and require sophisticated

More information

Simple Data Source Crawler Plugin to Set the Document Title

Simple Data Source Crawler Plugin to Set the Document Title Simple Data Source Crawler Plugin to Set the Document Title IBM Content Analytics 1 Contents Introduction... 4 Basic FS Crawler behavior.... 8 Using the Customizer Filter to Modify the title Field... 13

More information

Secure Method Calls by Instrumenting Bytecode with Aspects

Secure Method Calls by Instrumenting Bytecode with Aspects Secure Method Calls by Instrumenting Bytecode with Aspects Xiaofeng Yang and Mohammad Zulkernine School of Computing, Queen s University Kingston, Ontario, Canada, K7L 3N6 {yang, mzulker}@cs.queensu.ca

More information

LaboratoriodiProgrammazione III

LaboratoriodiProgrammazione III LaboratoriodiProgrammazione III Lezione 15: Portabilità e Sicurezza, Java Massimo Tivoli Origins of the language James Gosling and others at Sun, 1990 95 Oak language for set top box small networked device

More information

Making Java more dynamic: runtime code generation for the JVM

Making Java more dynamic: runtime code generation for the JVM Making Java more dynamic: runtime code generation for the JVM The talk was way too high-level. I wish the speaker would have explained more technical details! This was way too low-level. I did not understand

More information