Advice Weaving in AspectJ Alex Gontmakher. Outline Possible implementation approaches Quick JVM primer AJC implementation Performance Evaluation.

Slides:



Advertisements
Similar presentations
AspectWerkz 2 - and the road to AspectJ 5 Jonas Bonér Senior Software Engineer BEA Systems.
Advertisements

Eclipse TPTP TPTP Heap and Thread Profilers High-level Design Rev 1.0 Asaf Yaffe July, 2006.
Chapter 16 Java Virtual Machine. To compile a java program in Simple.java, enter javac Simple.java javac outputs Simple.class, a file that contains bytecode.
Virtual Machines Matthew Dwyer 324E Nichols Hall
1 Lecture 10 Intermediate Representations. 2 front end »produces an intermediate representation (IR) for the program. optimizer »transforms the code in.
Compilation 2007 Code Generation Michael I. Schwartzbach BRICS, University of Aarhus.
Java Virtual Machine (JVM). Lecture Objectives Learn about the Java Virtual Machine (JVM) Understand the functionalities of the class loader subsystem.
1 1 Lecture 14 Java Virtual Machine Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
Advice Weaving in AspectJ Paper by Erik Hilsdale Jim Hugunin Presented by Shay Cohen.
Overview of AspectJ Aspect Oriented Software Development Seminar Technion presented by Oren Mishali.
Lab 9 Java Bytecode & The Jasmin Assembler
JVM-1 Java Virtual Machine Reading Assignment: Chapter 1: All Chapter 3: Sections.
Introduction to Java Programming
IPT Readings on Instrumentation, Profiling, and Tracing Seminar presentation by Alessandra Gorla University of Lugano December 7, 2006.
Scott Grissom, copyright 2004Ch 3: Java Features Slide 1 Why Java? It is object-oriented provides many ready to use classes platform independent modern.
Chapter 16 Java Virtual Machine. To compile a java program in Simple.java, enter javac Simple.java javac outputs Simple.class, a file that contains bytecode.
Unit 061 Java Virtual Machine (JVM) What is Java Virtual Machine? The Class Loader Subsystem Linking oVerification oPreparation oResolution Class Initialization.
COMP 14: Intro. to Intro. to Programming May 23, 2000 Nick Vallidis.
1 Memory Model of A Program, Methods Overview l Memory Model of JVM »Method Area »Heap »Stack.
Aspect-Oriented Software Development (AOSD) Tutorial #3 AspectJ - continued.
Lecture 1: Overview of Java. What is java? Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed.
Code Generation Introduction. Compiler (scalac, gcc) Compiler (scalac, gcc) machine code (e.g. x86, arm, JVM) efficient to execute i=0 while (i < 10)
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 18: 0xCAFEBABE (Java Byte Codes)
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Java Programming Robert Chatley William Lee
UNDER THE HOOD: THE JAVA VIRTUAL MACHINE Lecture 24 – CS2110 – Fall 2009.
The Java Virtual Machine 1 Course Overview PART I: overview material 1Introduction 2Language processors (tombstone diagrams, bootstrapping) 3Architecture.
Java Bytecode What is a.class file anyway? Dan Fleck George Mason University Fall 2007.
1 Module Objective & Outline Module Objective: After completing this Module, you will be able to, appreciate java as a programming language, write java.
1 Introduction to JVM Based on material produced by Bill Venners.
1 Java Bytecode Optimization Optimizing Java Bytecode for Embedded Systems Stefan Hepp.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Java Virtual Machine Case Study on the Design of JikesRVM.
Java PathFinder (JPF) cs498dm Software Testing January 19, 2012.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
AOP-1 Aspect Oriented Programming. AOP-2 Aspects of AOP and Related Tools Limitation of OO Separation of Concerns Aspect Oriented programming AspectJ.
Virtual Support for Dynamic Join Points C. Bockisch, M. Haupt, M. Mezini, K. Ostermann Presented by Itai Sharon
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Inter-Type Declarations in AspectJ Awais Rashid Steffen Zschaler © Awais Rashid, Steffen Zschaler 2009.
AspectJ – AOP for Java Tom Janofsky. Instructor at Penn State Abington Consultant with Chariot Solutions JUG Member.
CS 153: Concepts of Compiler Design November 23 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
Chap. 10, Intermediate Representations J. H. Wang Dec. 14, 2015.
Programming Languages and Paradigms Activation Records in Java.
CS216: Program and Data Representation University of Virginia Computer Science Spring 2006 David Evans Lecture 18: Code Safety and Virtual Machines
Comparison of Different AOP Approaches Presented by: Xiaojing Wang.
Chap. 10, Intermediate Representations J. H. Wang Dec. 27, 2011.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Just-In-Time Aspects Based on:  Efficient Dynamic Weaving for Java By: Andrei Popivici, Gustavo Alonso and Thomas Gross  Dynamic Aspect Oriented Infrastructure.
UNDER THE HOOD: THE JAVA VIRTUAL MACHINE II CS2110 Fall 200 Lecture 25 1.
AOP with AspectJ Awais Rashid, Steffen Zschaler © Awais Rashid, Steffen Zschaler 2009.
RealTimeSystems Lab Jong-Koo, Lim
Features of AOP languages AOP languages have the following main elements: –a join point model (JPM) wrt base PL –a specification language for expressing.
Sung-Dong Kim, Dept. of Computer Engineering, Hansung University Java - Introduction.
CS 432: Compiler Construction Lecture 15
The need for Programming Languages
Multitasking without Compromise: a Virtual Machine Evolution
The Java Virtual Machine (JVM)
CS216: Program and Data Representation
Java Primer 1: Types, Classes and Operators
Java Virtual Machine (JVM)
Aspect-Oriented Programming
CSc 453 Interpreters & Interpretation
Introduction to Algorithm Design
Lecture 19: 0xCAFEBABE (Java Byte Codes) CS201j: Engineering Software
Byte Code Verification
Course Overview PART I: overview material PART II: inside a compiler
Aspect Oriented Programming
CSc 453 Interpreters & Interpretation
Corresponds with Chapter 5
Presentation transcript:

Advice Weaving in AspectJ Alex Gontmakher

Outline Possible implementation approaches Quick JVM primer AJC implementation Performance Evaluation

Approaches to Aspect code generation Change the VM to recognize aspects Compile-time weaving of aspects Load-time weaving  Reflection

Changing the VM Can provide full support for all Aspect features Data for aspects separate from the code Not portable (generated code is not Java bytecode) Problems with the reference Java implementation  Hard to make changes to Java standard  Hard to evolve AspectJ implementation

Load-time weaving Modify the code during loading Probably can be done  Same benefits as with VM-supported aspects Potentially slow  Trade-Off between load-time and run-time  Expensive to do static analysis (optimization)

Compile time code generation Portable Fast Necessarily limited

Compile-time code generation: The problem before(): get(int Point.x) { System.out.println(“get x”); } Compiler doesn't see all the code  Code that is dynamically loaded  Code that is called through reflection

Compile-time code generation: Solution AspectJ solution: aspects apply only to code that the implementation controls Loosely speaking: all the bytecode available at compile time  Can change between implementations and versions

Compile-time code generation: The limitations Advice on field access  Accessor code must be available Advice on method and constructor call  Calling code must be available Advice on method execution  The method code must be available Etc. Limitations not met  Compile time error!

Part 2: JVM Primer

Java Virtual Machine: structure Frame 0 Frame 1 Frame 2 SP Stack (per thread) Constant Pool Class Hello method: print() method: () Class Main method: main() method: () field: int fM String “hello world” Frame 2 locals: this int i int j Param stack: System.out String … Class: Frame 1 locals: this … Param stack: Hello … Class: Heap Object Hello field: int f1 field: String f2

JVM primer: instructions 1 Arithmetic Instructions  take inputs from param stack, write results back Getting values to and from local vars Getting values to and from objects Method calls and returns Exception handling Etc.

JVM Primer: instructions 2 Arithmetic instructions  iadd: …, value1, value2  …, value1+value2 Load and store local variables  iload VAR: …  …,  iload_ : …  …,  istore VAR: …, value  … {VAR = value}  istore_ : …, value  … {VAR_n = value} Stack manipulation  dup: …, value  …, value, value

JVM primer: instructions 3 Object access  Accessing object’s fields: getfield, putfield getfield FID: …, objectref  …, value putfield FID: …, value, objectref  …  Accessing object’s static fields: getstatic, putstatic getstatic FID: …  …, value putstatic FID:..., value  …

JVM primer: instructions 4 Calling methods:  invokevirtual N:…, param1, [param2,…]  result calls Nth method of class  invokespecial N calls constructors etc.  invokestatic N  Invokeinterface N  return, ireturn, … Creating objects:  new N – allocates and inits memory.  Then, constructor must be called

JVM Primer: example int i; // An instance variable MyObj example() { MyObj o = new MyObj(); return silly(o); } MyObj silly(MyObj o) { if (o != null) { return o; } else { return o; } Method MyObj example() 0 new [Class MyObj] 3 dup 4 invokespecial [MyObj. ()] 7 astore_1 8 aload_0 9 aload_1 10 invokevirtual [silly] 13 areturn Method MyObj silly(MyObj) 0 aload_1 1 ifnull 6 4aload_1 5 areturn 6 aload_1 7 areturn

JVM primer: exception handling Exception handling  throw N: throw an exception of class N  Exception table: FROMTOClassHandler 13178

Part 3: Aspects implementation Munger Shadow Residue

AspectJ: the process Java sourceAspects source Java bytecodeAspects bytecode Java Library Aspects Library AspectJ compiler Weaver Woven program  shadows  mungers

Advice Implementation: the 4 questions WHERE- shadows WHEN- residues WHAT- the aspect code HOW- weaving

Join Point Shadows: WHERE Static code sections that potentially match a join point Example: “hello world” public static void main(String[] s) { System.out.println(“hello world”); } 0: getstatic [java/lang/System.out] 3: ldc [String “hello world”] 5: invokevirtual [java/io/Printstream.println] 8: return Field-get Target: from stack Args: none Method-call Target: From stack Args: From stack !Parameters must be stored and re-loaded Method-execution Target: this Args: local vars

Join Point Shadows: Notes Java bytecodes carry plentiful meta- information  Instructions’ intent easily recognizable  Shadow is completely defined by region of code  No need for source code! It is sometimes impossible to determine statically if aspect should be executed  residue

Advice compilation: WHAT Each advice compiles to a regular Java method  Parameters statically typed  used for matching  Advice always runs in the context of aspect instance  Additional information encoded in attributes Each residue compiles to a regular Java method

Residues: WHEN Dynamic part of the pointcut Residue types:  if Computes conditions on parameters Parameters passed if necessary  instanceof Checks type  cflow Check the stack for cflow conditions Store cflow status in the stack Each relevant join point checks the status

Residues example: if residue before(): execution(void main(*)) && if(Tracing.level == 1) { System.out.println(“here”); } 0: invokestatic [A.ajc$if_0] 3: ifeq 12 6: invokestatic [A.aspectof] 9: invokevirtual [A.ajc$before$A$a6] 12: getstatic [java/lang/System.out] 15: ldc [String “hello world”] 17: invokevirtual [java/io/Printstream.println] 20: return Residue Aspect

Residues example: instanceof before(String s): execution(void go(*)) && args(s) { System.out.println(s); } Case 1: void go(java.lang.String) { }  Advice is always called Case 2: void go(java.lang.Object) { }  Advice called only if the parameter is a String

Residues: instanceof contd void go(java/lang/Object); 0: aload_1 1: astore_2 2: aload_2 3: instanceof[String] 6: ifeq 14# skip advice 9: invokestatic[A.aspectOf] 10: aload_1 13: invokevirtual [A.ajc$before$A$a3] 16: return Residue Aspect

Residues: cflow On entry to the method, compute the cflow conditions  Store the result in a local variable  At the join point, check the variable The test is completely dynamic  Static optimization would need whole- program analysis

The Matching process 1. For each advice:  Create a shadow munger 2. For each shadow munger:  For each class: For each shadow, apply the munger [optimization] If the munger has withincode attribute, check only in that method

Weaving: HOW Expose the context  Copy stack parameters  Push local variables (for calls)  Create a JoinPoint object if necessary Reflective information on the join point: getKind(), getSignature(), getLocation(), getArgs(), …  Done once per shadow Insert the advice code  Implementation depends on advice kind  Weaving in inverse precedence order

Weaving: advice types Before advice  Advice code just inserted in the beginning of the shadow After returning advice  Call: Expose the return value Insert the code in the end of the shadow  Execution: All the return points must be captured Generate gotos into a single return point

Weaving: more advice types After throwing advice  Add a new exception handler in the enclosing method After finally advice  Combine After returning and After throwing Control flow entry advice  Same as before advice Control flow exit advice  Same as After finally advice

Weaving: more advice types Around advice  Replaces the original shadow code  If no call to proceed, just inline the advice code  If there is a call to proceed: class Closure$i extends AroundClosure { public void run() { // perform the advised code } } Create the Closure$i object and pass it as a parameter to advice Declare warning and error  Just print the message, no bytecode changes

Weaving: inlining Advice code is [almost] never inlined  Why? Because JIT does a better work.  Avoids code duplication

Aspects performance: Benchmark Xalan – XSLT processor  826 source files, 7700 methods, 144K lines of code  Measure the slowdown caused by aspects  Compare to hand-coded version public aspect Trace { private static Logger log = Logger.getLogger(“xalan”); pointcut traced(): execution(* *(..)); before(): traced() { Signature s = thisJoinPointStaticPart.getSignature(); log.entering( s.getDeclaringType().getName(), s.getname()); }

Aspects Performance: first results Logging enabled Logging disabled

Aspects performance: optimizing Avoid class.getName() if not used before() traced() { if (!log.isLoggable(Level.FINER)) return; … } Check log.isLoggable in the residue pointcut traced(): execution(* *(..)) && if (log.isLoggable(Level.FINER));  Avoids method call of the aspect Store the result of log.isLoggable() pointcut traced(): … && if (enabled) && log.isLoggable()  Faster than hand-coded version Remove the aspect altogether

Aspects performance: results Best implementation: 76% better than handcoded  Same could be done manually, but impractical

Conclusions Weaving advices in Java is easy  Rich bytecode  C++ would be much harder – certainly would require source code access! More static analysis will allow for faster code

References Advice weaving in AspectJ, Eric Hillsdale and Jim Hugunin, In Proceedings of AOSD'04 The AspectJ project homepage, The JVM Specification book,