issue_id
int64
2.03k
426k
title
stringlengths
9
251
body
stringlengths
1
32.8k
status
stringclasses
6 values
after_fix_sha
stringlengths
7
7
project_name
stringclasses
6 values
repo_url
stringclasses
6 values
repo_name
stringclasses
6 values
language
stringclasses
1 value
issue_url
null
before_fix_sha
null
pull_url
null
commit_datetime
unknown
report_datetime
unknown
updated_file
stringlengths
2
187
file_content
stringlengths
0
368k
228,633
Bug 228633 AST Support for PointcutDesignators
I would like an enhancement to be able to match two PointcutDesignators (called 'pointcut definitions' in the AJ5 quick reference). Currently, the following test fails: ---------------AjASTMatcherTest.java--------------- public void testMatchDefaultPointcut() { AjAST ast = AjAST.newAjAST(AST.JLS3); DefaultPointcut dp1 = ast.newDefaultPointcut(); DefaultPointcut dp2 = ast.newDefaultPointcut(); dp1.setDetail("call(* *.foo(..)"); dp2.setDetail("call(* *.bar(..)"); assertFalse(dp1.subtreeMatch(new AjASTMatcher(), dp2)); } --------------------------------------------------- The reason is that there are no implementations for the many different kinds of pointcut definitions of AspectJ. Instead, DefaultPointcut simply contains the pointcut definition in a String-field "detail" as shown in the test case. The same is true for DefaultTypePattern and SignaturePattern. Additionally, in the current implementation a DefaultPointcut, DefaultTypePattern, and SignaturePattern node will always match another AST node if that node is of the same type (instanceof). From what I see, it is necessary to 1) add types for every possible pointcut definition, 2) extend the current implementation of type name patterns and 3) signature patterns, 4) extend the parser (internal and external?) to create nodes for the pointcut definitions, 5) extend the converter to convert the new node types, and finally 6) extend the matcher to be able to match two pointcut definitions. Implementation is already done for combinations of poincuts using and (&&), or (||), not (!), cflow, and reference pointcuts (without parameters). Please comment on the task list as it is just an initial overview resulting from my limited knowledge on this field.
resolved fixed
bed3f4e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-04-24T16:45:17Z"
"2008-04-24T09:40:00Z"
org.aspectj.ajdt.core/src/org/aspectj/org/eclipse/jdt/core/dom/AjASTMatcher.java
/******************************************************************************* * Copyright (c) 2000, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.aspectj.org.eclipse.jdt.core.dom; public class AjASTMatcher extends ASTMatcher { /** * Creates a new AST matcher instance. * <p> * For backwards compatibility, the matcher ignores tag * elements below doc comments by default. Use * {@link #ASTMatcher(boolean) ASTMatcher(true)} * for a matcher that compares doc tags by default. * </p> */ public AjASTMatcher() { this(false); } /** * Creates a new AST matcher instance. * * @param matchDocTags <code>true</code> if doc comment tags are * to be compared by default, and <code>false</code> otherwise * @see #match(Javadoc,Object) * @since 3.0 */ public AjASTMatcher(boolean matchDocTags) { super(matchDocTags); } public boolean match(PointcutDeclaration node, Object other) { // ajh02: method added if (!(other instanceof PointcutDeclaration)) { return false; } PointcutDeclaration o = (PointcutDeclaration) other; int level = node.getAST().apiLevel; if (level == AST.JLS2_INTERNAL) { if (node.getModifiers() != o.getModifiers()) { return false; } } if (level >= AST.JLS3) { if (!safeSubtreeListMatch(node.modifiers(), o.modifiers())) { return false; } } return safeSubtreeMatch(node.getJavadoc(), o.getJavadoc()) && safeSubtreeMatch(node.getName(), o.getName()) && safeSubtreeMatch(node.getDesignator(), o.getDesignator()); } public boolean match(DefaultPointcut node, Object other) { return (other instanceof DefaultPointcut); } public boolean match(ReferencePointcut node, Object other) { if (!(other instanceof ReferencePointcut)) { return false; } ReferencePointcut o = (ReferencePointcut) other; int level = node.getAST().apiLevel; return safeSubtreeMatch(node.getName(), o.getName()); // ajh02: will have to add something here when ReferencePointcuts are given // a list of Types for parameters } public boolean match(NotPointcut node, Object other) { if (!(other instanceof NotPointcut)) { return false; } NotPointcut o = (NotPointcut) other; return safeSubtreeMatch(node.getBody(), o.getBody()); } public boolean match(PerObject node, Object other) { if (!(other instanceof PerObject)) { return false; } PerObject o = (PerObject) other; return safeSubtreeMatch(node.getBody(), o.getBody()) && o.isThis() == node.isThis(); } public boolean match(PerCflow node, Object other) { if (!(other instanceof PerCflow)) { return false; } PerCflow o = (PerCflow) other; return safeSubtreeMatch(node.getBody(), o.getBody()) && node.isBelow() == o.isBelow(); } public boolean match(PerTypeWithin node, Object other) { if (!(other instanceof PerTypeWithin)) { return false; } PerTypeWithin o = (PerTypeWithin) other; return true; // ajh02: stub, should look at the type pattern } public boolean match(CflowPointcut node, Object other) { if (!(other instanceof CflowPointcut)) { return false; } CflowPointcut o = (CflowPointcut) other; return safeSubtreeMatch(node.getBody(), o.getBody()); } public boolean match(AndPointcut node, Object other) { if (!(other instanceof AndPointcut)) { return false; } AndPointcut o = (AndPointcut) other; return safeSubtreeMatch(node.getLeft(), o.getLeft()) && safeSubtreeMatch(node.getRight(), o.getRight()); } public boolean match(OrPointcut node, Object other) { if (!(other instanceof OrPointcut)) { return false; } OrPointcut o = (OrPointcut) other; return safeSubtreeMatch(node.getLeft(), o.getLeft()) && safeSubtreeMatch(node.getRight(), o.getRight()); } public boolean match(BeforeAdviceDeclaration node, Object other) { // ajh02: method added if (!(other instanceof BeforeAdviceDeclaration)) { return false; } BeforeAdviceDeclaration o = (BeforeAdviceDeclaration) other; return safeSubtreeMatch(node.getJavadoc(), o.getJavadoc()) && safeSubtreeListMatch(node.parameters(), o.parameters()) && safeSubtreeMatch(node.getPointcut(), o.getPointcut()) && safeSubtreeListMatch(node.thrownExceptions(), o.thrownExceptions()) && safeSubtreeMatch(node.getBody(), o.getBody()); } public boolean match(AfterAdviceDeclaration node, Object other) { // ajh02: todo: should have special methods to match // afterReturning and afterThrowing if (!(other instanceof AfterAdviceDeclaration)) { return false; } AfterAdviceDeclaration o = (AfterAdviceDeclaration) other; return safeSubtreeMatch(node.getJavadoc(), o.getJavadoc()) && safeSubtreeListMatch(node.parameters(), o.parameters()) && safeSubtreeMatch(node.getPointcut(), o.getPointcut()) && safeSubtreeListMatch(node.thrownExceptions(), o.thrownExceptions()) && safeSubtreeMatch(node.getBody(), o.getBody()); } public boolean match(AroundAdviceDeclaration node, Object other) { if (!(other instanceof AroundAdviceDeclaration)) { return false; } AroundAdviceDeclaration o = (AroundAdviceDeclaration) other; int level = node.getAST().apiLevel; if (level == AST.JLS2_INTERNAL) { if (!safeSubtreeMatch(node.internalGetReturnType(), o.internalGetReturnType())) { return false; } } if (level >= AST.JLS3) { if (!safeSubtreeMatch(node.getReturnType2(), o.getReturnType2())) { return false; } if (!safeSubtreeListMatch(node.typeParameters(), o.typeParameters())) { return false; } } return safeSubtreeMatch(node.getJavadoc(), o.getJavadoc()) && safeSubtreeListMatch(node.parameters(), o.parameters()) && safeSubtreeMatch(node.getPointcut(), o.getPointcut()) && safeSubtreeListMatch(node.thrownExceptions(), o.thrownExceptions()) && safeSubtreeMatch(node.getBody(), o.getBody()); } public boolean match(DeclareDeclaration node, Object other) { // ajh02: method added if (!(other instanceof DeclareDeclaration)) { return false; } DeclareDeclaration o = (DeclareDeclaration) other; int level = node.getAST().apiLevel; return safeSubtreeMatch(node.getJavadoc(), o.getJavadoc()); } public boolean match(InterTypeFieldDeclaration node, Object other) { // ajh02: method added if (!(other instanceof InterTypeFieldDeclaration)) { return false; } InterTypeFieldDeclaration o = (InterTypeFieldDeclaration) other; int level = node.getAST().apiLevel; if (level == AST.JLS2_INTERNAL) { if (node.getModifiers() != o.getModifiers()) { return false; } } if (level >= AST.JLS3) { if (!safeSubtreeListMatch(node.modifiers(), o.modifiers())) { return false; } } return safeSubtreeMatch(node.getJavadoc(), o.getJavadoc()) && safeSubtreeMatch(node.getType(), o.getType()) && safeSubtreeListMatch(node.fragments(), o.fragments()); } public boolean match(InterTypeMethodDeclaration node, Object other) { // ajh02: method added if (!(other instanceof InterTypeMethodDeclaration)) { return false; } InterTypeMethodDeclaration o = (InterTypeMethodDeclaration) other; int level = node.getAST().apiLevel; if (level == AST.JLS2_INTERNAL) { if (node.getModifiers() != o.getModifiers()) { return false; } if (!safeSubtreeMatch(node.internalGetReturnType(), o.internalGetReturnType())) { return false; } } if (level >= AST.JLS3) { if (!safeSubtreeListMatch(node.modifiers(), o.modifiers())) { return false; } if (!safeSubtreeMatch(node.getReturnType2(), o.getReturnType2())) { return false; } // n.b. compare type parameters even for constructors if (!safeSubtreeListMatch(node.typeParameters(), o.typeParameters())) { return false; } } return ((node.isConstructor() == o.isConstructor()) && safeSubtreeMatch(node.getJavadoc(), o.getJavadoc()) && safeSubtreeMatch(node.getName(), o.getName()) // n.b. compare return type even for constructors && safeSubtreeListMatch(node.parameters(), o.parameters()) && node.getExtraDimensions() == o.getExtraDimensions() && safeSubtreeListMatch(node.thrownExceptions(), o.thrownExceptions()) && safeSubtreeMatch(node.getBody(), o.getBody())); } public boolean match(DefaultTypePattern node, Object other) { return (other instanceof DefaultTypePattern); } public boolean match(SignaturePattern node, Object other) { return (other instanceof SignaturePattern); } }
230,817
Bug 230817 LazyMethodGen.remap() NullPointerException
This has been reported a few times by different users, but has always proved tough to diagnose. The typical stack trace is something like: java.lang.NullPointerException org.aspectj.weaver.bcel.LazyMethodGen.remap(LazyMethodGen.java:1237) org.aspectj.weaver.bcel.LazyMethodGen.addExceptionHandlers(LazyMethodGen.java:1132) org.aspectj.weaver.bcel.LazyMethodGen.packBody(LazyMethodGen.java:1078) org.aspectj.weaver.bcel.LazyMethodGen.pack(LazyMethodGen.java:977) org.aspectj.weaver.bcel.LazyMethodGen.getMethod(LazyMethodGen.java:484) org.aspectj.weaver.bcel.LazyClassGen.writeBack(LazyClassGen.java:512) org.aspectj.weaver.bcel.LazyClassGen.getJavaClassBytesIncludingReweavable(LazyClassGen.java:652) org.aspectj.weaver.bcel.BcelWeaver.getClassFilesFor(BcelWeaver.java:1420) org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1390) And that is an exception on this line in remap() ih = ih.getNext(); called from the addExceptionHandlers() line: gen.addExceptionHandler( remap(r.getRealStart(), map), remap(r.getRealEnd(), map), remap(r.getHandler(), map), (r.getCatchType() == null) ? null : (ObjectType) BcelWorld.makeBcelType(r.getCatchType())); During weaving, an instruction list is augmented with extra entries representing where shadows start and end (method-call, method-execution, handler, etc). When weaving is complete we want to remove these temporary elements and use the remaining instructions to produce the method bytecode. Now sometimes these temporary entries are targeted by other elements (line number tags, local variable tags and exception handlers usually). During packing we use remap() to reposition the locations so they move off of temporary placeholders and onto real instructions that will make it out into the bytecode. What the above exception tells us is that we started walking over temporary placeholder entries, but before we came to a real instruction, we ran out of instructions! This cannot happen, and indicates something went seriously wrong, we should always encounter an instruction when remapping off a temporary element. After some digging it is actually the remap() call for the handler (not the start or end) that leads to the problem. The handler represents where to jump to in the code when an exception of the specified type occurs between the instructions pointed at by start and end. I sent a debug build to a user encountering this problem (I could not recreate it) and in that I was looking at where in fact the handler was pointing before we called remap(). I learned that when this problem occurs, the handler is not pointing to anywhere in the method currently being processed (not good). In a second debug build I tried to ascertain who was setting these handlers to point to nowhere. This debug never triggered, no-one was setting them to point to nowhere... I happened to notice whilst going through the instructions in the debug output that cobertura was being used, a coverage toolkit that works by doing bytecode manipulation to insert calls out to a library. AspectJ was being called after cobertura and I asked the user to try the steps the other way round - it worked fine. Indicating cobertura was doing something to the bytecode that gave us problems. After much messing about, I recreated it by applying around advice to within(*) to all the classes in rt.jar (I just used that as a very large standalone jar file I could weave into). I learned that Cobertura creates catch blocks that look a little different to what javac and other compilers create. The typical bytecode sequence a compiler produces for a catch block starts with a STORE instruction, to store the exception being caught (whether the body of the catch block uses it or not). But the cobertura catch blocks started with an INVOKESTATIC instruction, a call out to another method. What does this mean? It means the same instruction has two shadows, a 'handler' shadow and a 'method-call' shadow - and it turns out this is what causes our problem. If around advice is applied to the call join point and it cannot be inlined then the body of the call shadow (the call itself) is pulled out into a new method. Because the handler was the same instruction, this meant the handler *was also being pulled out* into the new method, leaving behind an exception handler that jumped to an invalid location (in fact it 'jumped' to an instruction in a different method!). So the reason I never saw the handler location being set incorrectly is that it was set correctly up front, but then dragged out with the method-call shadow into the wrong place. In bytecode terms it looks like this: method-execution() | ICONST_0 | ISTORE_2 | SIPUSH -1 | ISTORE_3 | catch java.lang.Exception (1806389629) -> E0 | | method-call(ProjectData ProjectData.getGlobalProjectData()) | | | INVOKESTATIC ProjectData.getGlobalProjectData () | | method-call(ProjectData getGlobalProjectData()) | | LDC "SomeString" | | method-call(ClassData getOrCreateClassData(java.lang.String)) | | | INVOKEVIRTUAL ProjectData.getOrCreateClassData (LString;) | | method-call(ClassData ProjectData.getOrCreateClassData(String)) | | SIPUSH 106 | | method-call(void ClassData.touch(int)) | | | INVOKEVIRTUAL ClassData.touch (I)V | | method-call(void ClassData.touch(int)) | | ALOAD_1 | | method-call(Object Expression.getValue()) | | | INVOKEVIRTUAL Expression.getValue () | | method-call(Object Expression.getValue()) | catch java.lang.Exception (1806389629) -> E0 | ARETURN | method-call(nProjectData ProjectData.getGlobalProjectData()) | | E0: INVOKESTATIC ProjectData.getGlobalProjectData () | method-call(ProjectData ProjectData.getGlobalProjectData()) | LDC "Object" We can see the problem in that final method-call. The target for the exception handler seen earlier (E0) is within the method-call shadow. What to do?
resolved fixed
5f97d46
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-05-07T15:31:18Z"
"2008-05-07T03:13:20Z"
weaver/src/org/aspectj/weaver/bcel/BcelClassWeaver.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.generic.ANEWARRAY; import org.aspectj.apache.bcel.generic.BranchInstruction; import org.aspectj.apache.bcel.generic.CPInstruction; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldGen; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.GOTO; import org.aspectj.apache.bcel.generic.GOTO_W; import org.aspectj.apache.bcel.generic.INVOKESPECIAL; import org.aspectj.apache.bcel.generic.IndexedInstruction; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InstructionTargeter; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.LineNumberTag; import org.aspectj.apache.bcel.generic.LocalVariableInstruction; import org.aspectj.apache.bcel.generic.LocalVariableTag; import org.aspectj.apache.bcel.generic.MONITORENTER; import org.aspectj.apache.bcel.generic.MONITOREXIT; import org.aspectj.apache.bcel.generic.MULTIANEWARRAY; import org.aspectj.apache.bcel.generic.MethodGen; import org.aspectj.apache.bcel.generic.NEW; import org.aspectj.apache.bcel.generic.NEWARRAY; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.PUTFIELD; import org.aspectj.apache.bcel.generic.PUTSTATIC; import org.aspectj.apache.bcel.generic.RET; import org.aspectj.apache.bcel.generic.ReturnInstruction; import org.aspectj.apache.bcel.generic.Select; import org.aspectj.apache.bcel.generic.Tag; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.generic.annotation.AnnotationGen; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.util.PartialOrder; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.IClassWeaver; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.MissingResolvedTypeWithKnownSignature; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverMetrics; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.ExactTypePattern; import org.aspectj.weaver.tools.Trace; import org.aspectj.weaver.tools.TraceFactory; class BcelClassWeaver implements IClassWeaver { private static Trace trace = TraceFactory.getTraceFactory().getTrace(BcelClassWeaver.class); /** * This is called from {@link BcelWeaver} to perform the per-class weaving process. */ public static boolean weave( BcelWorld world, LazyClassGen clazz, List shadowMungers, List typeMungers, List lateTypeMungers) { boolean b = new BcelClassWeaver(world, clazz, shadowMungers, typeMungers, lateTypeMungers).weave(); //System.out.println(clazz.getClassName() + ", " + clazz.getType().getWeaverState()); //clazz.print(); return b; } // -------------------------------------------- private final LazyClassGen clazz; private final List shadowMungers; private final List typeMungers; private final List lateTypeMungers; private final BcelObjectType ty; // alias of clazz.getType() private final BcelWorld world; // alias of ty.getWorld() private final ConstantPoolGen cpg; // alias of clazz.getConstantPoolGen() private final InstructionFactory fact; // alias of clazz.getFactory(); private final List addedLazyMethodGens = new ArrayList(); private final Set addedDispatchTargets = new HashSet(); // Static setting across BcelClassWeavers private static boolean inReweavableMode = false; private List addedSuperInitializersAsList = null; // List<IfaceInitList> private final Map addedSuperInitializers = new HashMap(); // Interface -> IfaceInitList private List addedThisInitializers = new ArrayList(); // List<NewFieldMunger> private List addedClassInitializers = new ArrayList(); // List<NewFieldMunger> private Map mapToAnnotations = new HashMap(); private BcelShadow clinitShadow = null; /** * This holds the initialization and pre-initialization shadows for this class * that were actually matched by mungers (if no match, then we don't even create the * shadows really). */ private final List initializationShadows = new ArrayList(1); private BcelClassWeaver( BcelWorld world, LazyClassGen clazz, List shadowMungers, List typeMungers, List lateTypeMungers) { super(); // assert world == clazz.getType().getWorld() this.world = world; this.clazz = clazz; this.shadowMungers = shadowMungers; this.typeMungers = typeMungers; this.lateTypeMungers = lateTypeMungers; this.ty = clazz.getBcelObjectType(); this.cpg = clazz.getConstantPoolGen(); this.fact = clazz.getFactory(); fastMatchShadowMungers(shadowMungers); initializeSuperInitializerMap(ty.getResolvedTypeX()); if (!checkedXsetForLowLevelContextCapturing) { Properties p = world.getExtraConfiguration(); if (p!=null) { String s = p.getProperty(World.xsetCAPTURE_ALL_CONTEXT,"false"); captureLowLevelContext = s.equalsIgnoreCase("true"); if (captureLowLevelContext) world.getMessageHandler().handleMessage(MessageUtil.info("["+World.xsetCAPTURE_ALL_CONTEXT+"=true] Enabling collection of low level context for debug/crash messages")); } checkedXsetForLowLevelContextCapturing=true; } } private List[] perKindShadowMungers; private boolean canMatchBodyShadows = false; private boolean canMatchInitialization = false; private void fastMatchShadowMungers(List shadowMungers) { // beware the annoying property that SHADOW_KINDS[i].getKey == (i+1) ! perKindShadowMungers = new List[Shadow.MAX_SHADOW_KIND + 1]; for (int i = 0; i < perKindShadowMungers.length; i++) { perKindShadowMungers[i] = new ArrayList(0); } for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); int couldMatchKinds = munger.getPointcut().couldMatchKinds(); for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { Shadow.Kind kind = Shadow.SHADOW_KINDS[i]; if (kind.isSet(couldMatchKinds)) perKindShadowMungers[kind.getKey()].add(munger); } // Set couldMatchKinds = munger.getPointcut().couldMatchKinds(); // for (Iterator kindIterator = couldMatchKinds.iterator(); // kindIterator.hasNext();) { // Shadow.Kind aKind = (Shadow.Kind) kindIterator.next(); // perKindShadowMungers[aKind.getKey()].add(munger); // } } if (!perKindShadowMungers[Shadow.Initialization.getKey()].isEmpty()) canMatchInitialization = true; for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { Shadow.Kind kind = Shadow.SHADOW_KINDS[i]; if (!kind.isEnclosingKind() && !perKindShadowMungers[i+1].isEmpty()) { canMatchBodyShadows = true; } if (perKindShadowMungers[i+1].isEmpty()) { perKindShadowMungers[i+1] = null; } } } private boolean canMatch(Shadow.Kind kind) { return perKindShadowMungers[kind.getKey()] != null; } // private void fastMatchShadowMungers(List shadowMungers, ArrayList mungers, Kind kind) { // FastMatchInfo info = new FastMatchInfo(clazz.getType(), kind); // for (Iterator i = shadowMungers.iterator(); i.hasNext();) { // ShadowMunger munger = (ShadowMunger) i.next(); // FuzzyBoolean fb = munger.getPointcut().fastMatch(info); // WeaverMetrics.recordFastMatchResult(fb);// Could pass: munger.getPointcut().toString() // if (fb.maybeTrue()) mungers.add(munger); // } // } private void initializeSuperInitializerMap(ResolvedType child) { ResolvedType[] superInterfaces = child.getDeclaredInterfaces(); for (int i=0, len=superInterfaces.length; i < len; i++) { if (ty.getResolvedTypeX().isTopmostImplementor(superInterfaces[i])) { if (addSuperInitializer(superInterfaces[i])) { initializeSuperInitializerMap(superInterfaces[i]); } } } } private boolean addSuperInitializer(ResolvedType onType) { if (onType.isRawType() || onType.isParameterizedType()) onType = onType.getGenericType(); IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType); if (l != null) return false; l = new IfaceInitList(onType); addedSuperInitializers.put(onType, l); return true; } public void addInitializer(ConcreteTypeMunger cm) { NewFieldTypeMunger m = (NewFieldTypeMunger) cm.getMunger(); ResolvedType onType = m.getSignature().getDeclaringType().resolve(world); if (onType.isRawType()) onType = onType.getGenericType(); if (m.getSignature().isStatic()) { addedClassInitializers.add(cm); } else { if (onType == ty.getResolvedTypeX()) { addedThisInitializers.add(cm); } else { IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType); l.list.add(cm); } } } private static class IfaceInitList implements PartialOrder.PartialComparable { final ResolvedType onType; List list = new ArrayList(); IfaceInitList(ResolvedType onType) { this.onType = onType; } public int compareTo(Object other) { IfaceInitList o = (IfaceInitList)other; if (onType.isAssignableFrom(o.onType)) return +1; else if (o.onType.isAssignableFrom(onType)) return -1; else return 0; } public int fallbackCompareTo(Object other) { return 0; } } // XXX this is being called, but the result doesn't seem to be being used public boolean addDispatchTarget(ResolvedMember m) { return addedDispatchTargets.add(m); } public void addLazyMethodGen(LazyMethodGen gen) { addedLazyMethodGens.add(gen); } public void addOrReplaceLazyMethodGen(LazyMethodGen mg) { if (alreadyDefined(clazz, mg)) return; for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) { LazyMethodGen existing = (LazyMethodGen)i.next(); if (signaturesMatch(mg, existing)) { if (existing.definingType == null) { // this means existing was introduced on the class itself return; } else if (mg.definingType.isAssignableFrom(existing.definingType)) { // existing is mg's subtype and dominates mg return; } else if (existing.definingType.isAssignableFrom(mg.definingType)) { // mg is existing's subtype and dominates existing i.remove(); addedLazyMethodGens.add(mg); return; } else { throw new BCException("conflict between: " + mg + " and " + existing); } } } addedLazyMethodGens.add(mg); } private boolean alreadyDefined(LazyClassGen clazz, LazyMethodGen mg) { for (Iterator i = clazz.getMethodGens().iterator(); i.hasNext(); ) { LazyMethodGen existing = (LazyMethodGen)i.next(); if (signaturesMatch(mg, existing)) { if (!mg.isAbstract() && existing.isAbstract()) { i.remove(); return false; } return true; } } return false; } private boolean signaturesMatch(LazyMethodGen mg, LazyMethodGen existing) { return mg.getName().equals(existing.getName()) && mg.getSignature().equals(existing.getSignature()); } protected static LazyMethodGen makeBridgeMethod(LazyClassGen gen, ResolvedMember member) { // remove abstract modifier int mods = member.getModifiers(); if (Modifier.isAbstract(mods)) mods = mods - Modifier.ABSTRACT; LazyMethodGen ret = new LazyMethodGen( mods, BcelWorld.makeBcelType(member.getReturnType()), member.getName(), BcelWorld.makeBcelTypes(member.getParameterTypes()), UnresolvedType.getNames(member.getExceptions()), gen); // 43972 : Static crosscutting makes interfaces unusable for javac // ret.makeSynthetic(); return ret; } /** * Create a single bridge method called 'theBridgeMethod' that bridges to 'whatToBridgeTo' */ private static void createBridgeMethod(BcelWorld world, LazyMethodGen whatToBridgeToMethodGen, LazyClassGen clazz,ResolvedMember theBridgeMethod) { InstructionList body; InstructionFactory fact; int pos = 0; ResolvedMember whatToBridgeTo = whatToBridgeToMethodGen.getMemberView(); if (whatToBridgeTo==null) { whatToBridgeTo = new ResolvedMemberImpl(Member.METHOD, whatToBridgeToMethodGen.getEnclosingClass().getType(), whatToBridgeToMethodGen.getAccessFlags(), whatToBridgeToMethodGen.getName(), whatToBridgeToMethodGen.getSignature()); } LazyMethodGen bridgeMethod = makeBridgeMethod(clazz,theBridgeMethod); // The bridge method in this type will have the same signature as the one in the supertype bridgeMethod.setAccessFlags(bridgeMethod.getAccessFlags() | 0x00000040 /*BRIDGE = 0x00000040*/ ); Type returnType = BcelWorld.makeBcelType(theBridgeMethod.getReturnType()); Type[] paramTypes = BcelWorld.makeBcelTypes(theBridgeMethod.getParameterTypes()); Type[] newParamTypes=whatToBridgeToMethodGen.getArgumentTypes(); body = bridgeMethod.getBody(); fact = clazz.getFactory(); if (!whatToBridgeToMethodGen.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); if (!newParamTypes[i].equals(paramTypes[i])) { if (world.forDEBUG_bridgingCode) System.err.println("Bridging: Cast "+newParamTypes[i]+" from "+paramTypes[i]); body.append(fact.createCast(paramTypes[i],newParamTypes[i])); } pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, world,whatToBridgeTo)); body.append(InstructionFactory.createReturn(returnType)); clazz.addMethodGen(bridgeMethod); } // ---- public boolean weave() { if (clazz.isWoven() && !clazz.isReweavable()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ALREADY_WOVEN,clazz.getType().getName()), ty.getSourceLocation(), null); return false; } Set aspectsAffectingType = null; if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType = new HashSet(); boolean isChanged = false; // we want to "touch" all aspects if (clazz.getType().isAspect()) isChanged = true; // start by munging all typeMungers for (Iterator i = typeMungers.iterator(); i.hasNext(); ) { Object o = i.next(); if ( !(o instanceof BcelTypeMunger) ) { //???System.err.println("surprising: " + o); continue; } BcelTypeMunger munger = (BcelTypeMunger)o; boolean typeMungerAffectedType = munger.munge(this); if (typeMungerAffectedType) { isChanged = true; if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.add(munger.getAspectType().getName()); } } // Weave special half type/half shadow mungers... isChanged = weaveDeclareAtMethodCtor(clazz) || isChanged; isChanged = weaveDeclareAtField(clazz) || isChanged; // XXX do major sort of stuff // sort according to: Major: type hierarchy // within each list: dominates // don't forget to sort addedThisInitialiers according to dominates addedSuperInitializersAsList = new ArrayList(addedSuperInitializers.values()); addedSuperInitializersAsList = PartialOrder.sort(addedSuperInitializersAsList); if (addedSuperInitializersAsList == null) { throw new BCException("circularity in inter-types"); } // this will create a static initializer if there isn't one // this is in just as bad taste as NOPs LazyMethodGen staticInit = clazz.getStaticInitializer(); staticInit.getBody().insert(genInitInstructions(addedClassInitializers, true)); // now go through each method, and match against each method. This // sets up each method's {@link LazyMethodGen#matchedShadows} field, // and it also possibly adds to {@link #initializationShadows}. List methodGens = new ArrayList(clazz.getMethodGens()); for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen)i.next(); if (! mg.hasBody()) continue; if (world.isJoinpointSynchronizationEnabled() && world.areSynchronizationPointcutsInUse() && mg.getMethod().isSynchronized()) { transformSynchronizedMethod(mg); } boolean shadowMungerMatched = match(mg); if (shadowMungerMatched) { // For matching mungers, add their declaring aspects to the list that affected this type if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.addAll(findAspectsForMungers(mg)); isChanged = true; } } // now we weave all but the initialization shadows for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen)i.next(); if (! mg.hasBody()) continue; implement(mg); } // if we matched any initialization shadows, we inline and weave if (!initializationShadows.isEmpty()) { // Repeat next step until nothing left to inline...cant go on // infinetly as compiler will have detected and reported // "Recursive constructor invocation" while (inlineSelfConstructors(methodGens)); positionAndImplement(initializationShadows); } // now proceed with late type mungers if (lateTypeMungers != null) { for (Iterator i = lateTypeMungers.iterator(); i.hasNext(); ) { BcelTypeMunger munger = (BcelTypeMunger)i.next(); if (munger.matches(clazz.getType())) { boolean typeMungerAffectedType = munger.munge(this); if (typeMungerAffectedType) { isChanged = true; if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.add(munger.getAspectType().getName()); } } } } //FIXME AV - see #75442, for now this is not enough to fix the bug, comment that out until we really fix it // // flush to save some memory // PerObjectInterfaceTypeMunger.unregisterFromAsAdvisedBy(clazz.getType()); // finally, if we changed, we add in the introduced methods. if (isChanged) { clazz.getOrCreateWeaverStateInfo(inReweavableMode); weaveInAddedMethods(); // FIXME asc are these potentially affected by declare annotation? } if (inReweavableMode) { WeaverStateInfo wsi = clazz.getOrCreateWeaverStateInfo(true); wsi.addAspectsAffectingType(aspectsAffectingType); wsi.setUnwovenClassFileData(ty.getJavaClass().getBytes()); wsi.setReweavable(true); } else { clazz.getOrCreateWeaverStateInfo(false).setReweavable(false); } return isChanged; } // **************************** start of bridge method creation code ***************** // FIXME asc tidy this lot up !! // FIXME asc refactor into ResolvedType or even ResolvedMember? /** * Check if a particular method is overriding another - refactored into this helper so it * can be used from multiple places. */ private static ResolvedMember isOverriding(ResolvedType typeToCheck,ResolvedMember methodThatMightBeGettingOverridden,String mname,String mrettype,int mmods,boolean inSamePackage,UnresolvedType[] methodParamsArray) { // Check if we can be an override... if (methodThatMightBeGettingOverridden.isStatic()) return null; // we can't be overriding a static method if (methodThatMightBeGettingOverridden.isPrivate()) return null; // we can't be overriding a private method if (!methodThatMightBeGettingOverridden.getName().equals(mname)) return null; // names dont match (this will also skip <init> and <clinit> too) if (methodThatMightBeGettingOverridden.getParameterTypes().length!=methodParamsArray.length) return null; // check same number of parameters if (!isVisibilityOverride(mmods,methodThatMightBeGettingOverridden,inSamePackage)) return null; if (typeToCheck.getWorld().forDEBUG_bridgingCode) System.err.println(" Bridging:seriously considering this might be getting overridden '"+methodThatMightBeGettingOverridden+"'"); // Look at erasures of parameters (List<String> erased is List) boolean sameParams = true; for (int p = 0;p<methodThatMightBeGettingOverridden.getParameterTypes().length;p++) { if (!methodThatMightBeGettingOverridden.getParameterTypes()[p].getErasureSignature().equals(methodParamsArray[p].getErasureSignature())) sameParams = false; } // If the 'typeToCheck' represents a parameterized type then the method will be the parameterized form of the // generic method in the generic type. So if the method was 'void m(List<T> lt, T t)' and the parameterized type here // is I<String> then the method we are looking at will be 'void m(List<String> lt, String t)' which when erased // is 'void m(List lt,String t)' - so if the parameters *do* match then there is a generic method we are // overriding if (sameParams) { // check for covariance if (typeToCheck.isParameterizedType()) { return methodThatMightBeGettingOverridden.getBackingGenericMember(); } else if (!methodThatMightBeGettingOverridden.getReturnType().getErasureSignature().equals(mrettype)) { // addressing the wierd situation from bug 147801 // just check whether these things are in the right relationship for covariance... ResolvedType superReturn = typeToCheck.getWorld().resolve(UnresolvedType.forSignature(methodThatMightBeGettingOverridden.getReturnType().getErasureSignature())); ResolvedType subReturn = typeToCheck.getWorld().resolve(UnresolvedType.forSignature(mrettype)); if (superReturn.isAssignableFrom(subReturn)) return methodThatMightBeGettingOverridden; } } return null; } /** * Looks at the visibility modifiers between two methods, and knows whether they are from classes in * the same package, and decides whether one overrides the other. * @return true if there is an overrides rather than a 'hides' relationship */ static boolean isVisibilityOverride(int methodMods, ResolvedMember inheritedMethod,boolean inSamePackage) { if (inheritedMethod.isStatic()) return false; if (methodMods == inheritedMethod.getModifiers()) return true; if (inheritedMethod.isPrivate()) return false; boolean isPackageVisible = !inheritedMethod.isPrivate() && !inheritedMethod.isProtected() && !inheritedMethod.isPublic(); if (isPackageVisible && !inSamePackage) return false; return true; } /** * This method recurses up a specified type looking for a method that overrides the one passed in. * * @return the method being overridden or null if none is found */ public static ResolvedMember checkForOverride(ResolvedType typeToCheck,String mname,String mparams,String mrettype,int mmods,String mpkg,UnresolvedType[] methodParamsArray) { if (typeToCheck==null) return null; if (typeToCheck instanceof MissingResolvedTypeWithKnownSignature) return null; // we just can't tell ! if (typeToCheck.getWorld().forDEBUG_bridgingCode) System.err.println(" Bridging:checking for override of "+mname+" in "+typeToCheck); String packageName = typeToCheck.getPackageName(); if (packageName==null) packageName=""; boolean inSamePackage = packageName.equals(mpkg); // used when looking at visibility rules ResolvedMember [] methods = typeToCheck.getDeclaredMethods(); for (int ii=0;ii<methods.length;ii++) { ResolvedMember methodThatMightBeGettingOverridden = methods[ii]; // the method we are going to check ResolvedMember isOverriding = isOverriding(typeToCheck,methodThatMightBeGettingOverridden,mname,mrettype,mmods,inSamePackage,methodParamsArray); if (isOverriding!=null) return isOverriding; } List l = typeToCheck.getInterTypeMungers(); for (Iterator iterator = l.iterator(); iterator.hasNext();) { Object o = iterator.next(); // FIXME asc if its not a BcelTypeMunger then its an EclipseTypeMunger ... do I need to worry about that? if (o instanceof BcelTypeMunger) { BcelTypeMunger element = (BcelTypeMunger)o; if (element.getMunger() instanceof NewMethodTypeMunger) { if (typeToCheck.getWorld().forDEBUG_bridgingCode) System.err.println("Possible ITD candidate "+element); ResolvedMember aMethod = element.getSignature(); ResolvedMember isOverriding = isOverriding(typeToCheck,aMethod,mname,mrettype,mmods,inSamePackage,methodParamsArray); if (isOverriding!=null) return isOverriding; } } } if (typeToCheck.equals(UnresolvedType.OBJECT)) return null; ResolvedType superclass = typeToCheck.getSuperclass(); ResolvedMember overriddenMethod = checkForOverride(superclass,mname,mparams,mrettype,mmods,mpkg,methodParamsArray); if (overriddenMethod!=null) return overriddenMethod; ResolvedType[] interfaces = typeToCheck.getDeclaredInterfaces(); for (int i = 0; i < interfaces.length; i++) { ResolvedType anInterface = interfaces[i]; overriddenMethod = checkForOverride(anInterface,mname,mparams,mrettype,mmods,mpkg,methodParamsArray); if (overriddenMethod!=null) return overriddenMethod; } return null; } /** * We need to determine if any methods in this type require bridge methods - this method should only * be called if necessary to do this calculation, i.e. we are on a 1.5 VM (where covariance/generics exist) and * the type hierarchy for the specified class has changed (via decp/itd). * * See pr108101 */ public static boolean calculateAnyRequiredBridgeMethods(BcelWorld world,LazyClassGen clazz) { world.ensureAdvancedConfigurationProcessed(); if (!world.isInJava5Mode()) return false; // just double check... the caller should have already verified this if (clazz.isInterface()) return false; // dont bother if we're an interface boolean didSomething=false; // set if we build any bridge methods // So what methods do we have right now in this class? List /*LazyMethodGen*/ methods = clazz.getMethodGens(); // Keep a set of all methods from this type - it'll help us to check if bridge methods // have already been created, we don't want to do it twice! Set methodsSet = new HashSet(); for (int i = 0; i < methods.size(); i++) { LazyMethodGen aMethod = (LazyMethodGen)methods.get(i); methodsSet.add(aMethod.getName()+aMethod.getSignature()); // e.g. "foo(Ljava/lang/String;)V" } // Now go through all the methods in this type for (int i = 0; i < methods.size(); i++) { // This is the local method that we *might* have to bridge to LazyMethodGen bridgeToCandidate = (LazyMethodGen)methods.get(i); if (bridgeToCandidate.isBridgeMethod()) continue; // Doh! String name = bridgeToCandidate.getName(); String psig = bridgeToCandidate.getParameterSignature(); String rsig = bridgeToCandidate.getReturnType().getSignature(); //if (bridgeToCandidate.isAbstract()) continue; if (bridgeToCandidate.isStatic()) continue; // ignore static methods if (name.endsWith("init>")) continue; // Skip constructors and static initializers if (world.forDEBUG_bridgingCode) System.err.println("Bridging: Determining if we have to bridge to "+clazz.getName()+"."+name+""+bridgeToCandidate.getSignature()); // Let's take a look at the superclass ResolvedType theSuperclass= clazz.getSuperClass(); if (world.forDEBUG_bridgingCode) System.err.println("Bridging: Checking supertype "+theSuperclass); String pkgName = clazz.getPackageName(); UnresolvedType[] bm = BcelWorld.fromBcel(bridgeToCandidate.getArgumentTypes()); ResolvedMember overriddenMethod = checkForOverride(theSuperclass,name,psig,rsig,bridgeToCandidate.getAccessFlags(),pkgName,bm); if (overriddenMethod!=null) { boolean alreadyHaveABridgeMethod = methodsSet.contains(overriddenMethod.getName()+overriddenMethod.getSignature()); if (!alreadyHaveABridgeMethod) { if (world.forDEBUG_bridgingCode) System.err.println("Bridging:bridging to '"+overriddenMethod+"'"); createBridgeMethod(world, bridgeToCandidate, clazz, overriddenMethod); didSomething = true; continue; // look at the next method } } // Check superinterfaces String[] interfaces = clazz.getInterfaceNames(); for (int j = 0; j < interfaces.length; j++) { if (world.forDEBUG_bridgingCode) System.err.println("Bridging:checking superinterface "+interfaces[j]); ResolvedType interfaceType = world.resolve(interfaces[j]); overriddenMethod = checkForOverride(interfaceType,name,psig,rsig,bridgeToCandidate.getAccessFlags(),clazz.getPackageName(),bm); if (overriddenMethod!=null) { boolean alreadyHaveABridgeMethod = methodsSet.contains(overriddenMethod.getName()+overriddenMethod.getSignature()); if (!alreadyHaveABridgeMethod) { createBridgeMethod(world, bridgeToCandidate, clazz, overriddenMethod); didSomething=true; if (world.forDEBUG_bridgingCode) System.err.println("Bridging:bridging to "+overriddenMethod); continue; // look at the next method } } } } return didSomething; } // **************************** end of bridge method creation code ***************** /** * Weave any declare @method/@ctor statements into the members of the supplied class */ private boolean weaveDeclareAtMethodCtor(LazyClassGen clazz) { List reportedProblems = new ArrayList(); List allDecams = world.getDeclareAnnotationOnMethods(); if (allDecams.isEmpty()) return false; // nothing to do boolean isChanged = false; // deal with ITDs List itdMethodsCtors = getITDSubset(clazz,ResolvedTypeMunger.Method); itdMethodsCtors.addAll(getITDSubset(clazz,ResolvedTypeMunger.Constructor)); if (!itdMethodsCtors.isEmpty()) { // Can't use the subset called 'decaMs' as it won't be right for ITDs... isChanged = weaveAtMethodOnITDSRepeatedly(allDecams,itdMethodsCtors,reportedProblems); } // deal with all the other methods... List members = clazz.getMethodGens(); List decaMs = getMatchingSubset(allDecams,clazz.getType()); if (decaMs.isEmpty()) return false; // nothing to do if (!members.isEmpty()) { Set unusedDecams = new HashSet(); unusedDecams.addAll(decaMs); for (int memberCounter = 0;memberCounter<members.size();memberCounter++) { LazyMethodGen mg = (LazyMethodGen)members.get(memberCounter); if (!mg.getName().startsWith(NameMangler.PREFIX)) { // Single first pass List worthRetrying = new ArrayList(); boolean modificationOccured = false; List /*AnnotationGen*/ annotationsToAdd = null; for (Iterator iter = decaMs.iterator(); iter.hasNext();) { DeclareAnnotation decaM = (DeclareAnnotation) iter.next(); if (decaM.matches(mg.getMemberView(),world)) { if (doesAlreadyHaveAnnotation(mg.getMemberView(),decaM,reportedProblems)) { // remove the declare @method since don't want an error when // the annotation is already there unusedDecams.remove(decaM); continue; // skip this one... } if (annotationsToAdd==null) annotationsToAdd = new ArrayList(); Annotation a = decaM.getAnnotationX().getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,clazz.getConstantPoolGen(),true); annotationsToAdd.add(ag); mg.addAnnotation(decaM.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaM.getSourceLocation(),clazz.getName(),mg.getMethod()); reportMethodCtorWeavingMessage(clazz, mg.getMemberView(), decaM,mg.getDeclarationLineNumber()); isChanged = true; modificationOccured = true; // remove the declare @method since have matched against it unusedDecams.remove(decaM); } else { if (!decaM.isStarredAnnotationPattern()) worthRetrying.add(decaM); // an annotation is specified that might be put on by a subsequent decaf } } // Multiple secondary passes while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; // lets have another go List forRemoval = new ArrayList(); for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaM = (DeclareAnnotation) iter.next(); if (decaM.matches(mg.getMemberView(),world)) { if (doesAlreadyHaveAnnotation(mg.getMemberView(),decaM,reportedProblems)) { // remove the declare @method since don't want an error when // the annotation is already there unusedDecams.remove(decaM); continue; // skip this one... } if (annotationsToAdd==null) annotationsToAdd = new ArrayList(); Annotation a = decaM.getAnnotationX().getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,clazz.getConstantPoolGen(),true); annotationsToAdd.add(ag); mg.addAnnotation(decaM.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaM.getSourceLocation(),clazz.getName(),mg.getMethod()); isChanged = true; modificationOccured = true; forRemoval.add(decaM); // remove the declare @method since have matched against it unusedDecams.remove(decaM); } } worthRetrying.removeAll(forRemoval); } if (annotationsToAdd!=null) { Method oldMethod = mg.getMethod(); MethodGen myGen = new MethodGen(oldMethod,clazz.getClassName(),clazz.getConstantPoolGen(),false);// dont use tags, they won't get repaired like for woven methods. for (Iterator iter = annotationsToAdd.iterator(); iter.hasNext();) { AnnotationGen a = (AnnotationGen) iter.next(); myGen.addAnnotation(a); } Method newMethod = myGen.getMethod(); members.set(memberCounter,new LazyMethodGen(newMethod,clazz)); } } } checkUnusedDeclareAtTypes(unusedDecams, false); } return isChanged; } // TAG: WeavingMessage private void reportMethodCtorWeavingMessage(LazyClassGen clazz, ResolvedMember member, DeclareAnnotation decaM,int memberLineNumber) { if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){ StringBuffer parmString = new StringBuffer("("); UnresolvedType[] paramTypes = member.getParameterTypes(); for (int i = 0; i < paramTypes.length; i++) { UnresolvedType type = paramTypes[i]; String s = org.aspectj.apache.bcel.classfile.Utility.signatureToString(type.getSignature()); if (s.lastIndexOf(".")!=-1) s =s.substring(s.lastIndexOf(".")+1); parmString.append(s); if ((i+1)<paramTypes.length) parmString.append(","); } parmString.append(")"); String methodName = member.getName(); StringBuffer sig = new StringBuffer(); sig.append(org.aspectj.apache.bcel.classfile.Utility.accessToString(member.getModifiers())); sig.append(" "); sig.append(member.getReturnType().toString()); sig.append(" "); sig.append(member.getDeclaringType().toString()); sig.append("."); sig.append(methodName.equals("<init>")?"new":methodName); sig.append(parmString); StringBuffer loc = new StringBuffer(); if (clazz.getFileName()==null) { loc.append("no debug info available"); } else { loc.append(clazz.getFileName()); if (memberLineNumber!=-1) { loc.append(":"+memberLineNumber); } } getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES, new String[]{ sig.toString(), loc.toString(), decaM.getAnnotationString(), methodName.startsWith("<init>")?"constructor":"method", decaM.getAspect().toString(), Utility.beautifyLocation(decaM.getSourceLocation()) })); } } /** * Looks through a list of declare annotation statements and only returns * those that could possibly match on a field/method/ctor in type. */ private List getMatchingSubset(List declareAnnotations, ResolvedType type) { List subset = new ArrayList(); for (Iterator iter = declareAnnotations.iterator(); iter.hasNext();) { DeclareAnnotation da = (DeclareAnnotation) iter.next(); if (da.couldEverMatch(type)) { subset.add(da); } } return subset; } /** * Get a subset of all the type mungers defined on this aspect */ private List getITDSubset(LazyClassGen clazz,ResolvedTypeMunger.Kind wantedKind) { List subset = new ArrayList(); Collection c = clazz.getBcelObjectType().getTypeMungers(); for (Iterator iter = c.iterator();iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger)iter.next(); if (typeMunger.getMunger().getKind()==wantedKind) subset.add(typeMunger); } return subset; } public LazyMethodGen locateAnnotationHolderForFieldMunger(LazyClassGen clazz,BcelTypeMunger fieldMunger) { NewFieldTypeMunger nftm = (NewFieldTypeMunger)fieldMunger.getMunger(); ResolvedMember lookingFor =AjcMemberMaker.interFieldInitializer(nftm.getSignature(),clazz.getType()); List meths = clazz.getMethodGens(); for (Iterator iter = meths.iterator(); iter.hasNext();) { LazyMethodGen element = (LazyMethodGen) iter.next(); if (element.getName().equals(lookingFor.getName())) return element; } return null; } // FIXME asc refactor this to neaten it up public LazyMethodGen locateAnnotationHolderForMethodCtorMunger(LazyClassGen clazz,BcelTypeMunger methodCtorMunger) { if (methodCtorMunger.getMunger() instanceof NewMethodTypeMunger) { NewMethodTypeMunger nftm = (NewMethodTypeMunger)methodCtorMunger.getMunger(); ResolvedMember lookingFor = AjcMemberMaker.interMethodDispatcher(nftm.getSignature(),methodCtorMunger.getAspectType()); List meths = clazz.getMethodGens(); for (Iterator iter = meths.iterator(); iter.hasNext();) { LazyMethodGen element = (LazyMethodGen) iter.next(); if (element.getName().equals(lookingFor.getName()) && element.getParameterSignature().equals(lookingFor.getParameterSignature())) return element; } return null; } else if (methodCtorMunger.getMunger() instanceof NewConstructorTypeMunger) { NewConstructorTypeMunger nftm = (NewConstructorTypeMunger)methodCtorMunger.getMunger(); ResolvedMember lookingFor =AjcMemberMaker.postIntroducedConstructor(methodCtorMunger.getAspectType(),nftm.getSignature().getDeclaringType(),nftm.getSignature().getParameterTypes()); List meths = clazz.getMethodGens(); for (Iterator iter = meths.iterator(); iter.hasNext();) { LazyMethodGen element = (LazyMethodGen) iter.next(); if (element.getName().equals(lookingFor.getName()) && element.getParameterSignature().equals(lookingFor.getParameterSignature())) return element; } return null; } else { throw new RuntimeException("Not sure what this is: "+methodCtorMunger); } } /** * Applies some set of declare @field constructs (List<DeclareAnnotation>) to some bunch * of ITDfields (List<BcelTypeMunger>. It will iterate over the fields repeatedly until * everything has been applied. * */ private boolean weaveAtFieldRepeatedly(List decaFs, List itdFields,List reportedErrors) { boolean isChanged = false; for (Iterator iter = itdFields.iterator(); iter.hasNext();) { BcelTypeMunger fieldMunger = (BcelTypeMunger) iter.next(); ResolvedMember itdIsActually = fieldMunger.getSignature(); List worthRetrying = new ArrayList(); boolean modificationOccured = false; for (Iterator iter2 = decaFs.iterator(); iter2.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter2.next(); if (decaF.matches(itdIsActually,world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,fieldMunger); if (doesAlreadyHaveAnnotation(annotationHolder,itdIsActually,decaF,reportedErrors)) continue; // skip this one... annotationHolder.addAnnotation(decaF.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),itdIsActually.getSourceLocation()); isChanged = true; modificationOccured = true; } else { if (!decaF.isStarredAnnotationPattern()) worthRetrying.add(decaF); // an annotation is specified that might be put on by a subsequent decaf } } while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; List forRemoval = new ArrayList(); for (Iterator iter2 = worthRetrying.iterator(); iter2.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter2.next(); if (decaF.matches(itdIsActually,world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,fieldMunger); if (doesAlreadyHaveAnnotation(annotationHolder,itdIsActually,decaF,reportedErrors)) continue; // skip this one... annotationHolder.addAnnotation(decaF.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),itdIsActually.getSourceLocation()); isChanged = true; modificationOccured = true; forRemoval.add(decaF); } worthRetrying.removeAll(forRemoval); } } } return isChanged; } /** * Applies some set of declare @method/@ctor constructs (List<DeclareAnnotation>) to some bunch * of ITDmembers (List<BcelTypeMunger>. It will iterate over the fields repeatedly until * everything has been applied. */ private boolean weaveAtMethodOnITDSRepeatedly(List decaMCs, List itdMethodsCtors,List reportedErrors) { boolean isChanged = false; for (Iterator iter = itdMethodsCtors.iterator(); iter.hasNext();) { BcelTypeMunger methodctorMunger = (BcelTypeMunger) iter.next(); ResolvedMember unMangledInterMethod = methodctorMunger.getSignature(); List worthRetrying = new ArrayList(); boolean modificationOccured = false; for (Iterator iter2 = decaMCs.iterator(); iter2.hasNext();) { DeclareAnnotation decaMC = (DeclareAnnotation) iter2.next(); if (decaMC.matches(unMangledInterMethod,world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForMethodCtorMunger(clazz,methodctorMunger); if (annotationHolder == null || doesAlreadyHaveAnnotation(annotationHolder,unMangledInterMethod,decaMC,reportedErrors)){ continue; // skip this one... } annotationHolder.addAnnotation(decaMC.getAnnotationX()); isChanged=true; AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaMC.getSourceLocation(),unMangledInterMethod.getSourceLocation()); reportMethodCtorWeavingMessage(clazz, unMangledInterMethod, decaMC,-1); modificationOccured = true; } else { if (!decaMC.isStarredAnnotationPattern()) worthRetrying.add(decaMC); // an annotation is specified that might be put on by a subsequent decaf } } while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; List forRemoval = new ArrayList(); for (Iterator iter2 = worthRetrying.iterator(); iter2.hasNext();) { DeclareAnnotation decaMC = (DeclareAnnotation) iter2.next(); if (decaMC.matches(unMangledInterMethod,world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,methodctorMunger); if (doesAlreadyHaveAnnotation(annotationHolder,unMangledInterMethod,decaMC,reportedErrors)) continue; // skip this one... annotationHolder.addAnnotation(decaMC.getAnnotationX()); unMangledInterMethod.addAnnotation(decaMC.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaMC.getSourceLocation(),unMangledInterMethod.getSourceLocation()); isChanged = true; modificationOccured = true; forRemoval.add(decaMC); } worthRetrying.removeAll(forRemoval); } } } return isChanged; } private boolean dontAddTwice(DeclareAnnotation decaF, Annotation [] dontAddMeTwice){ for (int i = 0; i < dontAddMeTwice.length; i++){ Annotation ann = dontAddMeTwice[i]; if (ann != null && decaF.getAnnotationX().getTypeName().equals(ann.getTypeName())){ //dontAddMeTwice[i] = null; // incase it really has been added twice! return true; } } return false; } /** * Weave any declare @field statements into the fields of the supplied class * * Interesting case relating to public ITDd fields. The annotations are really stored against * the interfieldinit method in the aspect, but the public field is placed in the target * type and then is processed in the 2nd pass over fields that occurs. I think it would be * more expensive to avoid putting the annotation on that inserted public field than just to * have it put there as well as on the interfieldinit method. */ private boolean weaveDeclareAtField(LazyClassGen clazz) { // BUGWARNING not getting enough warnings out on declare @field ? // There is a potential problem here with warnings not coming out - this // will occur if they are created on the second iteration round this loop. // We currently deactivate error reporting for the second time round. // A possible solution is to record what annotations were added by what // decafs and check that to see if an error needs to be reported - this // would be expensive so lets skip it for now List reportedProblems = new ArrayList(); List allDecafs = world.getDeclareAnnotationOnFields(); if (allDecafs.isEmpty()) return false; // nothing to do boolean isChanged = false; List itdFields = getITDSubset(clazz,ResolvedTypeMunger.Field); if (itdFields!=null) { isChanged = weaveAtFieldRepeatedly(allDecafs,itdFields,reportedProblems); } List decaFs = getMatchingSubset(allDecafs,clazz.getType()); if (decaFs.isEmpty()) return false; // nothing more to do Field[] fields = clazz.getFieldGens(); if (fields!=null) { Set unusedDecafs = new HashSet(); unusedDecafs.addAll(decaFs); for (int fieldCounter = 0;fieldCounter<fields.length;fieldCounter++) { BcelField aBcelField = new BcelField(clazz.getBcelObjectType(),fields[fieldCounter]); if (!aBcelField.getName().startsWith(NameMangler.PREFIX)) { // Single first pass List worthRetrying = new ArrayList(); boolean modificationOccured = false; Annotation [] dontAddMeTwice = fields[fieldCounter].getAnnotations(); // go through all the declare @field statements for (Iterator iter = decaFs.iterator(); iter.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter.next(); if (decaF.matches(aBcelField,world)) { if (!dontAddTwice(decaF,dontAddMeTwice)){ if (doesAlreadyHaveAnnotation(aBcelField,decaF,reportedProblems)){ // remove the declare @field since don't want an error when // the annotation is already there unusedDecafs.remove(decaF); continue; } if(decaF.getAnnotationX().isRuntimeVisible()){ // isAnnotationWithRuntimeRetention(clazz.getJavaClass(world))){ //if(decaF.getAnnotationTypeX().isAnnotationWithRuntimeRetention(world)){ // it should be runtime visible, so put it on the Field Annotation a = decaF.getAnnotationX().getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,clazz.getConstantPoolGen(),true); FieldGen myGen = new FieldGen(fields[fieldCounter],clazz.getConstantPoolGen()); myGen.addAnnotation(ag); Field newField = myGen.getField(); aBcelField.addAnnotation(decaF.getAnnotationX()); clazz.replaceField(fields[fieldCounter],newField); fields[fieldCounter]=newField; } else{ aBcelField.addAnnotation(decaF.getAnnotationX()); } } AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),clazz.getName(),fields[fieldCounter]); reportFieldAnnotationWeavingMessage(clazz, fields, fieldCounter, decaF); isChanged = true; modificationOccured = true; // remove the declare @field since have matched against it unusedDecafs.remove(decaF); } else { if (!decaF.isStarredAnnotationPattern()) worthRetrying.add(decaF); // an annotation is specified that might be put on by a subsequent decaf } } // Multiple secondary passes while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; // lets have another go List forRemoval = new ArrayList(); for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter.next(); if (decaF.matches(aBcelField,world)) { // below code is for recursive things if (doesAlreadyHaveAnnotation(aBcelField,decaF,reportedProblems)) { // remove the declare @field since don't want an error when // the annotation is already there unusedDecafs.remove(decaF); continue; // skip this one... } aBcelField.addAnnotation(decaF.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),clazz.getName(),fields[fieldCounter]); isChanged = true; modificationOccured = true; forRemoval.add(decaF); // remove the declare @field since have matched against it unusedDecafs.remove(decaF); } } worthRetrying.removeAll(forRemoval); } } } checkUnusedDeclareAtTypes(unusedDecafs,true); } return isChanged; } // bug 99191 - put out an error message if the type doesn't exist /** * Report an error if the reason a "declare @method/ctor/field" was not used was because the member * specified does not exist. This method is passed some set of declare statements that didn't * match and a flag indicating whether the set contains declare @field or declare @method/ctor * entries. */ private void checkUnusedDeclareAtTypes(Set unusedDecaTs, boolean isDeclareAtField) { for (Iterator iter = unusedDecaTs.iterator(); iter.hasNext();) { DeclareAnnotation declA = (DeclareAnnotation) iter.next(); // Error if an exact type pattern was specified if ((declA.isExactPattern() || (declA.getSignaturePattern().getDeclaringType() instanceof ExactTypePattern)) && (!declA.getSignaturePattern().getName().isAny() || (declA.getKind() == DeclareAnnotation.AT_CONSTRUCTOR))) { // Quickly check if an ITD meets supplies the 'missing' member boolean itdMatch = false; List lst = clazz.getType().getInterTypeMungers(); for (Iterator iterator = lst.iterator(); iterator.hasNext() && !itdMatch;) { BcelTypeMunger element = (BcelTypeMunger) iterator.next(); if (element.getMunger() instanceof NewFieldTypeMunger) { NewFieldTypeMunger nftm = (NewFieldTypeMunger)element.getMunger(); itdMatch = declA.getSignaturePattern().matches(nftm.getSignature(),world,false); }else if (element.getMunger() instanceof NewMethodTypeMunger) { NewMethodTypeMunger nmtm = (NewMethodTypeMunger)element.getMunger(); itdMatch = declA.getSignaturePattern().matches(nmtm.getSignature(),world,false); } else if (element.getMunger() instanceof NewConstructorTypeMunger) { NewConstructorTypeMunger nctm = (NewConstructorTypeMunger)element.getMunger(); itdMatch = declA.getSignaturePattern().matches(nctm.getSignature(),world,false); } } if (!itdMatch) { IMessage message = null; if (isDeclareAtField) { message = new Message( "The field '"+ declA.getSignaturePattern().toString() + "' does not exist", declA.getSourceLocation() , true); } else { message = new Message( "The method '"+ declA.getSignaturePattern().toString() + "' does not exist", declA.getSourceLocation() , true); } world.getMessageHandler().handleMessage(message); } } } } // TAG: WeavingMessage private void reportFieldAnnotationWeavingMessage(LazyClassGen clazz, Field[] fields, int fieldCounter, DeclareAnnotation decaF) { if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){ Field theField = fields[fieldCounter]; world.getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES, new String[]{ theField.toString() + "' of type '" + clazz.getName(), clazz.getFileName(), decaF.getAnnotationString(), "field", decaF.getAspect().toString(), Utility.beautifyLocation(decaF.getSourceLocation())})); } } /** * Check if a resolved member (field/method/ctor) already has an annotation, if it * does then put out a warning and return true */ private boolean doesAlreadyHaveAnnotation(ResolvedMember rm,DeclareAnnotation deca,List reportedProblems) { if (rm.hasAnnotation(deca.getAnnotationTypeX())) { if (world.getLint().elementAlreadyAnnotated.isEnabled()) { Integer uniqueID = new Integer(rm.hashCode()*deca.hashCode()); if (!reportedProblems.contains(uniqueID)) { reportedProblems.add(uniqueID); world.getLint().elementAlreadyAnnotated.signal( new String[]{rm.toString(),deca.getAnnotationTypeX().toString()}, rm.getSourceLocation(),new ISourceLocation[]{deca.getSourceLocation()}); } } return true; } return false; } private boolean doesAlreadyHaveAnnotation(LazyMethodGen rm,ResolvedMember itdfieldsig,DeclareAnnotation deca,List reportedProblems) { if (rm != null && rm.hasAnnotation(deca.getAnnotationTypeX())) { if (world.getLint().elementAlreadyAnnotated.isEnabled()) { Integer uniqueID = new Integer(rm.hashCode()*deca.hashCode()); if (!reportedProblems.contains(uniqueID)) { reportedProblems.add(uniqueID); reportedProblems.add(new Integer(itdfieldsig.hashCode()*deca.hashCode())); world.getLint().elementAlreadyAnnotated.signal( new String[]{itdfieldsig.toString(),deca.getAnnotationTypeX().toString()}, rm.getSourceLocation(),new ISourceLocation[]{deca.getSourceLocation()}); } } return true; } return false; } private Set findAspectsForMungers(LazyMethodGen mg) { Set aspectsAffectingType = new HashSet(); for (Iterator iter = mg.matchedShadows.iterator(); iter.hasNext();) { BcelShadow aShadow = (BcelShadow) iter.next(); // Mungers in effect on that shadow for (Iterator iter2 = aShadow.getMungers().iterator();iter2.hasNext();) { ShadowMunger aMunger = (ShadowMunger) iter2.next(); if (aMunger instanceof BcelAdvice) { BcelAdvice bAdvice = (BcelAdvice)aMunger; if(bAdvice.getConcreteAspect() != null){ aspectsAffectingType.add(bAdvice.getConcreteAspect().getName()); } } else { // It is a 'Checker' - we don't need to remember aspects that only contributed Checkers... } } } return aspectsAffectingType; } private boolean inlineSelfConstructors(List methodGens) { boolean inlinedSomething = false; for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen) i.next(); if (! mg.getName().equals("<init>")) continue; InstructionHandle ih = findSuperOrThisCall(mg); if (ih != null && isThisCall(ih)) { LazyMethodGen donor = getCalledMethod(ih); inlineMethod(donor, mg, ih); inlinedSomething = true; } } return inlinedSomething; } private void positionAndImplement(List initializationShadows) { for (Iterator i = initializationShadows.iterator(); i.hasNext(); ) { BcelShadow s = (BcelShadow) i.next(); positionInitializationShadow(s); //s.getEnclosingMethod().print(); s.implement(); } } private void positionInitializationShadow(BcelShadow s) { LazyMethodGen mg = s.getEnclosingMethod(); InstructionHandle call = findSuperOrThisCall(mg); InstructionList body = mg.getBody(); ShadowRange r = new ShadowRange(body); r.associateWithShadow((BcelShadow) s); if (s.getKind() == Shadow.PreInitialization) { // XXX assert first instruction is an ALOAD_0. // a pre shadow goes from AFTER the first instruction (which we believe to // be an ALOAD_0) to just before the call to super r.associateWithTargets( Range.genStart(body, body.getStart().getNext()), Range.genEnd(body, call.getPrev())); } else { // assert s.getKind() == Shadow.Initialization r.associateWithTargets( Range.genStart(body, call.getNext()), Range.genEnd(body)); } } private boolean isThisCall(InstructionHandle ih) { INVOKESPECIAL inst = (INVOKESPECIAL) ih.getInstruction(); return inst.getClassName(cpg).equals(clazz.getName()); } /** inline a particular call in bytecode. * * @param donor the method we want to inline * @param recipient the method containing the call we want to inline * @param call the instructionHandle in recipient's body holding the call we want to * inline. */ public static void inlineMethod( LazyMethodGen donor, LazyMethodGen recipient, InstructionHandle call) { // assert recipient.contains(call) /* Implementation notes: * * We allocate two slots for every tempvar so we don't screw up * longs and doubles which may share space. This could be conservatively avoided * (no reference to a long/double instruction, don't do it) or packed later. * Right now we don't bother to pack. * * Allocate a new var for each formal param of the inlined. Fill with stack * contents. Then copy the inlined instructions in with the appropriate remap * table. Any framelocs used by locals in inlined are reallocated to top of * frame, */ final InstructionFactory fact = recipient.getEnclosingClass().getFactory(); IntMap frameEnv = new IntMap(); // this also sets up the initial environment InstructionList argumentStores = genArgumentStores(donor, recipient, frameEnv, fact); InstructionList inlineInstructions = genInlineInstructions(donor, recipient, frameEnv, fact, false); inlineInstructions.insert(argumentStores); recipient.getBody().append(call, inlineInstructions); Utility.deleteInstruction(call, recipient); } // public BcelVar genTempVar(UnresolvedType typeX) { // return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize())); // } // // private int genTempVarIndex(int size) { // return enclosingMethod.allocateLocal(size); // } /** * Input method is a synchronized method, we remove the bit flag for synchronized and * then insert a try..finally block * * Some jumping through firey hoops required - depending on the input code level (1.5 or not) * we may or may not be able to use the LDC instruction that takes a class literal (doesnt on * <1.5). * * FIXME asc Before promoting -Xjoinpoints:synchronization to be a standard option, this needs a bunch of * tidying up - there is some duplication that can be removed. */ public static void transformSynchronizedMethod(LazyMethodGen synchronizedMethod) { if (trace.isTraceEnabled()) trace.enter("transformSynchronizedMethod",synchronizedMethod); // System.err.println("DEBUG: Transforming synchronized method: "+synchronizedMethod.getName()); final InstructionFactory fact = synchronizedMethod.getEnclosingClass().getFactory(); InstructionList body = synchronizedMethod.getBody(); InstructionList prepend = new InstructionList(); Type enclosingClassType = BcelWorld.makeBcelType(synchronizedMethod.getEnclosingClass().getType()); Type javaLangClassType = Type.getType(Class.class); // STATIC METHOD TRANSFORMATION if (synchronizedMethod.isStatic()) { // What to do here depends on the level of the class file! // LDC can handle class literals in Java5 and above *sigh* if (synchronizedMethod.getEnclosingClass().isAtLeastJava5()) { // MONITORENTER logic: // 0: ldc #2; //class C // 2: dup // 3: astore_0 // 4: monitorenter int slotForLockObject = synchronizedMethod.allocateLocal(enclosingClassType); prepend.append(fact.createConstant(enclosingClassType)); prepend.append(InstructionFactory.createDup(1)); prepend.append(InstructionFactory.createStore(enclosingClassType, slotForLockObject)); prepend.append(InstructionFactory.MONITORENTER); // MONITOREXIT logic: // We basically need to wrap the code from the method in a finally block that // will ensure monitorexit is called. Content on the finally block seems to // be always: // // E1: ALOAD_1 // MONITOREXIT // ATHROW // // so lets build that: InstructionList finallyBlock = new InstructionList(); finallyBlock.append(InstructionFactory.createLoad(Type.getType(java.lang.Class.class),slotForLockObject)); finallyBlock.append(InstructionConstants.MONITOREXIT); finallyBlock.append(InstructionConstants.ATHROW); // finally -> E1 // | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 21) // | LDC "hello" // | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V // | ALOAD_1 (line 20) // | MONITOREXIT // finally -> E1 // GOTO L0 // finally -> E1 // | E1: ALOAD_1 // | MONITOREXIT // finally -> E1 // ATHROW // L0: RETURN (line 23) // search for 'returns' and make them jump to the aload_<n>,monitorexit InstructionHandle walker = body.getStart(); List rets = new ArrayList(); while (walker!=null) { if (walker.getInstruction() instanceof ReturnInstruction) { rets.add(walker); } walker = walker.getNext(); } if (rets.size()>0) { // need to ensure targeters for 'return' now instead target the load instruction // (so we never jump over the monitorexit logic) for (Iterator iter = rets.iterator(); iter.hasNext();) { InstructionHandle element = (InstructionHandle) iter.next(); InstructionList monitorExitBlock = new InstructionList(); monitorExitBlock.append(InstructionFactory.createLoad(enclosingClassType,slotForLockObject)); monitorExitBlock.append(InstructionConstants.MONITOREXIT); //monitorExitBlock.append(Utility.copyInstruction(element.getInstruction())); //element.setInstruction(InstructionFactory.createLoad(classType,slotForThis)); InstructionHandle monitorExitBlockStart = body.insert(element,monitorExitBlock); // now move the targeters from the RET to the start of the monitorexit block InstructionTargeter[] targeters = element.getTargeters(); if (targeters!=null) { for (int i = 0; i < targeters.length; i++) { InstructionTargeter targeter = targeters[i]; // what kinds are there? if (targeter instanceof LocalVariableTag) { // ignore } else if (targeter instanceof LineNumberTag) { // ignore } else if (targeter instanceof GOTO || targeter instanceof GOTO_W) { // move it... targeter.updateTarget(element, monitorExitBlockStart); } else if (targeter instanceof BranchInstruction) { // move it targeter.updateTarget(element, monitorExitBlockStart); } else { throw new RuntimeException("Unexpected targeter encountered during transform: "+targeter); } } } } } // now the magic, putting the finally block around the code InstructionHandle finallyStart = finallyBlock.getStart(); InstructionHandle tryPosition = body.getStart(); InstructionHandle catchPosition = body.getEnd(); body.insert(body.getStart(),prepend); // now we can put the monitorenter stuff on synchronizedMethod.getBody().append(finallyBlock); synchronizedMethod.addExceptionHandler(tryPosition, catchPosition,finallyStart,null/*==finally*/,false); synchronizedMethod.addExceptionHandler(finallyStart,finallyStart.getNext(),finallyStart,null,false); } else { // TRANSFORMING STATIC METHOD ON PRE JAVA5 // Hideous nightmare, class literal references prior to Java5 // YIKES! this is just the code for MONITORENTER ! // 0: getstatic #59; //Field class$1:Ljava/lang/Class; // 3: dup // 4: ifnonnull 32 // 7: pop // try // 8: ldc #61; //String java.lang.String // 10: invokestatic #44; //Method java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class; // 13: dup // catch // 14: putstatic #59; //Field class$1:Ljava/lang/Class; // 17: goto 32 // 20: new #46; //class java/lang/NoClassDefFoundError // 23: dup_x1 // 24: swap // 25: invokevirtual #52; //Method java/lang/Throwable.getMessage:()Ljava/lang/String; // 28: invokespecial #54; //Method java/lang/NoClassDefFoundError."<init>":(Ljava/lang/String;)V // 31: athrow // 32: dup <-- partTwo (branch target) // 33: astore_0 // 34: monitorenter // // plus exceptiontable entry! // 8 13 20 Class java/lang/ClassNotFoundException Type classType = BcelWorld.makeBcelType(synchronizedMethod.getEnclosingClass().getType()); Type clazzType = Type.getType(Class.class); InstructionList parttwo = new InstructionList(); parttwo.append(InstructionFactory.createDup(1)); int slotForThis = synchronizedMethod.allocateLocal(classType); parttwo.append(InstructionFactory.createStore(clazzType, slotForThis)); // ? should be the real type ? String or something? parttwo.append(InstructionFactory.MONITORENTER); String fieldname = synchronizedMethod.getEnclosingClass().allocateField("class$"); Field f = new FieldGen(Modifier.STATIC | Modifier.PRIVATE, Type.getType(Class.class),fieldname,synchronizedMethod.getEnclosingClass().getConstantPoolGen()).getField(); synchronizedMethod.getEnclosingClass().addField(f, null); // 10: invokestatic #44; //Method java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class; // 13: dup // 14: putstatic #59; //Field class$1:Ljava/lang/Class; // 17: goto 32 // 20: new #46; //class java/lang/NoClassDefFoundError // 23: dup_x1 // 24: swap // 25: invokevirtual #52; //Method java/lang/Throwable.getMessage:()Ljava/lang/String; // 28: invokespecial #54; //Method java/lang/NoClassDefFoundError."<init>":(Ljava/lang/String;)V // 31: athrow String name = synchronizedMethod.getEnclosingClass().getName(); prepend.append(fact.createGetStatic(name, fieldname, Type.getType(Class.class))); prepend.append(InstructionFactory.createDup(1)); prepend.append(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, parttwo.getStart())); prepend.append(InstructionFactory.POP); prepend.append(fact.createConstant(name)); InstructionHandle tryInstruction = prepend.getEnd(); prepend.append(fact.createInvoke("java.lang.Class", "forName", clazzType,new Type[]{ Type.getType(String.class)}, Constants.INVOKESTATIC)); InstructionHandle catchInstruction = prepend.getEnd(); prepend.append(InstructionFactory.createDup(1)); prepend.append(fact.createPutStatic(synchronizedMethod.getEnclosingClass().getType().getName(), fieldname, Type.getType(Class.class))); prepend.append(InstructionFactory.createBranchInstruction(Constants.GOTO, parttwo.getStart())); // start of catch block InstructionList catchBlockForLiteralLoadingFail = new InstructionList(); catchBlockForLiteralLoadingFail.append(fact.createNew((ObjectType)Type.getType(NoClassDefFoundError.class))); catchBlockForLiteralLoadingFail.append(InstructionFactory.createDup_1(1)); catchBlockForLiteralLoadingFail.append(InstructionFactory.SWAP); catchBlockForLiteralLoadingFail.append(fact.createInvoke("java.lang.Throwable", "getMessage", Type.getType(String.class),new Type[]{}, Constants.INVOKEVIRTUAL)); catchBlockForLiteralLoadingFail.append(fact.createInvoke("java.lang.NoClassDefFoundError", "<init>", Type.VOID,new Type[]{ Type.getType(String.class)}, Constants.INVOKESPECIAL)); catchBlockForLiteralLoadingFail.append(InstructionFactory.ATHROW); InstructionHandle catchBlockStart = catchBlockForLiteralLoadingFail.getStart(); prepend.append(catchBlockForLiteralLoadingFail); prepend.append(parttwo); // MONITORENTER // pseudocode: load up 'this' (var0), dup it, store it in a new local var (for use with monitorexit) and call monitorenter: // ALOAD_0, DUP, ASTORE_<n>, MONITORENTER // prepend.append(InstructionFactory.createLoad(classType,0)); // prepend.append(InstructionFactory.createDup(1)); // int slotForThis = synchronizedMethod.allocateLocal(classType); // prepend.append(InstructionFactory.createStore(classType, slotForThis)); // prepend.append(InstructionFactory.MONITORENTER); // MONITOREXIT // here be dragons // We basically need to wrap the code from the method in a finally block that // will ensure monitorexit is called. Content on the finally block seems to // be always: // // E1: ALOAD_1 // MONITOREXIT // ATHROW // // so lets build that: InstructionList finallyBlock = new InstructionList(); finallyBlock.append(InstructionFactory.createLoad(Type.getType(java.lang.Class.class),slotForThis)); finallyBlock.append(InstructionConstants.MONITOREXIT); finallyBlock.append(InstructionConstants.ATHROW); // finally -> E1 // | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 21) // | LDC "hello" // | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V // | ALOAD_1 (line 20) // | MONITOREXIT // finally -> E1 // GOTO L0 // finally -> E1 // | E1: ALOAD_1 // | MONITOREXIT // finally -> E1 // ATHROW // L0: RETURN (line 23) //frameEnv.put(donorFramePos, thisSlot); // search for 'returns' and make them to the aload_<n>,monitorexit InstructionHandle walker = body.getStart(); List rets = new ArrayList(); while (walker!=null) { //!walker.equals(body.getEnd())) { if (walker.getInstruction() instanceof ReturnInstruction) { rets.add(walker); } walker = walker.getNext(); } if (rets.size()>0) { // need to ensure targeters for 'return' now instead target the load instruction // (so we never jump over the monitorexit logic) for (Iterator iter = rets.iterator(); iter.hasNext();) { InstructionHandle element = (InstructionHandle) iter.next(); // System.err.println("Adding monitor exit block at "+element); InstructionList monitorExitBlock = new InstructionList(); monitorExitBlock.append(InstructionFactory.createLoad(classType,slotForThis)); monitorExitBlock.append(InstructionConstants.MONITOREXIT); //monitorExitBlock.append(Utility.copyInstruction(element.getInstruction())); //element.setInstruction(InstructionFactory.createLoad(classType,slotForThis)); InstructionHandle monitorExitBlockStart = body.insert(element,monitorExitBlock); // now move the targeters from the RET to the start of the monitorexit block InstructionTargeter[] targeters = element.getTargeters(); if (targeters!=null) { for (int i = 0; i < targeters.length; i++) { InstructionTargeter targeter = targeters[i]; // what kinds are there? if (targeter instanceof LocalVariableTag) { // ignore } else if (targeter instanceof LineNumberTag) { // ignore } else if (targeter instanceof GOTO || targeter instanceof GOTO_W) { // move it... targeter.updateTarget(element, monitorExitBlockStart); } else if (targeter instanceof BranchInstruction) { // move it targeter.updateTarget(element, monitorExitBlockStart); } else { throw new RuntimeException("Unexpected targeter encountered during transform: "+targeter); } } } } } // body = rewriteWithMonitorExitCalls(body,fact,true,slotForThis,classType); // synchronizedMethod.setBody(body); // now the magic, putting the finally block around the code InstructionHandle finallyStart = finallyBlock.getStart(); InstructionHandle tryPosition = body.getStart(); InstructionHandle catchPosition = body.getEnd(); body.insert(body.getStart(),prepend); // now we can put the monitorenter stuff on synchronizedMethod.getBody().append(finallyBlock); synchronizedMethod.addExceptionHandler(tryPosition, catchPosition,finallyStart,null/*==finally*/,false); synchronizedMethod.addExceptionHandler(tryInstruction, catchInstruction,catchBlockStart,(ObjectType)Type.getType(ClassNotFoundException.class),true); synchronizedMethod.addExceptionHandler(finallyStart,finallyStart.getNext(),finallyStart,null,false); } } else { // TRANSFORMING NON STATIC METHOD Type classType = BcelWorld.makeBcelType(synchronizedMethod.getEnclosingClass().getType()); // MONITORENTER // pseudocode: load up 'this' (var0), dup it, store it in a new local var (for use with monitorexit) and call monitorenter: // ALOAD_0, DUP, ASTORE_<n>, MONITORENTER prepend.append(InstructionFactory.createLoad(classType,0)); prepend.append(InstructionFactory.createDup(1)); int slotForThis = synchronizedMethod.allocateLocal(classType); prepend.append(InstructionFactory.createStore(classType, slotForThis)); prepend.append(InstructionFactory.MONITORENTER); // body.insert(body.getStart(),prepend); // MONITOREXIT // We basically need to wrap the code from the method in a finally block that // will ensure monitorexit is called. Content on the finally block seems to // be always: // // E1: ALOAD_1 // MONITOREXIT // ATHROW // // so lets build that: InstructionList finallyBlock = new InstructionList(); finallyBlock.append(InstructionFactory.createLoad(classType,slotForThis)); finallyBlock.append(InstructionConstants.MONITOREXIT); finallyBlock.append(InstructionConstants.ATHROW); // finally -> E1 // | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 21) // | LDC "hello" // | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V // | ALOAD_1 (line 20) // | MONITOREXIT // finally -> E1 // GOTO L0 // finally -> E1 // | E1: ALOAD_1 // | MONITOREXIT // finally -> E1 // ATHROW // L0: RETURN (line 23) //frameEnv.put(donorFramePos, thisSlot); // search for 'returns' and make them to the aload_<n>,monitorexit InstructionHandle walker = body.getStart(); List rets = new ArrayList(); while (walker!=null) { //!walker.equals(body.getEnd())) { if (walker.getInstruction() instanceof ReturnInstruction) { rets.add(walker); } walker = walker.getNext(); } if (rets.size()>0) { // need to ensure targeters for 'return' now instead target the load instruction // (so we never jump over the monitorexit logic) for (Iterator iter = rets.iterator(); iter.hasNext();) { InstructionHandle element = (InstructionHandle) iter.next(); // System.err.println("Adding monitor exit block at "+element); InstructionList monitorExitBlock = new InstructionList(); monitorExitBlock.append(InstructionFactory.createLoad(classType,slotForThis)); monitorExitBlock.append(InstructionConstants.MONITOREXIT); //monitorExitBlock.append(Utility.copyInstruction(element.getInstruction())); //element.setInstruction(InstructionFactory.createLoad(classType,slotForThis)); InstructionHandle monitorExitBlockStart = body.insert(element,monitorExitBlock); // now move the targeters from the RET to the start of the monitorexit block InstructionTargeter[] targeters = element.getTargeters(); if (targeters!=null) { for (int i = 0; i < targeters.length; i++) { InstructionTargeter targeter = targeters[i]; // what kinds are there? if (targeter instanceof LocalVariableTag) { // ignore } else if (targeter instanceof LineNumberTag) { // ignore } else if (targeter instanceof GOTO || targeter instanceof GOTO_W) { // move it... targeter.updateTarget(element, monitorExitBlockStart); } else if (targeter instanceof BranchInstruction) { // move it targeter.updateTarget(element, monitorExitBlockStart); } else { throw new RuntimeException("Unexpected targeter encountered during transform: "+targeter); } } } } } // now the magic, putting the finally block around the code InstructionHandle finallyStart = finallyBlock.getStart(); InstructionHandle tryPosition = body.getStart(); InstructionHandle catchPosition = body.getEnd(); body.insert(body.getStart(),prepend); // now we can put the monitorenter stuff on synchronizedMethod.getBody().append(finallyBlock); synchronizedMethod.addExceptionHandler(tryPosition, catchPosition,finallyStart,null/*==finally*/,false); synchronizedMethod.addExceptionHandler(finallyStart,finallyStart.getNext(),finallyStart,null,false); // also the exception handling for the finally block jumps to itself // max locals will already have been modified in the allocateLocal() call // synchronized bit is removed on LazyMethodGen.pack() } // gonna have to go through and change all aload_0s to load the var from a variable, // going to add a new variable for the this var if (trace.isTraceEnabled()) trace.exit("transformSynchronizedMethod"); } /** generate the instructions to be inlined. * * @param donor the method from which we will copy (and adjust frame and jumps) * instructions. * @param recipient the method the instructions will go into. Used to get the frame * size so we can allocate new frame locations for locals in donor. * @param frameEnv an environment to map from donor frame to recipient frame, * initially populated with argument locations. * @param fact an instruction factory for recipient */ static InstructionList genInlineInstructions( LazyMethodGen donor, LazyMethodGen recipient, IntMap frameEnv, InstructionFactory fact, boolean keepReturns) { InstructionList footer = new InstructionList(); InstructionHandle end = footer.append(InstructionConstants.NOP); InstructionList ret = new InstructionList(); InstructionList sourceList = donor.getBody(); Map srcToDest = new HashMap(); ConstantPoolGen donorCpg = donor.getEnclosingClass().getConstantPoolGen(); ConstantPoolGen recipientCpg = recipient.getEnclosingClass().getConstantPoolGen(); boolean isAcrossClass = donorCpg != recipientCpg; // first pass: copy the instructions directly, populate the srcToDest map, // fix frame instructions for (InstructionHandle src = sourceList.getStart(); src != null; src = src.getNext()) { Instruction fresh = Utility.copyInstruction(src.getInstruction()); InstructionHandle dest; if (fresh instanceof CPInstruction) { // need to reset index to go to new constant pool. This is totally // a computation leak... we're testing this LOTS of times. Sigh. if (isAcrossClass) { CPInstruction cpi = (CPInstruction) fresh; cpi.setIndex( recipientCpg.addConstant( donorCpg.getConstant(cpi.getIndex()), donorCpg)); } } if (src.getInstruction() == Range.RANGEINSTRUCTION) { dest = ret.append(Range.RANGEINSTRUCTION); } else if (fresh instanceof ReturnInstruction) { if (keepReturns) { dest = ret.append(fresh); } else { dest = ret.append(InstructionFactory.createBranchInstruction(Constants.GOTO, end)); } } else if (fresh instanceof BranchInstruction) { dest = ret.append((BranchInstruction) fresh); } else if ( fresh instanceof LocalVariableInstruction || fresh instanceof RET) { IndexedInstruction indexed = (IndexedInstruction) fresh; int oldIndex = indexed.getIndex(); int freshIndex; if (!frameEnv.hasKey(oldIndex)) { freshIndex = recipient.allocateLocal(2); frameEnv.put(oldIndex, freshIndex); } else { freshIndex = frameEnv.get(oldIndex); } indexed.setIndex(freshIndex); dest = ret.append(fresh); } else { dest = ret.append(fresh); } srcToDest.put(src, dest); } // second pass: retarget branch instructions, copy ranges and tags Map tagMap = new HashMap(); Map shadowMap = new HashMap(); for (InstructionHandle dest = ret.getStart(), src = sourceList.getStart(); dest != null; dest = dest.getNext(), src = src.getNext()) { Instruction inst = dest.getInstruction(); // retarget branches if (inst instanceof BranchInstruction) { BranchInstruction branch = (BranchInstruction) inst; InstructionHandle oldTarget = branch.getTarget(); InstructionHandle newTarget = (InstructionHandle) srcToDest.get(oldTarget); if (newTarget == null) { // assert this is a GOTO // this was a return instruction we previously replaced } else { branch.setTarget(newTarget); if (branch instanceof Select) { Select select = (Select) branch; InstructionHandle[] oldTargets = select.getTargets(); for (int k = oldTargets.length - 1; k >= 0; k--) { select.setTarget( k, (InstructionHandle) srcToDest.get(oldTargets[k])); } } } } //copy over tags and range attributes InstructionTargeter[] srcTargeters = src.getTargeters(); if (srcTargeters != null) { for (int j = srcTargeters.length - 1; j >= 0; j--) { InstructionTargeter old = srcTargeters[j]; if (old instanceof Tag) { Tag oldTag = (Tag) old; Tag fresh = (Tag) tagMap.get(oldTag); if (fresh == null) { fresh = oldTag.copy(); tagMap.put(oldTag, fresh); } dest.addTargeter(fresh); } else if (old instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) old; if (er.getStart() == src) { ExceptionRange freshEr = new ExceptionRange( recipient.getBody(), er.getCatchType(), er.getPriority()); freshEr.associateWithTargets( dest, (InstructionHandle)srcToDest.get(er.getEnd()), (InstructionHandle)srcToDest.get(er.getHandler())); } } else if (old instanceof ShadowRange) { ShadowRange oldRange = (ShadowRange) old; if (oldRange.getStart() == src) { BcelShadow oldShadow = oldRange.getShadow(); BcelShadow freshEnclosing = oldShadow.getEnclosingShadow() == null ? null : (BcelShadow) shadowMap.get(oldShadow.getEnclosingShadow()); BcelShadow freshShadow = oldShadow.copyInto(recipient, freshEnclosing); ShadowRange freshRange = new ShadowRange(recipient.getBody()); freshRange.associateWithShadow(freshShadow); freshRange.associateWithTargets( dest, (InstructionHandle) srcToDest.get(oldRange.getEnd())); shadowMap.put(oldRange, freshRange); //recipient.matchedShadows.add(freshShadow); // XXX should go through the NEW copied shadow and update // the thisVar, targetVar, and argsVar // ??? Might want to also go through at this time and add // "extra" vars to the shadow. } } } } } if (!keepReturns) ret.append(footer); return ret; } static InstructionList rewriteWithMonitorExitCalls(InstructionList sourceList,InstructionFactory fact,boolean keepReturns,int monitorVarSlot,Type monitorVarType) { InstructionList footer = new InstructionList(); InstructionHandle end = footer.append(InstructionConstants.NOP); InstructionList newList = new InstructionList(); Map srcToDest = new HashMap(); // first pass: copy the instructions directly, populate the srcToDest map, // fix frame instructions for (InstructionHandle src = sourceList.getStart(); src != null; src = src.getNext()) { Instruction fresh = Utility.copyInstruction(src.getInstruction()); InstructionHandle dest; if (src.getInstruction() == Range.RANGEINSTRUCTION) { dest = newList.append(Range.RANGEINSTRUCTION); } else if (fresh instanceof ReturnInstruction) { if (keepReturns) { newList.append(InstructionFactory.createLoad(monitorVarType,monitorVarSlot)); newList.append(InstructionConstants.MONITOREXIT); dest = newList.append(fresh); } else { dest = newList.append(InstructionFactory.createBranchInstruction(Constants.GOTO, end)); } } else if (fresh instanceof BranchInstruction) { dest = newList.append((BranchInstruction) fresh); } else if ( fresh instanceof LocalVariableInstruction || fresh instanceof RET) { IndexedInstruction indexed = (IndexedInstruction) fresh; int oldIndex = indexed.getIndex(); int freshIndex; // if (!frameEnv.hasKey(oldIndex)) { // freshIndex = recipient.allocateLocal(2); // frameEnv.put(oldIndex, freshIndex); // } else { freshIndex = oldIndex;//frameEnv.get(oldIndex); // } indexed.setIndex(freshIndex); dest = newList.append(fresh); } else { dest = newList.append(fresh); } srcToDest.put(src, dest); } // second pass: retarget branch instructions, copy ranges and tags Map tagMap = new HashMap(); Map shadowMap = new HashMap(); for (InstructionHandle dest = newList.getStart(), src = sourceList.getStart(); dest != null; dest = dest.getNext(), src = src.getNext()) { Instruction inst = dest.getInstruction(); // retarget branches if (inst instanceof BranchInstruction) { BranchInstruction branch = (BranchInstruction) inst; InstructionHandle oldTarget = branch.getTarget(); InstructionHandle newTarget = (InstructionHandle) srcToDest.get(oldTarget); if (newTarget == null) { // assert this is a GOTO // this was a return instruction we previously replaced } else { branch.setTarget(newTarget); if (branch instanceof Select) { Select select = (Select) branch; InstructionHandle[] oldTargets = select.getTargets(); for (int k = oldTargets.length - 1; k >= 0; k--) { select.setTarget( k, (InstructionHandle) srcToDest.get(oldTargets[k])); } } } } //copy over tags and range attributes InstructionTargeter[] srcTargeters = src.getTargeters(); if (srcTargeters != null) { for (int j = srcTargeters.length - 1; j >= 0; j--) { InstructionTargeter old = srcTargeters[j]; if (old instanceof Tag) { Tag oldTag = (Tag) old; Tag fresh = (Tag) tagMap.get(oldTag); if (fresh == null) { fresh = oldTag.copy(); tagMap.put(oldTag, fresh); } dest.addTargeter(fresh); } else if (old instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) old; if (er.getStart() == src) { ExceptionRange freshEr = new ExceptionRange(newList/*recipient.getBody()*/,er.getCatchType(),er.getPriority()); freshEr.associateWithTargets( dest, (InstructionHandle)srcToDest.get(er.getEnd()), (InstructionHandle)srcToDest.get(er.getHandler())); } } /*else if (old instanceof ShadowRange) { ShadowRange oldRange = (ShadowRange) old; if (oldRange.getStart() == src) { BcelShadow oldShadow = oldRange.getShadow(); BcelShadow freshEnclosing = oldShadow.getEnclosingShadow() == null ? null : (BcelShadow) shadowMap.get(oldShadow.getEnclosingShadow()); BcelShadow freshShadow = oldShadow.copyInto(recipient, freshEnclosing); ShadowRange freshRange = new ShadowRange(recipient.getBody()); freshRange.associateWithShadow(freshShadow); freshRange.associateWithTargets( dest, (InstructionHandle) srcToDest.get(oldRange.getEnd())); shadowMap.put(oldRange, freshRange); //recipient.matchedShadows.add(freshShadow); // XXX should go through the NEW copied shadow and update // the thisVar, targetVar, and argsVar // ??? Might want to also go through at this time and add // "extra" vars to the shadow. } }*/ } } } if (!keepReturns) newList.append(footer); return newList; } /** generate the argument stores in preparation for inlining. * * @param donor the method we will inline from. Used to get the signature. * @param recipient the method we will inline into. Used to get the frame size * so we can allocate fresh locations. * @param frameEnv an empty environment we populate with a map from donor frame to * recipient frame. * @param fact an instruction factory for recipient */ private static InstructionList genArgumentStores( LazyMethodGen donor, LazyMethodGen recipient, IntMap frameEnv, InstructionFactory fact) { InstructionList ret = new InstructionList(); int donorFramePos = 0; // writing ret back to front because we're popping. if (! donor.isStatic()) { int targetSlot = recipient.allocateLocal(Type.OBJECT); ret.insert(InstructionFactory.createStore(Type.OBJECT, targetSlot)); frameEnv.put(donorFramePos, targetSlot); donorFramePos += 1; } Type[] argTypes = donor.getArgumentTypes(); for (int i = 0, len = argTypes.length; i < len; i++) { Type argType = argTypes[i]; int argSlot = recipient.allocateLocal(argType); ret.insert(InstructionFactory.createStore(argType, argSlot)); frameEnv.put(donorFramePos, argSlot); donorFramePos += argType.getSize(); } return ret; } /** get a called method: Assumes the called method is in this class, * and the reference to it is exact (a la INVOKESPECIAL). * * @param ih The InvokeInstruction instructionHandle pointing to the called method. */ private LazyMethodGen getCalledMethod( InstructionHandle ih) { InvokeInstruction inst = (InvokeInstruction) ih.getInstruction(); String methodName = inst.getName(cpg); String signature = inst.getSignature(cpg); return clazz.getLazyMethodGen(methodName, signature); } private void weaveInAddedMethods() { Collections.sort(addedLazyMethodGens, new Comparator() { public int compare(Object a, Object b) { LazyMethodGen aa = (LazyMethodGen) a; LazyMethodGen bb = (LazyMethodGen) b; int i = aa.getName().compareTo(bb.getName()); if (i != 0) return i; return aa.getSignature().compareTo(bb.getSignature()); } } ); for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) { clazz.addMethodGen((LazyMethodGen)i.next()); } } void addPerSingletonField(Member field) { ObjectType aspectType = (ObjectType) BcelWorld.makeBcelType(field.getReturnType()); String aspectName = field.getReturnType().getName(); LazyMethodGen clinit = clazz.getStaticInitializer(); InstructionList setup = new InstructionList(); InstructionFactory fact = clazz.getFactory(); setup.append(fact.createNew(aspectType)); setup.append(InstructionFactory.createDup(1)); setup.append(fact.createInvoke( aspectName, "<init>", Type.VOID, new Type[0], Constants.INVOKESPECIAL)); setup.append( fact.createFieldAccess( aspectName, field.getName(), aspectType, Constants.PUTSTATIC)); clinit.getBody().insert(setup); } /** * Returns null if this is not a Java constructor, and then we won't * weave into it at all */ private InstructionHandle findSuperOrThisCall(LazyMethodGen mg) { int depth = 1; InstructionHandle start = mg.getBody().getStart(); while (true) { if (start == null) return null; Instruction inst = start.getInstruction(); if (inst instanceof INVOKESPECIAL && ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) { depth--; if (depth == 0) return start; } else if (inst instanceof NEW) { depth++; } start = start.getNext(); } } // ---- private boolean match(LazyMethodGen mg) { BcelShadow enclosingShadow; List shadowAccumulator = new ArrayList(); boolean startsAngly = mg.getName().charAt(0)=='<'; // we want to match ajsynthetic constructors... if (startsAngly && mg.getName().equals("<init>")) { return matchInit(mg, shadowAccumulator); } else if (!shouldWeaveBody(mg)) { //.isAjSynthetic()) { return false; } else { if (startsAngly && mg.getName().equals("<clinit>")) { clinitShadow = enclosingShadow = BcelShadow.makeStaticInitialization(world, mg); //System.err.println(enclosingShadow); } else if (mg.isAdviceMethod()) { enclosingShadow = BcelShadow.makeAdviceExecution(world, mg); } else { AjAttribute.EffectiveSignatureAttribute effective = mg.getEffectiveSignature(); if (effective == null) { enclosingShadow = BcelShadow.makeMethodExecution(world, mg, !canMatchBodyShadows); } else if (effective.isWeaveBody()) { ResolvedMember rm = effective.getEffectiveSignature(); // Annotations for things with effective signatures are never stored in the effective // signature itself - we have to hunt for them. Storing them in the effective signature // would mean keeping two sets up to date (no way!!) fixAnnotationsForResolvedMember(rm,mg.getMemberView()); enclosingShadow = BcelShadow.makeShadowForMethod(world,mg,effective.getShadowKind(),rm); } else { return false; } } if (canMatchBodyShadows) { for (InstructionHandle h = mg.getBody().getStart(); h != null; h = h.getNext()) { match(mg, h, enclosingShadow, shadowAccumulator); } } // FIXME asc change from string match if we can, rather brittle. this check actually prevents field-exec jps if (canMatch(enclosingShadow.getKind()) && !(mg.getName().charAt(0)=='a' && mg.getName().startsWith("ajc$interFieldInit"))) { if (match(enclosingShadow, shadowAccumulator)) { enclosingShadow.init(); } } mg.matchedShadows = shadowAccumulator; return !shadowAccumulator.isEmpty(); } } private boolean matchInit(LazyMethodGen mg, List shadowAccumulator) { BcelShadow enclosingShadow; // XXX the enclosing join point is wrong for things before ignoreMe. InstructionHandle superOrThisCall = findSuperOrThisCall(mg); // we don't walk bodies of things where it's a wrong constructor thingie if (superOrThisCall == null) return false; enclosingShadow = BcelShadow.makeConstructorExecution(world, mg, superOrThisCall); if (mg.getEffectiveSignature() != null) { enclosingShadow.setMatchingSignature(mg.getEffectiveSignature().getEffectiveSignature()); } // walk the body boolean beforeSuperOrThisCall = true; if (shouldWeaveBody(mg)) { if (canMatchBodyShadows) { for (InstructionHandle h = mg.getBody().getStart(); h != null; h = h.getNext()) { if (h == superOrThisCall) { beforeSuperOrThisCall = false; continue; } match(mg, h, beforeSuperOrThisCall ? null : enclosingShadow, shadowAccumulator); } } if (canMatch(Shadow.ConstructorExecution)) match(enclosingShadow, shadowAccumulator); } // XXX we don't do pre-inits of interfaces // now add interface inits if (superOrThisCall != null && ! isThisCall(superOrThisCall)) { InstructionHandle curr = enclosingShadow.getRange().getStart(); for (Iterator i = addedSuperInitializersAsList.iterator(); i.hasNext(); ) { IfaceInitList l = (IfaceInitList) i.next(); Member ifaceInitSig = AjcMemberMaker.interfaceConstructor(l.onType); BcelShadow initShadow = BcelShadow.makeIfaceInitialization(world, mg, ifaceInitSig); // insert code in place InstructionList inits = genInitInstructions(l.list, false); if (match(initShadow, shadowAccumulator) || !inits.isEmpty()) { initShadow.initIfaceInitializer(curr); initShadow.getRange().insert(inits, Range.OutsideBefore); } } // now we add our initialization code InstructionList inits = genInitInstructions(addedThisInitializers, false); enclosingShadow.getRange().insert(inits, Range.OutsideBefore); } // actually, you only need to inline the self constructors that are // in a particular group (partition the constructors into groups where members // call or are called only by those in the group). Then only inline // constructors // in groups where at least one initialization jp matched. Future work. boolean addedInitialization = match( BcelShadow.makeUnfinishedInitialization(world, mg), initializationShadows); addedInitialization |= match( BcelShadow.makeUnfinishedPreinitialization(world, mg), initializationShadows); mg.matchedShadows = shadowAccumulator; return addedInitialization || !shadowAccumulator.isEmpty(); } private boolean shouldWeaveBody(LazyMethodGen mg) { if (mg.isBridgeMethod()) return false; if (mg.isAjSynthetic()) return mg.getName().equals("<clinit>"); AjAttribute.EffectiveSignatureAttribute a = mg.getEffectiveSignature(); if (a != null) return a.isWeaveBody(); return true; } /** * first sorts the mungers, then gens the initializers in the right order */ private InstructionList genInitInstructions(List list, boolean isStatic) { list = PartialOrder.sort(list); if (list == null) { throw new BCException("circularity in inter-types"); } InstructionList ret = new InstructionList(); for (Iterator i = list.iterator(); i.hasNext();) { ConcreteTypeMunger cmunger = (ConcreteTypeMunger) i.next(); NewFieldTypeMunger munger = (NewFieldTypeMunger) cmunger.getMunger(); ResolvedMember initMethod = munger.getInitMethod(cmunger.getAspectType()); if (!isStatic) ret.append(InstructionConstants.ALOAD_0); ret.append(Utility.createInvoke(fact, world, initMethod)); } return ret; } private void match( LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { Instruction i = ih.getInstruction(); if ((i instanceof FieldInstruction) && (canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet)) ) { FieldInstruction fi = (FieldInstruction) i; if (fi instanceof PUTFIELD || fi instanceof PUTSTATIC) { // check for sets of constant fields. We first check the previous // instruction. If the previous instruction is a LD_WHATEVER (push // constant on the stack) then we must resolve the field to determine // if it's final. If it is final, then we don't generate a shadow. InstructionHandle prevHandle = ih.getPrev(); Instruction prevI = prevHandle.getInstruction(); if (Utility.isConstantPushInstruction(prevI)) { Member field = BcelWorld.makeFieldJoinPointSignature(clazz, (FieldInstruction) i); ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. } else if (Modifier.isFinal(resolvedField.getModifiers())) { // it's final, so it's the set of a final constant, so it's // not a join point according to 1.0.6 and 1.1. } else { if (canMatch(Shadow.FieldSet)) matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else { if (canMatch(Shadow.FieldSet)) matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else { if (canMatch(Shadow.FieldGet)) matchGetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else if (i instanceof InvokeInstruction) { InvokeInstruction ii = (InvokeInstruction) i; if (ii.getMethodName(clazz.getConstantPoolGen()).equals("<init>")) { if (canMatch(Shadow.ConstructorCall)) match( BcelShadow.makeConstructorCall(world, mg, ih, enclosingShadow), shadowAccumulator); } else if (ii instanceof INVOKESPECIAL) { String onTypeName = ii.getClassName(cpg); if (onTypeName.equals(mg.getEnclosingClass().getName())) { // we are private matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator); } else { // we are a super call, and this is not a join point in AspectJ-1.{0,1} } } else { matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator); } } else if (world.isJoinpointArrayConstructionEnabled() && (i instanceof NEWARRAY || i instanceof ANEWARRAY || i instanceof MULTIANEWARRAY)) { if (canMatch(Shadow.ConstructorCall)) { boolean debug = false; if (debug) System.err.println("Found new array instruction: "+i); if (i instanceof ANEWARRAY) { ANEWARRAY arrayInstruction = (ANEWARRAY)i; ObjectType arrayType = arrayInstruction.getLoadClassType(clazz.getConstantPoolGen()); if (debug) System.err.println("Array type is "+arrayType); BcelShadow ctorCallShadow = BcelShadow.makeArrayConstructorCall(world,mg,ih,enclosingShadow); match(ctorCallShadow,shadowAccumulator); } else if (i instanceof NEWARRAY) { NEWARRAY arrayInstruction = (NEWARRAY)i; Type arrayType = arrayInstruction.getType(); if (debug) System.err.println("Array type is "+arrayType); BcelShadow ctorCallShadow = BcelShadow.makeArrayConstructorCall(world,mg,ih,enclosingShadow); match(ctorCallShadow,shadowAccumulator); } else if (i instanceof MULTIANEWARRAY) { MULTIANEWARRAY arrayInstruction = (MULTIANEWARRAY)i; ObjectType arrayType = arrayInstruction.getLoadClassType(clazz.getConstantPoolGen()); if (debug) System.err.println("Array type is "+arrayType); BcelShadow ctorCallShadow = BcelShadow.makeArrayConstructorCall(world,mg,ih,enclosingShadow); match(ctorCallShadow,shadowAccumulator); } } // see pr77166 if you are thinking about implementing this // } else if (i instanceof AALOAD ) { // AALOAD arrayLoad = (AALOAD)i; // Type arrayType = arrayLoad.getType(clazz.getConstantPoolGen()); // BcelShadow arrayLoadShadow = BcelShadow.makeArrayLoadCall(world,mg,ih,enclosingShadow); // match(arrayLoadShadow,shadowAccumulator); // } else if (i instanceof AASTORE) { // // ... magic required } else if ( world.isJoinpointSynchronizationEnabled() && ((i instanceof MONITORENTER) || (i instanceof MONITOREXIT))) { // if (canMatch(Shadow.Monitoring)) { if (i instanceof MONITORENTER) { BcelShadow monitorEntryShadow = BcelShadow.makeMonitorEnter(world,mg,ih,enclosingShadow); match(monitorEntryShadow,shadowAccumulator); } else { BcelShadow monitorExitShadow = BcelShadow.makeMonitorExit(world,mg,ih,enclosingShadow); match(monitorExitShadow,shadowAccumulator); } // } } // performance optimization... we only actually care about ASTORE instructions, // since that's what every javac type thing ever uses to start a handler, but for // now we'll do this for everybody. if (!canMatch(Shadow.ExceptionHandler)) return; if (Range.isRangeHandle(ih)) return; InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int j = 0; j < targeters.length; j++) { InstructionTargeter t = targeters[j]; if (t instanceof ExceptionRange) { // assert t.getHandler() == ih ExceptionRange er = (ExceptionRange) t; if (er.getCatchType() == null) continue; if (isInitFailureHandler(ih)) return; match( BcelShadow.makeExceptionHandler( world, er, mg, ih, enclosingShadow), shadowAccumulator); } } } } private boolean isInitFailureHandler(InstructionHandle ih) { // Skip the astore_0 and aload_0 at the start of the handler and // then check if the instruction following these is // 'putstatic ajc$initFailureCause'. If it is then we are // in the handler we created in AspectClinit.generatePostSyntheticCode() InstructionHandle twoInstructionsAway = ih.getNext().getNext(); if (twoInstructionsAway.getInstruction() instanceof PUTSTATIC) { String name = ((PUTSTATIC)twoInstructionsAway.getInstruction()).getFieldName(cpg); if (name.equals(NameMangler.INITFAILURECAUSE_FIELD_NAME)) return true; } return false; } private void matchSetInstruction( LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { FieldInstruction fi = (FieldInstruction) ih.getInstruction(); Member field = BcelWorld.makeFieldJoinPointSignature(clazz, fi); // synthetic fields are never join points if (field.getName().startsWith(NameMangler.PREFIX)) return; ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. return; } else if ( Modifier.isFinal(resolvedField.getModifiers()) && Utility.isConstantPushInstruction(ih.getPrev().getInstruction())) { // it's the set of a final constant, so it's // not a join point according to 1.0.6 and 1.1. return; } else if (resolvedField.isSynthetic()) { // sets of synthetics aren't join points in 1.1 return; } else { // Fix for bug 172107 (similar the "get" fix for bug 109728) BcelShadow bs= BcelShadow.makeFieldSet(world, resolvedField, mg, ih, enclosingShadow); String cname = fi.getClassName(cpg); if (!resolvedField.getDeclaringType().getName().equals(cname)) { bs.setActualTargetType(cname); } match(bs, shadowAccumulator); } } private void matchGetInstruction(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { FieldInstruction fi = (FieldInstruction) ih.getInstruction(); Member field = BcelWorld.makeFieldJoinPointSignature(clazz, fi); // synthetic fields are never join points if (field.getName().startsWith(NameMangler.PREFIX)) return; ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. return; } else if (resolvedField.isSynthetic()) { // sets of synthetics aren't join points in 1.1 return; } else { BcelShadow bs = BcelShadow.makeFieldGet(world,resolvedField,mg,ih,enclosingShadow); String cname = fi.getClassName(cpg); if (!resolvedField.getDeclaringType().getName().equals(cname)) { bs.setActualTargetType(cname); } match(bs, shadowAccumulator); } } /** * For some named resolved type, this method looks for a member with a particular name - * it should only be used when you truly believe there is only one member with that * name in the type as it returns the first one it finds. */ private ResolvedMember findResolvedMemberNamed(ResolvedType type,String methodName) { ResolvedMember[] allMethods = type.getDeclaredMethods(); for (int i = 0; i < allMethods.length; i++) { ResolvedMember member = allMethods[i]; if (member.getName().equals(methodName)) return member; } return null; } /** * For a given resolvedmember, this will discover the real annotations for it. * <b>Should only be used when the resolvedmember is the contents of an effective signature * attribute, as thats the only time when the annotations aren't stored directly in the * resolvedMember</b> * @param rm the sig we want it to pretend to be 'int A.m()' or somesuch ITD like thing * @param declaredSig the real sig 'blah.ajc$xxx' */ private void fixAnnotationsForResolvedMember(ResolvedMember rm,ResolvedMember declaredSig) { try { UnresolvedType memberHostType = declaredSig.getDeclaringType(); ResolvedType[] annotations = (ResolvedType[])mapToAnnotations.get(rm); String methodName = declaredSig.getName(); // FIXME asc shouldnt really rely on string names ! if (annotations == null) { if (rm.getKind()==Member.FIELD) { if (methodName.startsWith("ajc$inlineAccessField")) { ResolvedMember resolvedDooberry = world.resolve(rm); annotations = resolvedDooberry.getAnnotationTypes(); } else { ResolvedMember realthing = AjcMemberMaker.interFieldInitializer(rm,memberHostType); ResolvedMember resolvedDooberry = world.resolve(realthing); annotations = resolvedDooberry.getAnnotationTypes(); } } else if (rm.getKind()==Member.METHOD && !rm.isAbstract()) { if (methodName.startsWith("ajc$inlineAccessMethod") || methodName.startsWith("ajc$superDispatch")) { ResolvedMember resolvedDooberry = world.resolve(declaredSig); annotations = resolvedDooberry.getAnnotationTypes(); } else { ResolvedMember realthing = AjcMemberMaker.interMethodDispatcher(rm.resolve(world),memberHostType).resolve(world); // ResolvedMember resolvedDooberry = world.resolve(realthing); ResolvedMember theRealMember = findResolvedMemberNamed(memberHostType.resolve(world),realthing.getName()); // AMC temp guard for M4 if (theRealMember == null) { throw new UnsupportedOperationException("Known limitation in M4 - can't find ITD members when type variable is used as an argument and has upper bound specified"); } annotations = theRealMember.getAnnotationTypes(); } } else if (rm.getKind()==Member.CONSTRUCTOR) { ResolvedMember realThing = AjcMemberMaker.postIntroducedConstructor(memberHostType.resolve(world),rm.getDeclaringType(),rm.getParameterTypes()); ResolvedMember resolvedDooberry = world.resolve(realThing); // AMC temp guard for M4 if (resolvedDooberry == null) { throw new UnsupportedOperationException("Known limitation in M4 - can't find ITD members when type variable is used as an argument and has upper bound specified"); } annotations = resolvedDooberry.getAnnotationTypes(); } if (annotations == null) annotations = new ResolvedType[0]; mapToAnnotations.put(rm,annotations); } rm.setAnnotationTypes(annotations); } catch (UnsupportedOperationException ex) { throw ex; } catch (Throwable t) { //FIXME asc remove this catch after more testing has confirmed the above stuff is OK throw new BCException("Unexpectedly went bang when searching for annotations on "+rm,t); } } private void matchInvokeInstruction(LazyMethodGen mg, InstructionHandle ih, InvokeInstruction invoke, BcelShadow enclosingShadow, List shadowAccumulator) { String methodName = invoke.getName(cpg); if (methodName.startsWith(NameMangler.PREFIX)) { Member jpSig = world.makeJoinPointSignatureForMethodInvocation(clazz, invoke); ResolvedMember declaredSig = jpSig.resolve(world); //System.err.println(method + ", declaredSig: " +declaredSig); if (declaredSig == null) return; if (declaredSig.getKind() == Member.FIELD) { Shadow.Kind kind; if (jpSig.getReturnType().equals(ResolvedType.VOID)) { kind = Shadow.FieldSet; } else { kind = Shadow.FieldGet; } if (canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet)) match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow, kind, declaredSig), shadowAccumulator); } else { AjAttribute.EffectiveSignatureAttribute effectiveSig = declaredSig.getEffectiveSignature(); if (effectiveSig == null) return; //System.err.println("call to inter-type member: " + effectiveSig); if (effectiveSig.isWeaveBody()) return; ResolvedMember rm = effectiveSig.getEffectiveSignature(); fixAnnotationsForResolvedMember(rm,declaredSig); // abracadabra if (canMatch(effectiveSig.getShadowKind())) match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow, effectiveSig.getShadowKind(), rm), shadowAccumulator); } } else { if (canMatch(Shadow.MethodCall)) match( BcelShadow.makeMethodCall(world, mg, ih, enclosingShadow), shadowAccumulator); } } // static ... so all worlds will share the config for the first one created... private static boolean checkedXsetForLowLevelContextCapturing = false; private static boolean captureLowLevelContext = false; private boolean match(BcelShadow shadow, List shadowAccumulator) { //System.err.println("match: " + shadow); if (captureLowLevelContext) { // duplicate blocks - one with context capture, one without, seems faster than multiple 'ifs()' ContextToken shadowMatchToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MATCHING_SHADOW, shadow); boolean isMatched = false; for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) { ShadowMunger munger = (ShadowMunger)i.next(); ContextToken mungerMatchToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MATCHING_POINTCUT, munger.getPointcut()); if (munger.match(shadow, world)) { WeaverMetrics.recordMatchResult(true);// Could pass: munger shadow.addMunger(munger); isMatched = true; if (shadow.getKind() == Shadow.StaticInitialization) { clazz.warnOnAddedStaticInitializer(shadow,munger.getSourceLocation()); } } else { WeaverMetrics.recordMatchResult(false); // Could pass: munger } CompilationAndWeavingContext.leavingPhase(mungerMatchToken); } if (isMatched) shadowAccumulator.add(shadow); CompilationAndWeavingContext.leavingPhase(shadowMatchToken); return isMatched; } else { boolean isMatched = false; for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) { ShadowMunger munger = (ShadowMunger)i.next(); if (munger.match(shadow, world)) { shadow.addMunger(munger); isMatched = true; if (shadow.getKind() == Shadow.StaticInitialization) { clazz.warnOnAddedStaticInitializer(shadow,munger.getSourceLocation()); } } } if (isMatched) shadowAccumulator.add(shadow); return isMatched; } } // ---- private void implement(LazyMethodGen mg) { List shadows = mg.matchedShadows; if (shadows == null) return; // We depend on a partial order such that inner shadows are earlier on the list // than outer shadows. That's fine. This order is preserved if: // A preceeds B iff B.getStart() is LATER THAN A.getStart(). for (Iterator i = shadows.iterator(); i.hasNext(); ) { BcelShadow shadow = (BcelShadow)i.next(); ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.IMPLEMENTING_ON_SHADOW,shadow); shadow.implement(); CompilationAndWeavingContext.leavingPhase(tok); } int ii = mg.getMaxLocals(); mg.matchedShadows = null; } // ---- public LazyClassGen getLazyClassGen() { return clazz; } public List getShadowMungers() { return shadowMungers; } public BcelWorld getWorld() { return world; } // Called by the BcelWeaver to let us know all BcelClassWeavers need to collect reweavable info public static void setReweavableMode(boolean mode) { inReweavableMode = mode; } public static boolean getReweavableMode() { return inReweavableMode; } public String toString() { return "BcelClassWeaver instance for : "+clazz; } }
230,817
Bug 230817 LazyMethodGen.remap() NullPointerException
This has been reported a few times by different users, but has always proved tough to diagnose. The typical stack trace is something like: java.lang.NullPointerException org.aspectj.weaver.bcel.LazyMethodGen.remap(LazyMethodGen.java:1237) org.aspectj.weaver.bcel.LazyMethodGen.addExceptionHandlers(LazyMethodGen.java:1132) org.aspectj.weaver.bcel.LazyMethodGen.packBody(LazyMethodGen.java:1078) org.aspectj.weaver.bcel.LazyMethodGen.pack(LazyMethodGen.java:977) org.aspectj.weaver.bcel.LazyMethodGen.getMethod(LazyMethodGen.java:484) org.aspectj.weaver.bcel.LazyClassGen.writeBack(LazyClassGen.java:512) org.aspectj.weaver.bcel.LazyClassGen.getJavaClassBytesIncludingReweavable(LazyClassGen.java:652) org.aspectj.weaver.bcel.BcelWeaver.getClassFilesFor(BcelWeaver.java:1420) org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1390) And that is an exception on this line in remap() ih = ih.getNext(); called from the addExceptionHandlers() line: gen.addExceptionHandler( remap(r.getRealStart(), map), remap(r.getRealEnd(), map), remap(r.getHandler(), map), (r.getCatchType() == null) ? null : (ObjectType) BcelWorld.makeBcelType(r.getCatchType())); During weaving, an instruction list is augmented with extra entries representing where shadows start and end (method-call, method-execution, handler, etc). When weaving is complete we want to remove these temporary elements and use the remaining instructions to produce the method bytecode. Now sometimes these temporary entries are targeted by other elements (line number tags, local variable tags and exception handlers usually). During packing we use remap() to reposition the locations so they move off of temporary placeholders and onto real instructions that will make it out into the bytecode. What the above exception tells us is that we started walking over temporary placeholder entries, but before we came to a real instruction, we ran out of instructions! This cannot happen, and indicates something went seriously wrong, we should always encounter an instruction when remapping off a temporary element. After some digging it is actually the remap() call for the handler (not the start or end) that leads to the problem. The handler represents where to jump to in the code when an exception of the specified type occurs between the instructions pointed at by start and end. I sent a debug build to a user encountering this problem (I could not recreate it) and in that I was looking at where in fact the handler was pointing before we called remap(). I learned that when this problem occurs, the handler is not pointing to anywhere in the method currently being processed (not good). In a second debug build I tried to ascertain who was setting these handlers to point to nowhere. This debug never triggered, no-one was setting them to point to nowhere... I happened to notice whilst going through the instructions in the debug output that cobertura was being used, a coverage toolkit that works by doing bytecode manipulation to insert calls out to a library. AspectJ was being called after cobertura and I asked the user to try the steps the other way round - it worked fine. Indicating cobertura was doing something to the bytecode that gave us problems. After much messing about, I recreated it by applying around advice to within(*) to all the classes in rt.jar (I just used that as a very large standalone jar file I could weave into). I learned that Cobertura creates catch blocks that look a little different to what javac and other compilers create. The typical bytecode sequence a compiler produces for a catch block starts with a STORE instruction, to store the exception being caught (whether the body of the catch block uses it or not). But the cobertura catch blocks started with an INVOKESTATIC instruction, a call out to another method. What does this mean? It means the same instruction has two shadows, a 'handler' shadow and a 'method-call' shadow - and it turns out this is what causes our problem. If around advice is applied to the call join point and it cannot be inlined then the body of the call shadow (the call itself) is pulled out into a new method. Because the handler was the same instruction, this meant the handler *was also being pulled out* into the new method, leaving behind an exception handler that jumped to an invalid location (in fact it 'jumped' to an instruction in a different method!). So the reason I never saw the handler location being set incorrectly is that it was set correctly up front, but then dragged out with the method-call shadow into the wrong place. In bytecode terms it looks like this: method-execution() | ICONST_0 | ISTORE_2 | SIPUSH -1 | ISTORE_3 | catch java.lang.Exception (1806389629) -> E0 | | method-call(ProjectData ProjectData.getGlobalProjectData()) | | | INVOKESTATIC ProjectData.getGlobalProjectData () | | method-call(ProjectData getGlobalProjectData()) | | LDC "SomeString" | | method-call(ClassData getOrCreateClassData(java.lang.String)) | | | INVOKEVIRTUAL ProjectData.getOrCreateClassData (LString;) | | method-call(ClassData ProjectData.getOrCreateClassData(String)) | | SIPUSH 106 | | method-call(void ClassData.touch(int)) | | | INVOKEVIRTUAL ClassData.touch (I)V | | method-call(void ClassData.touch(int)) | | ALOAD_1 | | method-call(Object Expression.getValue()) | | | INVOKEVIRTUAL Expression.getValue () | | method-call(Object Expression.getValue()) | catch java.lang.Exception (1806389629) -> E0 | ARETURN | method-call(nProjectData ProjectData.getGlobalProjectData()) | | E0: INVOKESTATIC ProjectData.getGlobalProjectData () | method-call(ProjectData ProjectData.getGlobalProjectData()) | LDC "Object" We can see the problem in that final method-call. The target for the exception handler seen earlier (E0) is within the method-call shadow. What to do?
resolved fixed
5f97d46
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-05-07T15:31:18Z"
"2008-05-07T03:13:20Z"
weaver/src/org/aspectj/weaver/bcel/LazyMethodGen.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Stack; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.ConstantPool; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Synthetic; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.generic.BranchHandle; import org.aspectj.apache.bcel.generic.BranchInstruction; import org.aspectj.apache.bcel.generic.CPInstruction; import org.aspectj.apache.bcel.generic.ClassGenException; import org.aspectj.apache.bcel.generic.CodeExceptionGen; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InstructionTargeter; import org.aspectj.apache.bcel.generic.LineNumberGen; import org.aspectj.apache.bcel.generic.LineNumberTag; import org.aspectj.apache.bcel.generic.LocalVariableGen; import org.aspectj.apache.bcel.generic.LocalVariableInstruction; import org.aspectj.apache.bcel.generic.LocalVariableTag; import org.aspectj.apache.bcel.generic.MethodGen; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.Select; import org.aspectj.apache.bcel.generic.Tag; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.generic.annotation.AnnotationGen; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.MessageUtil; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.MemberImpl; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.AjAttribute.WeaverVersionInfo; import org.aspectj.weaver.tools.Traceable; /** * A LazyMethodGen should be treated as a MethodGen. It's our way of abstracting over the * low-level Method objects. It converts through {@link MethodGen} to create * and to serialize, but that's it. * * <p> At any rate, there are two ways to create LazyMethodGens. * One is from a method, which * does work through MethodGen to do the correct thing. * The other is the creation of a completely empty * LazyMethodGen, and it is used when we're constructing code from scratch. * * <p> We stay away from targeters for rangey things like Shadows and Exceptions. */ public final class LazyMethodGen implements Traceable { private static final int ACC_SYNTHETIC = 0x1000; private int accessFlags; private Type returnType; private final String name; private Type[] argumentTypes; //private final String[] argumentNames; private String[] declaredExceptions; private InstructionList body; // leaving null for abstracts private Attribute[] attributes; private List newAnnotations; private final LazyClassGen enclosingClass; private BcelMethod memberView; private AjAttribute.EffectiveSignatureAttribute effectiveSignature; int highestLineNumber = 0; /* * This option specifies whether we let the BCEL classes create LineNumberGens and LocalVariableGens * or if we make it create LineNumberTags and LocalVariableTags. Up until 1.5.1 we always created * Gens - then on return from the MethodGen ctor we took them apart, reprocessed them all and * created Tags. (see unpackLocals/unpackLineNumbers). As we have our own copy of Bcel, why not create * the right thing straightaway? So setting this to true will call the MethodGen ctor() in such * a way that it creates Tags - removing the need for unpackLocals/unpackLineNumbers - HOWEVER see * the ensureAllLineNumberSetup() method for some other relevant info. * * Whats the difference between a Tag and a Gen? A Tag is more lightweight, it doesn't know which * instructions it targets, it relies on the instructions targetting *it* - this reduces the amount * of targeter manipulation we have to do. * * Because this *could* go wrong - it passes all our tests, but you never know, the option: * -Xset:optimizeWithTags=false * will turn it *OFF* */ public static boolean avoidUseOfBcelGenObjects = true; public static boolean checkedXsetOption = false; /** This is nonnull if this method is the result of an "inlining". We currently * copy methods into other classes for around advice. We add this field so * we can get JSR45 information correct. If/when we do _actual_ inlining, * we'll need to subtype LineNumberTag to have external line numbers. */ String fromFilename = null; private int maxLocals; private boolean canInline = true; // private boolean hasExceptionHandlers; private boolean isSynthetic = false; /** * only used by {@link BcelClassWeaver} */ List /*ShadowMungers*/ matchedShadows; List /*Test*/ matchedShadowTests; // Used for interface introduction // this is the type of the interface the method is technically on public ResolvedType definingType = null; public LazyMethodGen( int accessFlags, Type returnType, String name, Type[] paramTypes, String[] declaredExceptions, LazyClassGen enclosingClass) { //System.err.println("raw create of: " + name + ", " + enclosingClass.getName() + ", " + returnType); this.memberView = null; // ??? should be okay, since constructed ones aren't woven into this.accessFlags = accessFlags; this.returnType = returnType; this.name = name; this.argumentTypes = paramTypes; //this.argumentNames = Utility.makeArgNames(paramTypes.length); this.declaredExceptions = declaredExceptions; if (!Modifier.isAbstract(accessFlags)) { body = new InstructionList(); setMaxLocals(calculateMaxLocals()); } else { body = null; } this.attributes = new Attribute[0]; this.enclosingClass = enclosingClass; assertGoodBody(); // @AJ advice are not inlined by default since requires further analysis // and weaving ordering control // TODO AV - improve - note: no room for improvement as long as aspects are reweavable // since the inlined version with wrappers and an to be done annotation to keep // inline state will be garbaged due to reweavable impl if (memberView != null && isAdviceMethod()) { if (enclosingClass.getType().isAnnotationStyleAspect()) { //TODO we could check for @Around advice as well this.canInline = false; } } } private int calculateMaxLocals() { int ret = 0; if (!Modifier.isStatic(accessFlags)) ret++; for (int i = 0, len = argumentTypes.length; i < len; i++) { ret += argumentTypes[i].getSize(); } return ret; } private Method savedMethod = null; // build from an existing method, lazy build saves most work for initialization public LazyMethodGen(Method m, LazyClassGen enclosingClass) { savedMethod = m; this.enclosingClass = enclosingClass; if (!(m.isAbstract() || m.isNative()) && m.getCode() == null) { throw new RuntimeException("bad non-abstract method with no code: " + m + " on " + enclosingClass); } if ((m.isAbstract() || m.isNative()) && m.getCode() != null) { throw new RuntimeException("bad abstract method with code: " + m + " on " + enclosingClass); } this.memberView = new BcelMethod(enclosingClass.getBcelObjectType(), m); this.accessFlags = m.getAccessFlags(); this.name = m.getName(); // @AJ advice are not inlined by default since requires further analysis // and weaving ordering control // TODO AV - improve - note: no room for improvement as long as aspects are reweavable // since the inlined version with wrappers and an to be done annotation to keep // inline state will be garbaged due to reweavable impl if (memberView != null && isAdviceMethod()) { if (enclosingClass.getType().isAnnotationStyleAspect()) { //TODO we could check for @Around advice as well this.canInline = false; } } } public boolean hasDeclaredLineNumberInfo() { return (memberView != null && memberView.hasDeclarationLineNumberInfo()); } public int getDeclarationLineNumber() { if (hasDeclaredLineNumberInfo()) { return memberView.getDeclarationLineNumber(); } else { return -1; } } public int getDeclarationOffset() { if (hasDeclaredLineNumberInfo()) { return memberView.getDeclarationOffset(); } else { return 0; } } public void addAnnotation(AnnotationX ax) { initialize(); if (memberView==null) { // If member view is null, we manage them in newAnnotations if (newAnnotations==null) newAnnotations = new ArrayList(); newAnnotations.add(ax); } else { memberView.addAnnotation(ax); } } public boolean hasAnnotation(UnresolvedType annotationTypeX) { initialize(); if (memberView==null) { // Check local annotations first if (newAnnotations!=null) { for (Iterator iter = newAnnotations.iterator(); iter.hasNext();) { AnnotationX element = (AnnotationX) iter.next(); if (element.getBcelAnnotation().getTypeName().equals(annotationTypeX.getName())) return true; } } memberView = new BcelMethod(getEnclosingClass().getBcelObjectType(), getMethod()); return memberView.hasAnnotation(annotationTypeX); } return memberView.hasAnnotation(annotationTypeX); } private void initialize() { if (returnType != null) return; // Check whether we need to configure the optimization if (!checkedXsetOption) { Properties p = enclosingClass.getWorld().getExtraConfiguration(); if (p!=null) { String s = p.getProperty("optimizeWithTags","true"); avoidUseOfBcelGenObjects = s.equalsIgnoreCase("true"); if (!avoidUseOfBcelGenObjects) enclosingClass.getWorld().getMessageHandler().handleMessage(MessageUtil.info("[optimizeWithTags=false] Disabling optimization to use Tags rather than Gens")); } checkedXsetOption=true; } //System.err.println("initializing: " + getName() + ", " + enclosingClass.getName() + ", " + returnType + ", " + savedMethod); MethodGen gen = new MethodGen(savedMethod, enclosingClass.getName(), enclosingClass.getConstantPoolGen(),avoidUseOfBcelGenObjects); this.returnType = gen.getReturnType(); this.argumentTypes = gen.getArgumentTypes(); this.declaredExceptions = gen.getExceptions(); this.attributes = gen.getAttributes(); //this.annotations = gen.getAnnotations(); this.maxLocals = gen.getMaxLocals(); // this.returnType = BcelWorld.makeBcelType(memberView.getReturnType()); // this.argumentTypes = BcelWorld.makeBcelTypes(memberView.getParameterTypes()); // // this.declaredExceptions = UnresolvedType.getNames(memberView.getExceptions()); //gen.getExceptions(); // this.attributes = new Attribute[0]; //gen.getAttributes(); // this.maxLocals = savedMethod.getCode().getMaxLocals(); if (gen.isAbstract() || gen.isNative()) { body = null; } else { //body = new InstructionList(savedMethod.getCode().getCode()); body = gen.getInstructionList(); unpackHandlers(gen); if (avoidUseOfBcelGenObjects) { ensureAllLineNumberSetup(gen); highestLineNumber = gen.getHighestlinenumber(); } else { unpackLineNumbers(gen); unpackLocals(gen); } } assertGoodBody(); //System.err.println("initialized: " + this.getClassName() + "." + this.getName()); } // XXX we're relying on the javac promise I've just made up that we won't have an early exception // in the list mask a later exception: That is, for two exceptions E and F, // if E preceeds F, then either E \cup F = {}, or E \nonstrictsubset F. So when we add F, // we add it on the _OUTSIDE_ of any handlers that share starts or ends with it. // with that in mind, we merrily go adding ranges for exceptions. private void unpackHandlers(MethodGen gen) { CodeExceptionGen[] exns = gen.getExceptionHandlers(); if (exns != null) { int len = exns.length; // if (len > 0) hasExceptionHandlers = true; int priority = len - 1; for (int i = 0; i < len; i++, priority--) { CodeExceptionGen exn = exns[i]; InstructionHandle start = Range.genStart( body, getOutermostExceptionStart(exn.getStartPC())); InstructionHandle end = Range.genEnd(body, getOutermostExceptionEnd(exn.getEndPC())); // this doesn't necessarily handle overlapping correctly!!! ExceptionRange er = new ExceptionRange( body, exn.getCatchType() == null ? null : BcelWorld.fromBcel(exn.getCatchType()), priority); er.associateWithTargets(start, end, exn.getHandlerPC()); exn.setStartPC(null); // also removes from target exn.setEndPC(null); // also removes from target exn.setHandlerPC(null); // also removes from target } gen.removeExceptionHandlers(); } } private InstructionHandle getOutermostExceptionStart(InstructionHandle ih) { while (true) { if (ExceptionRange.isExceptionStart(ih.getPrev())) { ih = ih.getPrev(); } else { return ih; } } } private InstructionHandle getOutermostExceptionEnd(InstructionHandle ih) { while (true) { if (ExceptionRange.isExceptionEnd(ih.getNext())) { ih = ih.getNext(); } else { return ih; } } } private void unpackLineNumbers(MethodGen gen) { LineNumberTag lr = null; for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter targeter = targeters[i]; if (targeter instanceof LineNumberGen) { LineNumberGen lng = (LineNumberGen) targeter; lng.updateTarget(ih, null); int lineNumber = lng.getSourceLine(); if (highestLineNumber < lineNumber) highestLineNumber = lineNumber; lr = new LineNumberTag(lineNumber); } } } if (lr != null) { ih.addTargeter(lr); } } gen.removeLineNumbers(); } /** * On entry to this method we have a method whose instruction stream contains a few instructions * that have line numbers assigned to them (LineNumberTags). The aim is to ensure every instruction * has the right line number. This is necessary because some of them may be extracted out into other * methods - and it'd be useful for them to maintain the source line number for debugging. */ private void ensureAllLineNumberSetup(MethodGen gen) { LineNumberTag lr = null; boolean skip = false; for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { InstructionTargeter[] targeters = ih.getTargeters(); skip = false; if (targeters != null) { for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter targeter = targeters[i]; if (targeter instanceof LineNumberTag) { lr = (LineNumberTag) targeter; skip=true; } } } if (lr != null && !skip) { ih.addTargeter(lr); } } } private void unpackLocals(MethodGen gen) { Set locals = new HashSet(); for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { InstructionTargeter[] targeters = ih.getTargeters(); List ends = new ArrayList(0); if (targeters != null) { for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter targeter = targeters[i]; if (targeter instanceof LocalVariableGen) { LocalVariableGen lng = (LocalVariableGen) targeter; LocalVariableTag lr = new LocalVariableTag(lng.getType().getSignature()/*BcelWorld.fromBcel(lng.getType())*/, lng.getName(), lng.getIndex(), lng.getStart().getPosition()); if (lng.getStart() == ih) { locals.add(lr); } else { ends.add(lr); } } } } for (Iterator i = locals.iterator(); i.hasNext(); ) { ih.addTargeter((LocalVariableTag) i.next()); } locals.removeAll(ends); } gen.removeLocalVariables(); } // =============== public int allocateLocal(Type type) { return allocateLocal(type.getSize()); } public int allocateLocal(int slots) { int max = getMaxLocals(); setMaxLocals(max + slots); return max; } public Method getMethod() { if (savedMethod != null) return savedMethod; //??? this relies on gentle treatment of constant pool try { MethodGen gen = pack(); return gen.getMethod(); } catch (ClassGenException e) { enclosingClass.getBcelObjectType().getResolvedTypeX().getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.PROBLEM_GENERATING_METHOD, this.getClassName(), this.getName(), e.getMessage()), this.getMemberView() == null ? null : this.getMemberView().getSourceLocation(), null); // throw e; PR 70201.... let the normal problem reporting infrastructure deal with this rather than crashing. body = null; MethodGen gen = pack(); return gen.getMethod(); } } public void markAsChanged() { initialize(); savedMethod = null; } // ============================= public String toString() { WeaverVersionInfo weaverVersion = enclosingClass.getBcelObjectType().getWeaverVersionAttribute(); return toLongString(weaverVersion); } public String toShortString() { String access = org.aspectj.apache.bcel.classfile.Utility.accessToString(getAccessFlags()); StringBuffer buf = new StringBuffer(); if (!access.equals("")) { buf.append(access); buf.append(" "); } buf.append( org.aspectj.apache.bcel.classfile.Utility.signatureToString( getReturnType().getSignature(), true)); buf.append(" "); buf.append(getName()); buf.append("("); { int len = argumentTypes.length; if (len > 0) { buf.append( org.aspectj.apache.bcel.classfile.Utility.signatureToString( argumentTypes[0].getSignature(), true)); for (int i = 1; i < argumentTypes.length; i++) { buf.append(", "); buf.append( org.aspectj.apache.bcel.classfile.Utility.signatureToString( argumentTypes[i].getSignature(), true)); } } } buf.append(")"); { int len = declaredExceptions != null ? declaredExceptions.length : 0; if (len > 0) { buf.append(" throws "); buf.append(declaredExceptions[0]); for (int i = 1; i < declaredExceptions.length; i++) { buf.append(", "); buf.append(declaredExceptions[i]); } } } return buf.toString(); } public String toLongString(WeaverVersionInfo weaverVersion) { ByteArrayOutputStream s = new ByteArrayOutputStream(); print(new PrintStream(s),weaverVersion); return new String(s.toByteArray()); } public void print(WeaverVersionInfo weaverVersion) { print(System.out,weaverVersion); } public void print(PrintStream out, WeaverVersionInfo weaverVersion) { out.print(" " + toShortString()); printAspectAttributes(out,weaverVersion); InstructionList body = getBody(); if (body == null) { out.println(";"); return; } out.println(":"); new BodyPrinter(out).run(); out.println(" end " + toShortString()); } private void printAspectAttributes(PrintStream out, WeaverVersionInfo weaverVersion) { ISourceContext context = null; if (enclosingClass != null && enclosingClass.getType() != null) { context = enclosingClass.getType().getSourceContext(); } List as = BcelAttributes.readAjAttributes(getClassName(),attributes, context,null,weaverVersion); if (! as.isEmpty()) { out.println(" " + as.get(0)); // XXX assuming exactly one attribute, munger... } } private class BodyPrinter { Map prefixMap = new HashMap(); Map suffixMap = new HashMap(); Map labelMap = new HashMap(); InstructionList body; PrintStream out; ConstantPool pool; List ranges; BodyPrinter(PrintStream out) { this.pool = enclosingClass.getConstantPoolGen().getConstantPool(); this.body = getBody(); this.out = out; } void run() { //killNops(); assignLabels(); print(); } // label assignment void assignLabels() { LinkedList exnTable = new LinkedList(); String pendingLabel = null; // boolean hasPendingTargeters = false; int lcounter = 0; for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter t = targeters[i]; if (t instanceof ExceptionRange) { // assert isRangeHandle(h); ExceptionRange r = (ExceptionRange) t; if (r.getStart() == ih) { insertHandler(r, exnTable); } } else if (t instanceof BranchInstruction) { if (pendingLabel == null) { pendingLabel = "L" + lcounter++; } } else { // assert isRangeHandle(h) } } } if (pendingLabel != null) { labelMap.put(ih, pendingLabel); if (! Range.isRangeHandle(ih)) { pendingLabel = null; } } } int ecounter = 0; for (Iterator i = exnTable.iterator(); i.hasNext();) { ExceptionRange er = (ExceptionRange) i.next(); String exceptionLabel = "E" + ecounter++; labelMap.put(Range.getRealStart(er.getHandler()), exceptionLabel); labelMap.put(er.getHandler(), exceptionLabel); } } // printing void print() { int depth = 0; int currLine = -1; bodyPrint: for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { if (Range.isRangeHandle(ih)) { Range r = Range.getRange(ih); // don't print empty ranges, that is, ranges who contain no actual instructions for (InstructionHandle xx = r.getStart(); Range.isRangeHandle(xx); xx = xx.getNext()) { if (xx == r.getEnd()) continue bodyPrint; } // doesn't handle nested: if (r.getStart().getNext() == r.getEnd()) continue; if (r.getStart() == ih) { printRangeString(r, depth++); } else { if (r.getEnd() != ih) throw new RuntimeException("bad"); printRangeString(r, --depth); } } else { printInstruction(ih, depth); int line = getLineNumber(ih, currLine); if (line != currLine) { currLine = line; out.println(" (line " + line + ")"); } else { out.println(); } } } } void printRangeString(Range r, int depth) { printDepth(depth); out.println(getRangeString(r, labelMap)); } String getRangeString(Range r, Map labelMap) { if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; return er.toString() + " -> " + labelMap.get(er.getHandler()); // // + " PRI " + er.getPriority(); } else { return r.toString(); } } void printDepth(int depth) { pad(BODY_INDENT); while (depth > 0) { out.print("| "); depth--; } } void printLabel(String s, int depth) { int space = Math.max(CODE_INDENT - depth * 2, 0); if (s == null) { pad(space); } else { space = Math.max(space - (s.length() + 2), 0); pad(space); out.print(s); out.print(": "); } } void printInstruction(InstructionHandle h, int depth) { printDepth(depth); printLabel((String) labelMap.get(h), depth); Instruction inst = h.getInstruction(); if (inst instanceof CPInstruction) { CPInstruction cpinst = (CPInstruction) inst; out.print(Constants.OPCODE_NAMES[cpinst.getOpcode()].toUpperCase()); out.print(" "); out.print(pool.constantToString(pool.getConstant(cpinst.getIndex()))); } else if (inst instanceof Select) { Select sinst = (Select) inst; out.println(Constants.OPCODE_NAMES[sinst.getOpcode()].toUpperCase()); int[] matches = sinst.getMatchs(); InstructionHandle[] targets = sinst.getTargets(); InstructionHandle defaultTarget = sinst.getTarget(); for (int i = 0, len = matches.length; i < len; i++) { printDepth(depth); printLabel(null, depth); out.print(" "); out.print(matches[i]); out.print(": \t"); out.println(labelMap.get(targets[i])); } printDepth(depth); printLabel(null, depth); out.print(" "); out.print("default: \t"); out.print(labelMap.get(defaultTarget)); } else if (inst instanceof BranchInstruction) { BranchInstruction brinst = (BranchInstruction) inst; out.print(Constants.OPCODE_NAMES[brinst.getOpcode()].toUpperCase()); out.print(" "); out.print(labelMap.get(brinst.getTarget())); } else if (inst instanceof LocalVariableInstruction) { LocalVariableInstruction lvinst = (LocalVariableInstruction) inst; out.print(inst.toString(false).toUpperCase()); int index = lvinst.getIndex(); LocalVariableTag tag = getLocalVariableTag(h, index); if (tag != null) { out.print(" // "); out.print(tag.getType()); out.print(" "); out.print(tag.getName()); } } else { out.print(inst.toString(false).toUpperCase()); } } static final int BODY_INDENT = 4; static final int CODE_INDENT = 16; void pad(int size) { for (int i = 0; i < size; i++) { out.print(" "); } } } static LocalVariableTag getLocalVariableTag( InstructionHandle ih, int index) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters == null) return null; for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter t = targeters[i]; if (t instanceof LocalVariableTag) { LocalVariableTag lvt = (LocalVariableTag) t; if (lvt.getSlot() == index) return lvt; } } return null; } static int getLineNumber( InstructionHandle ih, int prevLine) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters == null) return prevLine; for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter t = targeters[i]; if (t instanceof LineNumberTag) { return ((LineNumberTag)t).getLineNumber(); } } return prevLine; } public boolean isStatic() { return Modifier.isStatic(getAccessFlags()); } public boolean isAbstract() { return Modifier.isAbstract(getAccessFlags()); } public boolean isBridgeMethod() { return (getAccessFlags() & Constants.ACC_BRIDGE) != 0; } public void addExceptionHandler( InstructionHandle start, InstructionHandle end, InstructionHandle handlerStart, ObjectType catchType, boolean highPriority) { InstructionHandle start1 = Range.genStart(body, start); InstructionHandle end1 = Range.genEnd(body, end); ExceptionRange er = new ExceptionRange(body, (catchType==null?null:BcelWorld.fromBcel(catchType)), highPriority); er.associateWithTargets(start1, end1, handlerStart); } public int getAccessFlags() { return accessFlags; } public int getAccessFlagsWithoutSynchronized() { if (isSynchronized()) return accessFlags - Modifier.SYNCHRONIZED; return accessFlags; } public boolean isSynchronized() { return (accessFlags & Modifier.SYNCHRONIZED)!=0; } public void setAccessFlags(int newFlags) { this.accessFlags = newFlags; } public Type[] getArgumentTypes() { initialize(); return argumentTypes; } public LazyClassGen getEnclosingClass() { return enclosingClass; } public int getMaxLocals() { return maxLocals; } public String getName() { return name; } public String getGenericReturnTypeSignature() { if (memberView == null) { return getReturnType().getSignature(); } else { return memberView.getGenericReturnType().getSignature(); } } public Type getReturnType() { initialize(); return returnType; } public void setMaxLocals(int maxLocals) { this.maxLocals = maxLocals; } public InstructionList getBody() { markAsChanged(); return body; } public boolean hasBody() { if (savedMethod != null) return savedMethod.getCode() != null; return body != null; } public Attribute[] getAttributes() { return attributes; } public String[] getDeclaredExceptions() { return declaredExceptions; } public String getClassName() { return enclosingClass.getName(); } // ---- packing! public MethodGen pack() { forceSyntheticForAjcMagicMembers(); //killNops(); int flags = getAccessFlags(); if (enclosingClass.getWorld().isJoinpointSynchronizationEnabled() && enclosingClass.getWorld().areSynchronizationPointcutsInUse()) { flags = getAccessFlagsWithoutSynchronized(); } MethodGen gen = new MethodGen( flags, getReturnType(), getArgumentTypes(), null, //getArgumentNames(), getName(), getEnclosingClass().getName(), new InstructionList(), getEnclosingClass().getConstantPoolGen()); for (int i = 0, len = declaredExceptions.length; i < len; i++) { gen.addException(declaredExceptions[i]); } for (int i = 0, len = attributes.length; i < len; i++) { gen.addAttribute(attributes[i]); } if (newAnnotations!=null) { for (Iterator iter = newAnnotations.iterator(); iter.hasNext();) { AnnotationX element = (AnnotationX) iter.next(); gen.addAnnotation(new AnnotationGen(element.getBcelAnnotation(),gen.getConstantPool(),true)); } } if (memberView!=null && memberView.getAnnotations()!=null && memberView.getAnnotations().length!=0) { AnnotationX[] ans = memberView.getAnnotations(); for (int i = 0, len = ans.length; i < len; i++) { Annotation a= ans[i].getBcelAnnotation(); gen.addAnnotation(new AnnotationGen(a,gen.getConstantPool(),true)); } } if (isSynthetic) { if (enclosingClass.getWorld().isInJava5Mode()) { gen.setModifiers(gen.getModifiers() | ACC_SYNTHETIC); } // belt and braces, do the attribute even on Java 5 in addition to the modifier flag ConstantPoolGen cpg = gen.getConstantPool(); int index = cpg.addUtf8("Synthetic"); gen.addAttribute(new Synthetic(index, 0, new byte[0], cpg.getConstantPool())); } if (hasBody()) { packBody(gen); gen.setMaxLocals(); gen.setMaxStack(); } else { gen.setInstructionList(null); } return gen; } private void forceSyntheticForAjcMagicMembers() { if (NameMangler.isSyntheticMethod(getName(), inAspect())) { makeSynthetic(); } } private boolean inAspect() { BcelObjectType objectType = enclosingClass.getBcelObjectType(); return (objectType == null ? false : objectType.isAspect()); } public void makeSynthetic() { isSynthetic = true; } private static class LVPosition { InstructionHandle start = null; InstructionHandle end = null; } /** fill the newly created method gen with our body, * inspired by InstructionList.copy() */ public void packBody(MethodGen gen) { InstructionList fresh = gen.getInstructionList(); Map map = copyAllInstructionsExceptRangeInstructionsInto(fresh); // at this point, no rangeHandles are in fresh. Let's use that... /* Update branch targets and insert various attributes. * Insert our exceptionHandlers * into a sorted list, so they can be added in order later. */ InstructionHandle oldInstructionHandle = getBody().getStart(); InstructionHandle newInstructionHandle = fresh.getStart(); LinkedList exceptionList = new LinkedList(); // map from localvariabletag to instruction handle Map localVariables = new HashMap(); int currLine = -1; int lineNumberOffset = (fromFilename == null) ? 0: getEnclosingClass().getSourceDebugExtensionOffset(fromFilename); while (oldInstructionHandle != null) { if (map.get(oldInstructionHandle) == null) { // must be a range instruction since they're the only things we didn't copy across handleRangeInstruction(oldInstructionHandle, exceptionList); // just increment ih. oldInstructionHandle = oldInstructionHandle.getNext(); } else { // assert map.get(ih) == jh Instruction oldInstruction = oldInstructionHandle.getInstruction(); Instruction newInstruction = newInstructionHandle.getInstruction(); if (oldInstruction instanceof BranchInstruction) { handleBranchInstruction(map, oldInstruction, newInstruction); } // now deal with line numbers // and store up info for local variables InstructionTargeter[] targeters = oldInstructionHandle.getTargeters(); if (targeters != null) { for (int k = targeters.length - 1; k >= 0; k--) { InstructionTargeter targeter = targeters[k]; if (targeter instanceof LineNumberTag) { int line = ((LineNumberTag)targeter).getLineNumber(); if (line != currLine) { gen.addLineNumber(newInstructionHandle, line + lineNumberOffset); currLine = line; } } else if (targeter instanceof LocalVariableTag) { LocalVariableTag lvt = (LocalVariableTag) targeter; LVPosition p = (LVPosition)localVariables.get(lvt); // If we don't know about it, create a new position and store // If we do know about it - update its end position if (p==null) { LVPosition newp = new LVPosition(); newp.start=newp.end=newInstructionHandle; localVariables.put(lvt,newp); } else { p.end = newInstructionHandle; } } } } // now continue oldInstructionHandle = oldInstructionHandle.getNext(); newInstructionHandle = newInstructionHandle.getNext(); } } addExceptionHandlers(gen, map, exceptionList); addLocalVariables(gen,localVariables); // JAVAC adds line number tables (with just one entry) to generated accessor methods - this // keeps some tools that rely on finding at least some form of linenumbertable happy. // Let's check if we have one - if we don't then let's add one. // TODO Could be made conditional on whether line debug info is being produced if (gen.getLineNumbers().length==0) { gen.addLineNumber(gen.getInstructionList().getStart(),1); } } private void addLocalVariables(MethodGen gen, Map localVariables) { // now add local variables gen.removeLocalVariables(); // this next iteration _might_ be overkill, but we had problems with // bcel before with duplicate local variables. Now that we're patching // bcel we should be able to do without it if we're paranoid enough // through the rest of the compiler. Map duplicatedLocalMap = new HashMap(); for (Iterator iter = localVariables.keySet().iterator(); iter.hasNext(); ) { LocalVariableTag tag = (LocalVariableTag) iter.next(); // have we already added one with the same slot number and start location? // if so, just continue. LVPosition lvpos = (LVPosition)localVariables.get(tag); InstructionHandle start = lvpos.start; Set slots = (Set) duplicatedLocalMap.get(start); if (slots == null) { slots = new HashSet(); duplicatedLocalMap.put(start, slots); } else if (slots.contains(new Integer(tag.getSlot()))) { // we already have a var starting at this tag with this slot continue; } slots.add(new Integer(tag.getSlot())); Type t = tag.getRealType(); if (t==null) { t = BcelWorld.makeBcelType(UnresolvedType.forSignature(tag.getType())); } gen.addLocalVariable( tag.getName(), t, tag.getSlot(),(InstructionHandle) start,(InstructionHandle) lvpos.end); } } private void addExceptionHandlers(MethodGen gen, Map map, LinkedList exnList) { // now add exception handlers for (Iterator iter = exnList.iterator(); iter.hasNext();) { ExceptionRange r = (ExceptionRange) iter.next(); if (r.isEmpty()) continue; gen.addExceptionHandler( remap(r.getRealStart(), map), remap(r.getRealEnd(), map), remap(r.getHandler(), map), (r.getCatchType() == null) ? null : (ObjectType) BcelWorld.makeBcelType(r.getCatchType())); } } private void handleBranchInstruction(Map map, Instruction oldInstruction, Instruction newInstruction) { BranchInstruction oldBranchInstruction = (BranchInstruction) oldInstruction; BranchInstruction newBranchInstruction = (BranchInstruction) newInstruction; InstructionHandle oldTarget = oldBranchInstruction.getTarget(); // old target // try { // New target is in hash map newBranchInstruction.setTarget(remap(oldTarget, map)); // } catch (NullPointerException e) { // print(); // System.out.println("Was trying to remap " + bi); // System.out.println("who's target was supposedly " + itarget); // throw e; // } if (oldBranchInstruction instanceof Select) { // Either LOOKUPSWITCH or TABLESWITCH InstructionHandle[] oldTargets = ((Select) oldBranchInstruction).getTargets(); InstructionHandle[] newTargets = ((Select) newBranchInstruction).getTargets(); for (int k = oldTargets.length - 1; k >= 0; k--) { // Update all targets newTargets[k] = remap(oldTargets[k], map); newTargets[k].addTargeter(newBranchInstruction); } } } private void handleRangeInstruction(InstructionHandle ih, LinkedList exnList) { // we're a range instruction Range r = Range.getRange(ih); if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; if (er.getStart() == ih) { //System.err.println("er " + er); if (!er.isEmpty()){ // order is important, insert handlers in order of start insertHandler(er, exnList); } } } else { // we must be a shadow range or something equally useless, // so forget about doing anything } } /* Make copies of all instructions, append them to the new list * and associate old instruction references with the new ones, i.e., * a 1:1 mapping. */ private Map copyAllInstructionsExceptRangeInstructionsInto(InstructionList intoList) { HashMap map = new HashMap(); for (InstructionHandle ih = getBody().getStart(); ih != null; ih = ih.getNext()) { if (Range.isRangeHandle(ih)) { continue; } Instruction i = ih.getInstruction(); Instruction c = Utility.copyInstruction(i); if (c instanceof BranchInstruction) map.put(ih, intoList.append((BranchInstruction) c)); else map.put(ih, intoList.append(c)); } return map; } /** This procedure should not currently be used. */ // public void killNops() { // InstructionHandle curr = body.getStart(); // while (true) { // if (curr == null) break; // InstructionHandle next = curr.getNext(); // if (curr.getInstruction() instanceof NOP) { // InstructionTargeter[] targeters = curr.getTargeters(); // if (targeters != null) { // for (int i = 0, len = targeters.length; i < len; i++) { // InstructionTargeter targeter = targeters[i]; // targeter.updateTarget(curr, next); // } // } // try { // body.delete(curr); // } catch (TargetLostException e) { // } // } // curr = next; // } // } private static InstructionHandle remap(InstructionHandle ih, Map map) { while (true) { Object ret = map.get(ih); if (ret == null) { ih = ih.getNext(); } else { return (InstructionHandle) ret; } } } // Update to all these comments, ASC 11-01-2005 // The right thing to do may be to do more with priorities as // we create new exception handlers, but that is a relatively // complex task. In the meantime, just taking account of the // priority here enables a couple of bugs to be fixed to do // with using return or break in code that contains a finally // block (pr78021,pr79554). // exception ordering. // What we should be doing is dealing with priority inversions way earlier than we are // and counting on the tree structure. In which case, the below code is in fact right. // XXX THIS COMMENT BELOW IS CURRENTLY WRONG. // An exception A preceeds an exception B in the exception table iff: // * A and B were in the original method, and A preceeded B in the original exception table // * If A has a higher priority than B, than it preceeds B. // * If A and B have the same priority, then the one whose START happens EARLIEST has LEAST priority. // in short, the outermost exception has least priority. // we implement this with a LinkedList. We could possibly implement this with a java.util.SortedSet, // but I don't trust the only implementation, TreeSet, to do the right thing. /* private */ static void insertHandler(ExceptionRange fresh, LinkedList l) { // Old implementation, simply: l.add(0,fresh); for (ListIterator iter = l.listIterator(); iter.hasNext();) { ExceptionRange r = (ExceptionRange) iter.next(); // int freal = fresh.getRealStart().getPosition(); // int rreal = r.getRealStart().getPosition(); if (fresh.getPriority() >= r.getPriority()) { iter.previous(); iter.add(fresh); return; } } // we have reached the end l.add(fresh); } public boolean isPrivate() { return Modifier.isPrivate(getAccessFlags()); } public boolean isProtected() { return Modifier.isProtected(getAccessFlags()); } public boolean isDefault() { return !(isProtected() || isPrivate() || isPublic()); } public boolean isPublic() { return Modifier.isPublic(getAccessFlags()); } // ---- /** A good body is a body with the following properties: * * <ul> * <li> For each branch instruction S in body, target T of S is in body. * <li> For each branch instruction S in body, target T of S has S as a targeter. * <li> For each instruction T in body, for each branch instruction S that is a * targeter of T, S is in body. * <li> For each non-range-handle instruction T in body, for each instruction S * that is a targeter of T, S is * either a branch instruction, an exception range or a tag * <li> For each range-handle instruction T in body, there is exactly one targeter S * that is a range. * <li> For each range-handle instruction T in body, the range R targeting T is in body. * <li> For each instruction T in body, for each exception range R targeting T, R is * in body. * <li> For each exception range R in body, let T := R.handler. T is in body, and R is one * of T's targeters * <li> All ranges are properly nested: For all ranges Q and R, if Q.start preceeds * R.start, then R.end preceeds Q.end. * </ul> * * Where the shorthand "R is in body" means "R.start is in body, R.end is in body, and * any InstructionHandle stored in a field of R (such as an exception handle) is in body". */ public void assertGoodBody() { if (true) return; // only enable for debugging, consider using cheaper toString() assertGoodBody(getBody(), toString()); //definingType.getNameAsIdentifier() + "." + getName()); //toString()); } public static void assertGoodBody(InstructionList il, String from) { if (true) return; // only to be enabled for debugging if (il == null) return; Set body = new HashSet(); Stack ranges = new Stack(); for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) { body.add(ih); if (ih.getInstruction() instanceof BranchInstruction) { body.add(ih.getInstruction()); } } for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) { assertGoodHandle(ih, body, ranges, from); InstructionTargeter[] ts = ih.getTargeters(); if (ts != null) { for (int i = ts.length - 1; i >= 0; i--) { assertGoodTargeter(ts[i], ih, body, from); } } } } private static void assertGoodHandle(InstructionHandle ih, Set body, Stack ranges, String from) { Instruction inst = ih.getInstruction(); if ((inst instanceof BranchInstruction) ^ (ih instanceof BranchHandle)) { throw new BCException("bad instruction/handle pair in " + from); } if (Range.isRangeHandle(ih)) { assertGoodRangeHandle(ih, body, ranges, from); } else if (inst instanceof BranchInstruction) { assertGoodBranchInstruction((BranchHandle) ih, (BranchInstruction) inst, body, ranges, from); } } private static void assertGoodBranchInstruction( BranchHandle ih, BranchInstruction inst, Set body, Stack ranges, String from) { if (ih.getTarget() != inst.getTarget()) { throw new BCException("bad branch instruction/handle pair in " + from); } InstructionHandle target = ih.getTarget(); assertInBody(target, body, from); assertTargetedBy(target, inst, from); if (inst instanceof Select) { Select sel = (Select) inst; InstructionHandle[] itargets = sel.getTargets(); for (int k = itargets.length - 1; k >= 0; k--) { assertInBody(itargets[k], body, from); assertTargetedBy(itargets[k], inst, from); } } } /** ih is an InstructionHandle or a BranchInstruction */ private static void assertInBody(Object ih, Set body, String from) { if (! body.contains(ih)) throw new BCException("thing not in body in " + from); } private static void assertGoodRangeHandle(InstructionHandle ih, Set body, Stack ranges, String from) { Range r = getRangeAndAssertExactlyOne(ih, from); assertGoodRange(r, body, from); if (r.getStart() == ih) { ranges.push(r); } else if (r.getEnd() == ih) { if (ranges.peek() != r) throw new BCException("bad range inclusion in " + from); ranges.pop(); } } private static void assertGoodRange(Range r, Set body, String from) { assertInBody(r.getStart(), body, from); assertRangeHandle(r.getStart(), from); assertTargetedBy(r.getStart(), r, from); assertInBody(r.getEnd(), body, from); assertRangeHandle(r.getEnd(), from); assertTargetedBy(r.getEnd(), r, from); if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; assertInBody(er.getHandler(), body, from); assertTargetedBy(er.getHandler(), r, from); } } private static void assertRangeHandle(InstructionHandle ih, String from) { if (! Range.isRangeHandle(ih)) throw new BCException("bad range handle " + ih + " in " + from); } private static void assertTargetedBy( InstructionHandle target, InstructionTargeter targeter, String from) { InstructionTargeter[] ts = target.getTargeters(); if (ts == null) throw new BCException("bad targeting relationship in " + from); for (int i = ts.length - 1; i >= 0; i--) { if (ts[i] == targeter) return; } throw new RuntimeException("bad targeting relationship in " + from); } private static void assertTargets(InstructionTargeter targeter, InstructionHandle target, String from) { if (targeter instanceof Range) { Range r = (Range) targeter; if (r.getStart() == target || r.getEnd() == target) return; if (r instanceof ExceptionRange) { if (((ExceptionRange)r).getHandler() == target) return; } } else if (targeter instanceof BranchInstruction) { BranchInstruction bi = (BranchInstruction) targeter; if (bi.getTarget() == target) return; if (targeter instanceof Select) { Select sel = (Select) targeter; InstructionHandle[] itargets = sel.getTargets(); for (int k = itargets.length - 1; k >= 0; k--) { if (itargets[k] == target) return; } } } else if (targeter instanceof Tag) { return; } throw new BCException(targeter + " doesn't target " + target + " in " + from ); } private static Range getRangeAndAssertExactlyOne(InstructionHandle ih, String from) { Range ret = null; InstructionTargeter[] ts = ih.getTargeters(); if (ts == null) throw new BCException("range handle with no range in " + from); for (int i = ts.length - 1; i >= 0; i--) { if (ts[i] instanceof Range) { if (ret != null) throw new BCException("range handle with multiple ranges in " + from); ret = (Range) ts[i]; } } if (ret == null) throw new BCException("range handle with no range in " + from); return ret; } private static void assertGoodTargeter( InstructionTargeter t, InstructionHandle ih, Set body, String from) { assertTargets(t, ih, from); if (t instanceof Range) { assertGoodRange((Range) t, body, from); } else if (t instanceof BranchInstruction) { assertInBody(t, body, from); } } // ---- boolean isAdviceMethod() { return memberView.getAssociatedShadowMunger() != null; } boolean isAjSynthetic() { if (memberView == null) return true; return memberView.isAjSynthetic(); } boolean isSynthetic() { if (memberView == null) return false; return memberView.isSynthetic(); } public ISourceLocation getSourceLocation() { if (memberView!=null) return memberView.getSourceLocation(); return null; } public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() { //if (memberView == null) return null; if (effectiveSignature != null) return effectiveSignature; return memberView.getEffectiveSignature(); } public void setEffectiveSignature(ResolvedMember member, Shadow.Kind kind, boolean shouldWeave) { this.effectiveSignature = new AjAttribute.EffectiveSignatureAttribute(member,kind,shouldWeave); } public String getSignature() { if (memberView!=null) return memberView.getSignature(); return MemberImpl.typesToSignature(BcelWorld.fromBcel(getReturnType()), BcelWorld.fromBcel(getArgumentTypes()),false); } public String getParameterSignature() { if (memberView!=null) return memberView.getParameterSignature(); return MemberImpl.typesToSignature(BcelWorld.fromBcel(getArgumentTypes())); } public BcelMethod getMemberView() { return memberView; } public void forcePublic() { markAsChanged(); accessFlags = Utility.makePublic(accessFlags); } public boolean getCanInline() { return canInline; } public void setCanInline(boolean canInline) { this.canInline = canInline; } /** * Adds an attribute to the method * @param attr */ public void addAttribute(Attribute attr) { Attribute[] newAttributes = new Attribute[attributes.length + 1]; System.arraycopy(attributes, 0, newAttributes, 0, attributes.length); newAttributes[attributes.length] = attr; attributes = newAttributes; } public String toTraceString() { return toShortString(); } }
209,372
Bug 209372 Compile error: IllegalArgumentException thrown: negative line: -1
If line numbers have not been added to the generated class files the following exception is thrown: java.lang.IllegalArgumentException at org.aspectj.bridge.SourceLocation.validLine(SourceLocation.java:41) at org.aspectj.bridge.SourceLocation.<init>(SourceLocation.java:96) at org.aspectj.bridge.SourceLocation.<init>(SourceLocation.java:85) at org.aspectj.bridge.SourceLocation.<init>(SourceLocation.java:70) at org.aspectj.ajdt.internal.core.builder.EclipseSourceContext.makeSourceLocation(EclipseSourceContext.java:57) at org.aspectj.we ... reUtility.java:155) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) Compile error: IllegalArgumentException thrown: negative line: -1 An easy way to reproduce the problem is to uncheck the corresponding checkbox in the Classfile Generation section of the Java Compiler options in Eclipse. A full build is performed during which an AspectJ Internal Compiler Error is thrown. My Eclipse feature version is org.eclipse.ajdt_1.5.0.200706070619.
resolved fixed
d3c3e32
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-05-07T22:08:01Z"
"2007-11-09T20:26:40Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/EclipseAdapterUtils.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.File; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.SourceLocation; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.aspectj.weaver.LintMessage; import org.aspectj.weaver.World; public class EclipseAdapterUtils { //XXX some cut-and-paste from eclipse sources public static String makeLocationContext(ICompilationUnit compilationUnit, IProblem problem) { //extra from the source the innacurate token //and "highlight" it using some underneath ^^^^^ //put some context around too. //this code assumes that the font used in the console is fixed size //sanity ..... int startPosition = problem.getSourceStart(); int endPosition = problem.getSourceEnd(); if ((startPosition > endPosition) || ((startPosition <= 0) && (endPosition <= 0)) || compilationUnit==null) //return Util.bind("problem.noSourceInformation"); //$NON-NLS-1$ return "(no source information available)"; final char SPACE = '\u0020'; final char MARK = '^'; final char TAB = '\t'; char[] source = compilationUnit.getContents(); //the next code tries to underline the token..... //it assumes (for a good display) that token source does not //contain any \r \n. This is false on statements ! //(the code still works but the display is not optimal !) //compute the how-much-char we are displaying around the inaccurate token int begin = startPosition >= source.length ? source.length - 1 : startPosition; if (begin==-1) return "(no source information available)"; // Dont like this - why does it occur? pr152835 int relativeStart = 0; int end = endPosition >= source.length ? source.length - 1 : endPosition; int relativeEnd = 0; label : for (relativeStart = 0;; relativeStart++) { if (begin == 0) break label; if ((source[begin - 1] == '\n') || (source[begin - 1] == '\r')) break label; begin--; } label : for (relativeEnd = 0;; relativeEnd++) { if ((end + 1) >= source.length) break label; if ((source[end + 1] == '\r') || (source[end + 1] == '\n')) { break label; } end++; } //extract the message form the source char[] extract = new char[end - begin + 1]; System.arraycopy(source, begin, extract, 0, extract.length); char c; //remove all SPACE and TAB that begin the error message... int trimLeftIndex = 0; while ( (((c = extract[trimLeftIndex++]) == TAB) || (c == SPACE)) && trimLeftIndex<extract.length ) { }; if (trimLeftIndex>=extract.length) return new String(extract)+"\n"; System.arraycopy( extract, trimLeftIndex - 1, extract = new char[extract.length - trimLeftIndex + 1], 0, extract.length); relativeStart -= trimLeftIndex; //buffer spaces and tabs in order to reach the error position int pos = 0; char[] underneath = new char[extract.length]; // can't be bigger for (int i = 0; i <= relativeStart; i++) { if (extract[i] == TAB) { underneath[pos++] = TAB; } else { underneath[pos++] = SPACE; } } //mark the error position for (int i = startPosition + trimLeftIndex; // AMC if we took stuff off the start, take it into account! i <= (endPosition >= source.length ? source.length - 1 : endPosition); i++) underneath[pos++] = MARK; //resize underneathto remove 'null' chars System.arraycopy(underneath, 0, underneath = new char[pos], 0, pos); return new String(extract) + "\n" + new String(underneath); //$NON-NLS-2$ //$NON-NLS-1$ } /** * Extract source location file, start and end lines, and context. * Column is not extracted correctly. * @return ISourceLocation with correct file and lines but not column. */ public static ISourceLocation makeSourceLocation(ICompilationUnit unit, IProblem problem) { int line = problem.getSourceLineNumber(); File file = new File(new String(problem.getOriginatingFileName())); String context = makeLocationContext(unit, problem); // XXX 0 column is wrong but recoverable from makeLocationContext return new SourceLocation(file, line, line, 0, context); } /** * Extract message text and source location, including context. * @param world */ public static IMessage makeMessage(ICompilationUnit unit, IProblem problem, World world) { ISourceLocation sourceLocation = makeSourceLocation(unit, problem); IProblem[] seeAlso = problem.seeAlso(); ISourceLocation[] seeAlsoLocations = new ISourceLocation[seeAlso.length]; for (int i = 0; i < seeAlso.length; i++) { seeAlsoLocations[i] = new SourceLocation(new File(new String(seeAlso[i].getOriginatingFileName())), seeAlso[i].getSourceLineNumber()); } // We transform messages from AJ types to eclipse IProblems // and back to AJ types. During their time as eclipse problems, // we remember whether the message originated from a declare // in the extraDetails. String extraDetails = problem.getSupplementaryMessageInfo(); boolean declared = false; boolean isLintMessage = false; String lintkey = null; if (extraDetails!=null && extraDetails.endsWith("[deow=true]")) { declared = true; extraDetails = extraDetails.substring(0,extraDetails.length()-"[deow=true]".length()); } if (extraDetails!=null && extraDetails.indexOf("[Xlint:")!=-1) { isLintMessage = true; lintkey = extraDetails.substring(extraDetails.indexOf("[Xlint:")); lintkey = lintkey.substring("[Xlint:".length()); lintkey = lintkey.substring(0,lintkey.indexOf("]")); } // If the 'problem' represents a TO DO kind of thing then use the message kind that // represents this so AJDT sees it correctly. IMessage.Kind kind; if (problem.getID()==IProblem.Task) { kind=IMessage.TASKTAG; } else { if (problem.isError()) { kind = IMessage.ERROR; } else { kind = IMessage.WARNING; } } IMessage msg = null; if (isLintMessage) { msg = new LintMessage( problem.getMessage(), extraDetails, world.getLint().fromKey(lintkey), kind, sourceLocation, null, seeAlsoLocations, declared, problem.getID(), problem.getSourceStart(),problem.getSourceEnd()); } else { msg = new Message(problem.getMessage(), extraDetails, kind, sourceLocation, null, seeAlsoLocations, declared, problem.getID(), problem.getSourceStart(),problem.getSourceEnd()); } return msg; } public static IMessage makeErrorMessage(ICompilationUnit unit, String text, Exception ex) { ISourceLocation loc = new SourceLocation(new File(new String(unit.getFileName())), 0,0,0,""); IMessage msg = new Message(text,IMessage.ERROR,ex,loc); return msg; } public static IMessage makeErrorMessage(String srcFile, String text, Exception ex) { ISourceLocation loc = new SourceLocation(new File(srcFile), 0,0,0,""); IMessage msg = new Message(text,IMessage.ERROR,ex,loc); return msg; } private EclipseAdapterUtils() { } }
231,467
Bug 231467 Cant Compile new Statement for the Generic Class
[aspectj:iajc] error at (no source information available) [aspectj:iajc] C:\Development\PI\JavaSrc\com\centricsoftware\pi\service\expression\FuncNewMatrix.java:0::0 Internal compiler error [aspectj:iajc] java.lang.ArrayIndexOutOfBoundsException: 1 [aspectj:iajc] at org.aspectj.weaver.ResolvedType.getMemberParameterizationMap(ResolvedType.java:744) [aspectj:iajc] at org.aspectj.weaver.ReferenceType.getDeclaredInterfaces(ReferenceType.java:411) [aspectj:iajc] at org.aspectj.weaver.ResolvedType.getDirectSupertypes(ResolvedType.java:68) [aspectj:iajc] at org.aspectj.weaver.ResolvedType.collectInterTypeMungers(ResolvedType.java:1206) [aspectj:iajc] at org.aspectj.weaver.ResolvedType.collectInterTypeMungers(ResolvedType.java:1211) [aspectj:iajc] at org.aspectj.weaver.ResolvedType.collectInterTypeMungers(ResolvedType.java:1211) [aspectj:iajc] at org.aspectj.weaver.ResolvedType.getInterTypeMungersIncludingSupers(ResolvedType.java:1185) [aspectj:iajc] at org.aspectj.weaver.ResolvedType.checkInterTypeMungers(ResolvedType.java:1255) [aspectj:iajc] at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:646) [aspectj:iajc] at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:522) [aspectj:iajc] at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.createBinaryTypeFrom(AjLookupEnvironment.java:1105) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.createBinaryTypeFrom(LookupEnvironment.java:599) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.accept(Compiler.java:276) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.askForType(LookupEnvironment.java:113) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.UnresolvedReferenceBinding.resolve(UnresolvedReferenceBinding.java:49) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding.resolveType(BinaryTypeBinding.java:99) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding.getMemberType(BinaryTypeBinding.java:755) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope.findMemberType(Scope.java:986) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope.getMemberType(Scope.java:2116) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference.findNextTypeBinding(QualifiedTypeReference.java:43) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference.getTypeBinding(QualifiedTypeReference.java:77) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference.resolveType(TypeReference.java:142) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AllocationExpression.resolveType(AllocationExpression.java:258) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration.resolve(LocalDeclaration.java:196) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:433) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:196) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:404) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1109) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1188) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:366) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:625) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:392) [aspectj:iajc] at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:990) [aspectj:iajc] at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:264) [aspectj:iajc] at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:180) [aspectj:iajc] at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:112) [aspectj:iajc] at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) [aspectj:iajc] at org.aspectj.tools.ajc.Main.run(Main.java:378) [aspectj:iajc] at org.aspectj.tools.ajc.Main.runMain(Main.java:253) [aspectj:iajc] at org.aspectj.tools.ant.taskdefs.AjcTask.executeInSameVM(AjcTask.java:1303) [aspectj:iajc] at org.aspectj.tools.ant.taskdefs.AjcTask.execute(AjcTask.java:1101) [aspectj:iajc] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288) [aspectj:iajc] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [aspectj:iajc] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [aspectj:iajc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [aspectj:iajc] at java.lang.reflect.Method.invoke(Method.java:585) [aspectj:iajc] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:105) [aspectj:iajc] at org.apache.tools.ant.Task.perform(Task.java:348) [aspectj:iajc] at org.apache.tools.ant.Target.execute(Target.java:357) [aspectj:iajc] at org.apache.tools.ant.Target.performTasks(Target.java:385) [aspectj:iajc] at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1329) [aspectj:iajc] at org.apache.tools.ant.Project.executeTarget(Project.java:1298) [aspectj:iajc] at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41) [aspectj:iajc] at org.eclipse.ant.internal.ui.antsupport.EclipseDefaultExecutor.executeTargets(EclipseDefaultExecutor.java:32) [aspectj:iajc] at org.apache.tools.ant.Project.executeTargets(Project.java:1181) [aspectj:iajc] at org.eclipse.ant.internal.ui.antsupport.InternalAntRunner.run(InternalAntRunner.java:423) [aspectj:iajc] at org.eclipse.ant.internal.ui.antsupport.InternalAntRunner.main(InternalAntRunner.java:137) [aspectj:iajc] abort ABORT -- (ArrayIndexOutOfBoundsException) 1 [aspectj:iajc] 1 [aspectj:iajc] java.lang.ArrayIndexOutOfBoundsException: 1 [aspectj:iajc] at org.aspectj.weaver.ResolvedType.getMemberParameterizationMap(ResolvedType.java:744) [aspectj:iajc] at org.aspectj.weaver.ReferenceType.getDeclaredInterfaces(ReferenceType.java:411) [aspectj:iajc] at org.aspectj.weaver.ResolvedType.getDirectSupertypes(ResolvedType.java:68) [aspectj:iajc] at org.aspectj.weaver.ResolvedType.collectInterTypeMungers(ResolvedType.java:1206) [aspectj:iajc] at org.aspectj.weaver.ResolvedType.collectInterTypeMungers(ResolvedType.java:1211) [aspectj:iajc] at org.aspectj.weaver.ResolvedType.collectInterTypeMungers(ResolvedType.java:1211) [aspectj:iajc] at org.aspectj.weaver.ResolvedType.getInterTypeMungersIncludingSupers(ResolvedType.java:1185) [aspectj:iajc] at org.aspectj.weaver.ResolvedType.checkInterTypeMungers(ResolvedType.java:1255) [aspectj:iajc] at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:646) [aspectj:iajc] at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:522) [aspectj:iajc] at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.createBinaryTypeFrom(AjLookupEnvironment.java:1105) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.createBinaryTypeFrom(LookupEnvironment.java:599) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.accept(Compiler.java:276) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.askForType(LookupEnvironment.java:113) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.UnresolvedReferenceBinding.resolve(UnresolvedReferenceBinding.java:49) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding.resolveType(BinaryTypeBinding.java:99) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding.getMemberType(BinaryTypeBinding.java:755) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope.findMemberType(Scope.java:986) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope.getMemberType(Scope.java:2116) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference.findNextTypeBinding(QualifiedTypeReference.java:43) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference.getTypeBinding(QualifiedTypeReference.java:77) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference.resolveType(TypeReference.java:142) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AllocationExpression.resolveType(AllocationExpression.java:258) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration.resolve(LocalDeclaration.java:196) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:433) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:196) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:404) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1109) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1188) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:366) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:625) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:392) [aspectj:iajc] at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:990) [aspectj:iajc] at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:264) [aspectj:iajc] at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:180) [aspectj:iajc] at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:112) [aspectj:iajc] at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) [aspectj:iajc] at org.aspectj.tools.ajc.Main.run(Main.java:378) [aspectj:iajc] at org.aspectj.tools.ajc.Main.runMain(Main.java:253) [aspectj:iajc] at org.aspectj.tools.ant.taskdefs.AjcTask.executeInSameVM(AjcTask.java:1303) [aspectj:iajc] at org.aspectj.tools.ant.taskdefs.AjcTask.execute(AjcTask.java:1101) [aspectj:iajc] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288) [aspectj:iajc] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [aspectj:iajc] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [aspectj:iajc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [aspectj:iajc] at java.lang.reflect.Method.invoke(Method.java:585) [aspectj:iajc] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:105) [aspectj:iajc] at org.apache.tools.ant.Task.perform(Task.java:348) [aspectj:iajc] at org.apache.tools.ant.Target.execute(Target.java:357) [aspectj:iajc] at org.apache.tools.ant.Target.performTasks(Target.java:385) [aspectj:iajc] at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1329) [aspectj:iajc] at org.apache.tools.ant.Project.executeTarget(Project.java:1298) [aspectj:iajc] at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41) [aspectj:iajc] at org.eclipse.ant.internal.ui.antsupport.EclipseDefaultExecutor.executeTargets(EclipseDefaultExecutor.java:32) [aspectj:iajc] at org.apache.tools.ant.Project.executeTargets(Project.java:1181) [aspectj:iajc] at org.eclipse.ant.internal.ui.antsupport.InternalAntRunner.run(InternalAntRunner.java:423) [aspectj:iajc] at org.eclipse.ant.internal.ui.antsupport.InternalAntRunner.main(InternalAntRunner.java:137) [aspectj:iajc] May 11, 2008 9:35:06 AM org.aspectj.weaver.tools.Jdk14Trace info [aspectj:iajc] INFO: Dumping to C:\Development\PI\Projects\PI-ServiceCommon\.\ajcore.20080511.093506.214.txt [aspectj:iajc] MessageHolder: (92 info) (1 error) (1 abort) [aspectj:iajc] [error 0]: error at (no source information available) [aspectj:iajc] C:\Development\PI\JavaSrc\com\centricsoftware\pi\service\expression\FuncNewMatrix.java:0::0 Internal compiler error [aspectj:iajc] java.lang.ArrayIndexOutOfBoundsException: 1 [aspectj:iajc] at org.aspectj.weaver.ResolvedType.getMemberParameterizationMap(ResolvedType.java:744) [aspectj:iajc] at org.aspectj.weaver.ReferenceType.getDeclaredInterfaces(ReferenceType.java:411) [aspectj:iajc] at org.aspectj.weaver.ResolvedType.getDirectSupertypes(ResolvedType.java:68) [aspectj:iajc] at org.aspectj.weaver.ResolvedType.collectInterTypeMungers(ResolvedType.java:1206) [aspectj:iajc] at org.aspectj.weaver.ResolvedType.collectInterTypeMungers(ResolvedType.java:1211) [aspectj:iajc] at org.aspectj.weaver.ResolvedType.collectInterTypeMungers(ResolvedType.java:1211) [aspectj:iajc] at org.aspectj.weaver.ResolvedType.getInterTypeMungersIncludingSupers(ResolvedType.java:1185) [aspectj:iajc] at org.aspectj.weaver.ResolvedType.checkInterTypeMungers(ResolvedType.java:1255) [aspectj:iajc] at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:646) [aspectj:iajc] at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:522) [aspectj:iajc] at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.createBinaryTypeFrom(AjLookupEnvironment.java:1105) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.createBinaryTypeFrom(LookupEnvironment.java:599) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.accept(Compiler.java:276) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.askForType(LookupEnvironment.java:113) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.UnresolvedReferenceBinding.resolve(UnresolvedReferenceBinding.java:49) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding.resolveType(BinaryTypeBinding.java:99) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding.getMemberType(BinaryTypeBinding.java:755) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope.findMemberType(Scope.java:986) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope.getMemberType(Scope.java:2116) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference.findNextTypeBinding(QualifiedTypeReference.java:43) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference.getTypeBinding(QualifiedTypeReference.java:77) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference.resolveType(TypeReference.java:142) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AllocationExpression.resolveType(AllocationExpression.java:258) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration.resolve(LocalDeclaration.java:196) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:433) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:196) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:404) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1109) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1188) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:366) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:625) [aspectj:iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:392) [aspectj:iajc] at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:990) [aspectj:iajc] at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:264) [aspectj:iajc] at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:180) [aspectj:iajc] at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:112) [aspectj:iajc] at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) [aspectj:iajc] at org.aspectj.tools.ajc.Main.run(Main.java:378) [aspectj:iajc] at org.aspectj.tools.ajc.Main.runMain(Main.java:253) [aspectj:iajc] at org.aspectj.tools.ant.taskdefs.AjcTask.executeInSameVM(AjcTask.java:1303) [aspectj:iajc] at org.aspectj.tools.ant.taskdefs.AjcTask.execute(AjcTask.java:1101) [aspectj:iajc] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288) [aspectj:iajc] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [aspectj:iajc] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [aspectj:iajc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [aspectj:iajc] at java.lang.reflect.Method.invoke(Method.java:585) [aspectj:iajc] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:105) [aspectj:iajc] at org.apache.tools.ant.Task.perform(Task.java:348) [aspectj:iajc] at org.apache.tools.ant.Target.execute(Target.java:357) [aspectj:iajc] at org.apache.tools.ant.Target.performTasks(Target.java:385) [aspectj:iajc] at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1329) [aspectj:iajc] at org.apache.tools.ant.Project.executeTarget(Project.java:1298) [aspectj:iajc] at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41) [aspectj:iajc] at org.eclipse.ant.internal.ui.antsupport.EclipseDefaultExecutor.executeTargets(EclipseDefaultExecutor.java:32) [aspectj:iajc] at org.apache.tools.ant.Project.executeTargets(Project.java:1181) [aspectj:iajc] at org.eclipse.ant.internal.ui.antsupport.InternalAntRunner.run(InternalAntRunner.java:423) [aspectj:iajc] at org.eclipse.ant.internal.ui.antsupport.InternalAntRunner.main(InternalAntRunner.java:137)
resolved fixed
a8739e3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-05-13T19:54:27Z"
"2008-05-11T15:33:20Z"
weaver/src/org/aspectj/weaver/TypeFactory.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.util.ArrayList; import java.util.List; import org.aspectj.weaver.UnresolvedType.TypeKind; /** * @author colyer * */ public class TypeFactory { /** * Create a parameterized version of a generic type. * @param aGenericType * @param someTypeParameters note, in the case of an inner type of a parameterized type, * this parameter may legitimately be null * @param inAWorld * @return */ public static ReferenceType createParameterizedType( ResolvedType aBaseType, UnresolvedType[] someTypeParameters, World inAWorld ) { ResolvedType baseType = aBaseType; if (!aBaseType.isGenericType()) { // try and find the generic type... if (someTypeParameters != null && someTypeParameters.length>0) { if (!aBaseType.isRawType()) throw new IllegalStateException("Expecting raw type, not: "+aBaseType); baseType = baseType.getGenericType(); if (baseType == null) throw new IllegalStateException("Raw type does not have generic type set"); } // else if someTypeParameters is null, then the base type is allowed to be non-generic, it's an inner } ResolvedType[] resolvedParameters = inAWorld.resolve(someTypeParameters); ReferenceType pType = new ReferenceType(baseType,resolvedParameters,inAWorld); // pType.setSourceContext(aBaseType.getSourceContext()); return (ReferenceType) pType.resolve(inAWorld); } /** * Create an *unresolved* parameterized version of a generic type. */ public static UnresolvedType createUnresolvedParameterizedType(String sig,String erasuresig,UnresolvedType[] arguments) { return new UnresolvedType(sig,erasuresig,arguments); } public static ReferenceType createRawType( ResolvedType aBaseType, World inAWorld ) { if (aBaseType.isRawType()) return (ReferenceType) aBaseType; if (!aBaseType.isGenericType()) { if (!aBaseType.isRawType()) throw new IllegalStateException("Expecting generic type"); } ReferenceType rType = new ReferenceType(aBaseType,inAWorld); //rType.setSourceContext(aBaseType.getSourceContext()); return (ReferenceType) rType.resolve(inAWorld); } /** * Creates a sensible unresolvedtype from some signature, for example: * signature = LIGuard<TT;>; * bound = toString=IGuard<T> sig=PIGuard<TT;>; sigErasure=LIGuard; kind=parameterized */ private static UnresolvedType convertSigToType(String aSignature) { UnresolvedType bound = null; int startOfParams = aSignature.indexOf('<'); if (startOfParams==-1) { bound = UnresolvedType.forSignature(aSignature); } else { int endOfParams = aSignature.lastIndexOf('>'); String signatureErasure = "L" + aSignature.substring(1,startOfParams) + ";"; UnresolvedType[] typeParams = createTypeParams(aSignature.substring(startOfParams +1, endOfParams)); bound = new UnresolvedType("P"+aSignature.substring(1),signatureErasure,typeParams); } return bound; } /** * Used by UnresolvedType.read, creates a type from a full signature. * @param signature * @return */ public static UnresolvedType createTypeFromSignature(String signature) { if (signature.equals(ResolvedType.MISSING_NAME)) return ResolvedType.MISSING; char firstChar = signature.charAt(0); if (firstChar=='P') { // parameterized type, calculate signature erasure and type parameters // (see pr122458) It is possible for a parameterized type to have *no* type parameters visible in its signature. // This happens for an inner type of a parameterized type which simply inherits the type parameters // of its parent. In this case it is parameterized but theres no < in the signature. int startOfParams = signature.indexOf('<'); if (startOfParams==-1) { // Should be an inner type of a parameterized type - could assert there is a '$' in the signature.... String signatureErasure = "L" + signature.substring(1); UnresolvedType[] typeParams = new UnresolvedType[0]; return new UnresolvedType(signature,signatureErasure,typeParams); } else { int endOfParams = locateMatchingEndBracket(signature,startOfParams);//signature.lastIndexOf('>'); StringBuffer erasureSig = new StringBuffer(signature); while (startOfParams!=-1) { erasureSig.delete(startOfParams,endOfParams+1); startOfParams = locateFirstBracket(erasureSig); if (startOfParams!=-1) endOfParams = locateMatchingEndBracket(erasureSig,startOfParams); } String signatureErasure = "L" + erasureSig.toString().substring(1); // the type parameters of interest are only those that apply to the 'last type' in the signature // if the signature is 'PMyInterface<String>$MyOtherType;' then there are none... String lastType = null; int nestedTypePosition = signature.indexOf("$", endOfParams); // don't look for $ INSIDE the parameters if (nestedTypePosition!=-1) lastType = signature.substring(nestedTypePosition+1); else lastType = new String(signature); startOfParams = lastType.indexOf("<"); endOfParams = locateMatchingEndBracket(lastType,startOfParams); UnresolvedType[] typeParams = UnresolvedType.NONE; if (startOfParams!=-1) { typeParams = createTypeParams(lastType.substring(startOfParams +1, endOfParams)); } return new UnresolvedType(signature,signatureErasure,typeParams); } // can't replace above with convertSigToType - leads to stackoverflow } else if (signature.equals("?")){ UnresolvedType ret = UnresolvedType.SOMETHING; ret.typeKind = TypeKind.WILDCARD; return ret; } else if(firstChar=='+') { // ? extends ... UnresolvedType ret = new UnresolvedType(signature); ret.typeKind = TypeKind.WILDCARD; // UnresolvedType bound1 = UnresolvedType.forSignature(signature.substring(1)); // UnresolvedType bound2 = convertSigToType(signature.substring(1)); ret.setUpperBound(convertSigToType(signature.substring(1))); return ret; } else if (firstChar=='-') { // ? super ... // UnresolvedType bound = UnresolvedType.forSignature(signature.substring(1)); // UnresolvedType bound2 = convertSigToType(signature.substring(1)); UnresolvedType ret = new UnresolvedType(signature); ret.typeKind = TypeKind.WILDCARD; ret.setLowerBound(convertSigToType(signature.substring(1))); return ret; } else if (firstChar=='T') { String typeVariableName = signature.substring(1); if (typeVariableName.endsWith(";")) { typeVariableName = typeVariableName.substring(0, typeVariableName.length() -1); } return new UnresolvedTypeVariableReferenceType(new TypeVariable(typeVariableName)); } else if (firstChar=='[') { int dims = 0; while (signature.charAt(dims)=='[') dims++; UnresolvedType componentType = createTypeFromSignature(signature.substring(dims)); return new UnresolvedType(signature, signature.substring(0,dims)+componentType.getErasureSignature()); } else if (signature.length()==1) { // could be a primitive switch (firstChar) { case 'V': return ResolvedType.VOID; case 'Z': return ResolvedType.BOOLEAN; case 'B': return ResolvedType.BYTE; case 'C': return ResolvedType.CHAR; case 'D': return ResolvedType.DOUBLE; case 'F': return ResolvedType.FLOAT; case 'I': return ResolvedType.INT; case 'J': return ResolvedType.LONG; case 'S': return ResolvedType.SHORT; } } return new UnresolvedType(signature); } private static int locateMatchingEndBracket(String signature, int startOfParams) { if (startOfParams==-1) return -1; int count =1; int idx = startOfParams; while (count>0 && idx<signature.length()) { idx++; if (signature.charAt(idx)=='<') count++; if (signature.charAt(idx)=='>') count--; } return idx; } private static int locateMatchingEndBracket(StringBuffer signature, int startOfParams) { if (startOfParams==-1) return -1; int count =1; int idx = startOfParams; while (count>0 && idx<signature.length()) { idx++; if (signature.charAt(idx)=='<') count++; if (signature.charAt(idx)=='>') count--; } return idx; } private static int locateFirstBracket(StringBuffer signature) { int idx = 0; while (idx<signature.length()) { if (signature.charAt(idx)=='<') return idx; idx++; } return -1; } private static UnresolvedType[] createTypeParams(String typeParameterSpecification) { String remainingToProcess = typeParameterSpecification; List types = new ArrayList(); while(!remainingToProcess.equals("")) { int endOfSig = 0; int anglies = 0; boolean sigFound = false; for (endOfSig = 0; (endOfSig < remainingToProcess.length()) && !sigFound; endOfSig++) { char thisChar = remainingToProcess.charAt(endOfSig); switch(thisChar) { case '<' : anglies++; break; case '>' : anglies--; break; case ';' : if (anglies == 0) { sigFound = true; break; } } } types.add(createTypeFromSignature(remainingToProcess.substring(0,endOfSig))); remainingToProcess = remainingToProcess.substring(endOfSig); } UnresolvedType[] typeParams = new UnresolvedType[types.size()]; types.toArray(typeParams); return typeParams; } }
232,712
Bug 232712 ClassFormatError during LTW using annotation approach
The following exception is obtained when using the annotation approach and load-time weaving: [AppClassLoader@1f12c4e] info AspectJ Weaver Version 1.5.4 built on Thursday Dec 20, 2007 at 13:44:10 GMT [AppClassLoader@1f12c4e] info register classloader sun.misc.Launcher$AppClassLoader@1f12c4e [AppClassLoader@1f12c4e] info using configuration /H:/temp/aspectj_bug/scratch/classes/scratch/aop/annotationbug/aspect/aop-bug.xml [AppClassLoader@1f12c4e] info register aspect scratch.aop.annotationbug.aspect.BugAspect doSomething() Exception in thread "main" java.lang.ClassFormatError: Code attribute in native or abstract methods in class file scratch/aop/annotationbug/extra/SubClass at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$000(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) at scratch.aop.annotationbug.extra.BugOther.getSubClass(BugOther.java:22) at scratch.aop.annotationbug.main.BugMain.somethingElse(BugMain.java:36) at scratch.aop.annotationbug.main.BugMain.doSomething(BugMain.java:30) at scratch.aop.annotationbug.main.BugMain.execute(BugMain.java:24) at scratch.aop.annotationbug.main.BugDriver.doExecute(BugDriver.java:27) at scratch.aop.annotationbug.main.BugDriver.main(BugDriver.java:21) The same advice logic does not result in a ClassFormatError when using the Aspect approach, it only appears using the annotation approach. Unfortunately we have not been able to track down exactly why the above Error occurs but have attached a test case that manifests it. To run simply use the runtime configuration on the BugDriver main(): -Dorg.aspectj.weaver.loadtime.configuration="scratch/aop/annotationbug/aspect/aop-bug.xml" Along with the AspectJ Load-Time Weaver Agent. The above occurs with both AspectJ 1.5.4 and AspectJ 1.6.0. Interestingly when using the aspectj 1.6.0 weaver, the AppClassLoader log still indicates "1.5.4".
resolved fixed
f014275
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-05-20T18:30:38Z"
"2008-05-18T22:33:20Z"
weaver/src/org/aspectj/weaver/bcel/BcelClassWeaver.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.generic.ANEWARRAY; import org.aspectj.apache.bcel.generic.BranchInstruction; import org.aspectj.apache.bcel.generic.CPInstruction; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldGen; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.GOTO; import org.aspectj.apache.bcel.generic.GOTO_W; import org.aspectj.apache.bcel.generic.INVOKESPECIAL; import org.aspectj.apache.bcel.generic.IndexedInstruction; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InstructionTargeter; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.LineNumberTag; import org.aspectj.apache.bcel.generic.LocalVariableInstruction; import org.aspectj.apache.bcel.generic.LocalVariableTag; import org.aspectj.apache.bcel.generic.MONITORENTER; import org.aspectj.apache.bcel.generic.MONITOREXIT; import org.aspectj.apache.bcel.generic.MULTIANEWARRAY; import org.aspectj.apache.bcel.generic.MethodGen; import org.aspectj.apache.bcel.generic.NEW; import org.aspectj.apache.bcel.generic.NEWARRAY; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.PUTFIELD; import org.aspectj.apache.bcel.generic.PUTSTATIC; import org.aspectj.apache.bcel.generic.RET; import org.aspectj.apache.bcel.generic.ReturnInstruction; import org.aspectj.apache.bcel.generic.Select; import org.aspectj.apache.bcel.generic.StoreInstruction; import org.aspectj.apache.bcel.generic.Tag; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.generic.annotation.AnnotationGen; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.util.PartialOrder; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.IClassWeaver; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.MissingResolvedTypeWithKnownSignature; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.ExactTypePattern; import org.aspectj.weaver.tools.Trace; import org.aspectj.weaver.tools.TraceFactory; class BcelClassWeaver implements IClassWeaver { private static Trace trace = TraceFactory.getTraceFactory().getTrace(BcelClassWeaver.class); /** * This is called from {@link BcelWeaver} to perform the per-class weaving process. */ public static boolean weave( BcelWorld world, LazyClassGen clazz, List shadowMungers, List typeMungers, List lateTypeMungers) { boolean b = new BcelClassWeaver(world, clazz, shadowMungers, typeMungers, lateTypeMungers).weave(); //System.out.println(clazz.getClassName() + ", " + clazz.getType().getWeaverState()); //clazz.print(); return b; } // -------------------------------------------- private final LazyClassGen clazz; private final List shadowMungers; private final List typeMungers; private final List lateTypeMungers; private final BcelObjectType ty; // alias of clazz.getType() private final BcelWorld world; // alias of ty.getWorld() private final ConstantPoolGen cpg; // alias of clazz.getConstantPoolGen() private final InstructionFactory fact; // alias of clazz.getFactory(); private final List addedLazyMethodGens = new ArrayList(); private final Set addedDispatchTargets = new HashSet(); // Static setting across BcelClassWeavers private static boolean inReweavableMode = false; private List addedSuperInitializersAsList = null; // List<IfaceInitList> private final Map addedSuperInitializers = new HashMap(); // Interface -> IfaceInitList private List addedThisInitializers = new ArrayList(); // List<NewFieldMunger> private List addedClassInitializers = new ArrayList(); // List<NewFieldMunger> private Map mapToAnnotations = new HashMap(); private BcelShadow clinitShadow = null; /** * This holds the initialization and pre-initialization shadows for this class * that were actually matched by mungers (if no match, then we don't even create the * shadows really). */ private final List initializationShadows = new ArrayList(1); private BcelClassWeaver( BcelWorld world, LazyClassGen clazz, List shadowMungers, List typeMungers, List lateTypeMungers) { super(); // assert world == clazz.getType().getWorld() this.world = world; this.clazz = clazz; this.shadowMungers = shadowMungers; this.typeMungers = typeMungers; this.lateTypeMungers = lateTypeMungers; this.ty = clazz.getBcelObjectType(); this.cpg = clazz.getConstantPoolGen(); this.fact = clazz.getFactory(); fastMatchShadowMungers(shadowMungers); initializeSuperInitializerMap(ty.getResolvedTypeX()); if (!checkedXsetForLowLevelContextCapturing) { Properties p = world.getExtraConfiguration(); if (p!=null) { String s = p.getProperty(World.xsetCAPTURE_ALL_CONTEXT,"false"); captureLowLevelContext = s.equalsIgnoreCase("true"); if (captureLowLevelContext) world.getMessageHandler().handleMessage(MessageUtil.info("["+World.xsetCAPTURE_ALL_CONTEXT+"=true] Enabling collection of low level context for debug/crash messages")); } checkedXsetForLowLevelContextCapturing=true; } } private List[] perKindShadowMungers; private boolean canMatchBodyShadows = false; private boolean canMatchInitialization = false; private void fastMatchShadowMungers(List shadowMungers) { // beware the annoying property that SHADOW_KINDS[i].getKey == (i+1) ! perKindShadowMungers = new List[Shadow.MAX_SHADOW_KIND + 1]; for (int i = 0; i < perKindShadowMungers.length; i++) { perKindShadowMungers[i] = new ArrayList(0); } for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); int couldMatchKinds = munger.getPointcut().couldMatchKinds(); for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { Shadow.Kind kind = Shadow.SHADOW_KINDS[i]; if (kind.isSet(couldMatchKinds)) perKindShadowMungers[kind.getKey()].add(munger); } // Set couldMatchKinds = munger.getPointcut().couldMatchKinds(); // for (Iterator kindIterator = couldMatchKinds.iterator(); // kindIterator.hasNext();) { // Shadow.Kind aKind = (Shadow.Kind) kindIterator.next(); // perKindShadowMungers[aKind.getKey()].add(munger); // } } if (!perKindShadowMungers[Shadow.Initialization.getKey()].isEmpty()) canMatchInitialization = true; for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { Shadow.Kind kind = Shadow.SHADOW_KINDS[i]; if (!kind.isEnclosingKind() && !perKindShadowMungers[i+1].isEmpty()) { canMatchBodyShadows = true; } if (perKindShadowMungers[i+1].isEmpty()) { perKindShadowMungers[i+1] = null; } } } private boolean canMatch(Shadow.Kind kind) { return perKindShadowMungers[kind.getKey()] != null; } // private void fastMatchShadowMungers(List shadowMungers, ArrayList mungers, Kind kind) { // FastMatchInfo info = new FastMatchInfo(clazz.getType(), kind); // for (Iterator i = shadowMungers.iterator(); i.hasNext();) { // ShadowMunger munger = (ShadowMunger) i.next(); // FuzzyBoolean fb = munger.getPointcut().fastMatch(info); // WeaverMetrics.recordFastMatchResult(fb);// Could pass: munger.getPointcut().toString() // if (fb.maybeTrue()) mungers.add(munger); // } // } private void initializeSuperInitializerMap(ResolvedType child) { ResolvedType[] superInterfaces = child.getDeclaredInterfaces(); for (int i=0, len=superInterfaces.length; i < len; i++) { if (ty.getResolvedTypeX().isTopmostImplementor(superInterfaces[i])) { if (addSuperInitializer(superInterfaces[i])) { initializeSuperInitializerMap(superInterfaces[i]); } } } } private boolean addSuperInitializer(ResolvedType onType) { if (onType.isRawType() || onType.isParameterizedType()) onType = onType.getGenericType(); IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType); if (l != null) return false; l = new IfaceInitList(onType); addedSuperInitializers.put(onType, l); return true; } public void addInitializer(ConcreteTypeMunger cm) { NewFieldTypeMunger m = (NewFieldTypeMunger) cm.getMunger(); ResolvedType onType = m.getSignature().getDeclaringType().resolve(world); if (onType.isRawType()) onType = onType.getGenericType(); if (m.getSignature().isStatic()) { addedClassInitializers.add(cm); } else { if (onType == ty.getResolvedTypeX()) { addedThisInitializers.add(cm); } else { IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType); l.list.add(cm); } } } private static class IfaceInitList implements PartialOrder.PartialComparable { final ResolvedType onType; List list = new ArrayList(); IfaceInitList(ResolvedType onType) { this.onType = onType; } public int compareTo(Object other) { IfaceInitList o = (IfaceInitList)other; if (onType.isAssignableFrom(o.onType)) return +1; else if (o.onType.isAssignableFrom(onType)) return -1; else return 0; } public int fallbackCompareTo(Object other) { return 0; } } // XXX this is being called, but the result doesn't seem to be being used public boolean addDispatchTarget(ResolvedMember m) { return addedDispatchTargets.add(m); } public void addLazyMethodGen(LazyMethodGen gen) { addedLazyMethodGens.add(gen); } public void addOrReplaceLazyMethodGen(LazyMethodGen mg) { if (alreadyDefined(clazz, mg)) return; for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) { LazyMethodGen existing = (LazyMethodGen)i.next(); if (signaturesMatch(mg, existing)) { if (existing.definingType == null) { // this means existing was introduced on the class itself return; } else if (mg.definingType.isAssignableFrom(existing.definingType)) { // existing is mg's subtype and dominates mg return; } else if (existing.definingType.isAssignableFrom(mg.definingType)) { // mg is existing's subtype and dominates existing i.remove(); addedLazyMethodGens.add(mg); return; } else { throw new BCException("conflict between: " + mg + " and " + existing); } } } addedLazyMethodGens.add(mg); } private boolean alreadyDefined(LazyClassGen clazz, LazyMethodGen mg) { for (Iterator i = clazz.getMethodGens().iterator(); i.hasNext(); ) { LazyMethodGen existing = (LazyMethodGen)i.next(); if (signaturesMatch(mg, existing)) { if (!mg.isAbstract() && existing.isAbstract()) { i.remove(); return false; } return true; } } return false; } private boolean signaturesMatch(LazyMethodGen mg, LazyMethodGen existing) { return mg.getName().equals(existing.getName()) && mg.getSignature().equals(existing.getSignature()); } protected static LazyMethodGen makeBridgeMethod(LazyClassGen gen, ResolvedMember member) { // remove abstract modifier int mods = member.getModifiers(); if (Modifier.isAbstract(mods)) mods = mods - Modifier.ABSTRACT; LazyMethodGen ret = new LazyMethodGen( mods, BcelWorld.makeBcelType(member.getReturnType()), member.getName(), BcelWorld.makeBcelTypes(member.getParameterTypes()), UnresolvedType.getNames(member.getExceptions()), gen); // 43972 : Static crosscutting makes interfaces unusable for javac // ret.makeSynthetic(); return ret; } /** * Create a single bridge method called 'theBridgeMethod' that bridges to 'whatToBridgeTo' */ private static void createBridgeMethod(BcelWorld world, LazyMethodGen whatToBridgeToMethodGen, LazyClassGen clazz,ResolvedMember theBridgeMethod) { InstructionList body; InstructionFactory fact; int pos = 0; ResolvedMember whatToBridgeTo = whatToBridgeToMethodGen.getMemberView(); if (whatToBridgeTo==null) { whatToBridgeTo = new ResolvedMemberImpl(Member.METHOD, whatToBridgeToMethodGen.getEnclosingClass().getType(), whatToBridgeToMethodGen.getAccessFlags(), whatToBridgeToMethodGen.getName(), whatToBridgeToMethodGen.getSignature()); } LazyMethodGen bridgeMethod = makeBridgeMethod(clazz,theBridgeMethod); // The bridge method in this type will have the same signature as the one in the supertype bridgeMethod.setAccessFlags(bridgeMethod.getAccessFlags() | 0x00000040 /*BRIDGE = 0x00000040*/ ); Type returnType = BcelWorld.makeBcelType(theBridgeMethod.getReturnType()); Type[] paramTypes = BcelWorld.makeBcelTypes(theBridgeMethod.getParameterTypes()); Type[] newParamTypes=whatToBridgeToMethodGen.getArgumentTypes(); body = bridgeMethod.getBody(); fact = clazz.getFactory(); if (!whatToBridgeToMethodGen.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); if (!newParamTypes[i].equals(paramTypes[i])) { if (world.forDEBUG_bridgingCode) System.err.println("Bridging: Cast "+newParamTypes[i]+" from "+paramTypes[i]); body.append(fact.createCast(paramTypes[i],newParamTypes[i])); } pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, world,whatToBridgeTo)); body.append(InstructionFactory.createReturn(returnType)); clazz.addMethodGen(bridgeMethod); } // ---- public boolean weave() { if (clazz.isWoven() && !clazz.isReweavable()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ALREADY_WOVEN,clazz.getType().getName()), ty.getSourceLocation(), null); return false; } Set aspectsAffectingType = null; if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType = new HashSet(); boolean isChanged = false; // we want to "touch" all aspects if (clazz.getType().isAspect()) isChanged = true; // start by munging all typeMungers for (Iterator i = typeMungers.iterator(); i.hasNext(); ) { Object o = i.next(); if ( !(o instanceof BcelTypeMunger) ) { //???System.err.println("surprising: " + o); continue; } BcelTypeMunger munger = (BcelTypeMunger)o; boolean typeMungerAffectedType = munger.munge(this); if (typeMungerAffectedType) { isChanged = true; if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.add(munger.getAspectType().getName()); } } // Weave special half type/half shadow mungers... isChanged = weaveDeclareAtMethodCtor(clazz) || isChanged; isChanged = weaveDeclareAtField(clazz) || isChanged; // XXX do major sort of stuff // sort according to: Major: type hierarchy // within each list: dominates // don't forget to sort addedThisInitialiers according to dominates addedSuperInitializersAsList = new ArrayList(addedSuperInitializers.values()); addedSuperInitializersAsList = PartialOrder.sort(addedSuperInitializersAsList); if (addedSuperInitializersAsList == null) { throw new BCException("circularity in inter-types"); } // this will create a static initializer if there isn't one // this is in just as bad taste as NOPs LazyMethodGen staticInit = clazz.getStaticInitializer(); staticInit.getBody().insert(genInitInstructions(addedClassInitializers, true)); // now go through each method, and match against each method. This // sets up each method's {@link LazyMethodGen#matchedShadows} field, // and it also possibly adds to {@link #initializationShadows}. List methodGens = new ArrayList(clazz.getMethodGens()); for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen)i.next(); if (! mg.hasBody()) continue; if (world.isJoinpointSynchronizationEnabled() && world.areSynchronizationPointcutsInUse() && mg.getMethod().isSynchronized()) { transformSynchronizedMethod(mg); } boolean shadowMungerMatched = match(mg); if (shadowMungerMatched) { // For matching mungers, add their declaring aspects to the list that affected this type if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.addAll(findAspectsForMungers(mg)); isChanged = true; } } // now we weave all but the initialization shadows for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen)i.next(); if (! mg.hasBody()) continue; implement(mg); } // if we matched any initialization shadows, we inline and weave if (!initializationShadows.isEmpty()) { // Repeat next step until nothing left to inline...cant go on // infinetly as compiler will have detected and reported // "Recursive constructor invocation" while (inlineSelfConstructors(methodGens)); positionAndImplement(initializationShadows); } // now proceed with late type mungers if (lateTypeMungers != null) { for (Iterator i = lateTypeMungers.iterator(); i.hasNext(); ) { BcelTypeMunger munger = (BcelTypeMunger)i.next(); if (munger.matches(clazz.getType())) { boolean typeMungerAffectedType = munger.munge(this); if (typeMungerAffectedType) { isChanged = true; if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.add(munger.getAspectType().getName()); } } } } //FIXME AV - see #75442, for now this is not enough to fix the bug, comment that out until we really fix it // // flush to save some memory // PerObjectInterfaceTypeMunger.unregisterFromAsAdvisedBy(clazz.getType()); // finally, if we changed, we add in the introduced methods. if (isChanged) { clazz.getOrCreateWeaverStateInfo(inReweavableMode); weaveInAddedMethods(); // FIXME asc are these potentially affected by declare annotation? } if (inReweavableMode) { WeaverStateInfo wsi = clazz.getOrCreateWeaverStateInfo(true); wsi.addAspectsAffectingType(aspectsAffectingType); wsi.setUnwovenClassFileData(ty.getJavaClass().getBytes()); wsi.setReweavable(true); } else { clazz.getOrCreateWeaverStateInfo(false).setReweavable(false); } return isChanged; } // **************************** start of bridge method creation code ***************** // FIXME asc tidy this lot up !! // FIXME asc refactor into ResolvedType or even ResolvedMember? /** * Check if a particular method is overriding another - refactored into this helper so it * can be used from multiple places. */ private static ResolvedMember isOverriding(ResolvedType typeToCheck,ResolvedMember methodThatMightBeGettingOverridden,String mname,String mrettype,int mmods,boolean inSamePackage,UnresolvedType[] methodParamsArray) { // Check if we can be an override... if (methodThatMightBeGettingOverridden.isStatic()) return null; // we can't be overriding a static method if (methodThatMightBeGettingOverridden.isPrivate()) return null; // we can't be overriding a private method if (!methodThatMightBeGettingOverridden.getName().equals(mname)) return null; // names dont match (this will also skip <init> and <clinit> too) if (methodThatMightBeGettingOverridden.getParameterTypes().length!=methodParamsArray.length) return null; // check same number of parameters if (!isVisibilityOverride(mmods,methodThatMightBeGettingOverridden,inSamePackage)) return null; if (typeToCheck.getWorld().forDEBUG_bridgingCode) System.err.println(" Bridging:seriously considering this might be getting overridden '"+methodThatMightBeGettingOverridden+"'"); // Look at erasures of parameters (List<String> erased is List) boolean sameParams = true; for (int p = 0;p<methodThatMightBeGettingOverridden.getParameterTypes().length;p++) { if (!methodThatMightBeGettingOverridden.getParameterTypes()[p].getErasureSignature().equals(methodParamsArray[p].getErasureSignature())) sameParams = false; } // If the 'typeToCheck' represents a parameterized type then the method will be the parameterized form of the // generic method in the generic type. So if the method was 'void m(List<T> lt, T t)' and the parameterized type here // is I<String> then the method we are looking at will be 'void m(List<String> lt, String t)' which when erased // is 'void m(List lt,String t)' - so if the parameters *do* match then there is a generic method we are // overriding if (sameParams) { // check for covariance if (typeToCheck.isParameterizedType()) { return methodThatMightBeGettingOverridden.getBackingGenericMember(); } else if (!methodThatMightBeGettingOverridden.getReturnType().getErasureSignature().equals(mrettype)) { // addressing the wierd situation from bug 147801 // just check whether these things are in the right relationship for covariance... ResolvedType superReturn = typeToCheck.getWorld().resolve(UnresolvedType.forSignature(methodThatMightBeGettingOverridden.getReturnType().getErasureSignature())); ResolvedType subReturn = typeToCheck.getWorld().resolve(UnresolvedType.forSignature(mrettype)); if (superReturn.isAssignableFrom(subReturn)) return methodThatMightBeGettingOverridden; } } return null; } /** * Looks at the visibility modifiers between two methods, and knows whether they are from classes in * the same package, and decides whether one overrides the other. * @return true if there is an overrides rather than a 'hides' relationship */ static boolean isVisibilityOverride(int methodMods, ResolvedMember inheritedMethod,boolean inSamePackage) { if (inheritedMethod.isStatic()) return false; if (methodMods == inheritedMethod.getModifiers()) return true; if (inheritedMethod.isPrivate()) return false; boolean isPackageVisible = !inheritedMethod.isPrivate() && !inheritedMethod.isProtected() && !inheritedMethod.isPublic(); if (isPackageVisible && !inSamePackage) return false; return true; } /** * This method recurses up a specified type looking for a method that overrides the one passed in. * * @return the method being overridden or null if none is found */ public static ResolvedMember checkForOverride(ResolvedType typeToCheck,String mname,String mparams,String mrettype,int mmods,String mpkg,UnresolvedType[] methodParamsArray) { if (typeToCheck==null) return null; if (typeToCheck instanceof MissingResolvedTypeWithKnownSignature) return null; // we just can't tell ! if (typeToCheck.getWorld().forDEBUG_bridgingCode) System.err.println(" Bridging:checking for override of "+mname+" in "+typeToCheck); String packageName = typeToCheck.getPackageName(); if (packageName==null) packageName=""; boolean inSamePackage = packageName.equals(mpkg); // used when looking at visibility rules ResolvedMember [] methods = typeToCheck.getDeclaredMethods(); for (int ii=0;ii<methods.length;ii++) { ResolvedMember methodThatMightBeGettingOverridden = methods[ii]; // the method we are going to check ResolvedMember isOverriding = isOverriding(typeToCheck,methodThatMightBeGettingOverridden,mname,mrettype,mmods,inSamePackage,methodParamsArray); if (isOverriding!=null) return isOverriding; } List l = typeToCheck.getInterTypeMungers(); for (Iterator iterator = l.iterator(); iterator.hasNext();) { Object o = iterator.next(); // FIXME asc if its not a BcelTypeMunger then its an EclipseTypeMunger ... do I need to worry about that? if (o instanceof BcelTypeMunger) { BcelTypeMunger element = (BcelTypeMunger)o; if (element.getMunger() instanceof NewMethodTypeMunger) { if (typeToCheck.getWorld().forDEBUG_bridgingCode) System.err.println("Possible ITD candidate "+element); ResolvedMember aMethod = element.getSignature(); ResolvedMember isOverriding = isOverriding(typeToCheck,aMethod,mname,mrettype,mmods,inSamePackage,methodParamsArray); if (isOverriding!=null) return isOverriding; } } } if (typeToCheck.equals(UnresolvedType.OBJECT)) return null; ResolvedType superclass = typeToCheck.getSuperclass(); ResolvedMember overriddenMethod = checkForOverride(superclass,mname,mparams,mrettype,mmods,mpkg,methodParamsArray); if (overriddenMethod!=null) return overriddenMethod; ResolvedType[] interfaces = typeToCheck.getDeclaredInterfaces(); for (int i = 0; i < interfaces.length; i++) { ResolvedType anInterface = interfaces[i]; overriddenMethod = checkForOverride(anInterface,mname,mparams,mrettype,mmods,mpkg,methodParamsArray); if (overriddenMethod!=null) return overriddenMethod; } return null; } /** * We need to determine if any methods in this type require bridge methods - this method should only * be called if necessary to do this calculation, i.e. we are on a 1.5 VM (where covariance/generics exist) and * the type hierarchy for the specified class has changed (via decp/itd). * * See pr108101 */ public static boolean calculateAnyRequiredBridgeMethods(BcelWorld world,LazyClassGen clazz) { world.ensureAdvancedConfigurationProcessed(); if (!world.isInJava5Mode()) return false; // just double check... the caller should have already verified this if (clazz.isInterface()) return false; // dont bother if we're an interface boolean didSomething=false; // set if we build any bridge methods // So what methods do we have right now in this class? List /*LazyMethodGen*/ methods = clazz.getMethodGens(); // Keep a set of all methods from this type - it'll help us to check if bridge methods // have already been created, we don't want to do it twice! Set methodsSet = new HashSet(); for (int i = 0; i < methods.size(); i++) { LazyMethodGen aMethod = (LazyMethodGen)methods.get(i); methodsSet.add(aMethod.getName()+aMethod.getSignature()); // e.g. "foo(Ljava/lang/String;)V" } // Now go through all the methods in this type for (int i = 0; i < methods.size(); i++) { // This is the local method that we *might* have to bridge to LazyMethodGen bridgeToCandidate = (LazyMethodGen)methods.get(i); if (bridgeToCandidate.isBridgeMethod()) continue; // Doh! String name = bridgeToCandidate.getName(); String psig = bridgeToCandidate.getParameterSignature(); String rsig = bridgeToCandidate.getReturnType().getSignature(); //if (bridgeToCandidate.isAbstract()) continue; if (bridgeToCandidate.isStatic()) continue; // ignore static methods if (name.endsWith("init>")) continue; // Skip constructors and static initializers if (world.forDEBUG_bridgingCode) System.err.println("Bridging: Determining if we have to bridge to "+clazz.getName()+"."+name+""+bridgeToCandidate.getSignature()); // Let's take a look at the superclass ResolvedType theSuperclass= clazz.getSuperClass(); if (world.forDEBUG_bridgingCode) System.err.println("Bridging: Checking supertype "+theSuperclass); String pkgName = clazz.getPackageName(); UnresolvedType[] bm = BcelWorld.fromBcel(bridgeToCandidate.getArgumentTypes()); ResolvedMember overriddenMethod = checkForOverride(theSuperclass,name,psig,rsig,bridgeToCandidate.getAccessFlags(),pkgName,bm); if (overriddenMethod!=null) { boolean alreadyHaveABridgeMethod = methodsSet.contains(overriddenMethod.getName()+overriddenMethod.getSignature()); if (!alreadyHaveABridgeMethod) { if (world.forDEBUG_bridgingCode) System.err.println("Bridging:bridging to '"+overriddenMethod+"'"); createBridgeMethod(world, bridgeToCandidate, clazz, overriddenMethod); didSomething = true; continue; // look at the next method } } // Check superinterfaces String[] interfaces = clazz.getInterfaceNames(); for (int j = 0; j < interfaces.length; j++) { if (world.forDEBUG_bridgingCode) System.err.println("Bridging:checking superinterface "+interfaces[j]); ResolvedType interfaceType = world.resolve(interfaces[j]); overriddenMethod = checkForOverride(interfaceType,name,psig,rsig,bridgeToCandidate.getAccessFlags(),clazz.getPackageName(),bm); if (overriddenMethod!=null) { boolean alreadyHaveABridgeMethod = methodsSet.contains(overriddenMethod.getName()+overriddenMethod.getSignature()); if (!alreadyHaveABridgeMethod) { createBridgeMethod(world, bridgeToCandidate, clazz, overriddenMethod); didSomething=true; if (world.forDEBUG_bridgingCode) System.err.println("Bridging:bridging to "+overriddenMethod); continue; // look at the next method } } } } return didSomething; } // **************************** end of bridge method creation code ***************** /** * Weave any declare @method/@ctor statements into the members of the supplied class */ private boolean weaveDeclareAtMethodCtor(LazyClassGen clazz) { List reportedProblems = new ArrayList(); List allDecams = world.getDeclareAnnotationOnMethods(); if (allDecams.isEmpty()) return false; // nothing to do boolean isChanged = false; // deal with ITDs List itdMethodsCtors = getITDSubset(clazz,ResolvedTypeMunger.Method); itdMethodsCtors.addAll(getITDSubset(clazz,ResolvedTypeMunger.Constructor)); if (!itdMethodsCtors.isEmpty()) { // Can't use the subset called 'decaMs' as it won't be right for ITDs... isChanged = weaveAtMethodOnITDSRepeatedly(allDecams,itdMethodsCtors,reportedProblems); } // deal with all the other methods... List members = clazz.getMethodGens(); List decaMs = getMatchingSubset(allDecams,clazz.getType()); if (decaMs.isEmpty()) return false; // nothing to do if (!members.isEmpty()) { Set unusedDecams = new HashSet(); unusedDecams.addAll(decaMs); for (int memberCounter = 0;memberCounter<members.size();memberCounter++) { LazyMethodGen mg = (LazyMethodGen)members.get(memberCounter); if (!mg.getName().startsWith(NameMangler.PREFIX)) { // Single first pass List worthRetrying = new ArrayList(); boolean modificationOccured = false; List /*AnnotationGen*/ annotationsToAdd = null; for (Iterator iter = decaMs.iterator(); iter.hasNext();) { DeclareAnnotation decaM = (DeclareAnnotation) iter.next(); if (decaM.matches(mg.getMemberView(),world)) { if (doesAlreadyHaveAnnotation(mg.getMemberView(),decaM,reportedProblems)) { // remove the declare @method since don't want an error when // the annotation is already there unusedDecams.remove(decaM); continue; // skip this one... } if (annotationsToAdd==null) annotationsToAdd = new ArrayList(); Annotation a = decaM.getAnnotationX().getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,clazz.getConstantPoolGen(),true); annotationsToAdd.add(ag); mg.addAnnotation(decaM.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaM.getSourceLocation(),clazz.getName(),mg.getMethod()); reportMethodCtorWeavingMessage(clazz, mg.getMemberView(), decaM,mg.getDeclarationLineNumber()); isChanged = true; modificationOccured = true; // remove the declare @method since have matched against it unusedDecams.remove(decaM); } else { if (!decaM.isStarredAnnotationPattern()) worthRetrying.add(decaM); // an annotation is specified that might be put on by a subsequent decaf } } // Multiple secondary passes while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; // lets have another go List forRemoval = new ArrayList(); for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaM = (DeclareAnnotation) iter.next(); if (decaM.matches(mg.getMemberView(),world)) { if (doesAlreadyHaveAnnotation(mg.getMemberView(),decaM,reportedProblems)) { // remove the declare @method since don't want an error when // the annotation is already there unusedDecams.remove(decaM); continue; // skip this one... } if (annotationsToAdd==null) annotationsToAdd = new ArrayList(); Annotation a = decaM.getAnnotationX().getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,clazz.getConstantPoolGen(),true); annotationsToAdd.add(ag); mg.addAnnotation(decaM.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaM.getSourceLocation(),clazz.getName(),mg.getMethod()); isChanged = true; modificationOccured = true; forRemoval.add(decaM); // remove the declare @method since have matched against it unusedDecams.remove(decaM); } } worthRetrying.removeAll(forRemoval); } if (annotationsToAdd!=null) { Method oldMethod = mg.getMethod(); MethodGen myGen = new MethodGen(oldMethod,clazz.getClassName(),clazz.getConstantPoolGen(),false);// dont use tags, they won't get repaired like for woven methods. for (Iterator iter = annotationsToAdd.iterator(); iter.hasNext();) { AnnotationGen a = (AnnotationGen) iter.next(); myGen.addAnnotation(a); } Method newMethod = myGen.getMethod(); members.set(memberCounter,new LazyMethodGen(newMethod,clazz)); } } } checkUnusedDeclareAtTypes(unusedDecams, false); } return isChanged; } // TAG: WeavingMessage private void reportMethodCtorWeavingMessage(LazyClassGen clazz, ResolvedMember member, DeclareAnnotation decaM,int memberLineNumber) { if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){ StringBuffer parmString = new StringBuffer("("); UnresolvedType[] paramTypes = member.getParameterTypes(); for (int i = 0; i < paramTypes.length; i++) { UnresolvedType type = paramTypes[i]; String s = org.aspectj.apache.bcel.classfile.Utility.signatureToString(type.getSignature()); if (s.lastIndexOf(".")!=-1) s =s.substring(s.lastIndexOf(".")+1); parmString.append(s); if ((i+1)<paramTypes.length) parmString.append(","); } parmString.append(")"); String methodName = member.getName(); StringBuffer sig = new StringBuffer(); sig.append(org.aspectj.apache.bcel.classfile.Utility.accessToString(member.getModifiers())); sig.append(" "); sig.append(member.getReturnType().toString()); sig.append(" "); sig.append(member.getDeclaringType().toString()); sig.append("."); sig.append(methodName.equals("<init>")?"new":methodName); sig.append(parmString); StringBuffer loc = new StringBuffer(); if (clazz.getFileName()==null) { loc.append("no debug info available"); } else { loc.append(clazz.getFileName()); if (memberLineNumber!=-1) { loc.append(":"+memberLineNumber); } } getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES, new String[]{ sig.toString(), loc.toString(), decaM.getAnnotationString(), methodName.startsWith("<init>")?"constructor":"method", decaM.getAspect().toString(), Utility.beautifyLocation(decaM.getSourceLocation()) })); } } /** * Looks through a list of declare annotation statements and only returns * those that could possibly match on a field/method/ctor in type. */ private List getMatchingSubset(List declareAnnotations, ResolvedType type) { List subset = new ArrayList(); for (Iterator iter = declareAnnotations.iterator(); iter.hasNext();) { DeclareAnnotation da = (DeclareAnnotation) iter.next(); if (da.couldEverMatch(type)) { subset.add(da); } } return subset; } /** * Get a subset of all the type mungers defined on this aspect */ private List getITDSubset(LazyClassGen clazz,ResolvedTypeMunger.Kind wantedKind) { List subset = new ArrayList(); Collection c = clazz.getBcelObjectType().getTypeMungers(); for (Iterator iter = c.iterator();iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger)iter.next(); if (typeMunger.getMunger().getKind()==wantedKind) subset.add(typeMunger); } return subset; } public LazyMethodGen locateAnnotationHolderForFieldMunger(LazyClassGen clazz,BcelTypeMunger fieldMunger) { NewFieldTypeMunger nftm = (NewFieldTypeMunger)fieldMunger.getMunger(); ResolvedMember lookingFor =AjcMemberMaker.interFieldInitializer(nftm.getSignature(),clazz.getType()); List meths = clazz.getMethodGens(); for (Iterator iter = meths.iterator(); iter.hasNext();) { LazyMethodGen element = (LazyMethodGen) iter.next(); if (element.getName().equals(lookingFor.getName())) return element; } return null; } // FIXME asc refactor this to neaten it up public LazyMethodGen locateAnnotationHolderForMethodCtorMunger(LazyClassGen clazz,BcelTypeMunger methodCtorMunger) { if (methodCtorMunger.getMunger() instanceof NewMethodTypeMunger) { NewMethodTypeMunger nftm = (NewMethodTypeMunger)methodCtorMunger.getMunger(); ResolvedMember lookingFor = AjcMemberMaker.interMethodDispatcher(nftm.getSignature(),methodCtorMunger.getAspectType()); List meths = clazz.getMethodGens(); for (Iterator iter = meths.iterator(); iter.hasNext();) { LazyMethodGen element = (LazyMethodGen) iter.next(); if (element.getName().equals(lookingFor.getName()) && element.getParameterSignature().equals(lookingFor.getParameterSignature())) return element; } return null; } else if (methodCtorMunger.getMunger() instanceof NewConstructorTypeMunger) { NewConstructorTypeMunger nftm = (NewConstructorTypeMunger)methodCtorMunger.getMunger(); ResolvedMember lookingFor =AjcMemberMaker.postIntroducedConstructor(methodCtorMunger.getAspectType(),nftm.getSignature().getDeclaringType(),nftm.getSignature().getParameterTypes()); List meths = clazz.getMethodGens(); for (Iterator iter = meths.iterator(); iter.hasNext();) { LazyMethodGen element = (LazyMethodGen) iter.next(); if (element.getName().equals(lookingFor.getName()) && element.getParameterSignature().equals(lookingFor.getParameterSignature())) return element; } return null; } else { throw new RuntimeException("Not sure what this is: "+methodCtorMunger); } } /** * Applies some set of declare @field constructs (List<DeclareAnnotation>) to some bunch * of ITDfields (List<BcelTypeMunger>. It will iterate over the fields repeatedly until * everything has been applied. * */ private boolean weaveAtFieldRepeatedly(List decaFs, List itdFields,List reportedErrors) { boolean isChanged = false; for (Iterator iter = itdFields.iterator(); iter.hasNext();) { BcelTypeMunger fieldMunger = (BcelTypeMunger) iter.next(); ResolvedMember itdIsActually = fieldMunger.getSignature(); List worthRetrying = new ArrayList(); boolean modificationOccured = false; for (Iterator iter2 = decaFs.iterator(); iter2.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter2.next(); if (decaF.matches(itdIsActually,world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,fieldMunger); if (doesAlreadyHaveAnnotation(annotationHolder,itdIsActually,decaF,reportedErrors)) continue; // skip this one... annotationHolder.addAnnotation(decaF.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),itdIsActually.getSourceLocation()); isChanged = true; modificationOccured = true; } else { if (!decaF.isStarredAnnotationPattern()) worthRetrying.add(decaF); // an annotation is specified that might be put on by a subsequent decaf } } while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; List forRemoval = new ArrayList(); for (Iterator iter2 = worthRetrying.iterator(); iter2.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter2.next(); if (decaF.matches(itdIsActually,world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,fieldMunger); if (doesAlreadyHaveAnnotation(annotationHolder,itdIsActually,decaF,reportedErrors)) continue; // skip this one... annotationHolder.addAnnotation(decaF.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),itdIsActually.getSourceLocation()); isChanged = true; modificationOccured = true; forRemoval.add(decaF); } worthRetrying.removeAll(forRemoval); } } } return isChanged; } /** * Applies some set of declare @method/@ctor constructs (List<DeclareAnnotation>) to some bunch * of ITDmembers (List<BcelTypeMunger>. It will iterate over the fields repeatedly until * everything has been applied. */ private boolean weaveAtMethodOnITDSRepeatedly(List decaMCs, List itdMethodsCtors,List reportedErrors) { boolean isChanged = false; for (Iterator iter = itdMethodsCtors.iterator(); iter.hasNext();) { BcelTypeMunger methodctorMunger = (BcelTypeMunger) iter.next(); ResolvedMember unMangledInterMethod = methodctorMunger.getSignature(); List worthRetrying = new ArrayList(); boolean modificationOccured = false; for (Iterator iter2 = decaMCs.iterator(); iter2.hasNext();) { DeclareAnnotation decaMC = (DeclareAnnotation) iter2.next(); if (decaMC.matches(unMangledInterMethod,world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForMethodCtorMunger(clazz,methodctorMunger); if (annotationHolder == null || doesAlreadyHaveAnnotation(annotationHolder,unMangledInterMethod,decaMC,reportedErrors)){ continue; // skip this one... } annotationHolder.addAnnotation(decaMC.getAnnotationX()); isChanged=true; AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaMC.getSourceLocation(),unMangledInterMethod.getSourceLocation()); reportMethodCtorWeavingMessage(clazz, unMangledInterMethod, decaMC,-1); modificationOccured = true; } else { if (!decaMC.isStarredAnnotationPattern()) worthRetrying.add(decaMC); // an annotation is specified that might be put on by a subsequent decaf } } while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; List forRemoval = new ArrayList(); for (Iterator iter2 = worthRetrying.iterator(); iter2.hasNext();) { DeclareAnnotation decaMC = (DeclareAnnotation) iter2.next(); if (decaMC.matches(unMangledInterMethod,world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,methodctorMunger); if (doesAlreadyHaveAnnotation(annotationHolder,unMangledInterMethod,decaMC,reportedErrors)) continue; // skip this one... annotationHolder.addAnnotation(decaMC.getAnnotationX()); unMangledInterMethod.addAnnotation(decaMC.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaMC.getSourceLocation(),unMangledInterMethod.getSourceLocation()); isChanged = true; modificationOccured = true; forRemoval.add(decaMC); } worthRetrying.removeAll(forRemoval); } } } return isChanged; } private boolean dontAddTwice(DeclareAnnotation decaF, Annotation [] dontAddMeTwice){ for (int i = 0; i < dontAddMeTwice.length; i++){ Annotation ann = dontAddMeTwice[i]; if (ann != null && decaF.getAnnotationX().getTypeName().equals(ann.getTypeName())){ //dontAddMeTwice[i] = null; // incase it really has been added twice! return true; } } return false; } /** * Weave any declare @field statements into the fields of the supplied class * * Interesting case relating to public ITDd fields. The annotations are really stored against * the interfieldinit method in the aspect, but the public field is placed in the target * type and then is processed in the 2nd pass over fields that occurs. I think it would be * more expensive to avoid putting the annotation on that inserted public field than just to * have it put there as well as on the interfieldinit method. */ private boolean weaveDeclareAtField(LazyClassGen clazz) { // BUGWARNING not getting enough warnings out on declare @field ? // There is a potential problem here with warnings not coming out - this // will occur if they are created on the second iteration round this loop. // We currently deactivate error reporting for the second time round. // A possible solution is to record what annotations were added by what // decafs and check that to see if an error needs to be reported - this // would be expensive so lets skip it for now List reportedProblems = new ArrayList(); List allDecafs = world.getDeclareAnnotationOnFields(); if (allDecafs.isEmpty()) return false; // nothing to do boolean isChanged = false; List itdFields = getITDSubset(clazz,ResolvedTypeMunger.Field); if (itdFields!=null) { isChanged = weaveAtFieldRepeatedly(allDecafs,itdFields,reportedProblems); } List decaFs = getMatchingSubset(allDecafs,clazz.getType()); if (decaFs.isEmpty()) return false; // nothing more to do Field[] fields = clazz.getFieldGens(); if (fields!=null) { Set unusedDecafs = new HashSet(); unusedDecafs.addAll(decaFs); for (int fieldCounter = 0;fieldCounter<fields.length;fieldCounter++) { BcelField aBcelField = new BcelField(clazz.getBcelObjectType(),fields[fieldCounter]); if (!aBcelField.getName().startsWith(NameMangler.PREFIX)) { // Single first pass List worthRetrying = new ArrayList(); boolean modificationOccured = false; Annotation [] dontAddMeTwice = fields[fieldCounter].getAnnotations(); // go through all the declare @field statements for (Iterator iter = decaFs.iterator(); iter.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter.next(); if (decaF.matches(aBcelField,world)) { if (!dontAddTwice(decaF,dontAddMeTwice)){ if (doesAlreadyHaveAnnotation(aBcelField,decaF,reportedProblems)){ // remove the declare @field since don't want an error when // the annotation is already there unusedDecafs.remove(decaF); continue; } if(decaF.getAnnotationX().isRuntimeVisible()){ // isAnnotationWithRuntimeRetention(clazz.getJavaClass(world))){ //if(decaF.getAnnotationTypeX().isAnnotationWithRuntimeRetention(world)){ // it should be runtime visible, so put it on the Field Annotation a = decaF.getAnnotationX().getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,clazz.getConstantPoolGen(),true); FieldGen myGen = new FieldGen(fields[fieldCounter],clazz.getConstantPoolGen()); myGen.addAnnotation(ag); Field newField = myGen.getField(); aBcelField.addAnnotation(decaF.getAnnotationX()); clazz.replaceField(fields[fieldCounter],newField); fields[fieldCounter]=newField; } else{ aBcelField.addAnnotation(decaF.getAnnotationX()); } } AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),clazz.getName(),fields[fieldCounter]); reportFieldAnnotationWeavingMessage(clazz, fields, fieldCounter, decaF); isChanged = true; modificationOccured = true; // remove the declare @field since have matched against it unusedDecafs.remove(decaF); } else { if (!decaF.isStarredAnnotationPattern()) worthRetrying.add(decaF); // an annotation is specified that might be put on by a subsequent decaf } } // Multiple secondary passes while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; // lets have another go List forRemoval = new ArrayList(); for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter.next(); if (decaF.matches(aBcelField,world)) { // below code is for recursive things if (doesAlreadyHaveAnnotation(aBcelField,decaF,reportedProblems)) { // remove the declare @field since don't want an error when // the annotation is already there unusedDecafs.remove(decaF); continue; // skip this one... } aBcelField.addAnnotation(decaF.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),clazz.getName(),fields[fieldCounter]); isChanged = true; modificationOccured = true; forRemoval.add(decaF); // remove the declare @field since have matched against it unusedDecafs.remove(decaF); } } worthRetrying.removeAll(forRemoval); } } } checkUnusedDeclareAtTypes(unusedDecafs,true); } return isChanged; } // bug 99191 - put out an error message if the type doesn't exist /** * Report an error if the reason a "declare @method/ctor/field" was not used was because the member * specified does not exist. This method is passed some set of declare statements that didn't * match and a flag indicating whether the set contains declare @field or declare @method/ctor * entries. */ private void checkUnusedDeclareAtTypes(Set unusedDecaTs, boolean isDeclareAtField) { for (Iterator iter = unusedDecaTs.iterator(); iter.hasNext();) { DeclareAnnotation declA = (DeclareAnnotation) iter.next(); // Error if an exact type pattern was specified if ((declA.isExactPattern() || (declA.getSignaturePattern().getDeclaringType() instanceof ExactTypePattern)) && (!declA.getSignaturePattern().getName().isAny() || (declA.getKind() == DeclareAnnotation.AT_CONSTRUCTOR))) { // Quickly check if an ITD meets supplies the 'missing' member boolean itdMatch = false; List lst = clazz.getType().getInterTypeMungers(); for (Iterator iterator = lst.iterator(); iterator.hasNext() && !itdMatch;) { BcelTypeMunger element = (BcelTypeMunger) iterator.next(); if (element.getMunger() instanceof NewFieldTypeMunger) { NewFieldTypeMunger nftm = (NewFieldTypeMunger)element.getMunger(); itdMatch = declA.getSignaturePattern().matches(nftm.getSignature(),world,false); }else if (element.getMunger() instanceof NewMethodTypeMunger) { NewMethodTypeMunger nmtm = (NewMethodTypeMunger)element.getMunger(); itdMatch = declA.getSignaturePattern().matches(nmtm.getSignature(),world,false); } else if (element.getMunger() instanceof NewConstructorTypeMunger) { NewConstructorTypeMunger nctm = (NewConstructorTypeMunger)element.getMunger(); itdMatch = declA.getSignaturePattern().matches(nctm.getSignature(),world,false); } } if (!itdMatch) { IMessage message = null; if (isDeclareAtField) { message = new Message( "The field '"+ declA.getSignaturePattern().toString() + "' does not exist", declA.getSourceLocation() , true); } else { message = new Message( "The method '"+ declA.getSignaturePattern().toString() + "' does not exist", declA.getSourceLocation() , true); } world.getMessageHandler().handleMessage(message); } } } } // TAG: WeavingMessage private void reportFieldAnnotationWeavingMessage(LazyClassGen clazz, Field[] fields, int fieldCounter, DeclareAnnotation decaF) { if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){ Field theField = fields[fieldCounter]; world.getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES, new String[]{ theField.toString() + "' of type '" + clazz.getName(), clazz.getFileName(), decaF.getAnnotationString(), "field", decaF.getAspect().toString(), Utility.beautifyLocation(decaF.getSourceLocation())})); } } /** * Check if a resolved member (field/method/ctor) already has an annotation, if it * does then put out a warning and return true */ private boolean doesAlreadyHaveAnnotation(ResolvedMember rm,DeclareAnnotation deca,List reportedProblems) { if (rm.hasAnnotation(deca.getAnnotationTypeX())) { if (world.getLint().elementAlreadyAnnotated.isEnabled()) { Integer uniqueID = new Integer(rm.hashCode()*deca.hashCode()); if (!reportedProblems.contains(uniqueID)) { reportedProblems.add(uniqueID); world.getLint().elementAlreadyAnnotated.signal( new String[]{rm.toString(),deca.getAnnotationTypeX().toString()}, rm.getSourceLocation(),new ISourceLocation[]{deca.getSourceLocation()}); } } return true; } return false; } private boolean doesAlreadyHaveAnnotation(LazyMethodGen rm,ResolvedMember itdfieldsig,DeclareAnnotation deca,List reportedProblems) { if (rm != null && rm.hasAnnotation(deca.getAnnotationTypeX())) { if (world.getLint().elementAlreadyAnnotated.isEnabled()) { Integer uniqueID = new Integer(rm.hashCode()*deca.hashCode()); if (!reportedProblems.contains(uniqueID)) { reportedProblems.add(uniqueID); reportedProblems.add(new Integer(itdfieldsig.hashCode()*deca.hashCode())); world.getLint().elementAlreadyAnnotated.signal( new String[]{itdfieldsig.toString(),deca.getAnnotationTypeX().toString()}, rm.getSourceLocation(),new ISourceLocation[]{deca.getSourceLocation()}); } } return true; } return false; } private Set findAspectsForMungers(LazyMethodGen mg) { Set aspectsAffectingType = new HashSet(); for (Iterator iter = mg.matchedShadows.iterator(); iter.hasNext();) { BcelShadow aShadow = (BcelShadow) iter.next(); // Mungers in effect on that shadow for (Iterator iter2 = aShadow.getMungers().iterator();iter2.hasNext();) { ShadowMunger aMunger = (ShadowMunger) iter2.next(); if (aMunger instanceof BcelAdvice) { BcelAdvice bAdvice = (BcelAdvice)aMunger; if(bAdvice.getConcreteAspect() != null){ aspectsAffectingType.add(bAdvice.getConcreteAspect().getName()); } } else { // It is a 'Checker' - we don't need to remember aspects that only contributed Checkers... } } } return aspectsAffectingType; } private boolean inlineSelfConstructors(List methodGens) { boolean inlinedSomething = false; for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen) i.next(); if (! mg.getName().equals("<init>")) continue; InstructionHandle ih = findSuperOrThisCall(mg); if (ih != null && isThisCall(ih)) { LazyMethodGen donor = getCalledMethod(ih); inlineMethod(donor, mg, ih); inlinedSomething = true; } } return inlinedSomething; } private void positionAndImplement(List initializationShadows) { for (Iterator i = initializationShadows.iterator(); i.hasNext(); ) { BcelShadow s = (BcelShadow) i.next(); positionInitializationShadow(s); //s.getEnclosingMethod().print(); s.implement(); } } private void positionInitializationShadow(BcelShadow s) { LazyMethodGen mg = s.getEnclosingMethod(); InstructionHandle call = findSuperOrThisCall(mg); InstructionList body = mg.getBody(); ShadowRange r = new ShadowRange(body); r.associateWithShadow((BcelShadow) s); if (s.getKind() == Shadow.PreInitialization) { // XXX assert first instruction is an ALOAD_0. // a pre shadow goes from AFTER the first instruction (which we believe to // be an ALOAD_0) to just before the call to super r.associateWithTargets( Range.genStart(body, body.getStart().getNext()), Range.genEnd(body, call.getPrev())); } else { // assert s.getKind() == Shadow.Initialization r.associateWithTargets( Range.genStart(body, call.getNext()), Range.genEnd(body)); } } private boolean isThisCall(InstructionHandle ih) { INVOKESPECIAL inst = (INVOKESPECIAL) ih.getInstruction(); return inst.getClassName(cpg).equals(clazz.getName()); } /** inline a particular call in bytecode. * * @param donor the method we want to inline * @param recipient the method containing the call we want to inline * @param call the instructionHandle in recipient's body holding the call we want to * inline. */ public static void inlineMethod( LazyMethodGen donor, LazyMethodGen recipient, InstructionHandle call) { // assert recipient.contains(call) /* Implementation notes: * * We allocate two slots for every tempvar so we don't screw up * longs and doubles which may share space. This could be conservatively avoided * (no reference to a long/double instruction, don't do it) or packed later. * Right now we don't bother to pack. * * Allocate a new var for each formal param of the inlined. Fill with stack * contents. Then copy the inlined instructions in with the appropriate remap * table. Any framelocs used by locals in inlined are reallocated to top of * frame, */ final InstructionFactory fact = recipient.getEnclosingClass().getFactory(); IntMap frameEnv = new IntMap(); // this also sets up the initial environment InstructionList argumentStores = genArgumentStores(donor, recipient, frameEnv, fact); InstructionList inlineInstructions = genInlineInstructions(donor, recipient, frameEnv, fact, false); inlineInstructions.insert(argumentStores); recipient.getBody().append(call, inlineInstructions); Utility.deleteInstruction(call, recipient); } // public BcelVar genTempVar(UnresolvedType typeX) { // return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize())); // } // // private int genTempVarIndex(int size) { // return enclosingMethod.allocateLocal(size); // } /** * Input method is a synchronized method, we remove the bit flag for synchronized and * then insert a try..finally block * * Some jumping through firey hoops required - depending on the input code level (1.5 or not) * we may or may not be able to use the LDC instruction that takes a class literal (doesnt on * <1.5). * * FIXME asc Before promoting -Xjoinpoints:synchronization to be a standard option, this needs a bunch of * tidying up - there is some duplication that can be removed. */ public static void transformSynchronizedMethod(LazyMethodGen synchronizedMethod) { if (trace.isTraceEnabled()) trace.enter("transformSynchronizedMethod",synchronizedMethod); // System.err.println("DEBUG: Transforming synchronized method: "+synchronizedMethod.getName()); final InstructionFactory fact = synchronizedMethod.getEnclosingClass().getFactory(); InstructionList body = synchronizedMethod.getBody(); InstructionList prepend = new InstructionList(); Type enclosingClassType = BcelWorld.makeBcelType(synchronizedMethod.getEnclosingClass().getType()); Type javaLangClassType = Type.getType(Class.class); // STATIC METHOD TRANSFORMATION if (synchronizedMethod.isStatic()) { // What to do here depends on the level of the class file! // LDC can handle class literals in Java5 and above *sigh* if (synchronizedMethod.getEnclosingClass().isAtLeastJava5()) { // MONITORENTER logic: // 0: ldc #2; //class C // 2: dup // 3: astore_0 // 4: monitorenter int slotForLockObject = synchronizedMethod.allocateLocal(enclosingClassType); prepend.append(fact.createConstant(enclosingClassType)); prepend.append(InstructionFactory.createDup(1)); prepend.append(InstructionFactory.createStore(enclosingClassType, slotForLockObject)); prepend.append(InstructionFactory.MONITORENTER); // MONITOREXIT logic: // We basically need to wrap the code from the method in a finally block that // will ensure monitorexit is called. Content on the finally block seems to // be always: // // E1: ALOAD_1 // MONITOREXIT // ATHROW // // so lets build that: InstructionList finallyBlock = new InstructionList(); finallyBlock.append(InstructionFactory.createLoad(Type.getType(java.lang.Class.class),slotForLockObject)); finallyBlock.append(InstructionConstants.MONITOREXIT); finallyBlock.append(InstructionConstants.ATHROW); // finally -> E1 // | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 21) // | LDC "hello" // | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V // | ALOAD_1 (line 20) // | MONITOREXIT // finally -> E1 // GOTO L0 // finally -> E1 // | E1: ALOAD_1 // | MONITOREXIT // finally -> E1 // ATHROW // L0: RETURN (line 23) // search for 'returns' and make them jump to the aload_<n>,monitorexit InstructionHandle walker = body.getStart(); List rets = new ArrayList(); while (walker!=null) { if (walker.getInstruction() instanceof ReturnInstruction) { rets.add(walker); } walker = walker.getNext(); } if (rets.size()>0) { // need to ensure targeters for 'return' now instead target the load instruction // (so we never jump over the monitorexit logic) for (Iterator iter = rets.iterator(); iter.hasNext();) { InstructionHandle element = (InstructionHandle) iter.next(); InstructionList monitorExitBlock = new InstructionList(); monitorExitBlock.append(InstructionFactory.createLoad(enclosingClassType,slotForLockObject)); monitorExitBlock.append(InstructionConstants.MONITOREXIT); //monitorExitBlock.append(Utility.copyInstruction(element.getInstruction())); //element.setInstruction(InstructionFactory.createLoad(classType,slotForThis)); InstructionHandle monitorExitBlockStart = body.insert(element,monitorExitBlock); // now move the targeters from the RET to the start of the monitorexit block InstructionTargeter[] targeters = element.getTargeters(); if (targeters!=null) { for (int i = 0; i < targeters.length; i++) { InstructionTargeter targeter = targeters[i]; // what kinds are there? if (targeter instanceof LocalVariableTag) { // ignore } else if (targeter instanceof LineNumberTag) { // ignore } else if (targeter instanceof GOTO || targeter instanceof GOTO_W) { // move it... targeter.updateTarget(element, monitorExitBlockStart); } else if (targeter instanceof BranchInstruction) { // move it targeter.updateTarget(element, monitorExitBlockStart); } else { throw new RuntimeException("Unexpected targeter encountered during transform: "+targeter); } } } } } // now the magic, putting the finally block around the code InstructionHandle finallyStart = finallyBlock.getStart(); InstructionHandle tryPosition = body.getStart(); InstructionHandle catchPosition = body.getEnd(); body.insert(body.getStart(),prepend); // now we can put the monitorenter stuff on synchronizedMethod.getBody().append(finallyBlock); synchronizedMethod.addExceptionHandler(tryPosition, catchPosition,finallyStart,null/*==finally*/,false); synchronizedMethod.addExceptionHandler(finallyStart,finallyStart.getNext(),finallyStart,null,false); } else { // TRANSFORMING STATIC METHOD ON PRE JAVA5 // Hideous nightmare, class literal references prior to Java5 // YIKES! this is just the code for MONITORENTER ! // 0: getstatic #59; //Field class$1:Ljava/lang/Class; // 3: dup // 4: ifnonnull 32 // 7: pop // try // 8: ldc #61; //String java.lang.String // 10: invokestatic #44; //Method java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class; // 13: dup // catch // 14: putstatic #59; //Field class$1:Ljava/lang/Class; // 17: goto 32 // 20: new #46; //class java/lang/NoClassDefFoundError // 23: dup_x1 // 24: swap // 25: invokevirtual #52; //Method java/lang/Throwable.getMessage:()Ljava/lang/String; // 28: invokespecial #54; //Method java/lang/NoClassDefFoundError."<init>":(Ljava/lang/String;)V // 31: athrow // 32: dup <-- partTwo (branch target) // 33: astore_0 // 34: monitorenter // // plus exceptiontable entry! // 8 13 20 Class java/lang/ClassNotFoundException Type classType = BcelWorld.makeBcelType(synchronizedMethod.getEnclosingClass().getType()); Type clazzType = Type.getType(Class.class); InstructionList parttwo = new InstructionList(); parttwo.append(InstructionFactory.createDup(1)); int slotForThis = synchronizedMethod.allocateLocal(classType); parttwo.append(InstructionFactory.createStore(clazzType, slotForThis)); // ? should be the real type ? String or something? parttwo.append(InstructionFactory.MONITORENTER); String fieldname = synchronizedMethod.getEnclosingClass().allocateField("class$"); Field f = new FieldGen(Modifier.STATIC | Modifier.PRIVATE, Type.getType(Class.class),fieldname,synchronizedMethod.getEnclosingClass().getConstantPoolGen()).getField(); synchronizedMethod.getEnclosingClass().addField(f, null); // 10: invokestatic #44; //Method java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class; // 13: dup // 14: putstatic #59; //Field class$1:Ljava/lang/Class; // 17: goto 32 // 20: new #46; //class java/lang/NoClassDefFoundError // 23: dup_x1 // 24: swap // 25: invokevirtual #52; //Method java/lang/Throwable.getMessage:()Ljava/lang/String; // 28: invokespecial #54; //Method java/lang/NoClassDefFoundError."<init>":(Ljava/lang/String;)V // 31: athrow String name = synchronizedMethod.getEnclosingClass().getName(); prepend.append(fact.createGetStatic(name, fieldname, Type.getType(Class.class))); prepend.append(InstructionFactory.createDup(1)); prepend.append(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, parttwo.getStart())); prepend.append(InstructionFactory.POP); prepend.append(fact.createConstant(name)); InstructionHandle tryInstruction = prepend.getEnd(); prepend.append(fact.createInvoke("java.lang.Class", "forName", clazzType,new Type[]{ Type.getType(String.class)}, Constants.INVOKESTATIC)); InstructionHandle catchInstruction = prepend.getEnd(); prepend.append(InstructionFactory.createDup(1)); prepend.append(fact.createPutStatic(synchronizedMethod.getEnclosingClass().getType().getName(), fieldname, Type.getType(Class.class))); prepend.append(InstructionFactory.createBranchInstruction(Constants.GOTO, parttwo.getStart())); // start of catch block InstructionList catchBlockForLiteralLoadingFail = new InstructionList(); catchBlockForLiteralLoadingFail.append(fact.createNew((ObjectType)Type.getType(NoClassDefFoundError.class))); catchBlockForLiteralLoadingFail.append(InstructionFactory.createDup_1(1)); catchBlockForLiteralLoadingFail.append(InstructionFactory.SWAP); catchBlockForLiteralLoadingFail.append(fact.createInvoke("java.lang.Throwable", "getMessage", Type.getType(String.class),new Type[]{}, Constants.INVOKEVIRTUAL)); catchBlockForLiteralLoadingFail.append(fact.createInvoke("java.lang.NoClassDefFoundError", "<init>", Type.VOID,new Type[]{ Type.getType(String.class)}, Constants.INVOKESPECIAL)); catchBlockForLiteralLoadingFail.append(InstructionFactory.ATHROW); InstructionHandle catchBlockStart = catchBlockForLiteralLoadingFail.getStart(); prepend.append(catchBlockForLiteralLoadingFail); prepend.append(parttwo); // MONITORENTER // pseudocode: load up 'this' (var0), dup it, store it in a new local var (for use with monitorexit) and call monitorenter: // ALOAD_0, DUP, ASTORE_<n>, MONITORENTER // prepend.append(InstructionFactory.createLoad(classType,0)); // prepend.append(InstructionFactory.createDup(1)); // int slotForThis = synchronizedMethod.allocateLocal(classType); // prepend.append(InstructionFactory.createStore(classType, slotForThis)); // prepend.append(InstructionFactory.MONITORENTER); // MONITOREXIT // here be dragons // We basically need to wrap the code from the method in a finally block that // will ensure monitorexit is called. Content on the finally block seems to // be always: // // E1: ALOAD_1 // MONITOREXIT // ATHROW // // so lets build that: InstructionList finallyBlock = new InstructionList(); finallyBlock.append(InstructionFactory.createLoad(Type.getType(java.lang.Class.class),slotForThis)); finallyBlock.append(InstructionConstants.MONITOREXIT); finallyBlock.append(InstructionConstants.ATHROW); // finally -> E1 // | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 21) // | LDC "hello" // | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V // | ALOAD_1 (line 20) // | MONITOREXIT // finally -> E1 // GOTO L0 // finally -> E1 // | E1: ALOAD_1 // | MONITOREXIT // finally -> E1 // ATHROW // L0: RETURN (line 23) //frameEnv.put(donorFramePos, thisSlot); // search for 'returns' and make them to the aload_<n>,monitorexit InstructionHandle walker = body.getStart(); List rets = new ArrayList(); while (walker!=null) { //!walker.equals(body.getEnd())) { if (walker.getInstruction() instanceof ReturnInstruction) { rets.add(walker); } walker = walker.getNext(); } if (rets.size()>0) { // need to ensure targeters for 'return' now instead target the load instruction // (so we never jump over the monitorexit logic) for (Iterator iter = rets.iterator(); iter.hasNext();) { InstructionHandle element = (InstructionHandle) iter.next(); // System.err.println("Adding monitor exit block at "+element); InstructionList monitorExitBlock = new InstructionList(); monitorExitBlock.append(InstructionFactory.createLoad(classType,slotForThis)); monitorExitBlock.append(InstructionConstants.MONITOREXIT); //monitorExitBlock.append(Utility.copyInstruction(element.getInstruction())); //element.setInstruction(InstructionFactory.createLoad(classType,slotForThis)); InstructionHandle monitorExitBlockStart = body.insert(element,monitorExitBlock); // now move the targeters from the RET to the start of the monitorexit block InstructionTargeter[] targeters = element.getTargeters(); if (targeters!=null) { for (int i = 0; i < targeters.length; i++) { InstructionTargeter targeter = targeters[i]; // what kinds are there? if (targeter instanceof LocalVariableTag) { // ignore } else if (targeter instanceof LineNumberTag) { // ignore } else if (targeter instanceof GOTO || targeter instanceof GOTO_W) { // move it... targeter.updateTarget(element, monitorExitBlockStart); } else if (targeter instanceof BranchInstruction) { // move it targeter.updateTarget(element, monitorExitBlockStart); } else { throw new RuntimeException("Unexpected targeter encountered during transform: "+targeter); } } } } } // body = rewriteWithMonitorExitCalls(body,fact,true,slotForThis,classType); // synchronizedMethod.setBody(body); // now the magic, putting the finally block around the code InstructionHandle finallyStart = finallyBlock.getStart(); InstructionHandle tryPosition = body.getStart(); InstructionHandle catchPosition = body.getEnd(); body.insert(body.getStart(),prepend); // now we can put the monitorenter stuff on synchronizedMethod.getBody().append(finallyBlock); synchronizedMethod.addExceptionHandler(tryPosition, catchPosition,finallyStart,null/*==finally*/,false); synchronizedMethod.addExceptionHandler(tryInstruction, catchInstruction,catchBlockStart,(ObjectType)Type.getType(ClassNotFoundException.class),true); synchronizedMethod.addExceptionHandler(finallyStart,finallyStart.getNext(),finallyStart,null,false); } } else { // TRANSFORMING NON STATIC METHOD Type classType = BcelWorld.makeBcelType(synchronizedMethod.getEnclosingClass().getType()); // MONITORENTER // pseudocode: load up 'this' (var0), dup it, store it in a new local var (for use with monitorexit) and call monitorenter: // ALOAD_0, DUP, ASTORE_<n>, MONITORENTER prepend.append(InstructionFactory.createLoad(classType,0)); prepend.append(InstructionFactory.createDup(1)); int slotForThis = synchronizedMethod.allocateLocal(classType); prepend.append(InstructionFactory.createStore(classType, slotForThis)); prepend.append(InstructionFactory.MONITORENTER); // body.insert(body.getStart(),prepend); // MONITOREXIT // We basically need to wrap the code from the method in a finally block that // will ensure monitorexit is called. Content on the finally block seems to // be always: // // E1: ALOAD_1 // MONITOREXIT // ATHROW // // so lets build that: InstructionList finallyBlock = new InstructionList(); finallyBlock.append(InstructionFactory.createLoad(classType,slotForThis)); finallyBlock.append(InstructionConstants.MONITOREXIT); finallyBlock.append(InstructionConstants.ATHROW); // finally -> E1 // | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 21) // | LDC "hello" // | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V // | ALOAD_1 (line 20) // | MONITOREXIT // finally -> E1 // GOTO L0 // finally -> E1 // | E1: ALOAD_1 // | MONITOREXIT // finally -> E1 // ATHROW // L0: RETURN (line 23) //frameEnv.put(donorFramePos, thisSlot); // search for 'returns' and make them to the aload_<n>,monitorexit InstructionHandle walker = body.getStart(); List rets = new ArrayList(); while (walker!=null) { //!walker.equals(body.getEnd())) { if (walker.getInstruction() instanceof ReturnInstruction) { rets.add(walker); } walker = walker.getNext(); } if (rets.size()>0) { // need to ensure targeters for 'return' now instead target the load instruction // (so we never jump over the monitorexit logic) for (Iterator iter = rets.iterator(); iter.hasNext();) { InstructionHandle element = (InstructionHandle) iter.next(); // System.err.println("Adding monitor exit block at "+element); InstructionList monitorExitBlock = new InstructionList(); monitorExitBlock.append(InstructionFactory.createLoad(classType,slotForThis)); monitorExitBlock.append(InstructionConstants.MONITOREXIT); //monitorExitBlock.append(Utility.copyInstruction(element.getInstruction())); //element.setInstruction(InstructionFactory.createLoad(classType,slotForThis)); InstructionHandle monitorExitBlockStart = body.insert(element,monitorExitBlock); // now move the targeters from the RET to the start of the monitorexit block InstructionTargeter[] targeters = element.getTargeters(); if (targeters!=null) { for (int i = 0; i < targeters.length; i++) { InstructionTargeter targeter = targeters[i]; // what kinds are there? if (targeter instanceof LocalVariableTag) { // ignore } else if (targeter instanceof LineNumberTag) { // ignore } else if (targeter instanceof GOTO || targeter instanceof GOTO_W) { // move it... targeter.updateTarget(element, monitorExitBlockStart); } else if (targeter instanceof BranchInstruction) { // move it targeter.updateTarget(element, monitorExitBlockStart); } else { throw new RuntimeException("Unexpected targeter encountered during transform: "+targeter); } } } } } // now the magic, putting the finally block around the code InstructionHandle finallyStart = finallyBlock.getStart(); InstructionHandle tryPosition = body.getStart(); InstructionHandle catchPosition = body.getEnd(); body.insert(body.getStart(),prepend); // now we can put the monitorenter stuff on synchronizedMethod.getBody().append(finallyBlock); synchronizedMethod.addExceptionHandler(tryPosition, catchPosition,finallyStart,null/*==finally*/,false); synchronizedMethod.addExceptionHandler(finallyStart,finallyStart.getNext(),finallyStart,null,false); // also the exception handling for the finally block jumps to itself // max locals will already have been modified in the allocateLocal() call // synchronized bit is removed on LazyMethodGen.pack() } // gonna have to go through and change all aload_0s to load the var from a variable, // going to add a new variable for the this var if (trace.isTraceEnabled()) trace.exit("transformSynchronizedMethod"); } /** generate the instructions to be inlined. * * @param donor the method from which we will copy (and adjust frame and jumps) * instructions. * @param recipient the method the instructions will go into. Used to get the frame * size so we can allocate new frame locations for locals in donor. * @param frameEnv an environment to map from donor frame to recipient frame, * initially populated with argument locations. * @param fact an instruction factory for recipient */ static InstructionList genInlineInstructions( LazyMethodGen donor, LazyMethodGen recipient, IntMap frameEnv, InstructionFactory fact, boolean keepReturns) { InstructionList footer = new InstructionList(); InstructionHandle end = footer.append(InstructionConstants.NOP); InstructionList ret = new InstructionList(); InstructionList sourceList = donor.getBody(); Map srcToDest = new HashMap(); ConstantPoolGen donorCpg = donor.getEnclosingClass().getConstantPoolGen(); ConstantPoolGen recipientCpg = recipient.getEnclosingClass().getConstantPoolGen(); boolean isAcrossClass = donorCpg != recipientCpg; // first pass: copy the instructions directly, populate the srcToDest map, // fix frame instructions for (InstructionHandle src = sourceList.getStart(); src != null; src = src.getNext()) { Instruction fresh = Utility.copyInstruction(src.getInstruction()); InstructionHandle dest; if (fresh instanceof CPInstruction) { // need to reset index to go to new constant pool. This is totally // a computation leak... we're testing this LOTS of times. Sigh. if (isAcrossClass) { CPInstruction cpi = (CPInstruction) fresh; cpi.setIndex( recipientCpg.addConstant( donorCpg.getConstant(cpi.getIndex()), donorCpg)); } } if (src.getInstruction() == Range.RANGEINSTRUCTION) { dest = ret.append(Range.RANGEINSTRUCTION); } else if (fresh instanceof ReturnInstruction) { if (keepReturns) { dest = ret.append(fresh); } else { dest = ret.append(InstructionFactory.createBranchInstruction(Constants.GOTO, end)); } } else if (fresh instanceof BranchInstruction) { dest = ret.append((BranchInstruction) fresh); } else if ( fresh instanceof LocalVariableInstruction || fresh instanceof RET) { IndexedInstruction indexed = (IndexedInstruction) fresh; int oldIndex = indexed.getIndex(); int freshIndex; if (!frameEnv.hasKey(oldIndex)) { freshIndex = recipient.allocateLocal(2); frameEnv.put(oldIndex, freshIndex); } else { freshIndex = frameEnv.get(oldIndex); } indexed.setIndex(freshIndex); dest = ret.append(fresh); } else { dest = ret.append(fresh); } srcToDest.put(src, dest); } // second pass: retarget branch instructions, copy ranges and tags Map tagMap = new HashMap(); Map shadowMap = new HashMap(); for (InstructionHandle dest = ret.getStart(), src = sourceList.getStart(); dest != null; dest = dest.getNext(), src = src.getNext()) { Instruction inst = dest.getInstruction(); // retarget branches if (inst instanceof BranchInstruction) { BranchInstruction branch = (BranchInstruction) inst; InstructionHandle oldTarget = branch.getTarget(); InstructionHandle newTarget = (InstructionHandle) srcToDest.get(oldTarget); if (newTarget == null) { // assert this is a GOTO // this was a return instruction we previously replaced } else { branch.setTarget(newTarget); if (branch instanceof Select) { Select select = (Select) branch; InstructionHandle[] oldTargets = select.getTargets(); for (int k = oldTargets.length - 1; k >= 0; k--) { select.setTarget( k, (InstructionHandle) srcToDest.get(oldTargets[k])); } } } } //copy over tags and range attributes InstructionTargeter[] srcTargeters = src.getTargeters(); if (srcTargeters != null) { for (int j = srcTargeters.length - 1; j >= 0; j--) { InstructionTargeter old = srcTargeters[j]; if (old instanceof Tag) { Tag oldTag = (Tag) old; Tag fresh = (Tag) tagMap.get(oldTag); if (fresh == null) { fresh = oldTag.copy(); tagMap.put(oldTag, fresh); } dest.addTargeter(fresh); } else if (old instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) old; if (er.getStart() == src) { ExceptionRange freshEr = new ExceptionRange( recipient.getBody(), er.getCatchType(), er.getPriority()); freshEr.associateWithTargets( dest, (InstructionHandle)srcToDest.get(er.getEnd()), (InstructionHandle)srcToDest.get(er.getHandler())); } } else if (old instanceof ShadowRange) { ShadowRange oldRange = (ShadowRange) old; if (oldRange.getStart() == src) { BcelShadow oldShadow = oldRange.getShadow(); BcelShadow freshEnclosing = oldShadow.getEnclosingShadow() == null ? null : (BcelShadow) shadowMap.get(oldShadow.getEnclosingShadow()); BcelShadow freshShadow = oldShadow.copyInto(recipient, freshEnclosing); ShadowRange freshRange = new ShadowRange(recipient.getBody()); freshRange.associateWithShadow(freshShadow); freshRange.associateWithTargets( dest, (InstructionHandle) srcToDest.get(oldRange.getEnd())); shadowMap.put(oldRange, freshRange); //recipient.matchedShadows.add(freshShadow); // XXX should go through the NEW copied shadow and update // the thisVar, targetVar, and argsVar // ??? Might want to also go through at this time and add // "extra" vars to the shadow. } } } } } if (!keepReturns) ret.append(footer); return ret; } static InstructionList rewriteWithMonitorExitCalls(InstructionList sourceList,InstructionFactory fact,boolean keepReturns,int monitorVarSlot,Type monitorVarType) { InstructionList footer = new InstructionList(); InstructionHandle end = footer.append(InstructionConstants.NOP); InstructionList newList = new InstructionList(); Map srcToDest = new HashMap(); // first pass: copy the instructions directly, populate the srcToDest map, // fix frame instructions for (InstructionHandle src = sourceList.getStart(); src != null; src = src.getNext()) { Instruction fresh = Utility.copyInstruction(src.getInstruction()); InstructionHandle dest; if (src.getInstruction() == Range.RANGEINSTRUCTION) { dest = newList.append(Range.RANGEINSTRUCTION); } else if (fresh instanceof ReturnInstruction) { if (keepReturns) { newList.append(InstructionFactory.createLoad(monitorVarType,monitorVarSlot)); newList.append(InstructionConstants.MONITOREXIT); dest = newList.append(fresh); } else { dest = newList.append(InstructionFactory.createBranchInstruction(Constants.GOTO, end)); } } else if (fresh instanceof BranchInstruction) { dest = newList.append((BranchInstruction) fresh); } else if ( fresh instanceof LocalVariableInstruction || fresh instanceof RET) { IndexedInstruction indexed = (IndexedInstruction) fresh; int oldIndex = indexed.getIndex(); int freshIndex; // if (!frameEnv.hasKey(oldIndex)) { // freshIndex = recipient.allocateLocal(2); // frameEnv.put(oldIndex, freshIndex); // } else { freshIndex = oldIndex;//frameEnv.get(oldIndex); // } indexed.setIndex(freshIndex); dest = newList.append(fresh); } else { dest = newList.append(fresh); } srcToDest.put(src, dest); } // second pass: retarget branch instructions, copy ranges and tags Map tagMap = new HashMap(); Map shadowMap = new HashMap(); for (InstructionHandle dest = newList.getStart(), src = sourceList.getStart(); dest != null; dest = dest.getNext(), src = src.getNext()) { Instruction inst = dest.getInstruction(); // retarget branches if (inst instanceof BranchInstruction) { BranchInstruction branch = (BranchInstruction) inst; InstructionHandle oldTarget = branch.getTarget(); InstructionHandle newTarget = (InstructionHandle) srcToDest.get(oldTarget); if (newTarget == null) { // assert this is a GOTO // this was a return instruction we previously replaced } else { branch.setTarget(newTarget); if (branch instanceof Select) { Select select = (Select) branch; InstructionHandle[] oldTargets = select.getTargets(); for (int k = oldTargets.length - 1; k >= 0; k--) { select.setTarget( k, (InstructionHandle) srcToDest.get(oldTargets[k])); } } } } //copy over tags and range attributes InstructionTargeter[] srcTargeters = src.getTargeters(); if (srcTargeters != null) { for (int j = srcTargeters.length - 1; j >= 0; j--) { InstructionTargeter old = srcTargeters[j]; if (old instanceof Tag) { Tag oldTag = (Tag) old; Tag fresh = (Tag) tagMap.get(oldTag); if (fresh == null) { fresh = oldTag.copy(); tagMap.put(oldTag, fresh); } dest.addTargeter(fresh); } else if (old instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) old; if (er.getStart() == src) { ExceptionRange freshEr = new ExceptionRange(newList/*recipient.getBody()*/,er.getCatchType(),er.getPriority()); freshEr.associateWithTargets( dest, (InstructionHandle)srcToDest.get(er.getEnd()), (InstructionHandle)srcToDest.get(er.getHandler())); } } /*else if (old instanceof ShadowRange) { ShadowRange oldRange = (ShadowRange) old; if (oldRange.getStart() == src) { BcelShadow oldShadow = oldRange.getShadow(); BcelShadow freshEnclosing = oldShadow.getEnclosingShadow() == null ? null : (BcelShadow) shadowMap.get(oldShadow.getEnclosingShadow()); BcelShadow freshShadow = oldShadow.copyInto(recipient, freshEnclosing); ShadowRange freshRange = new ShadowRange(recipient.getBody()); freshRange.associateWithShadow(freshShadow); freshRange.associateWithTargets( dest, (InstructionHandle) srcToDest.get(oldRange.getEnd())); shadowMap.put(oldRange, freshRange); //recipient.matchedShadows.add(freshShadow); // XXX should go through the NEW copied shadow and update // the thisVar, targetVar, and argsVar // ??? Might want to also go through at this time and add // "extra" vars to the shadow. } }*/ } } } if (!keepReturns) newList.append(footer); return newList; } /** generate the argument stores in preparation for inlining. * * @param donor the method we will inline from. Used to get the signature. * @param recipient the method we will inline into. Used to get the frame size * so we can allocate fresh locations. * @param frameEnv an empty environment we populate with a map from donor frame to * recipient frame. * @param fact an instruction factory for recipient */ private static InstructionList genArgumentStores( LazyMethodGen donor, LazyMethodGen recipient, IntMap frameEnv, InstructionFactory fact) { InstructionList ret = new InstructionList(); int donorFramePos = 0; // writing ret back to front because we're popping. if (! donor.isStatic()) { int targetSlot = recipient.allocateLocal(Type.OBJECT); ret.insert(InstructionFactory.createStore(Type.OBJECT, targetSlot)); frameEnv.put(donorFramePos, targetSlot); donorFramePos += 1; } Type[] argTypes = donor.getArgumentTypes(); for (int i = 0, len = argTypes.length; i < len; i++) { Type argType = argTypes[i]; int argSlot = recipient.allocateLocal(argType); ret.insert(InstructionFactory.createStore(argType, argSlot)); frameEnv.put(donorFramePos, argSlot); donorFramePos += argType.getSize(); } return ret; } /** get a called method: Assumes the called method is in this class, * and the reference to it is exact (a la INVOKESPECIAL). * * @param ih The InvokeInstruction instructionHandle pointing to the called method. */ private LazyMethodGen getCalledMethod( InstructionHandle ih) { InvokeInstruction inst = (InvokeInstruction) ih.getInstruction(); String methodName = inst.getName(cpg); String signature = inst.getSignature(cpg); return clazz.getLazyMethodGen(methodName, signature); } private void weaveInAddedMethods() { Collections.sort(addedLazyMethodGens, new Comparator() { public int compare(Object a, Object b) { LazyMethodGen aa = (LazyMethodGen) a; LazyMethodGen bb = (LazyMethodGen) b; int i = aa.getName().compareTo(bb.getName()); if (i != 0) return i; return aa.getSignature().compareTo(bb.getSignature()); } } ); for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) { clazz.addMethodGen((LazyMethodGen)i.next()); } } void addPerSingletonField(Member field) { ObjectType aspectType = (ObjectType) BcelWorld.makeBcelType(field.getReturnType()); String aspectName = field.getReturnType().getName(); LazyMethodGen clinit = clazz.getStaticInitializer(); InstructionList setup = new InstructionList(); InstructionFactory fact = clazz.getFactory(); setup.append(fact.createNew(aspectType)); setup.append(InstructionFactory.createDup(1)); setup.append(fact.createInvoke( aspectName, "<init>", Type.VOID, new Type[0], Constants.INVOKESPECIAL)); setup.append( fact.createFieldAccess( aspectName, field.getName(), aspectType, Constants.PUTSTATIC)); clinit.getBody().insert(setup); } /** * Returns null if this is not a Java constructor, and then we won't * weave into it at all */ private InstructionHandle findSuperOrThisCall(LazyMethodGen mg) { int depth = 1; InstructionHandle start = mg.getBody().getStart(); while (true) { if (start == null) return null; Instruction inst = start.getInstruction(); if (inst instanceof INVOKESPECIAL && ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) { depth--; if (depth == 0) return start; } else if (inst instanceof NEW) { depth++; } start = start.getNext(); } } // ---- private boolean match(LazyMethodGen mg) { BcelShadow enclosingShadow; List shadowAccumulator = new ArrayList(); boolean startsAngly = mg.getName().charAt(0)=='<'; // we want to match ajsynthetic constructors... if (startsAngly && mg.getName().equals("<init>")) { return matchInit(mg, shadowAccumulator); } else if (!shouldWeaveBody(mg)) { //.isAjSynthetic()) { return false; } else { if (startsAngly && mg.getName().equals("<clinit>")) { clinitShadow = enclosingShadow = BcelShadow.makeStaticInitialization(world, mg); //System.err.println(enclosingShadow); } else if (mg.isAdviceMethod()) { enclosingShadow = BcelShadow.makeAdviceExecution(world, mg); } else { AjAttribute.EffectiveSignatureAttribute effective = mg.getEffectiveSignature(); if (effective == null) { enclosingShadow = BcelShadow.makeMethodExecution(world, mg, !canMatchBodyShadows); } else if (effective.isWeaveBody()) { ResolvedMember rm = effective.getEffectiveSignature(); // Annotations for things with effective signatures are never stored in the effective // signature itself - we have to hunt for them. Storing them in the effective signature // would mean keeping two sets up to date (no way!!) fixAnnotationsForResolvedMember(rm,mg.getMemberView()); enclosingShadow = BcelShadow.makeShadowForMethod(world,mg,effective.getShadowKind(),rm); } else { return false; } } if (canMatchBodyShadows) { for (InstructionHandle h = mg.getBody().getStart(); h != null; h = h.getNext()) { match(mg, h, enclosingShadow, shadowAccumulator); } } // FIXME asc change from string match if we can, rather brittle. this check actually prevents field-exec jps if (canMatch(enclosingShadow.getKind()) && !(mg.getName().charAt(0)=='a' && mg.getName().startsWith("ajc$interFieldInit"))) { if (match(enclosingShadow, shadowAccumulator)) { enclosingShadow.init(); } } mg.matchedShadows = shadowAccumulator; return !shadowAccumulator.isEmpty(); } } private boolean matchInit(LazyMethodGen mg, List shadowAccumulator) { BcelShadow enclosingShadow; // XXX the enclosing join point is wrong for things before ignoreMe. InstructionHandle superOrThisCall = findSuperOrThisCall(mg); // we don't walk bodies of things where it's a wrong constructor thingie if (superOrThisCall == null) return false; enclosingShadow = BcelShadow.makeConstructorExecution(world, mg, superOrThisCall); if (mg.getEffectiveSignature() != null) { enclosingShadow.setMatchingSignature(mg.getEffectiveSignature().getEffectiveSignature()); } // walk the body boolean beforeSuperOrThisCall = true; if (shouldWeaveBody(mg)) { if (canMatchBodyShadows) { for (InstructionHandle h = mg.getBody().getStart(); h != null; h = h.getNext()) { if (h == superOrThisCall) { beforeSuperOrThisCall = false; continue; } match(mg, h, beforeSuperOrThisCall ? null : enclosingShadow, shadowAccumulator); } } if (canMatch(Shadow.ConstructorExecution)) match(enclosingShadow, shadowAccumulator); } // XXX we don't do pre-inits of interfaces // now add interface inits if (superOrThisCall != null && ! isThisCall(superOrThisCall)) { InstructionHandle curr = enclosingShadow.getRange().getStart(); for (Iterator i = addedSuperInitializersAsList.iterator(); i.hasNext(); ) { IfaceInitList l = (IfaceInitList) i.next(); Member ifaceInitSig = AjcMemberMaker.interfaceConstructor(l.onType); BcelShadow initShadow = BcelShadow.makeIfaceInitialization(world, mg, ifaceInitSig); // insert code in place InstructionList inits = genInitInstructions(l.list, false); if (match(initShadow, shadowAccumulator) || !inits.isEmpty()) { initShadow.initIfaceInitializer(curr); initShadow.getRange().insert(inits, Range.OutsideBefore); } } // now we add our initialization code InstructionList inits = genInitInstructions(addedThisInitializers, false); enclosingShadow.getRange().insert(inits, Range.OutsideBefore); } // actually, you only need to inline the self constructors that are // in a particular group (partition the constructors into groups where members // call or are called only by those in the group). Then only inline // constructors // in groups where at least one initialization jp matched. Future work. boolean addedInitialization = match( BcelShadow.makeUnfinishedInitialization(world, mg), initializationShadows); addedInitialization |= match( BcelShadow.makeUnfinishedPreinitialization(world, mg), initializationShadows); mg.matchedShadows = shadowAccumulator; return addedInitialization || !shadowAccumulator.isEmpty(); } private boolean shouldWeaveBody(LazyMethodGen mg) { if (mg.isBridgeMethod()) return false; if (mg.isAjSynthetic()) return mg.getName().equals("<clinit>"); AjAttribute.EffectiveSignatureAttribute a = mg.getEffectiveSignature(); if (a != null) return a.isWeaveBody(); return true; } /** * first sorts the mungers, then gens the initializers in the right order */ private InstructionList genInitInstructions(List list, boolean isStatic) { list = PartialOrder.sort(list); if (list == null) { throw new BCException("circularity in inter-types"); } InstructionList ret = new InstructionList(); for (Iterator i = list.iterator(); i.hasNext();) { ConcreteTypeMunger cmunger = (ConcreteTypeMunger) i.next(); NewFieldTypeMunger munger = (NewFieldTypeMunger) cmunger.getMunger(); ResolvedMember initMethod = munger.getInitMethod(cmunger.getAspectType()); if (!isStatic) ret.append(InstructionConstants.ALOAD_0); ret.append(Utility.createInvoke(fact, world, initMethod)); } return ret; } private void match( LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { Instruction i = ih.getInstruction(); // Exception handlers (pr230817) if (canMatch(Shadow.ExceptionHandler) && !Range.isRangeHandle(ih)) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int j = 0; j < targeters.length; j++) { InstructionTargeter t = targeters[j]; if (t instanceof ExceptionRange) { // assert t.getHandler() == ih ExceptionRange er = (ExceptionRange) t; if (er.getCatchType() == null) continue; if (isInitFailureHandler(ih)) return; if (!(ih.getInstruction() instanceof StoreInstruction) && ih.getInstruction().getOpcode()!=Constants.NOP) { // If using cobertura, the catch block stats with INVOKESTATIC rather than ASTORE, in order that the ranges // for the methodcall and exceptionhandler shadows that occur at this same // line, we need to modify the instruction list to split them - adding a // NOP before the invokestatic that gets all the targeters // that were aimed at the INVOKESTATIC mg.getBody().insert(ih,InstructionConstants.NOP); InstructionHandle newNOP = ih.getPrev(); // what about a try..catch that starts at the start of the exception handler? need to only include certain targeters really. er.updateTarget(ih, newNOP,mg.getBody()); for (int ii=0;ii<targeters.length;ii++) { newNOP.addTargeter(targeters[ii]); } ih.removeAllTargeters(); match( BcelShadow.makeExceptionHandler( world, er, mg, newNOP, enclosingShadow), shadowAccumulator); } else { match( BcelShadow.makeExceptionHandler( world, er, mg, ih, enclosingShadow), shadowAccumulator); } } } } } if ((i instanceof FieldInstruction) && (canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet)) ) { FieldInstruction fi = (FieldInstruction) i; if (fi instanceof PUTFIELD || fi instanceof PUTSTATIC) { // check for sets of constant fields. We first check the previous // instruction. If the previous instruction is a LD_WHATEVER (push // constant on the stack) then we must resolve the field to determine // if it's final. If it is final, then we don't generate a shadow. InstructionHandle prevHandle = ih.getPrev(); Instruction prevI = prevHandle.getInstruction(); if (Utility.isConstantPushInstruction(prevI)) { Member field = BcelWorld.makeFieldJoinPointSignature(clazz, (FieldInstruction) i); ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. } else if (Modifier.isFinal(resolvedField.getModifiers())) { // it's final, so it's the set of a final constant, so it's // not a join point according to 1.0.6 and 1.1. } else { if (canMatch(Shadow.FieldSet)) matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else { if (canMatch(Shadow.FieldSet)) matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else { if (canMatch(Shadow.FieldGet)) matchGetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else if (i instanceof InvokeInstruction) { InvokeInstruction ii = (InvokeInstruction) i; if (ii.getMethodName(clazz.getConstantPoolGen()).equals("<init>")) { if (canMatch(Shadow.ConstructorCall)) match( BcelShadow.makeConstructorCall(world, mg, ih, enclosingShadow), shadowAccumulator); } else if (ii instanceof INVOKESPECIAL) { String onTypeName = ii.getClassName(cpg); if (onTypeName.equals(mg.getEnclosingClass().getName())) { // we are private matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator); } else { // we are a super call, and this is not a join point in AspectJ-1.{0,1} } } else { matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator); } } else if (world.isJoinpointArrayConstructionEnabled() && (i instanceof NEWARRAY || i instanceof ANEWARRAY || i instanceof MULTIANEWARRAY)) { if (canMatch(Shadow.ConstructorCall)) { boolean debug = false; if (debug) System.err.println("Found new array instruction: "+i); if (i instanceof ANEWARRAY) { ANEWARRAY arrayInstruction = (ANEWARRAY)i; ObjectType arrayType = arrayInstruction.getLoadClassType(clazz.getConstantPoolGen()); if (debug) System.err.println("Array type is "+arrayType); BcelShadow ctorCallShadow = BcelShadow.makeArrayConstructorCall(world,mg,ih,enclosingShadow); match(ctorCallShadow,shadowAccumulator); } else if (i instanceof NEWARRAY) { NEWARRAY arrayInstruction = (NEWARRAY)i; Type arrayType = arrayInstruction.getType(); if (debug) System.err.println("Array type is "+arrayType); BcelShadow ctorCallShadow = BcelShadow.makeArrayConstructorCall(world,mg,ih,enclosingShadow); match(ctorCallShadow,shadowAccumulator); } else if (i instanceof MULTIANEWARRAY) { MULTIANEWARRAY arrayInstruction = (MULTIANEWARRAY)i; ObjectType arrayType = arrayInstruction.getLoadClassType(clazz.getConstantPoolGen()); if (debug) System.err.println("Array type is "+arrayType); BcelShadow ctorCallShadow = BcelShadow.makeArrayConstructorCall(world,mg,ih,enclosingShadow); match(ctorCallShadow,shadowAccumulator); } } // see pr77166 if you are thinking about implementing this // } else if (i instanceof AALOAD ) { // AALOAD arrayLoad = (AALOAD)i; // Type arrayType = arrayLoad.getType(clazz.getConstantPoolGen()); // BcelShadow arrayLoadShadow = BcelShadow.makeArrayLoadCall(world,mg,ih,enclosingShadow); // match(arrayLoadShadow,shadowAccumulator); // } else if (i instanceof AASTORE) { // // ... magic required } else if ( world.isJoinpointSynchronizationEnabled() && ((i instanceof MONITORENTER) || (i instanceof MONITOREXIT))) { // if (canMatch(Shadow.Monitoring)) { if (i instanceof MONITORENTER) { BcelShadow monitorEntryShadow = BcelShadow.makeMonitorEnter(world,mg,ih,enclosingShadow); match(monitorEntryShadow,shadowAccumulator); } else { BcelShadow monitorExitShadow = BcelShadow.makeMonitorExit(world,mg,ih,enclosingShadow); match(monitorExitShadow,shadowAccumulator); } // } } } private boolean isInitFailureHandler(InstructionHandle ih) { // Skip the astore_0 and aload_0 at the start of the handler and // then check if the instruction following these is // 'putstatic ajc$initFailureCause'. If it is then we are // in the handler we created in AspectClinit.generatePostSyntheticCode() InstructionHandle twoInstructionsAway = ih.getNext().getNext(); if (twoInstructionsAway.getInstruction() instanceof PUTSTATIC) { String name = ((PUTSTATIC)twoInstructionsAway.getInstruction()).getFieldName(cpg); if (name.equals(NameMangler.INITFAILURECAUSE_FIELD_NAME)) return true; } return false; } private void matchSetInstruction( LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { FieldInstruction fi = (FieldInstruction) ih.getInstruction(); Member field = BcelWorld.makeFieldJoinPointSignature(clazz, fi); // synthetic fields are never join points if (field.getName().startsWith(NameMangler.PREFIX)) return; ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. return; } else if ( Modifier.isFinal(resolvedField.getModifiers()) && Utility.isConstantPushInstruction(ih.getPrev().getInstruction())) { // it's the set of a final constant, so it's // not a join point according to 1.0.6 and 1.1. return; } else if (resolvedField.isSynthetic()) { // sets of synthetics aren't join points in 1.1 return; } else { // Fix for bug 172107 (similar the "get" fix for bug 109728) BcelShadow bs= BcelShadow.makeFieldSet(world, resolvedField, mg, ih, enclosingShadow); String cname = fi.getClassName(cpg); if (!resolvedField.getDeclaringType().getName().equals(cname)) { bs.setActualTargetType(cname); } match(bs, shadowAccumulator); } } private void matchGetInstruction(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { FieldInstruction fi = (FieldInstruction) ih.getInstruction(); Member field = BcelWorld.makeFieldJoinPointSignature(clazz, fi); // synthetic fields are never join points if (field.getName().startsWith(NameMangler.PREFIX)) return; ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. return; } else if (resolvedField.isSynthetic()) { // sets of synthetics aren't join points in 1.1 return; } else { BcelShadow bs = BcelShadow.makeFieldGet(world,resolvedField,mg,ih,enclosingShadow); String cname = fi.getClassName(cpg); if (!resolvedField.getDeclaringType().getName().equals(cname)) { bs.setActualTargetType(cname); } match(bs, shadowAccumulator); } } /** * For some named resolved type, this method looks for a member with a particular name - * it should only be used when you truly believe there is only one member with that * name in the type as it returns the first one it finds. */ private ResolvedMember findResolvedMemberNamed(ResolvedType type,String methodName) { ResolvedMember[] allMethods = type.getDeclaredMethods(); for (int i = 0; i < allMethods.length; i++) { ResolvedMember member = allMethods[i]; if (member.getName().equals(methodName)) return member; } return null; } /** * For a given resolvedmember, this will discover the real annotations for it. * <b>Should only be used when the resolvedmember is the contents of an effective signature * attribute, as thats the only time when the annotations aren't stored directly in the * resolvedMember</b> * @param rm the sig we want it to pretend to be 'int A.m()' or somesuch ITD like thing * @param declaredSig the real sig 'blah.ajc$xxx' */ private void fixAnnotationsForResolvedMember(ResolvedMember rm,ResolvedMember declaredSig) { try { UnresolvedType memberHostType = declaredSig.getDeclaringType(); ResolvedType[] annotations = (ResolvedType[])mapToAnnotations.get(rm); String methodName = declaredSig.getName(); // FIXME asc shouldnt really rely on string names ! if (annotations == null) { if (rm.getKind()==Member.FIELD) { if (methodName.startsWith("ajc$inlineAccessField")) { ResolvedMember resolvedDooberry = world.resolve(rm); annotations = resolvedDooberry.getAnnotationTypes(); } else { ResolvedMember realthing = AjcMemberMaker.interFieldInitializer(rm,memberHostType); ResolvedMember resolvedDooberry = world.resolve(realthing); annotations = resolvedDooberry.getAnnotationTypes(); } } else if (rm.getKind()==Member.METHOD && !rm.isAbstract()) { if (methodName.startsWith("ajc$inlineAccessMethod") || methodName.startsWith("ajc$superDispatch")) { ResolvedMember resolvedDooberry = world.resolve(declaredSig); annotations = resolvedDooberry.getAnnotationTypes(); } else { ResolvedMember realthing = AjcMemberMaker.interMethodDispatcher(rm.resolve(world),memberHostType).resolve(world); // ResolvedMember resolvedDooberry = world.resolve(realthing); ResolvedMember theRealMember = findResolvedMemberNamed(memberHostType.resolve(world),realthing.getName()); // AMC temp guard for M4 if (theRealMember == null) { throw new UnsupportedOperationException("Known limitation in M4 - can't find ITD members when type variable is used as an argument and has upper bound specified"); } annotations = theRealMember.getAnnotationTypes(); } } else if (rm.getKind()==Member.CONSTRUCTOR) { ResolvedMember realThing = AjcMemberMaker.postIntroducedConstructor(memberHostType.resolve(world),rm.getDeclaringType(),rm.getParameterTypes()); ResolvedMember resolvedDooberry = world.resolve(realThing); // AMC temp guard for M4 if (resolvedDooberry == null) { throw new UnsupportedOperationException("Known limitation in M4 - can't find ITD members when type variable is used as an argument and has upper bound specified"); } annotations = resolvedDooberry.getAnnotationTypes(); } if (annotations == null) annotations = new ResolvedType[0]; mapToAnnotations.put(rm,annotations); } rm.setAnnotationTypes(annotations); } catch (UnsupportedOperationException ex) { throw ex; } catch (Throwable t) { //FIXME asc remove this catch after more testing has confirmed the above stuff is OK throw new BCException("Unexpectedly went bang when searching for annotations on "+rm,t); } } private void matchInvokeInstruction(LazyMethodGen mg, InstructionHandle ih, InvokeInstruction invoke, BcelShadow enclosingShadow, List shadowAccumulator) { String methodName = invoke.getName(cpg); if (methodName.startsWith(NameMangler.PREFIX)) { Member jpSig = world.makeJoinPointSignatureForMethodInvocation(clazz, invoke); ResolvedMember declaredSig = jpSig.resolve(world); //System.err.println(method + ", declaredSig: " +declaredSig); if (declaredSig == null) return; if (declaredSig.getKind() == Member.FIELD) { Shadow.Kind kind; if (jpSig.getReturnType().equals(ResolvedType.VOID)) { kind = Shadow.FieldSet; } else { kind = Shadow.FieldGet; } if (canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet)) match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow, kind, declaredSig), shadowAccumulator); } else { AjAttribute.EffectiveSignatureAttribute effectiveSig = declaredSig.getEffectiveSignature(); if (effectiveSig == null) return; //System.err.println("call to inter-type member: " + effectiveSig); if (effectiveSig.isWeaveBody()) return; ResolvedMember rm = effectiveSig.getEffectiveSignature(); fixAnnotationsForResolvedMember(rm,declaredSig); // abracadabra if (canMatch(effectiveSig.getShadowKind())) match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow, effectiveSig.getShadowKind(), rm), shadowAccumulator); } } else { if (canMatch(Shadow.MethodCall)) { match( BcelShadow.makeMethodCall(world, mg, ih, enclosingShadow), shadowAccumulator); } } } // static ... so all worlds will share the config for the first one created... private static boolean checkedXsetForLowLevelContextCapturing = false; private static boolean captureLowLevelContext = false; private boolean match(BcelShadow shadow, List shadowAccumulator) { //System.err.println("match: " + shadow); if (captureLowLevelContext) { // duplicate blocks - one with context capture, one without, seems faster than multiple 'ifs()' ContextToken shadowMatchToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MATCHING_SHADOW, shadow); boolean isMatched = false; for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) { ShadowMunger munger = (ShadowMunger)i.next(); ContextToken mungerMatchToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MATCHING_POINTCUT, munger.getPointcut()); if (munger.match(shadow, world)) { shadow.addMunger(munger); isMatched = true; if (shadow.getKind() == Shadow.StaticInitialization) { clazz.warnOnAddedStaticInitializer(shadow,munger.getSourceLocation()); } } CompilationAndWeavingContext.leavingPhase(mungerMatchToken); } if (isMatched) shadowAccumulator.add(shadow); CompilationAndWeavingContext.leavingPhase(shadowMatchToken); return isMatched; } else { boolean isMatched = false; for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) { ShadowMunger munger = (ShadowMunger)i.next(); if (munger.match(shadow, world)) { shadow.addMunger(munger); isMatched = true; if (shadow.getKind() == Shadow.StaticInitialization) { clazz.warnOnAddedStaticInitializer(shadow,munger.getSourceLocation()); } } } if (isMatched) shadowAccumulator.add(shadow); return isMatched; } } // ---- private void implement(LazyMethodGen mg) { List shadows = mg.matchedShadows; if (shadows == null) return; // We depend on a partial order such that inner shadows are earlier on the list // than outer shadows. That's fine. This order is preserved if: // A preceeds B iff B.getStart() is LATER THAN A.getStart(). for (Iterator i = shadows.iterator(); i.hasNext(); ) { BcelShadow shadow = (BcelShadow)i.next(); ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.IMPLEMENTING_ON_SHADOW,shadow); shadow.implement(); CompilationAndWeavingContext.leavingPhase(tok); } int ii = mg.getMaxLocals(); mg.matchedShadows = null; } // ---- public LazyClassGen getLazyClassGen() { return clazz; } public List getShadowMungers() { return shadowMungers; } public BcelWorld getWorld() { return world; } // Called by the BcelWeaver to let us know all BcelClassWeavers need to collect reweavable info public static void setReweavableMode(boolean mode) { inReweavableMode = mode; } public static boolean getReweavableMode() { return inReweavableMode; } public String toString() { return "BcelClassWeaver instance for : "+clazz; } }
233,497
Bug 233497 StringIndexOutOfBoundsException thrown in BcelWeaver
null
resolved fixed
93b7bed
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-05-22T18:26:18Z"
"2008-05-22T18:13:20Z"
weaver/src/org/aspectj/weaver/bcel/BcelWeaver.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.jar.Attributes.Name; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.asm.AsmManager; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.SourceLocation; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.util.FileUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.CrosscuttingMembersSet; import org.aspectj.weaver.CustomMungerFactory; import org.aspectj.weaver.IClassFileProvider; import org.aspectj.weaver.IWeaveRequestor; import org.aspectj.weaver.IWeaver; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.BindingAnnotationTypePattern; import org.aspectj.weaver.patterns.BindingTypePattern; import org.aspectj.weaver.patterns.CflowPointcut; import org.aspectj.weaver.patterns.ConcreteCflowPointcut; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.FastMatchInfo; import org.aspectj.weaver.patterns.IfPointcut; import org.aspectj.weaver.patterns.KindedPointcut; import org.aspectj.weaver.patterns.NameBindingPointcut; import org.aspectj.weaver.patterns.NotPointcut; import org.aspectj.weaver.patterns.OrPointcut; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.PointcutRewriter; import org.aspectj.weaver.patterns.WithinPointcut; import org.aspectj.weaver.tools.Trace; import org.aspectj.weaver.tools.TraceFactory; public class BcelWeaver implements IWeaver { private BcelWorld world; private CrosscuttingMembersSet xcutSet; private IProgressListener progressListener = null; private double progressMade; private double progressPerClassFile; private boolean inReweavableMode = false; private static Trace trace = TraceFactory.getTraceFactory().getTrace(BcelWeaver.class); public BcelWeaver(BcelWorld world) { super(); if (trace.isTraceEnabled()) trace.enter("<init>",this,world); this.world = world; this.xcutSet = world.getCrosscuttingMembersSet(); if (trace.isTraceEnabled()) trace.exit("<init>"); } public BcelWeaver() { this(new BcelWorld()); } // ---- fields // private Map sourceJavaClasses = new HashMap(); /* String -> UnwovenClassFile */ private List addedClasses = new ArrayList(); /* List<UnovenClassFile> */ private List deletedTypenames = new ArrayList(); /* List<String> */ // private Map resources = new HashMap(); /* String -> UnwovenClassFile */ private Manifest manifest = null; private boolean needToReweaveWorld = false; private boolean isBatchWeave = true; private List shadowMungerList = null; // setup by prepareForWeave private List typeMungerList = null; // setup by prepareForWeave private List lateTypeMungerList = null; // setup by prepareForWeave private List declareParentsList = null; // setup by prepareForWeave private ZipOutputStream zipOutputStream; private CustomMungerFactory customMungerFactory; // ---- // only called for testing public void setShadowMungers(List l) { shadowMungerList = l; } /** * Add the given aspect to the weaver. * The type is resolved to support DOT for static inner classes as well as DOLLAR * * @param aspectName * @return aspect */ public ResolvedType addLibraryAspect(String aspectName) { if (trace.isTraceEnabled()) trace.enter("addLibraryAspect",this,aspectName); // 1 - resolve as is UnresolvedType unresolvedT = UnresolvedType.forName(aspectName); unresolvedT.setNeedsModifiableDelegate(true); ResolvedType type = world.resolve(unresolvedT, true); if (type.isMissing()) { // fallback on inner class lookup mechanism String fixedName = aspectName; int hasDot = fixedName.lastIndexOf('.'); while (hasDot > 0) { //System.out.println("BcelWeaver.addLibraryAspect " + fixedName); char[] fixedNameChars = fixedName.toCharArray(); fixedNameChars[hasDot] = '$'; fixedName = new String(fixedNameChars); hasDot = fixedName.lastIndexOf('.'); UnresolvedType ut = UnresolvedType.forName(fixedName); ut.setNeedsModifiableDelegate(true); type = world.resolve(ut, true); if (!type.isMissing()) { break; } } } //System.out.println("type: " + type + " for " + aspectName); if (type.isAspect()) { // Bug 119657 ensure we use the unwoven aspect WeaverStateInfo wsi = type.getWeaverState(); if (wsi != null && wsi.isReweavable()) { BcelObjectType classType = getClassType(type.getName()); JavaClass wovenJavaClass = classType.getJavaClass(); JavaClass unwovenJavaClass = Utility.makeJavaClass(wovenJavaClass.getFileName(), wsi.getUnwovenClassFileData(wovenJavaClass.getBytes())); world.storeClass(unwovenJavaClass); classType.setJavaClass(unwovenJavaClass); // classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData(classType.getJavaClass().getBytes()))); } //TODO AV - happens to reach that a lot of time: for each type flagged reweavable X for each aspect in the weaverstate //=> mainly for nothing for LTW - pbly for something in incremental build... xcutSet.addOrReplaceAspect(type); if (trace.isTraceEnabled()) trace.exit("addLibraryAspect",type); if (type.getSuperclass().isAspect()) { // If the supertype includes ITDs and the user has not included that aspect in the aop.xml, they will // not get picked up, which can give unusual behaviour! See bug 223094 // This change causes us to pick up the super aspect regardless of what was said in the aop.xml - giving // predictable behaviour. If the user also supplied it, there will be no problem other than the second // addition overriding the first addLibraryAspect(type.getSuperclass().getName()); } return type; } else { // FIXME AV - better warning upon no such aspect from aop.xml RuntimeException ex = new RuntimeException("Cannot register non aspect: " + type.getName() + " , " + aspectName); if (trace.isTraceEnabled()) trace.exit("addLibraryAspect",ex); throw ex; } } /** * * @param inFile File path to class directory or zip/jar class archive * @throws IOException */ public void addLibraryJarFile(File inFile) throws IOException { List addedAspects = null; if (inFile.isDirectory()) { addedAspects = addAspectsFromDirectory(inFile); } else { addedAspects = addAspectsFromJarFile(inFile); } for (Iterator i = addedAspects.iterator(); i.hasNext();) { ResolvedType aspectX = (ResolvedType) i.next(); xcutSet.addOrReplaceAspect(aspectX); } } private List addAspectsFromJarFile(File inFile) throws FileNotFoundException, IOException { ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered List addedAspects = new ArrayList(); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; } // FIXME ASC performance? of this alternative soln. ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName()); JavaClass jc = parser.parse(); inStream.closeEntry(); ResolvedType type = world.addSourceObjectType(jc).getResolvedTypeX(); type.setBinaryPath(inFile.getAbsolutePath()); if (type.isAspect()) { addedAspects.add(type); } } inStream.close(); return addedAspects; } private List addAspectsFromDirectory(File dir) throws FileNotFoundException, IOException{ List addedAspects = new ArrayList(); File[] classFiles = FileUtil.listFiles(dir,new FileFilter(){ public boolean accept(File pathname) { return pathname.getName().endsWith(".class"); } }); for (int i = 0; i < classFiles.length; i++) { FileInputStream fis = new FileInputStream(classFiles[i]); byte[] bytes = FileUtil.readAsByteArray(fis); addIfAspect(bytes,classFiles[i].getAbsolutePath(),addedAspects); fis.close(); } return addedAspects; } private void addIfAspect(byte[] bytes, String name, List toList) throws IOException { ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes),name); JavaClass jc = parser.parse(); ResolvedType type = world.addSourceObjectType(jc).getResolvedTypeX(); String typeName = type.getName().replace('.', File.separatorChar); int end = name.indexOf(typeName); String binaryPath = name.substring(0,end-1); type.setBinaryPath(binaryPath); if (type.isAspect()) { toList.add(type); } } // // The ANT copy task should be used to copy resources across. // private final static boolean CopyResourcesFromInpathDirectoriesToOutput=false; /** * Add any .class files in the directory to the outdir. Anything other than .class files in * the directory (or its subdirectories) are considered resources and are also copied. * */ public List addDirectoryContents(File inFile,File outDir) throws IOException { List addedClassFiles = new ArrayList(); // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(inFile,new FileFilter() { public boolean accept(File f) { boolean accept = !f.isDirectory(); return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { addedClassFiles.add(addClassFile(files[i],inFile,outDir)); } return addedClassFiles; } /** Adds all class files in the jar */ public List addJarFile(File inFile, File outDir, boolean canBeDirectory){ // System.err.println("? addJarFile(" + inFile + ", " + outDir + ")"); List addedClassFiles = new ArrayList(); needToReweaveWorld = true; JarFile inJar = null; try { // Is this a directory we are looking at? if (inFile.isDirectory() && canBeDirectory) { addedClassFiles.addAll(addDirectoryContents(inFile,outDir)); } else { inJar = new JarFile(inFile); addManifest(inJar.getManifest()); Enumeration entries = inJar.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry)entries.nextElement(); InputStream inStream = inJar.getInputStream(entry); byte[] bytes = FileUtil.readAsByteArray(inStream); String filename = entry.getName(); // System.out.println("? addJarFile() filename='" + filename + "'"); UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes); if (filename.endsWith(".class")) { this.addClassFile(classFile); addedClassFiles.add(classFile); } // else if (!entry.isDirectory()) { // // /* bug-44190 Copy meta-data */ // addResource(filename,classFile); // } inStream.close(); } inJar.close(); } } catch (FileNotFoundException ex) { IMessage message = new Message( "Could not find input jar file " + inFile.getPath() + ", ignoring", new SourceLocation(inFile,0), false); world.getMessageHandler().handleMessage(message); } catch (IOException ex) { IMessage message = new Message( "Could not read input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } finally { if (inJar != null) { try {inJar.close();} catch (IOException ex) { IMessage message = new Message( "Could not close input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } } } return addedClassFiles; } // public void addResource(String name, File inPath, File outDir) throws IOException { // // /* Eliminate CVS files. Relative paths use "/" */ // if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) { //// System.err.println("? addResource('" + name + "')"); //// BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(inPath)); //// byte[] bytes = new byte[(int)inPath.length()]; //// inStream.read(bytes); //// inStream.close(); // byte[] bytes = FileUtil.readAsByteArray(inPath); // UnwovenClassFile resourceFile = new UnwovenClassFile(new File(outDir, name).getAbsolutePath(), bytes); // addResource(name,resourceFile); // } // } public boolean needToReweaveWorld() { return needToReweaveWorld; } /** Should be addOrReplace */ public void addClassFile(UnwovenClassFile classFile) { addedClasses.add(classFile); // if (null != sourceJavaClasses.put(classFile.getClassName(), classFile)) { //// throw new RuntimeException(classFile.getClassName()); // } world.addSourceObjectType(classFile.getJavaClass()); } public UnwovenClassFile addClassFile(File classFile, File inPathDir, File outDir) throws IOException { FileInputStream fis = new FileInputStream(classFile); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = classFile.getAbsolutePath().substring( inPathDir.getAbsolutePath().length()+1); UnwovenClassFile ucf = new UnwovenClassFile(new File(outDir,filename).getAbsolutePath(),bytes); if (filename.endsWith(".class")) { // System.err.println("BCELWeaver: processing class from input directory "+classFile); this.addClassFile(ucf); } fis.close(); return ucf; } public void deleteClassFile(String typename) { deletedTypenames.add(typename); // sourceJavaClasses.remove(typename); world.deleteSourceObjectType(UnresolvedType.forName(typename)); } // public void addResource (String name, UnwovenClassFile resourceFile) { // /* bug-44190 Change error to warning and copy first resource */ // if (!resources.containsKey(name)) { // resources.put(name, resourceFile); // } // else { // world.showMessage(IMessage.WARNING, "duplicate resource: '" + name + "'", // null, null); // } // } // ---- weave preparation public void setIsBatchWeave(boolean b) { isBatchWeave=b; } public void prepareForWeave() { if (trace.isTraceEnabled()) trace.enter("prepareForWeave",this); needToReweaveWorld = xcutSet.hasChangedSinceLastReset(); // update mungers for (Iterator i = addedClasses.iterator(); i.hasNext(); ) { UnwovenClassFile jc = (UnwovenClassFile)i.next(); String name = jc.getClassName(); ResolvedType type = world.resolve(name); //System.err.println("added: " + type + " aspect? " + type.isAspect()); if (type.isAspect()) { needToReweaveWorld |= xcutSet.addOrReplaceAspect(type); } } for (Iterator i = deletedTypenames.iterator(); i.hasNext(); ) { String name = (String)i.next(); if (xcutSet.deleteAspect(UnresolvedType.forName(name))) needToReweaveWorld = true; } shadowMungerList = xcutSet.getShadowMungers(); // world.debug("shadow mungers=" + shadowMungerList); rewritePointcuts(shadowMungerList); // Sometimes an error occurs during rewriting pointcuts (for example, if ambiguous bindings // are detected) - we ought to fail the prepare when this happens because continuing with // inconsistent pointcuts could lead to problems typeMungerList = xcutSet.getTypeMungers(); lateTypeMungerList = xcutSet.getLateTypeMungers(); declareParentsList = xcutSet.getDeclareParents(); addCustomMungers(); // The ordering here used to be based on a string compare on toString() for the two mungers - // that breaks for the @AJ style where advice names aren't programmatically generated. So we // have changed the sorting to be based on source location in the file - this is reliable, in // the case of source locations missing, we assume they are 'sorted' - i.e. the order in // which they were added to the collection is correct, this enables the @AJ stuff to work properly. // When @AJ processing starts filling in source locations for mungers, this code may need // a bit of alteration... Collections.sort( shadowMungerList, new Comparator() { public int compare(Object o1, Object o2) { ShadowMunger sm1 = (ShadowMunger)o1; ShadowMunger sm2 = (ShadowMunger)o2; if (sm1.getSourceLocation()==null) return (sm2.getSourceLocation()==null?0:1); if (sm2.getSourceLocation()==null) return -1; return (sm2.getSourceLocation().getOffset()-sm1.getSourceLocation().getOffset()); } }); if (inReweavableMode) world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.REWEAVABLE_MODE), null, null); if (trace.isTraceEnabled()) trace.exit("prepareForWeave"); } private void addCustomMungers() { if (customMungerFactory != null) { for (Iterator i = addedClasses.iterator(); i.hasNext();) { UnwovenClassFile jc = (UnwovenClassFile) i.next(); String name = jc.getClassName(); ResolvedType type = world.resolve(name); if (type.isAspect()) { Collection/*ShadowMunger*/ shadowMungers = customMungerFactory.createCustomShadowMungers(type); if (shadowMungers != null) { shadowMungerList.addAll(shadowMungers); } Collection/*ConcreteTypeMunger*/ typeMungers = customMungerFactory .createCustomTypeMungers(type); if (typeMungers != null) typeMungerList.addAll(typeMungers); } } } } public void setCustomMungerFactory(CustomMungerFactory factory) { customMungerFactory = factory; } /* * Rewrite all of the pointcuts in the world into their most efficient * form for subsequent matching. Also ensure that if pc1.equals(pc2) * then pc1 == pc2 (for non-binding pcds) by making references all * point to the same instance. * Since pointcuts remember their match decision on the last shadow, * this makes matching faster when many pointcuts share common elements, * or even when one single pointcut has one common element (which can * be a side-effect of DNF rewriting). */ private void rewritePointcuts(List/*ShadowMunger*/ shadowMungers) { PointcutRewriter rewriter = new PointcutRewriter(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); Pointcut newP = rewriter.rewrite(p); // validateBindings now whilst we still have around the pointcut // that resembles what the user actually wrote in their program // text. if (munger instanceof Advice) { Advice advice = (Advice) munger; if (advice.getSignature() != null) { final int numFormals; final String names[]; // If the advice is being concretized in a @AJ aspect *and* the advice was declared in // an @AJ aspect (it could have been inherited from a code style aspect) then // evaluate the alternative set of formals. pr125699 if (advice.getConcreteAspect().isAnnotationStyleAspect() && advice.getDeclaringAspect()!=null && advice.getDeclaringAspect().resolve(world).isAnnotationStyleAspect()) { numFormals = advice.getBaseParameterCount(); int numArgs = advice.getSignature().getParameterTypes().length; if (numFormals > 0) { names = advice.getSignature().getParameterNames(world); validateBindings(newP,p,numArgs,names); } } else { numFormals = advice.getBaseParameterCount(); if (numFormals > 0) { names = advice.getBaseParameterNames(world); validateBindings(newP,p,numFormals,names); } } } } munger.setPointcut(newP); } // now that we have optimized individual pointcuts, optimize // across the set of pointcuts.... // Use a map from key based on pc equality, to value based on // pc identity. Map/*<Pointcut,Pointcut>*/ pcMap = new HashMap(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); munger.setPointcut(shareEntriesFromMap(p,pcMap)); } } private Pointcut shareEntriesFromMap(Pointcut p,Map pcMap) { // some things cant be shared... if (p instanceof NameBindingPointcut) return p; if (p instanceof IfPointcut) return p; if (p instanceof ConcreteCflowPointcut) return p; if (p instanceof AndPointcut) { AndPointcut apc = (AndPointcut) p; Pointcut left = shareEntriesFromMap(apc.getLeft(),pcMap); Pointcut right = shareEntriesFromMap(apc.getRight(),pcMap); return new AndPointcut(left,right); } else if (p instanceof OrPointcut) { OrPointcut opc = (OrPointcut) p; Pointcut left = shareEntriesFromMap(opc.getLeft(),pcMap); Pointcut right = shareEntriesFromMap(opc.getRight(),pcMap); return new OrPointcut(left,right); } else if (p instanceof NotPointcut) { NotPointcut npc = (NotPointcut) p; Pointcut not = shareEntriesFromMap(npc.getNegatedPointcut(),pcMap); return new NotPointcut(not); } else { // primitive pcd if (pcMap.containsKey(p)) { // based on equality return (Pointcut) pcMap.get(p); // same instance (identity) } else { pcMap.put(p,p); return p; } } } // userPointcut is the pointcut that the user wrote in the program text. // dnfPointcut is the same pointcut rewritten in DNF // numFormals is the number of formal parameters in the pointcut // if numFormals > 0 then every branch of a disjunction must bind each formal once and only once. // in addition, the left and right branches of a disjunction must hold on join point kinds in // common. private void validateBindings(Pointcut dnfPointcut, Pointcut userPointcut, int numFormals, String[] names) { if (numFormals == 0) return; // nothing to check if (dnfPointcut.couldMatchKinds()==Shadow.NO_SHADOW_KINDS_BITS) return; // cant have problems if you dont match! if (dnfPointcut instanceof OrPointcut) { OrPointcut orBasedDNFPointcut = (OrPointcut) dnfPointcut; Pointcut[] leftBindings = new Pointcut[numFormals]; Pointcut[] rightBindings = new Pointcut[numFormals]; validateOrBranch(orBasedDNFPointcut,userPointcut,numFormals,names,leftBindings,rightBindings); } else { Pointcut[] bindings = new Pointcut[numFormals]; validateSingleBranch(dnfPointcut, userPointcut, numFormals, names,bindings); } } private void validateOrBranch(OrPointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] leftBindings, Pointcut[] rightBindings) { Pointcut left = pc.getLeft(); Pointcut right = pc.getRight(); if (left instanceof OrPointcut) { Pointcut[] newRightBindings = new Pointcut[numFormals]; validateOrBranch((OrPointcut)left,userPointcut,numFormals,names,leftBindings,newRightBindings); } else { if (left.couldMatchKinds()!=Shadow.NO_SHADOW_KINDS_BITS) validateSingleBranch(left, userPointcut, numFormals, names, leftBindings); } if (right instanceof OrPointcut) { Pointcut[] newLeftBindings = new Pointcut[numFormals]; validateOrBranch((OrPointcut)right,userPointcut,numFormals,names,newLeftBindings,rightBindings); } else { if (right.couldMatchKinds()!=Shadow.NO_SHADOW_KINDS_BITS) validateSingleBranch(right, userPointcut, numFormals, names, rightBindings); } int kindsInCommon = left.couldMatchKinds() & right.couldMatchKinds(); if (kindsInCommon!=Shadow.NO_SHADOW_KINDS_BITS && couldEverMatchSameJoinPoints(left,right)) { // we know that every branch binds every formal, so there is no ambiguity // if each branch binds it in exactly the same way... List ambiguousNames = new ArrayList(); for (int i = 0; i < numFormals; i++) { if (leftBindings[i] == null) { if (rightBindings[i] != null) { ambiguousNames.add(names[i]); } } else if (!leftBindings[i].equals(rightBindings[i])) { ambiguousNames.add(names[i]); } } if (!ambiguousNames.isEmpty()) raiseAmbiguityInDisjunctionError(userPointcut,ambiguousNames); } } // pc is a pointcut that does not contain any disjunctions // check that every formal is bound (negation doesn't count). // we know that numFormals > 0 or else we would not be called private void validateSingleBranch(Pointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] bindings) { boolean[] foundFormals = new boolean[numFormals]; for (int i = 0; i < foundFormals.length; i++) { foundFormals[i] = false; } validateSingleBranchRecursion(pc, userPointcut, foundFormals, names, bindings); for (int i = 0; i < foundFormals.length; i++) { if (!foundFormals[i]) { boolean ignore = false; // ATAJ soften the unbound error for implicit bindings like JoinPoint in @AJ style for (int j = 0; j < userPointcut.m_ignoreUnboundBindingForNames.length; j++) { if (names[i] != null && names[i].equals(userPointcut.m_ignoreUnboundBindingForNames[j])) { ignore = true; break; } } if (!ignore) { raiseUnboundFormalError(names[i],userPointcut); } } } } // each formal must appear exactly once private void validateSingleBranchRecursion(Pointcut pc, Pointcut userPointcut, boolean[] foundFormals, String[] names, Pointcut[] bindings) { if (pc instanceof NotPointcut) { // nots can only appear at leaves in DNF NotPointcut not = (NotPointcut) pc; if (not.getNegatedPointcut() instanceof NameBindingPointcut) { NameBindingPointcut nnbp = (NameBindingPointcut) not.getNegatedPointcut(); if (!nnbp.getBindingAnnotationTypePatterns().isEmpty() && !nnbp.getBindingTypePatterns().isEmpty()) raiseNegationBindingError(userPointcut); } } else if (pc instanceof AndPointcut) { AndPointcut and = (AndPointcut) pc; validateSingleBranchRecursion(and.getLeft(), userPointcut,foundFormals,names,bindings); validateSingleBranchRecursion(and.getRight(),userPointcut,foundFormals,names,bindings); } else if (pc instanceof NameBindingPointcut) { List/*BindingTypePattern*/ btps = ((NameBindingPointcut)pc).getBindingTypePatterns(); for (Iterator iter = btps.iterator(); iter.hasNext();) { BindingTypePattern btp = (BindingTypePattern) iter.next(); int index = btp.getFormalIndex(); bindings[index] = pc; if (foundFormals[index]) { raiseAmbiguousBindingError(names[index],userPointcut); } else { foundFormals[index] = true; } } List/*BindingAnnotationTypePattern*/ baps = ((NameBindingPointcut)pc).getBindingAnnotationTypePatterns(); for (Iterator iter = baps.iterator(); iter.hasNext();) { BindingAnnotationTypePattern bap = (BindingAnnotationTypePattern) iter.next(); int index = bap.getFormalIndex(); bindings[index] = pc; if (foundFormals[index]) { raiseAmbiguousBindingError(names[index],userPointcut); } else { foundFormals[index] = true; } } } else if (pc instanceof ConcreteCflowPointcut) { ConcreteCflowPointcut cfp = (ConcreteCflowPointcut) pc; int[] slots = cfp.getUsedFormalSlots(); for (int i = 0; i < slots.length; i++) { bindings[slots[i]] = cfp; if (foundFormals[slots[i]]) { raiseAmbiguousBindingError(names[slots[i]],userPointcut); } else { foundFormals[slots[i]] = true; } } } } // By returning false from this method, we are allowing binding of the same // variable on either side of an or. // Be conservative :- have to consider overriding, varargs, autoboxing, // the effects of itds (on within for example), interfaces, the fact that // join points can have multiple signatures and so on. private boolean couldEverMatchSameJoinPoints(Pointcut left, Pointcut right) { if (left instanceof OrPointcut) { OrPointcut leftOrPointcut = (OrPointcut)left; if (couldEverMatchSameJoinPoints(leftOrPointcut.getLeft(),right)) return true; if (couldEverMatchSameJoinPoints(leftOrPointcut.getRight(),right)) return true; return false; } if (right instanceof OrPointcut) { OrPointcut rightOrPointcut = (OrPointcut)right; if (couldEverMatchSameJoinPoints(left,rightOrPointcut.getLeft())) return true; if (couldEverMatchSameJoinPoints(left,rightOrPointcut.getRight())) return true; return false; } // look for withins WithinPointcut leftWithin = (WithinPointcut) findFirstPointcutIn(left,WithinPointcut.class); WithinPointcut rightWithin = (WithinPointcut) findFirstPointcutIn(right,WithinPointcut.class); if ((leftWithin != null) && (rightWithin != null)) { if (!leftWithin.couldEverMatchSameJoinPointsAs(rightWithin)) return false; } // look for kinded KindedPointcut leftKind = (KindedPointcut) findFirstPointcutIn(left,KindedPointcut.class); KindedPointcut rightKind = (KindedPointcut) findFirstPointcutIn(right,KindedPointcut.class); if ((leftKind != null) && (rightKind != null)) { if (!leftKind.couldEverMatchSameJoinPointsAs(rightKind)) return false; } return true; } private Pointcut findFirstPointcutIn(Pointcut toSearch, Class toLookFor) { if (toSearch instanceof NotPointcut) return null; if (toLookFor.isInstance(toSearch)) return toSearch; if (toSearch instanceof AndPointcut) { AndPointcut apc = (AndPointcut) toSearch; Pointcut left = findFirstPointcutIn(apc.getLeft(),toLookFor); if (left != null) return left; return findFirstPointcutIn(apc.getRight(),toLookFor); } return null; } /** * @param userPointcut */ private void raiseNegationBindingError(Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.NEGATION_DOESNT_ALLOW_BINDING), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param name * @param userPointcut */ private void raiseAmbiguousBindingError(String name, Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING, name), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param userPointcut */ private void raiseAmbiguityInDisjunctionError(Pointcut userPointcut, List names) { StringBuffer formalNames = new StringBuffer(names.get(0).toString()); for (int i = 1; i < names.size(); i++) { formalNames.append(", "); formalNames.append(names.get(i)); } world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING_IN_OR,formalNames), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param name * @param userPointcut */ private void raiseUnboundFormalError(String name, Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.UNBOUND_FORMAL,name),userPointcut.getSourceLocation(),null); } // public void dumpUnwoven(File file) throws IOException { // BufferedOutputStream os = FileUtil.makeOutputStream(file); // this.zipOutputStream = new ZipOutputStream(os); // dumpUnwoven(); // /* BUG 40943*/ // dumpResourcesToOutJar(); // zipOutputStream.close(); //this flushes and closes the acutal file // } // // // public void dumpUnwoven() throws IOException { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // public void dumpResourcesToOutPath() throws IOException { //// System.err.println("? dumpResourcesToOutPath() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // UnwovenClassFile res = (UnwovenClassFile)resources.get(i.next()); // dumpUnchanged(res); // } // //resources = new HashMap(); // } // /* BUG #40943 */ // public void dumpResourcesToOutJar() throws IOException { //// System.err.println("? dumpResourcesToOutJar() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // String name = (String)i.next(); // UnwovenClassFile res = (UnwovenClassFile)resources.get(name); // writeZipEntry(name,res.getBytes()); // } // resources = new HashMap(); // } // // // halfway house for when the jar is managed outside of the weaver, but the resources // // to be copied are known in the weaver. // public void dumpResourcesToOutJar(ZipOutputStream zos) throws IOException { // this.zipOutputStream = zos; // dumpResourcesToOutJar(); // } public void addManifest (Manifest newManifest) { // System.out.println("? addManifest() newManifest=" + newManifest); if (manifest == null) { manifest = newManifest; } } public static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; private static final String WEAVER_MANIFEST_VERSION = "1.0"; private static final Attributes.Name CREATED_BY = new Name("Created-By"); private static final String WEAVER_CREATED_BY = "AspectJ Compiler"; public Manifest getManifest (boolean shouldCreate) { if (manifest == null && shouldCreate) { manifest = new Manifest(); Attributes attributes = manifest.getMainAttributes(); attributes.put(Name.MANIFEST_VERSION,WEAVER_MANIFEST_VERSION); attributes.put(CREATED_BY,WEAVER_CREATED_BY); } return manifest; } // ---- weaving // Used by some test cases only... public Collection weave(File file) throws IOException { OutputStream os = FileUtil.makeOutputStream(file); this.zipOutputStream = new ZipOutputStream(os); prepareForWeave(); Collection c = weave( new IClassFileProvider() { public boolean isApplyAtAspectJMungersOnly() { return false; } public Iterator getClassFileIterator() { return addedClasses.iterator(); } public IWeaveRequestor getRequestor() { return new IWeaveRequestor() { public void acceptResult(UnwovenClassFile result) { try { writeZipEntry(result.filename, result.bytes); } catch(IOException ex) {} } public void processingReweavableState() {} public void addingTypeMungers() {} public void weavingAspects() {} public void weavingClasses() {} public void weaveCompleted() {} }; } }); // /* BUG 40943*/ // dumpResourcesToOutJar(); zipOutputStream.close(); //this flushes and closes the acutal file return c; } // public Collection weave() throws IOException { // prepareForWeave(); // Collection filesToWeave; // // if (needToReweaveWorld) { // filesToWeave = sourceJavaClasses.values(); // } else { // filesToWeave = addedClasses; // } // // Collection wovenClassNames = new ArrayList(); // world.showMessage(IMessage.INFO, "might need to weave " + filesToWeave + // "(world=" + needToReweaveWorld + ")", null, null); // // // //System.err.println("typeMungers: " + typeMungerList); // // prepareToProcessReweavableState(); // // clear all state from files we'll be reweaving // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = getClassType(className); // processReweavableStateIfPresent(className, classType); // } // // // // //XXX this isn't quite the right place for this... // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // addTypeMungers(className); // } // // // first weave into aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // // then weave into non-aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (! classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // if (zipOutputStream != null && !needToReweaveWorld) { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // filesToDump.removeAll(filesToWeave); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // // addedClasses = new ArrayList(); // deletedTypenames = new ArrayList(); // // return wovenClassNames; // } // variation of "weave" that sources class files from an external source. public Collection weave(IClassFileProvider input) throws IOException { if (trace.isTraceEnabled()) trace.enter("weave",this,input); ContextToken weaveToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING, ""); Collection wovenClassNames = new ArrayList(); IWeaveRequestor requestor = input.getRequestor(); for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); if (AsmManager.isCreatingModel() && !isBatchWeave) { // remove all relationships where this file being woven is the target of the relationship AsmManager.getDefault().removeRelationshipsTargettingThisType(classFile.getClassName()); } } // Go through the types and ensure any 'damaged' during compile time are repaired prior to weaving for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); ResolvedType theType = world.resolve(className); if (theType!=null) { BcelObjectType classType = BcelWorld.getBcelObjectType(theType); if (classType!=null) classType.ensureDelegateConsistent(); } } // special case for AtAspectJMungerOnly - see #113587 if (input.isApplyAtAspectJMungersOnly()) { ContextToken atAspectJMungersOnly = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_ATASPECTJTYPE_MUNGERS_ONLY, ""); requestor.weavingAspects(); ContextToken aspectToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, ""); for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); ResolvedType theType = world.resolve(className); if (theType.isAnnotationStyleAspect()) { BcelObjectType classType = BcelWorld.getBcelObjectType(theType); if (classType==null) { throw new BCException("Can't find bcel delegate for "+className+" type="+theType.getClass()); } LazyClassGen clazz = classType.getLazyClassGen(); BcelPerClauseAspectAdder selfMunger = new BcelPerClauseAspectAdder(theType, theType.getPerClause().getKind()); selfMunger.forceMunge(clazz, true); classType.finishedWith(); UnwovenClassFile[] newClasses = getClassFilesFor(clazz); for (int news = 0; news < newClasses.length; news++) { requestor.acceptResult(newClasses[news]); } wovenClassNames.add(classFile.getClassName()); } } requestor.weaveCompleted(); CompilationAndWeavingContext.leavingPhase(atAspectJMungersOnly); return wovenClassNames; } requestor.processingReweavableState(); ContextToken reweaveToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE,""); prepareToProcessReweavableState(); // clear all state from files we'll be reweaving for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = getClassType(className); // null return from getClassType() means the delegate is an eclipse source type - so // there *cant* be any reweavable state... (he bravely claimed...) if (classType !=null) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE, className); processReweavableStateIfPresent(className, classType); CompilationAndWeavingContext.leavingPhase(tok); } } CompilationAndWeavingContext.leavingPhase(reweaveToken); ContextToken typeMungingToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS,""); requestor.addingTypeMungers(); // We process type mungers in two groups, first mungers that change the type // hierarchy, then 'normal' ITD type mungers. // Process the types in a predictable order (rather than the order encountered). // For class A, the order is superclasses of A then superinterfaces of A // (and this mechanism is applied recursively) List typesToProcess = new ArrayList(); for (Iterator iter = input.getClassFileIterator(); iter.hasNext();) { UnwovenClassFile clf = (UnwovenClassFile) iter.next(); typesToProcess.add(clf.getClassName()); } while (typesToProcess.size()>0) { weaveParentsFor(typesToProcess,(String)typesToProcess.get(0)); } for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); addNormalTypeMungers(className); } CompilationAndWeavingContext.leavingPhase(typeMungingToken); requestor.weavingAspects(); ContextToken aspectToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, ""); // first weave into aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); ResolvedType theType = world.resolve(className); if (theType.isAspect()) { BcelObjectType classType = BcelWorld.getBcelObjectType(theType); if (classType==null) { // Sometimes.. if the Bcel Delegate couldn't be found then a problem occurred at compile time - on // a previous compiler run. In this case I assert the delegate will still be an EclipseSourceType // and we can ignore the problem here (the original compile error will be reported again from // the eclipse source type) - pr113531 ReferenceTypeDelegate theDelegate = ((ReferenceType)theType).getDelegate(); if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) continue; throw new BCException("Can't find bcel delegate for "+className+" type="+theType.getClass()); } weaveAndNotify(classFile, classType,requestor); wovenClassNames.add(className); } } CompilationAndWeavingContext.leavingPhase(aspectToken); requestor.weavingClasses(); ContextToken classToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_CLASSES, ""); // then weave into non-aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); ResolvedType theType = world.resolve(className); if (!theType.isAspect()) { BcelObjectType classType = BcelWorld.getBcelObjectType(theType); if (classType==null) { // bug 119882 - see above comment for bug 113531 ReferenceTypeDelegate theDelegate = ((ReferenceType)theType).getDelegate(); // TODO urgh - put a method on the interface to check this, string compare is hideous if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) continue; throw new BCException("Can't find bcel delegate for "+className+" type="+theType.getClass()); } weaveAndNotify(classFile, classType, requestor); wovenClassNames.add(className); } } CompilationAndWeavingContext.leavingPhase(classToken); addedClasses = new ArrayList(); deletedTypenames = new ArrayList(); requestor.weaveCompleted(); CompilationAndWeavingContext.leavingPhase(weaveToken); if (trace.isTraceEnabled()) trace.exit("weave",wovenClassNames); return wovenClassNames; } public void allWeavingComplete() { warnOnUnmatchedAdvice(); } /** * In 1.5 mode and with XLint:adviceDidNotMatch enabled, put out messages for any * mungers that did not match anything. */ private void warnOnUnmatchedAdvice() { class AdviceLocation { private int lineNo; private UnresolvedType inAspect; public AdviceLocation(BcelAdvice advice) { this.lineNo = advice.getSourceLocation().getLine(); this.inAspect = advice.getDeclaringAspect(); } public boolean equals(Object obj) { if (!(obj instanceof AdviceLocation)) return false; AdviceLocation other = (AdviceLocation) obj; if (this.lineNo != other.lineNo) return false; if (!this.inAspect.equals(other.inAspect)) return false; return true; } public int hashCode() { return 37 + 17*lineNo + 17*inAspect.hashCode(); }; } // FIXME asc Should be factored out into Xlint code and done automatically for all xlint messages, ideally. // if a piece of advice hasn't matched anywhere and we are in -1.5 mode, put out a warning if (world.isInJava5Mode() && world.getLint().adviceDidNotMatch.isEnabled()) { List l = world.getCrosscuttingMembersSet().getShadowMungers(); Set alreadyWarnedLocations = new HashSet(); for (Iterator iter = l.iterator(); iter.hasNext();) { ShadowMunger element = (ShadowMunger) iter.next(); if (element instanceof BcelAdvice) { // This will stop us incorrectly reporting deow Checkers BcelAdvice ba = (BcelAdvice)element; if (!ba.hasMatchedSomething()) { // Because we implement some features of AJ itself by creating our own kind of mungers, you sometimes // find that ba.getSignature() is not a BcelMethod - for example it might be a cflow entry munger. if (ba.getSignature()!=null) { // check we haven't already warned on this advice and line // (cflow creates multiple mungers for the same advice) AdviceLocation loc = new AdviceLocation(ba); if (alreadyWarnedLocations.contains(loc)) { continue; } else { alreadyWarnedLocations.add(loc); } if (!(ba.getSignature() instanceof BcelMethod) || !Utility.isSuppressing((AnnotationX[])ba.getSignature().getAnnotations(),"adviceDidNotMatch")) { world.getLint().adviceDidNotMatch.signal(ba.getDeclaringAspect().toString(), new SourceLocation(element.getSourceLocation().getSourceFile(),element.getSourceLocation().getLine()));//element.getSourceLocation()); } } } } } } } /** * 'typeToWeave' is one from the 'typesForWeaving' list. This routine ensures we process * supertypes (classes/interfaces) of 'typeToWeave' that are in the * 'typesForWeaving' list before 'typeToWeave' itself. 'typesToWeave' is then removed from * the 'typesForWeaving' list. * * Note: Future gotcha in here ... when supplying partial hierarchies, this algorithm may * break down. If you have a hierarchy A>B>C and only give A and C to the weaver, it * may choose to weave them in either order - but you'll probably have other problems if * you are supplying partial hierarchies like that ! */ private void weaveParentsFor(List typesForWeaving,String typeToWeave) { // Look at the supertype first ResolvedType rtx = world.resolve(typeToWeave); ResolvedType superType = rtx.getSuperclass(); if (superType!=null && typesForWeaving.contains(superType.getName())) { weaveParentsFor(typesForWeaving,superType.getName()); } // Then look at the superinterface list ResolvedType[] interfaceTypes = rtx.getDeclaredInterfaces(); for (int i = 0; i < interfaceTypes.length; i++) { ResolvedType rtxI = interfaceTypes[i]; if (typesForWeaving.contains(rtxI.getName())) { weaveParentsFor(typesForWeaving,rtxI.getName()); } } ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS,rtx.getName()); weaveParentTypeMungers(rtx); // Now do this type CompilationAndWeavingContext.leavingPhase(tok); typesForWeaving.remove(typeToWeave); // and remove it from the list of those to process } public void prepareToProcessReweavableState() { } public void processReweavableStateIfPresent(String className, BcelObjectType classType) { // If the class is marked reweavable, check any aspects around when it was built are in this world WeaverStateInfo wsi = classType.getWeaverState(); if (wsi!=null && wsi.isReweavable()) { // Check all necessary types are around! world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.PROCESSING_REWEAVABLE,className,classType.getSourceLocation().getSourceFile()), null,null); Set aspectsPreviouslyInWorld = wsi.getAspectsAffectingType(); if (aspectsPreviouslyInWorld!=null) { // keep track of them just to ensure unique missing aspect error reporting Set alreadyConfirmedReweavableState = new HashSet(); for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) { String requiredTypeName = (String) iter.next(); if (!alreadyConfirmedReweavableState.contains(requiredTypeName)) { ResolvedType rtx = world.resolve(UnresolvedType.forName(requiredTypeName),true); boolean exists = !rtx.isMissing(); if (!exists) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE,requiredTypeName,className), classType.getSourceLocation(), null); } else { // weaved in aspect that are not declared in aop.xml trigger an error for now // may cause headhache for LTW and packaged lib without aop.xml in // see #104218 if(!xcutSet.containsAspect(rtx)){ world.showMessage( IMessage.ERROR, WeaverMessages.format( WeaverMessages.REWEAVABLE_ASPECT_NOT_REGISTERED, requiredTypeName, className ), null, null ); } else if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.VERIFIED_REWEAVABLE_TYPE,requiredTypeName,rtx.getSourceLocation().getSourceFile()), null,null); alreadyConfirmedReweavableState.add(requiredTypeName); } } } } // old: //classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData())); // new: reweavable default with clever diff classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData(classType.getJavaClass().getBytes()))); // } else { // classType.resetState(); } } private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType, IWeaveRequestor requestor) throws IOException { trace.enter("weaveAndNotify",this,new Object[] {classFile,classType,requestor}); ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_TYPE, classType.getResolvedTypeX().getName()); LazyClassGen clazz = weaveWithoutDump(classFile,classType); classType.finishedWith(); //clazz is null if the classfile was unchanged by weaving... if (clazz != null) { UnwovenClassFile[] newClasses = getClassFilesFor(clazz); // OPTIMIZE can we avoid using the string name at all in UnwovenClassFile instances? // Copy the char[] across as it means the WeaverAdapter.removeFromMap() can be fast! if (newClasses[0].getClassName().equals(classFile.getClassName())) { newClasses[0].setClassNameAsChars(classFile.getClassNameAsChars()); } for (int i = 0; i < newClasses.length; i++) { requestor.acceptResult(newClasses[i]); } } else { requestor.acceptResult(classFile); } classType.weavingCompleted(); CompilationAndWeavingContext.leavingPhase(tok); trace.exit("weaveAndNotify"); } /** helper method - will return NULL if the underlying delegate is an EclipseSourceType and not a BcelObjectType */ public BcelObjectType getClassType(String forClass) { return BcelWorld.getBcelObjectType(world.resolve(forClass)); } public void addParentTypeMungers(String typeName) { weaveParentTypeMungers(world.resolve(typeName)); } public void addNormalTypeMungers(String typeName) { weaveNormalTypeMungers(world.resolve(typeName)); } public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) { List childClasses = clazz.getChildClasses(world); UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()]; ret[0] = new UnwovenClassFile(clazz.getFileName(),clazz.getJavaClassBytesIncludingReweavable(world)); int index = 1; for (Iterator iter = childClasses.iterator(); iter.hasNext();) { UnwovenClassFile.ChildClass element = (UnwovenClassFile.ChildClass) iter.next(); UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes); ret[index++] = childClass; } return ret; } /** * Weaves new parents and annotations onto a type ("declare parents" and "declare @type") * * Algorithm: * 1. First pass, do parents then do annotations. During this pass record: * - any parent mungers that don't match but have a non-wild annotation type pattern * - any annotation mungers that don't match * 2. Multiple subsequent passes which go over the munger lists constructed in the first * pass, repeatedly applying them until nothing changes. * FIXME asc confirm that algorithm is optimal ?? */ public void weaveParentTypeMungers(ResolvedType onType) { if (onType.isRawType()) onType = onType.getGenericType(); onType.clearInterTypeMungers(); List decpToRepeat = new ArrayList(); boolean aParentChangeOccurred = false; boolean anAnnotationChangeOccurred = false; // First pass - apply all decp mungers for (Iterator i = declareParentsList.iterator(); i.hasNext(); ) { DeclareParents decp = (DeclareParents)i.next(); boolean typeChanged = applyDeclareParents(decp,onType); if (typeChanged) { aParentChangeOccurred = true; } else { decpToRepeat.add(decp); } } // Still first pass - apply all dec @type mungers for (Iterator i = xcutSet.getDeclareAnnotationOnTypes().iterator();i.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation)i.next(); boolean typeChanged = applyDeclareAtType(decA,onType,true); if (typeChanged) { anAnnotationChangeOccurred = true; } } while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) { anAnnotationChangeOccurred = aParentChangeOccurred = false; List decpToRepeatNextTime = new ArrayList(); for (Iterator iter = decpToRepeat.iterator(); iter.hasNext();) { DeclareParents decp = (DeclareParents) iter.next(); boolean typeChanged = applyDeclareParents(decp,onType); if (typeChanged) { aParentChangeOccurred = true; } else { decpToRepeatNextTime.add(decp); } } for (Iterator iter = xcutSet.getDeclareAnnotationOnTypes().iterator(); iter.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation) iter.next(); boolean typeChanged = applyDeclareAtType(decA,onType,false); if (typeChanged) { anAnnotationChangeOccurred = true; } } decpToRepeat = decpToRepeatNextTime; } } /** * Apply a declare @type - return true if we change the type */ private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedType onType,boolean reportProblems) { boolean didSomething = false; if (decA.matches(onType)) { if (onType.hasAnnotation(decA.getAnnotationX().getSignature())) { // Could put out a lint here for an already annotated type ... // if (reportProblems) { // world.getLint().elementAlreadyAnnotated.signal( // new String[]{onType.toString(),decA.getAnnotationTypeX().toString()}, // onType.getSourceLocation(),new ISourceLocation[]{decA.getSourceLocation()}); // } return false; } AnnotationX annoX = decA.getAnnotationX(); // check the annotation is suitable for the target boolean problemReported = verifyTargetIsOK(decA, onType, annoX,reportProblems); if (!problemReported) { AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decA.getSourceLocation(),onType.getSourceLocation()); // TAG: WeavingMessage if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){ getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES, new String[]{ onType.toString(), Utility.beautifyLocation(onType.getSourceLocation()), decA.getAnnotationString(), "type", decA.getAspect().toString(), Utility.beautifyLocation(decA.getSourceLocation()) })); } didSomething = true; ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX); newAnnotationTM.setSourceLocation(decA.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM,decA.getAspect().resolve(world))); decA.copyAnnotationTo(onType); } } return didSomething; } /** * Checks for an @target() on the annotation and if found ensures it allows the annotation * to be attached to the target type that matched. */ private boolean verifyTargetIsOK(DeclareAnnotation decA, ResolvedType onType, AnnotationX annoX,boolean outputProblems) { boolean problemReported = false; if (annoX.specifiesTarget()) { if ( (onType.isAnnotation() && !annoX.allowedOnAnnotationType()) || (!annoX.allowedOnRegularType())) { if (outputProblems) { if (decA.isExactPattern()) { world.getMessageHandler().handleMessage(MessageUtil.error( WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, onType.getName(),annoX.stringify(),annoX.getValidTargets()),decA.getSourceLocation())); } else { if (world.getLint().invalidTargetForAnnotation.isEnabled()) { world.getLint().invalidTargetForAnnotation.signal( new String[]{onType.getName(),annoX.stringify(),annoX.getValidTargets()},decA.getSourceLocation(),new ISourceLocation[]{onType.getSourceLocation()}); } } } problemReported = true; } } return problemReported; } /** * Apply a single declare parents - return true if we change the type */ private boolean applyDeclareParents(DeclareParents p, ResolvedType onType) { boolean didSomething = false; List newParents = p.findMatchingNewParents(onType,true); if (!newParents.isEmpty()) { didSomething=true; BcelObjectType classType = BcelWorld.getBcelObjectType(onType); //System.err.println("need to do declare parents for: " + onType); for (Iterator j = newParents.iterator(); j.hasNext(); ) { ResolvedType newParent = (ResolvedType)j.next(); // We set it here so that the imminent matching for ITDs can succeed - we // still haven't done the necessary changes to the class file itself // (like transform super calls) - that is done in BcelTypeMunger.mungeNewParent() classType.addParent(newParent); ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent); newParentMunger.setSourceLocation(p.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p))); } } return didSomething; } public void weaveNormalTypeMungers(ResolvedType onType) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS, onType.getName()); if (onType.isRawType() || onType.isParameterizedType()) onType = onType.getGenericType(); for (Iterator i = typeMungerList.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); if (!m.isLateMunger() && m.matches(onType)) { onType.addInterTypeMunger(m); } } CompilationAndWeavingContext.leavingPhase(tok); } // exposed for ClassLoader dynamic weaving public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { return weave(classFile, classType, false); } // non-private for testing LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { LazyClassGen ret = weave(classFile, classType, true); if (progressListener != null) { progressMade += progressPerClassFile; progressListener.setProgress(progressMade); progressListener.setText("woven: " + classFile.getFilename()); } return ret; } private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException { if (classType.isSynthetic()) { // Don't touch synthetic classes if (dump) dumpUnchanged(classFile); return null; } List shadowMungers = fastMatch(shadowMungerList, classType.getResolvedTypeX()); List typeMungers = classType.getResolvedTypeX().getInterTypeMungers(); classType.getResolvedTypeX().checkInterTypeMungers(); // Decide if we need to do actual weaving for this class boolean mightNeedToWeave = shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect() || world.getDeclareAnnotationOnMethods().size()>0 || world.getDeclareAnnotationOnFields().size()>0; // May need bridge methods if on 1.5 and something in our hierarchy is affected by ITDs boolean mightNeedBridgeMethods = world.isInJava5Mode() && !classType.isInterface() && classType.getResolvedTypeX().getInterTypeMungersIncludingSupers().size()>0; LazyClassGen clazz = null; if (mightNeedToWeave || mightNeedBridgeMethods) { clazz = classType.getLazyClassGen(); //System.err.println("got lazy gen: " + clazz + ", " + clazz.getWeaverState()); try { boolean isChanged = false; if (mightNeedToWeave) isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers, lateTypeMungerList); if (mightNeedBridgeMethods) isChanged = BcelClassWeaver.calculateAnyRequiredBridgeMethods(world,clazz) || isChanged; if (isChanged) { if (dump) dump(classFile, clazz); return clazz; } } catch (RuntimeException re) { String classDebugInfo = null; try { classDebugInfo = clazz.toLongString(); } catch (Exception e) { // recover from crash whilst producing debug string classDebugInfo = clazz.getClassName(); } String messageText = "trouble in: \n" + classDebugInfo; getWorld().getMessageHandler().handleMessage( new Message(messageText,IMessage.ABORT,re,null) ); } catch (Error re) { String classDebugInfo = null; try { classDebugInfo = clazz.toLongString(); } catch (Exception e) { // recover from crash whilst producing debug string classDebugInfo = clazz.getClassName(); } String messageText = "trouble in: \n" + classDebugInfo; getWorld().getMessageHandler().handleMessage( new Message(messageText,IMessage.ABORT,re,null) ); } } // this is very odd return behavior trying to keep everyone happy if (dump) { dumpUnchanged(classFile); return clazz; } else { // ATAJ: the class was not weaved, but since it gets there early it may have new generated inner classes // attached to it to support LTW perX aspectOf support (see BcelPerClauseAspectAdder) // that aggressively defines the inner <aspect>$mayHaveAspect interface. if (clazz != null && !clazz.getChildClasses(world).isEmpty()) { return clazz; } return null; } } // ---- writing private void dumpUnchanged(UnwovenClassFile classFile) throws IOException { if (zipOutputStream != null) { writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes()); } else { classFile.writeUnchangedBytes(); } } private String getEntryName(String className) { //XXX what does bcel's getClassName do for inner names return className.replace('.', '/') + ".class"; } private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException { if (zipOutputStream != null) { String mainClassName = classFile.getJavaClass().getClassName(); writeZipEntry(getEntryName(mainClassName), clazz.getJavaClass(world).getBytes()); if (!clazz.getChildClasses(world).isEmpty()) { for (Iterator i = clazz.getChildClasses(world).iterator(); i.hasNext();) { UnwovenClassFile.ChildClass c = (UnwovenClassFile.ChildClass) i.next(); writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes); } } } else { classFile.writeWovenBytes( clazz.getJavaClass(world).getBytes(), clazz.getChildClasses(world) ); } } private void writeZipEntry(String name, byte[] bytes) throws IOException { ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right zipOutputStream.putNextEntry(newEntry); zipOutputStream.write(bytes); zipOutputStream.closeEntry(); } private List fastMatch(List list, ResolvedType type) { if (list == null) return Collections.EMPTY_LIST; // here we do the coarsest grained fast match with no kind constraints // this will remove all obvious non-matches and see if we need to do any weaving FastMatchInfo info = new FastMatchInfo(type, null); List result = new ArrayList(); Iterator iter = list.iterator(); while (iter.hasNext()) { ShadowMunger munger = (ShadowMunger)iter.next(); FuzzyBoolean fb = munger.getPointcut().fastMatch(info); if (fb.maybeTrue()) { result.add(munger); } } return result; } public void setProgressListener(IProgressListener listener, double previousProgress, double progressPerClassFile) { progressListener = listener; this.progressMade = previousProgress; this.progressPerClassFile = progressPerClassFile; } public void setReweavableMode(boolean xNotReweavable) { if (trace.isTraceEnabled()) trace.enter("setReweavableMode",this,xNotReweavable); inReweavableMode = !xNotReweavable; WeaverStateInfo.setReweavableModeDefaults(!xNotReweavable,false,true); BcelClassWeaver.setReweavableMode(!xNotReweavable); if (trace.isTraceEnabled()) trace.exit("setReweavableMode"); } public boolean isReweavable() { return inReweavableMode; } public World getWorld() { return world; } public void tidyUp() { if (trace.isTraceEnabled()) trace.enter("tidyUp",this); shadowMungerList = null; // setup by prepareForWeave typeMungerList = null; // setup by prepareForWeave lateTypeMungerList = null; // setup by prepareForWeave declareParentsList = null; // setup by prepareForWeave if (trace.isTraceEnabled()) trace.exit("tidyUp"); } }
227,295
Bug 227295 AJC error, somehow connected with generics
Build ID: 1.5.0.20070607 Steps To Reproduce: I cannot find a way to reproduce it, it's somehow "randomic", for example it happened to me now while creating a new class in an aspectj project, but when i then saved the .java it compiled properly. That's why I'm filing it in AJDT and not in AspectJ directly. Based on the exception, IIUC, there is a narrowing in a generic (UnresolvedType should be something like Converter<?>, while BoundedReferenceType should be somethinf like Converter<? extends Number>), and the weaver is not handling it properly, but simply casting from one to the other .. but this are just silly assumptions. More information: java.lang.ClassCastException at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeTypeBinding1(EclipseFactory.java:656) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeTypeBinding(EclipseFactory.java:579) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeTypeBinding1(EclipseFactory.java:640) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeTypeBinding(EclipseFactory.java:579) at org.asp ... Worker.java:55) Compile error: ClassCastException thrown: org.aspectj.weaver.UnresolvedType cannot be cast to org.aspectj.weaver.BoundedReferenceType
resolved fixed
3b2109a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-06-06T20:38:14Z"
"2008-04-16T10:00:00Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Mik Kersten 2004-07-26 extended to allow overloading of * hierarchy builder * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.lookup; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration; import org.aspectj.ajdt.internal.compiler.ast.AstUtil; import org.aspectj.ajdt.internal.core.builder.AjBuildManager; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.org.eclipse.jdt.core.Flags; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.EmptyStatement; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Wildcard; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.Constant; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Binding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.RawTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SyntheticFieldBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.WildcardBinding; import org.aspectj.weaver.BoundedReferenceType; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.IHasPosition; import org.aspectj.weaver.Member; import org.aspectj.weaver.MemberKind; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeFactory; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.TypeVariableDeclaringElement; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.UnresolvedTypeVariableReferenceType; import org.aspectj.weaver.WildcardedUnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.UnresolvedType.TypeKind; /** * @author Jim Hugunin */ public class EclipseFactory { public static boolean DEBUG = false; public static int debug_mungerCount = -1; private AjBuildManager buildManager; private LookupEnvironment lookupEnvironment; private boolean xSerializableAspects; private World world; public Collection finishedTypeMungers = null; // We can get clashes if we don't treat raw types differently - we end up looking // up a raw and getting the generic type (pr115788) private Map/*UnresolvedType, TypeBinding*/ typexToBinding = new HashMap(); private Map/*UnresolvedType, TypeBinding*/ rawTypeXToBinding = new HashMap(); //XXX currently unused // private Map/*TypeBinding, ResolvedType*/ bindingToResolvedTypeX = new HashMap(); public static EclipseFactory fromLookupEnvironment(LookupEnvironment env) { AjLookupEnvironment aenv = (AjLookupEnvironment)env; return aenv.factory; } public static EclipseFactory fromScopeLookupEnvironment(Scope scope) { return fromLookupEnvironment(AstUtil.getCompilationUnitScope(scope).environment); } public EclipseFactory(LookupEnvironment lookupEnvironment,AjBuildManager buildManager) { this.lookupEnvironment = lookupEnvironment; this.buildManager = buildManager; this.world = buildManager.getWorld(); this.xSerializableAspects = buildManager.buildConfig.isXserializableAspects(); } public EclipseFactory(LookupEnvironment lookupEnvironment, World world, boolean xSer) { this.lookupEnvironment = lookupEnvironment; this.world = world; this.xSerializableAspects = xSer; this.buildManager = null; } public World getWorld() { return world; } public void showMessage( Kind kind, String message, ISourceLocation loc1, ISourceLocation loc2) { getWorld().showMessage(kind, message, loc1, loc2); } public ResolvedType fromEclipse(ReferenceBinding binding) { if (binding == null) return ResolvedType.MISSING; //??? this seems terribly inefficient //System.err.println("resolving: " + binding.getClass() + ", name = " + getName(binding)); ResolvedType ret = getWorld().resolve(fromBinding(binding)); //System.err.println(" got: " + ret); return ret; } public ResolvedType fromTypeBindingToRTX(TypeBinding tb) { if (tb == null) return ResolvedType.MISSING; ResolvedType ret = getWorld().resolve(fromBinding(tb)); return ret; } public ResolvedType[] fromEclipse(ReferenceBinding[] bindings) { if (bindings == null) { return ResolvedType.NONE; } int len = bindings.length; ResolvedType[] ret = new ResolvedType[len]; for (int i=0; i < len; i++) { ret[i] = fromEclipse(bindings[i]); } return ret; } public static String getName(TypeBinding binding) { if (binding instanceof TypeVariableBinding) { // The first bound may be null - so default to object? TypeVariableBinding tvb = (TypeVariableBinding)binding; if (tvb.firstBound!=null) { return getName(tvb.firstBound); } else { return getName(tvb.superclass); } } if (binding instanceof ReferenceBinding) { return new String( CharOperation.concatWith(((ReferenceBinding)binding).compoundName, '.')); } String packageName = new String(binding.qualifiedPackageName()); String className = new String(binding.qualifiedSourceName()).replace('.', '$'); if (packageName.length() > 0) { className = packageName + "." + className; } //XXX doesn't handle arrays correctly (or primitives?) return new String(className); } /** * Some generics notes: * * Andy 6-May-05 * We were having trouble with parameterized types in a couple of places - due to TypeVariableBindings. When we * see a TypeVariableBinding now we default to either the firstBound if it is specified or java.lang.Object. Not * sure when/if this gets us unstuck? It does mean we forget that it is a type variable when going back * the other way from the UnresolvedType and that would seem a bad thing - but I've yet to see the reason we need to * remember the type variable. * Adrian 10-July-05 * When we forget it's a type variable we come unstuck when getting the declared members of a parameterized * type - since we don't know it's a type variable we can't replace it with the type parameter. */ //??? going back and forth between strings and bindings is a waste of cycles public UnresolvedType fromBinding(TypeBinding binding) { if (binding instanceof HelperInterfaceBinding) { return ((HelperInterfaceBinding) binding).getTypeX(); } if (binding == null || binding.qualifiedSourceName() == null) { return ResolvedType.MISSING; } // first piece of generics support! if (binding instanceof TypeVariableBinding) { TypeVariableBinding tb = (TypeVariableBinding) binding; UnresolvedTypeVariableReferenceType utvrt = (UnresolvedTypeVariableReferenceType) fromTypeVariableBinding(tb); return utvrt; } // handle arrays since the component type may need special treatment too... if (binding instanceof ArrayBinding) { ArrayBinding aBinding = (ArrayBinding) binding; UnresolvedType componentType = fromBinding(aBinding.leafComponentType); return UnresolvedType.makeArray(componentType, aBinding.dimensions); } if (binding instanceof WildcardBinding) { WildcardBinding eWB = (WildcardBinding) binding; // Repair the bound // e.g. If the bound for the wildcard is a typevariable, e.g. '? extends E' then // the type variable in the unresolvedtype will be correct only in name. In that // case let's set it correctly based on the one in the eclipse WildcardBinding UnresolvedType theBound = null; if (eWB.bound instanceof TypeVariableBinding) { theBound = fromTypeVariableBinding((TypeVariableBinding)eWB.bound); } else { theBound = fromBinding(eWB.bound); } // if (eWB.boundKind == WildCard.SUPER) { // // } WildcardedUnresolvedType theType = (WildcardedUnresolvedType) TypeFactory.createTypeFromSignature(CharOperation.charToString(eWB.genericTypeSignature())); // if (theType.isGenericWildcard() && theType.isSuper()) theType.setLowerBound(theBound); // if (theType.isGenericWildcard() && theType.isExtends()) theType.setUpperBound(theBound); return theType; } if (binding instanceof ParameterizedTypeBinding) { if (binding instanceof RawTypeBinding) { // special case where no parameters are specified! return UnresolvedType.forRawTypeName(getName(binding)); } ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) binding; UnresolvedType[] arguments = null; if (ptb.arguments!=null) { // null can mean this is an inner type of a Parameterized Type with no bounds of its own (pr100227) arguments = new UnresolvedType[ptb.arguments.length]; for (int i = 0; i < arguments.length; i++) { arguments[i] = fromBinding(ptb.arguments[i]); } } String baseTypeSignature = null; ResolvedType baseType = getWorld().resolve(UnresolvedType.forName(getName(binding)),true); if (!baseType.isMissing()) { // can legitimately be missing if a bound refers to a type we haven't added to the world yet... // pr168044 - sometimes (whilst resolving types) we are working with 'half finished' types and so (for example) the underlying generic type for a raw type hasnt been set yet //if (!baseType.isGenericType() && arguments!=null) baseType = baseType.getGenericType(); baseTypeSignature = baseType.getErasureSignature(); } else { baseTypeSignature = UnresolvedType.forName(getName(binding)).getSignature(); } // Create an unresolved parameterized type. We can't create a resolved one as the // act of resolution here may cause recursion problems since the parameters may // be type variables that we haven't fixed up yet. if (arguments==null) arguments=new UnresolvedType[0]; String parameterizedSig = ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER+CharOperation.charToString(binding.genericTypeSignature()).substring(1); return TypeFactory.createUnresolvedParameterizedType(parameterizedSig,baseTypeSignature,arguments); } // Convert the source type binding for a generic type into a generic UnresolvedType // notice we can easily determine the type variables from the eclipse object // and we can recover the generic signature from it too - so we pass those // to the forGenericType() method. if (binding.isGenericType() && !binding.isParameterizedType() && !binding.isRawType()) { TypeVariableBinding[] tvbs = binding.typeVariables(); TypeVariable[] tVars = new TypeVariable[tvbs.length]; for (int i = 0; i < tvbs.length; i++) { TypeVariableBinding eclipseV = tvbs[i]; tVars[i] = ((TypeVariableReference)fromTypeVariableBinding(eclipseV)).getTypeVariable(); } //TODO asc generics - temporary guard.... if (!(binding instanceof SourceTypeBinding)) throw new RuntimeException("Cant get the generic sig for "+binding.debugName()); return UnresolvedType.forGenericType(getName(binding),tVars, CharOperation.charToString(((SourceTypeBinding)binding).genericSignature())); } // LocalTypeBinding have a name $Local$, we can get the real name by using the signature.... if (binding instanceof LocalTypeBinding) { LocalTypeBinding ltb = (LocalTypeBinding) binding; if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) { return UnresolvedType.forSignature(new String(binding.signature())); } else { // we're reporting a problem and don't have a resolved name for an // anonymous local type yet, report the issue on the enclosing type return UnresolvedType.forSignature(new String(ltb.enclosingType.signature())); } } return UnresolvedType.forName(getName(binding)); } /** * Some type variables refer to themselves recursively, this enables us to avoid * recursion problems. */ private static Map typeVariableBindingsInProgress = new HashMap(); /** * Convert from the eclipse form of type variable (TypeVariableBinding) to the AspectJ * form (TypeVariable). */ private UnresolvedType fromTypeVariableBinding(TypeVariableBinding aTypeVariableBinding) { // first, check for recursive call to this method for the same tvBinding if (typeVariableBindingsInProgress.containsKey(aTypeVariableBinding)) { return (UnresolvedType) typeVariableBindingsInProgress.get(aTypeVariableBinding); } // Check if its a type variable binding that we need to recover to an alias... if (typeVariablesForAliasRecovery!=null) { String aliasname = (String)typeVariablesForAliasRecovery.get(aTypeVariableBinding); if (aliasname!=null) { UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType(); ret.setTypeVariable(new TypeVariable(aliasname)); return ret; } } if (typeVariablesForThisMember.containsKey(new String(aTypeVariableBinding.sourceName))) { return (UnresolvedType)typeVariablesForThisMember.get(new String(aTypeVariableBinding.sourceName)); } // Create the UnresolvedTypeVariableReferenceType for the type variable String name = CharOperation.charToString(aTypeVariableBinding.sourceName()); UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType(); typeVariableBindingsInProgress.put(aTypeVariableBinding,ret); TypeVariable tv = new TypeVariable(name); ret.setTypeVariable(tv); // Dont set any bounds here, you'll get in a recursive mess // TODO -- what about lower bounds?? UnresolvedType superclassType = fromBinding(aTypeVariableBinding.superclass()); UnresolvedType[] superinterfaces = new UnresolvedType[aTypeVariableBinding.superInterfaces.length]; for (int i = 0; i < superinterfaces.length; i++) { superinterfaces[i] = fromBinding(aTypeVariableBinding.superInterfaces[i]); } tv.setUpperBound(superclassType); tv.setAdditionalInterfaceBounds(superinterfaces); tv.setRank(aTypeVariableBinding.rank); if (aTypeVariableBinding.declaringElement instanceof MethodBinding) { tv.setDeclaringElementKind(TypeVariable.METHOD); // tv.setDeclaringElement(fromBinding((MethodBinding)aTypeVariableBinding.declaringElement); } else { tv.setDeclaringElementKind(TypeVariable.TYPE); // // tv.setDeclaringElement(fromBinding(aTypeVariableBinding.declaringElement)); } if (aTypeVariableBinding.declaringElement instanceof MethodBinding) typeVariablesForThisMember.put(new String(aTypeVariableBinding.sourceName),ret); typeVariableBindingsInProgress.remove(aTypeVariableBinding); return ret; } public UnresolvedType[] fromBindings(TypeBinding[] bindings) { if (bindings == null) return UnresolvedType.NONE; int len = bindings.length; UnresolvedType[] ret = new UnresolvedType[len]; for (int i=0; i<len; i++) { ret[i] = fromBinding(bindings[i]); } return ret; } public static ASTNode astForLocation(IHasPosition location) { return new EmptyStatement(location.getStart(), location.getEnd()); } public Collection getDeclareParents() { return getWorld().getDeclareParents(); } public Collection getDeclareAnnotationOnTypes() { return getWorld().getDeclareAnnotationOnTypes(); } public Collection getDeclareAnnotationOnFields() { return getWorld().getDeclareAnnotationOnFields(); } public Collection getDeclareAnnotationOnMethods() { return getWorld().getDeclareAnnotationOnMethods(); } public boolean areTypeMungersFinished() { return finishedTypeMungers != null; } public void finishTypeMungers() { // make sure that type mungers are Collection ret = new ArrayList(); Collection baseTypeMungers = getWorld().getCrosscuttingMembersSet().getTypeMungers(); // XXX by Andy: why do we mix up the mungers here? it means later we know about two sets // and the late ones are a subset of the complete set? (see pr114436) // XXX by Andy removed this line finally, see pr141956 // baseTypeMungers.addAll(getWorld().getCrosscuttingMembersSet().getLateTypeMungers()); debug_mungerCount=baseTypeMungers.size(); for (Iterator i = baseTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger munger = (ConcreteTypeMunger) i.next(); EclipseTypeMunger etm = makeEclipseTypeMunger(munger); if (etm != null) ret.add(etm); } finishedTypeMungers = ret; } public EclipseTypeMunger makeEclipseTypeMunger(ConcreteTypeMunger concrete) { //System.err.println("make munger: " + concrete); //!!! can't do this if we want incremental to work right //if (concrete instanceof EclipseTypeMunger) return (EclipseTypeMunger)concrete; //System.err.println(" was not eclipse"); if (concrete.getMunger() != null && EclipseTypeMunger.supportsKind(concrete.getMunger().getKind())) { AbstractMethodDeclaration method = null; if (concrete instanceof EclipseTypeMunger) { method = ((EclipseTypeMunger)concrete).getSourceMethod(); } EclipseTypeMunger ret = new EclipseTypeMunger(this, concrete.getMunger(), concrete.getAspectType(), method); if (ret.getSourceLocation() == null) { ret.setSourceLocation(concrete.getSourceLocation()); } return ret; } else { return null; } } public Collection getTypeMungers() { //??? assert finishedTypeMungers != null return finishedTypeMungers; } public ResolvedMember makeResolvedMember(MethodBinding binding) { return makeResolvedMember(binding, binding.declaringClass); } public ResolvedMember makeResolvedMember(MethodBinding binding, Shadow.Kind shadowKind) { MemberKind memberKind = binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD; if (shadowKind == Shadow.AdviceExecution) memberKind = Member.ADVICE; return makeResolvedMember(binding,binding.declaringClass,memberKind); } /** * Conversion from a methodbinding (eclipse) to a resolvedmember (aspectj) is now done * in the scope of some type variables. Before converting the parts of a methodbinding * (params, return type) we store the type variables in this structure, then should any * component of the method binding refer to them, we grab them from the map. */ private Map typeVariablesForThisMember = new HashMap(); /** * This is a map from typevariablebindings (eclipsey things) to the names the user * originally specified in their ITD. For example if the target is 'interface I<N extends Number> {}' * and the ITD was 'public void I<X>.m(List<X> lxs) {}' then this map would contain a pointer * from the eclipse type 'N extends Number' to the letter 'X'. */ private Map typeVariablesForAliasRecovery; /** * Construct a resolvedmember from a methodbinding. The supplied map tells us about any * typevariablebindings that replaced typevariables whilst the compiler was resolving types - * this only happens if it is a generic itd that shares type variables with its target type. */ public ResolvedMember makeResolvedMemberForITD(MethodBinding binding,TypeBinding declaringType, Map /*TypeVariableBinding > original alias name*/ recoveryAliases) { ResolvedMember result = null; try { typeVariablesForAliasRecovery = recoveryAliases; result = makeResolvedMember(binding,declaringType); } finally { typeVariablesForAliasRecovery = null; } return result; } public ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType) { return makeResolvedMember(binding,declaringType, binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD); } public ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType, MemberKind memberKind) { //System.err.println("member for: " + binding + ", " + new String(binding.declaringClass.sourceName)); // Convert the type variables and store them UnresolvedType[] ajTypeRefs = null; typeVariablesForThisMember.clear(); // This is the set of type variables available whilst building the resolved member... if (binding.typeVariables!=null) { ajTypeRefs = new UnresolvedType[binding.typeVariables.length]; for (int i = 0; i < binding.typeVariables.length; i++) { ajTypeRefs[i] = fromBinding(binding.typeVariables[i]); typeVariablesForThisMember.put(new String(binding.typeVariables[i].sourceName),/*new Integer(binding.typeVariables[i].rank),*/ajTypeRefs[i]); } } // AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map ResolvedType realDeclaringType = world.resolve(fromBinding(declaringType)); if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType(); ResolvedMemberImpl ret = new EclipseResolvedMember(binding, memberKind, realDeclaringType, binding.modifiers, fromBinding(binding.returnType), new String(binding.selector), fromBindings(binding.parameters), fromBindings(binding.thrownExceptions),this ); if (binding.isVarargs()) { ret.setVarargsMethod(); } if (ajTypeRefs!=null) { TypeVariable[] tVars = new TypeVariable[ajTypeRefs.length]; for (int i=0;i<ajTypeRefs.length;i++) { tVars[i]=((TypeVariableReference)ajTypeRefs[i]).getTypeVariable(); } ret.setTypeVariables(tVars); } typeVariablesForThisMember.clear(); ret.resolve(world); return ret; } public ResolvedMember makeResolvedMember(FieldBinding binding) { return makeResolvedMember(binding, binding.declaringClass); } public ResolvedMember makeResolvedMember(FieldBinding binding, TypeBinding receiverType) { // AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map ResolvedType realDeclaringType = world.resolve(fromBinding(receiverType)); if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType(); ResolvedMemberImpl ret = new EclipseResolvedMember(binding, Member.FIELD, realDeclaringType, binding.modifiers, world.resolve(fromBinding(binding.type)), new String(binding.name), UnresolvedType.NONE); return ret; } public TypeBinding makeTypeBinding(UnresolvedType typeX) { TypeBinding ret = null; // looking up type variables can get us into trouble if (!typeX.isTypeVariableReference() && !isParameterizedWithTypeVariables(typeX)) { if (typeX.isRawType()) { ret = (TypeBinding)rawTypeXToBinding.get(typeX); } else { ret = (TypeBinding)typexToBinding.get(typeX); } } if (ret == null) { ret = makeTypeBinding1(typeX); if (!(typeX instanceof BoundedReferenceType) && !(typeX instanceof UnresolvedTypeVariableReferenceType) ) { if (typeX.isRawType()) { rawTypeXToBinding.put(typeX,ret); } else { typexToBinding.put(typeX, ret); } } } if (ret == null) { System.out.println("can't find: " + typeX); } return ret; } // return true if this is type variables are in the type arguments private boolean isParameterizedWithTypeVariables(UnresolvedType typeX) { if (!typeX.isParameterizedType()) return false; UnresolvedType[] typeArguments = typeX.getTypeParameters(); if (typeArguments!=null) { for (int i = 0; i < typeArguments.length; i++) { if (typeArguments[i].isTypeVariableReference()) return true; } } return false; } // When converting a parameterized type from our world to the eclipse world, these get set so that // resolution of the type parameters may known in what context it is occurring (pr114744) private ReferenceBinding baseTypeForParameterizedType; private int indexOfTypeParameterBeingConverted; private TypeBinding makeTypeBinding1(UnresolvedType typeX) { if (typeX.isPrimitiveType()) { if (typeX == ResolvedType.BOOLEAN) return TypeBinding.BOOLEAN; if (typeX == ResolvedType.BYTE) return TypeBinding.BYTE; if (typeX == ResolvedType.CHAR) return TypeBinding.CHAR; if (typeX == ResolvedType.DOUBLE) return TypeBinding.DOUBLE; if (typeX == ResolvedType.FLOAT) return TypeBinding.FLOAT; if (typeX == ResolvedType.INT) return TypeBinding.INT; if (typeX == ResolvedType.LONG) return TypeBinding.LONG; if (typeX == ResolvedType.SHORT) return TypeBinding.SHORT; if (typeX == ResolvedType.VOID) return TypeBinding.VOID; throw new RuntimeException("weird primitive type " + typeX); } else if (typeX.isArray()) { int dim = 0; while (typeX.isArray()) { dim++; typeX = typeX.getComponentType(); } return lookupEnvironment.createArrayType(makeTypeBinding(typeX), dim); } else if (typeX.isParameterizedType()) { // Converting back to a binding from a UnresolvedType UnresolvedType[] typeParameters = typeX.getTypeParameters(); ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName()); TypeBinding[] argumentBindings = new TypeBinding[typeParameters.length]; baseTypeForParameterizedType = baseTypeBinding; for (int i = 0; i < argumentBindings.length; i++) { indexOfTypeParameterBeingConverted = i; argumentBindings[i] = makeTypeBinding(typeParameters[i]); } indexOfTypeParameterBeingConverted = 0; baseTypeForParameterizedType = null; ParameterizedTypeBinding ptb = lookupEnvironment.createParameterizedType(baseTypeBinding,argumentBindings,baseTypeBinding.enclosingType()); return ptb; } else if (typeX.isTypeVariableReference()) { // return makeTypeVariableBinding((TypeVariableReference)typeX); return makeTypeVariableBindingFromAJTypeVariable(((TypeVariableReference)typeX).getTypeVariable()); } else if (typeX.isRawType()) { ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName()); RawTypeBinding rtb = lookupEnvironment.createRawType(baseTypeBinding,baseTypeBinding.enclosingType()); return rtb; } else if (typeX.isGenericWildcard()) { // translate from boundedreferencetype to WildcardBinding BoundedReferenceType brt = (BoundedReferenceType)typeX; // Work out 'kind' for the WildcardBinding int boundkind = Wildcard.UNBOUND; TypeBinding bound = null; if (brt.isExtends()) { boundkind = Wildcard.EXTENDS; bound = makeTypeBinding(brt.getUpperBound()); } else if (brt.isSuper()) { boundkind = Wildcard.SUPER; bound = makeTypeBinding(brt.getLowerBound()); } TypeBinding[] otherBounds = null; if (brt.getAdditionalBounds()!=null && brt.getAdditionalBounds().length!=0) otherBounds = makeTypeBindings(brt.getAdditionalBounds()); WildcardBinding wb = lookupEnvironment.createWildcard(baseTypeForParameterizedType,indexOfTypeParameterBeingConverted,bound,otherBounds,boundkind); return wb; } else { return lookupBinding(typeX.getName()); } } private ReferenceBinding lookupBinding(String sname) { char[][] name = CharOperation.splitOn('.', sname.toCharArray()); ReferenceBinding rb = lookupEnvironment.getType(name); return rb; } public TypeBinding[] makeTypeBindings(UnresolvedType[] types) { int len = types.length; TypeBinding[] ret = new TypeBinding[len]; for (int i = 0; i < len; i++) { ret[i] = makeTypeBinding(types[i]); } return ret; } // just like the code above except it returns an array of ReferenceBindings private ReferenceBinding[] makeReferenceBindings(UnresolvedType[] types) { int len = types.length; ReferenceBinding[] ret = new ReferenceBinding[len]; for (int i = 0; i < len; i++) { ret[i] = (ReferenceBinding)makeTypeBinding(types[i]); } return ret; } // field related public FieldBinding makeFieldBinding(NewFieldTypeMunger nftm) { return internalMakeFieldBinding(nftm.getSignature(),nftm.getTypeVariableAliases()); } /** * Convert a resolvedmember into an eclipse field binding */ public FieldBinding makeFieldBinding(ResolvedMember member,List aliases) { return internalMakeFieldBinding(member,aliases); } /** * Convert a resolvedmember into an eclipse field binding */ public FieldBinding makeFieldBinding(ResolvedMember member) { return internalMakeFieldBinding(member,null); } // OPTIMIZE tidy this up, must be able to optimize for the synthetic case, if we passed in the binding for the declaring type, that would make things easier /** * Build a new Eclipse SyntheticFieldBinding for an AspectJ ResolvedMember. */ public SyntheticFieldBinding createSyntheticFieldBinding(SourceTypeBinding owningType,ResolvedMember member) { SyntheticFieldBinding sfb = new SyntheticFieldBinding(member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), member.getModifiers() | Flags.AccSynthetic, owningType, Constant.NotAConstant, -1); // index filled in later owningType.addSyntheticField(sfb); return sfb; } /** * Take a normal AJ member and convert it into an eclipse fieldBinding. * Taking into account any aliases that it may include due to being * a generic itd. Any aliases are put into the typeVariableToBinding * map so that they will be substituted as appropriate in the returned * fieldbinding. */ public FieldBinding internalMakeFieldBinding(ResolvedMember member,List aliases) { typeVariableToTypeBinding.clear(); TypeVariableBinding[] tvbs = null; ReferenceBinding declaringType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType()); // If there are aliases, place them in the map if (aliases!=null && aliases.size()>0) { int i =0; for (Iterator iter = aliases.iterator(); iter.hasNext();) { String element = (String) iter.next(); typeVariableToTypeBinding.put(element,declaringType.typeVariables()[i++]); } } currentType = declaringType; FieldBinding fb = null; if (member.getName().startsWith(NameMangler.PREFIX)) { fb = new SyntheticFieldBinding(member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), member.getModifiers() | Flags.AccSynthetic, currentType, Constant.NotAConstant,-1); // index filled in later } else { fb = new FieldBinding(member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), member.getModifiers(), currentType, Constant.NotAConstant); } typeVariableToTypeBinding.clear(); currentType = null; if (member.getName().startsWith(NameMangler.PREFIX)) { fb.modifiers |= Flags.AccSynthetic; } return fb; } private ReferenceBinding currentType = null; // method binding related public MethodBinding makeMethodBinding(NewMethodTypeMunger nmtm) { return internalMakeMethodBinding(nmtm.getSignature(),nmtm.getTypeVariableAliases()); } /** * Convert a resolvedmember into an eclipse method binding. */ public MethodBinding makeMethodBinding(ResolvedMember member,List aliases) { return internalMakeMethodBinding(member,aliases); } /** * Creates a method binding for a resolvedmember taking into account type variable aliases - * this variant can take an aliasTargetType and should be used when the alias target type * cannot be retrieved from the resolvedmember. */ public MethodBinding makeMethodBinding(ResolvedMember member,List aliases,UnresolvedType aliasTargetType) { return internalMakeMethodBinding(member,aliases,aliasTargetType); } /** * Convert a resolvedmember into an eclipse method binding. */ public MethodBinding makeMethodBinding(ResolvedMember member) { return internalMakeMethodBinding(member,null); // there are no aliases } public MethodBinding internalMakeMethodBinding(ResolvedMember member,List aliases) { return internalMakeMethodBinding(member,aliases,member.getDeclaringType()); } /** * Take a normal AJ member and convert it into an eclipse methodBinding. * Taking into account any aliases that it may include due to being a * generic ITD. Any aliases are put into the typeVariableToBinding * map so that they will be substituted as appropriate in the returned * methodbinding */ public MethodBinding internalMakeMethodBinding(ResolvedMember member,List aliases,UnresolvedType aliasTargetType) { typeVariableToTypeBinding.clear(); TypeVariableBinding[] tvbs = null; if (member.getTypeVariables()!=null) { if (member.getTypeVariables().length==0) { tvbs = Binding.NO_TYPE_VARIABLES; } else { tvbs = makeTypeVariableBindingsFromAJTypeVariables(member.getTypeVariables()); // QQQ do we need to bother fixing up the declaring element here? } } ReferenceBinding declaringType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType()); // If there are aliases, place them in the map if (aliases!=null && aliases.size()!=0) { int i=0; ReferenceBinding aliasTarget = (ReferenceBinding)makeTypeBinding(aliasTargetType); if (aliasTarget.isRawType()) { aliasTarget = ((RawTypeBinding) aliasTarget).genericType(); } for (Iterator iter = aliases.iterator(); iter.hasNext();) { String element = (String) iter.next(); typeVariableToTypeBinding.put(element,aliasTarget.typeVariables()[i++]); } } currentType = declaringType; MethodBinding mb = new MethodBinding(member.getModifiers(), member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), makeTypeBindings(member.getParameterTypes()), makeReferenceBindings(member.getExceptions()), declaringType); if (tvbs!=null) mb.typeVariables = tvbs; typeVariableToTypeBinding.clear(); currentType = null; if (NameMangler.isSyntheticMethod(member.getName(), true)) { mb.modifiers |= Flags.AccSynthetic; } return mb; } /** * Convert a bunch of type variables in one go, from AspectJ form to Eclipse form. */ // private TypeVariableBinding[] makeTypeVariableBindings(UnresolvedType[] typeVariables) { // int len = typeVariables.length; // TypeVariableBinding[] ret = new TypeVariableBinding[len]; // for (int i = 0; i < len; i++) { // ret[i] = makeTypeVariableBinding((TypeVariableReference)typeVariables[i]); // } // return ret; // } private TypeVariableBinding[] makeTypeVariableBindingsFromAJTypeVariables(TypeVariable[] typeVariables) { int len = typeVariables.length; TypeVariableBinding[] ret = new TypeVariableBinding[len]; for (int i = 0; i < len; i++) { ret[i] = makeTypeVariableBindingFromAJTypeVariable(typeVariables[i]); } return ret; } // only accessed through private methods in this class. Ensures all type variables we encounter // map back to the same type binding - this is important later when Eclipse code is processing // a methodbinding trying to come up with possible bindings for the type variables. // key is currently the name of the type variable...is that ok? private Map typeVariableToTypeBinding = new HashMap(); /** * Converts from an TypeVariableReference to a TypeVariableBinding. A TypeVariableReference * in AspectJ world holds a TypeVariable and it is this type variable that is converted * to the TypeVariableBinding. */ private TypeVariableBinding makeTypeVariableBinding(TypeVariableReference tvReference) { TypeVariable tv = tvReference.getTypeVariable(); TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tv.getName()); if (currentType!=null) { TypeVariableBinding tvb = currentType.getTypeVariable(tv.getName().toCharArray()); if (tvb!=null) return tvb; } if (tvBinding==null) { Binding declaringElement = null; // this will cause an infinite loop or NPE... not required yet luckily. // if (tVar.getDeclaringElement() instanceof Member) { // declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement()); // } else { // declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement()); // } tvBinding = new TypeVariableBinding(tv.getName().toCharArray(),null,tv.getRank()); typeVariableToTypeBinding.put(tv.getName(),tvBinding); tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tv.getUpperBound()); tvBinding.firstBound=(ReferenceBinding)makeTypeBinding(tv.getFirstBound()); if (tv.getAdditionalInterfaceBounds()==null) { tvBinding.superInterfaces=TypeVariableBinding.NO_SUPERINTERFACES; } else { TypeBinding tbs[] = makeTypeBindings(tv.getAdditionalInterfaceBounds()); ReferenceBinding[] rbs= new ReferenceBinding[tbs.length]; for (int i = 0; i < tbs.length; i++) { rbs[i] = (ReferenceBinding)tbs[i]; } tvBinding.superInterfaces=rbs; } } return tvBinding; } private TypeVariableBinding makeTypeVariableBindingFromAJTypeVariable(TypeVariable tv) { TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tv.getName()); if (currentType!=null) { TypeVariableBinding tvb = currentType.getTypeVariable(tv.getName().toCharArray()); if (tvb!=null) return tvb; } if (tvBinding==null) { Binding declaringElement = null; // this will cause an infinite loop or NPE... not required yet luckily. // if (tVar.getDeclaringElement() instanceof Member) { // declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement()); // } else { // declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement()); // } tvBinding = new TypeVariableBinding(tv.getName().toCharArray(),declaringElement,tv.getRank()); typeVariableToTypeBinding.put(tv.getName(),tvBinding); tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tv.getUpperBound()); tvBinding.firstBound=(ReferenceBinding)makeTypeBinding(tv.getFirstBound()); if (tv.getAdditionalInterfaceBounds()==null) { tvBinding.superInterfaces=TypeVariableBinding.NO_SUPERINTERFACES; } else { TypeBinding tbs[] = makeTypeBindings(tv.getAdditionalInterfaceBounds()); ReferenceBinding[] rbs= new ReferenceBinding[tbs.length]; for (int i = 0; i < tbs.length; i++) { rbs[i] = (ReferenceBinding)tbs[i]; } tvBinding.superInterfaces=rbs; } } return tvBinding; } public MethodBinding makeMethodBindingForCall(Member member) { return new MethodBinding(member.getModifiers() & ~ Modifier.INTERFACE, member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), makeTypeBindings(member.getParameterTypes()), new ReferenceBinding[0], (ReferenceBinding)makeTypeBinding(member.getDeclaringType())); } public void finishedCompilationUnit(CompilationUnitDeclaration unit) { if ((buildManager != null) && buildManager.doGenerateModel()) { AjBuildManager.getAsmHierarchyBuilder().buildStructureForCompilationUnit(unit, buildManager.getStructureModel(), buildManager.buildConfig); } } public void addTypeBinding(TypeBinding binding) { typexToBinding.put(fromBinding(binding), binding); } public void addTypeBindingAndStoreInWorld(TypeBinding binding) { UnresolvedType ut = fromBinding(binding); typexToBinding.put(ut, binding); world.lookupOrCreateName(ut); } public Shadow makeShadow(ASTNode location, ReferenceContext context) { return EclipseShadow.makeShadow(this, location, context); } public Shadow makeShadow(ReferenceContext context) { return EclipseShadow.makeShadow(this, (ASTNode) context, context); } public void addSourceTypeBinding(SourceTypeBinding binding, CompilationUnitDeclaration unit) { TypeDeclaration decl = binding.scope.referenceContext; // Deal with the raw/basic type to give us an entry in the world type map UnresolvedType simpleTx = null; if (binding.isGenericType()) { simpleTx = UnresolvedType.forRawTypeName(getName(binding)); } else if (binding.isLocalType()) { LocalTypeBinding ltb = (LocalTypeBinding) binding; if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) { simpleTx = UnresolvedType.forSignature(new String(binding.signature())); } else { simpleTx = UnresolvedType.forName(getName(binding)); } }else { simpleTx = UnresolvedType.forName(getName(binding)); } ReferenceType name = getWorld().lookupOrCreateName(simpleTx); // A type can change from simple > generic > simple across a set of compiles. We need // to ensure the entry in the typemap is promoted and demoted correctly. The call // to setGenericType() below promotes a simple to a raw. This call demotes it back // to simple // pr125405 if (!binding.isRawType() && !binding.isGenericType() && name.getTypekind()==TypeKind.RAW) { name.demoteToSimpleType(); } EclipseSourceType t = new EclipseSourceType(name, this, binding, decl, unit); // For generics, go a bit further - build a typex for the generic type // give it the same delegate and link it to the raw type if (binding.isGenericType()) { UnresolvedType complexTx = fromBinding(binding); // fully aware of any generics info ResolvedType cName = world.resolve(complexTx,true); ReferenceType complexName = null; if (!cName.isMissing()) { complexName = (ReferenceType) cName; complexName = (ReferenceType) complexName.getGenericType(); if (complexName == null) complexName = new ReferenceType(complexTx,world); } else { complexName = new ReferenceType(complexTx,world); } name.setGenericType(complexName); complexName.setDelegate(t); } name.setDelegate(t); if (decl instanceof AspectDeclaration) { ((AspectDeclaration)decl).typeX = name; ((AspectDeclaration)decl).concreteName = t; } ReferenceBinding[] memberTypes = binding.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { addSourceTypeBinding((SourceTypeBinding) memberTypes[i], unit); } } // XXX this doesn't feel like it belongs here, but it breaks a hard dependency on // exposing AjBuildManager (needed by AspectDeclaration). public boolean isXSerializableAspects() { return xSerializableAspects; } public ResolvedMember fromBinding(MethodBinding binding) { return new ResolvedMemberImpl(Member.METHOD,fromBinding(binding.declaringClass),binding.modifiers, fromBinding(binding.returnType),CharOperation.charToString(binding.selector),fromBindings(binding.parameters)); } public TypeVariableDeclaringElement fromBinding(Binding declaringElement) { if (declaringElement instanceof TypeBinding) { return fromBinding(((TypeBinding)declaringElement)); } else { return fromBinding((MethodBinding)declaringElement); } } public void cleanup() { this.typexToBinding.clear(); this.rawTypeXToBinding.clear(); this.finishedTypeMungers = null; } public void minicleanup() { this.typexToBinding.clear(); this.rawTypeXToBinding.clear(); } }
155,347
Bug 155347 NPE during compilation of class file with pointcuts
I commented out a static nested aspect inside a class to let me do a rename refactoring in Eclipse. This results in the following exception, which even a full rebuild won't fix. The class does have pointcut definitions inside of it. Commenting those out avoids the problem (though it caused other syntax errors...) java.lang.ArrayIndexOutOfBoundsException at org.aspectj.weaver.patterns.IfPointcut.findResidueInternal(IfPointcut.java:186) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:269) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:93) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:269) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:93) at or ... ses when weaving when batch building BuildConfig[C:\devel\glassbox\.metadata\.plugins\org.eclipse.ajdt.core\glassboxAgent.generated.lst] #Files=210
resolved fixed
248962b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-06-10T20:48:36Z"
"2006-08-27T23:06:40Z"
weaver/src/org/aspectj/weaver/patterns/IfPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur if() implementation for @AJ style * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.bridge.IMessage; import org.aspectj.lang.JoinPoint; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Expr; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; public class IfPointcut extends Pointcut { public ResolvedMember testMethod; public int extraParameterFlags; /** * A token source dump that looks like a pointcut (but is NOT parseable at all - just here to help debugging etc) */ private String enclosingPointcutHint; public Pointcut residueSource; int baseArgsCount; //XXX some way to compute args public IfPointcut(ResolvedMember testMethod, int extraParameterFlags) { this.testMethod = testMethod; this.extraParameterFlags = extraParameterFlags; this.pointcutKind = IF; this.enclosingPointcutHint = null; } /** * No-arg constructor for @AJ style, where the if() body is actually the @Pointcut annotated method */ public IfPointcut(String enclosingPointcutHint) { this.pointcutKind = IF; this.enclosingPointcutHint = enclosingPointcutHint; this.testMethod = null;// resolved during concretize this.extraParameterFlags = -1;//allows to keep track of the @Aj style } public int couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS_BITS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { //??? this is not maximally efficient return FuzzyBoolean.MAYBE; } public boolean alwaysFalse() { return false; } public boolean alwaysTrue() { return false; } // enh 76055 public Pointcut getResidueSource() { return residueSource; } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.IF); s.writeBoolean(testMethod != null); // do we have a test method? if (testMethod != null) testMethod.write(s); s.writeByte(extraParameterFlags); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { boolean hasTestMethod = s.readBoolean(); ResolvedMember resolvedTestMethod = null; if (hasTestMethod) { // should always have a test method unless @AJ style resolvedTestMethod = ResolvedMemberImpl.readResolvedMember(s, context); } IfPointcut ret = new IfPointcut(resolvedTestMethod, s.readByte()); ret.readLocation(context, s); return ret; } public void resolveBindings(IScope scope, Bindings bindings) { //??? all we need is good error messages in here in cflow contexts } public boolean equals(Object other) { if (!(other instanceof IfPointcut)) return false; IfPointcut o = (IfPointcut)other; if (o.testMethod==null) return (this.testMethod==null); return o.testMethod.equals(this.testMethod); } public int hashCode() { int result = 17; result = 37*result + testMethod.hashCode(); return result; } public String toString() { if (extraParameterFlags < 0) { //@AJ style return "if()"; } else { return "if(" + testMethod + ")";//FIXME AV - bad, this makes it unparsable. Perhaps we can use if() for code style behind the scene! } } //??? The implementation of name binding and type checking in if PCDs is very convoluted // There has to be a better way... private boolean findingResidue = false; // Similar to lastMatchedShadowId - but only for if PCDs. private int ifLastMatchedShadowId; private Test ifLastMatchedShadowResidue; /** * At each shadow that matched, the residue can be different. */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (findingResidue) return Literal.TRUE; findingResidue = true; try { // Have we already been asked this question? if (shadow.shadowId == ifLastMatchedShadowId) return ifLastMatchedShadowResidue; Test ret = Literal.TRUE; List args = new ArrayList(); // code style if (extraParameterFlags >= 0) { // If there are no args to sort out, don't bother with the recursive call if (baseArgsCount > 0) { ExposedState myState = new ExposedState(baseArgsCount); //??? we throw out the test that comes from this walk. All we want here // is bindings for the arguments residueSource.findResidue(shadow, myState); // pr118149 // It is possible for vars in myState (which would normally be set // in the call to residueSource.findResidue) to not be set (be null) // in an Or pointcut with if expressions in both branches, and where // one branch is known statically to not match. In this situation we // simply return Test. for (int i=0; i < baseArgsCount; i++) { Var v = myState.get(i); if (v == null) continue; // pr118149 args.add(v); ret = Test.makeAnd(ret, Test.makeInstanceof(v, testMethod.getParameterTypes()[i].resolve(shadow.getIWorld()))); } } // handle thisJoinPoint parameters if ((extraParameterFlags & Advice.ThisJoinPoint) != 0) { args.add(shadow.getThisJoinPointVar()); } if ((extraParameterFlags & Advice.ThisJoinPointStaticPart) != 0) { args.add(shadow.getThisJoinPointStaticPartVar()); } if ((extraParameterFlags & Advice.ThisEnclosingJoinPointStaticPart) != 0) { args.add(shadow.getThisEnclosingJoinPointStaticPartVar()); } } else { // @style is slightly different int currentStateIndex = 0; //FIXME AV - "args(jp)" test(jp, thejp) will fail here for (int i = 0; i < testMethod.getParameterTypes().length; i++) { String argSignature = testMethod.getParameterTypes()[i].getSignature(); if (AjcMemberMaker.TYPEX_JOINPOINT.getSignature().equals(argSignature)) { args.add(shadow.getThisJoinPointVar()); } else if (AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.getSignature().equals(argSignature)) { args.add(shadow.getThisJoinPointVar()); } else if (AjcMemberMaker.TYPEX_STATICJOINPOINT.getSignature().equals(argSignature)) { args.add(shadow.getThisJoinPointStaticPartVar()); } else if (AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.getSignature().equals(argSignature)) { args.add(shadow.getThisEnclosingJoinPointStaticPartVar()); } else { // we don't use i as JoinPoint.* can be anywhere in the signature in @style Var v = state.get(currentStateIndex++); args.add(v); ret = Test.makeAnd(ret, Test.makeInstanceof(v, testMethod.getParameterTypes()[i].resolve(shadow.getIWorld()))); } } } ret = Test.makeAnd(ret, Test.makeCall(testMethod, (Expr[])args.toArray(new Expr[args.size()]))); // Remember... ifLastMatchedShadowId = shadow.shadowId; ifLastMatchedShadowResidue = ret; return ret; } finally { findingResidue = false; } } // amc - the only reason this override seems to be here is to stop the copy, but // that can be prevented by overriding shouldCopyLocationForConcretization, // allowing me to make the method final in Pointcut. // public Pointcut concretize(ResolvedType inAspect, IntMap bindings) { // return this.concretize1(inAspect, bindings); // } protected boolean shouldCopyLocationForConcretize() { return false; } private IfPointcut partiallyConcretized = null; public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { //System.err.println("concretize: " + this + " already: " + partiallyConcretized); if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.IF_IN_DECLARE), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } if (partiallyConcretized != null) { return partiallyConcretized; } final IfPointcut ret; if (extraParameterFlags < 0 && testMethod == null) { // @AJ style, we need to find the testMethod in the aspect defining the "if()" enclosing pointcut ResolvedPointcutDefinition def = bindings.peekEnclosingDefinition(); if (def != null) { ResolvedType aspect = inAspect.getWorld().resolve(def.getDeclaringType()); for (Iterator memberIter = aspect.getMethods(); memberIter.hasNext();) { ResolvedMember method = (ResolvedMember) memberIter.next(); if (def.getName().equals(method.getName()) && def.getParameterTypes().length == method.getParameterTypes().length) { boolean sameSig = true; for (int j = 0; j < method.getParameterTypes().length; j++) { UnresolvedType argJ = method.getParameterTypes()[j]; if (!argJ.equals(def.getParameterTypes()[j])) { sameSig = false; break; } } if (sameSig) { testMethod = method; break; } } } if (testMethod == null) { inAspect.getWorld().showMessage( IMessage.ERROR, "Cannot find if() body from '" + def.toString() + "' for '" + enclosingPointcutHint + "'", this.getSourceLocation(), null ); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } } else { testMethod = inAspect.getWorld().resolve(bindings.getAdviceSignature()); } ret = new IfPointcut(enclosingPointcutHint); ret.testMethod = testMethod; } else { ret = new IfPointcut(testMethod, extraParameterFlags); } ret.copyLocationFrom(this); partiallyConcretized = ret; // It is possible to directly code your pointcut expression in a per clause // rather than defining a pointcut declaration and referencing it in your // per clause. If you do this, we have problems (bug #62458). For now, // let's police that you are trying to code a pointcut in a per clause and // put out a compiler error. if (bindings.directlyInAdvice() && bindings.getEnclosingAdvice()==null) { // Assumption: if() is in a per clause if we say we are directly in advice // but we have no enclosing advice. inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.IF_IN_PERCLAUSE), this.getSourceLocation(),null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } if (bindings.directlyInAdvice()) { ShadowMunger advice = bindings.getEnclosingAdvice(); if (advice instanceof Advice) { ret.baseArgsCount = ((Advice)advice).getBaseParameterCount(); } else { ret.baseArgsCount = 0; } ret.residueSource = advice.getPointcut().concretize(inAspect, inAspect, ret.baseArgsCount, advice); } else { ResolvedPointcutDefinition def = bindings.peekEnclosingDefinition(); if (def == CflowPointcut.CFLOW_MARKER) { inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.IF_LEXICALLY_IN_CFLOW), getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } ret.baseArgsCount = def.getParameterTypes().length; // for @style, we have implicit binding for JoinPoint.* things //FIXME AV - will lead to failure for "args(jp)" test(jp, thejp) / see args() implementation if (ret.extraParameterFlags < 0) { ret.baseArgsCount = 0; for (int i = 0; i < testMethod.getParameterTypes().length; i++) { String argSignature = testMethod.getParameterTypes()[i].getSignature(); if (AjcMemberMaker.TYPEX_JOINPOINT.getSignature().equals(argSignature) || AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.getSignature().equals(argSignature) || AjcMemberMaker.TYPEX_STATICJOINPOINT.getSignature().equals(argSignature) || AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.getSignature().equals(argSignature)) { ; } else { ret.baseArgsCount++; } } } IntMap newBindings = IntMap.idMap(ret.baseArgsCount); newBindings.copyContext(bindings); ret.residueSource = def.getPointcut().concretize(inAspect, declaringType, newBindings); } return ret; } // we can't touch "if" methods public Pointcut parameterizeWith(Map typeVariableMap,World w) { return this; } // public static Pointcut MatchesNothing = new MatchesNothingPointcut(); // ??? there could possibly be some good optimizations to be done at this point public static IfPointcut makeIfFalsePointcut(State state) { IfPointcut ret = new IfFalsePointcut(); ret.state = state; return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public static class IfFalsePointcut extends IfPointcut { public IfFalsePointcut() { super(null,0); this.pointcutKind = Pointcut.IF_FALSE; } public int couldMatchKinds() { return Shadow.NO_SHADOW_KINDS_BITS; } public boolean alwaysFalse() { return true; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return Literal.FALSE; // can only get here if an earlier error occurred } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.NO; } protected FuzzyBoolean matchInternal(Shadow shadow) { return FuzzyBoolean.NO; } public FuzzyBoolean match(JoinPoint.StaticPart jpsp) { return FuzzyBoolean.NO; } public void resolveBindings(IScope scope, Bindings bindings) { } public void postRead(ResolvedType enclosingType) { } public Pointcut concretize1( ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.IF_IN_DECLARE), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } return makeIfFalsePointcut(state); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.IF_FALSE); } public int hashCode() { int result = 17; return result; } public String toString() { return "if(false)"; } } public static IfPointcut makeIfTruePointcut(State state) { IfPointcut ret = new IfTruePointcut(); ret.state = state; return ret; } public static class IfTruePointcut extends IfPointcut { public IfTruePointcut() { super(null,0); this.pointcutKind = Pointcut.IF_TRUE; } public boolean alwaysTrue() { return true; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return Literal.TRUE; // can only get here if an earlier error occurred } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.YES; } protected FuzzyBoolean matchInternal(Shadow shadow) { return FuzzyBoolean.YES; } public FuzzyBoolean match(JoinPoint.StaticPart jpsp) { return FuzzyBoolean.YES; } public void resolveBindings(IScope scope, Bindings bindings) { } public void postRead(ResolvedType enclosingType) { } public Pointcut concretize1( ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.IF_IN_DECLARE), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } return makeIfTruePointcut(state); } public void write(DataOutputStream s) throws IOException { s.writeByte(IF_TRUE); } public int hashCode() { int result = 37; return result; } public String toString() { return "if(true)"; } } }
203,367
Bug 203367 ITD of interface on generic type; can't match calls to methods on interface+
Build ID: I20070621-1340 Steps To Reproduce: package bug; // I used a "bug" package under the "src" source folder. public aspect CantMatchOnInterfaceIntroducedToGenericClass { public static interface Marker {} public static class NonGenericClass { public void doit(String msg) { System.out.println("doit(): msg = "+msg); } } public static class GenericClass<T> { public void doit(T t) { System.out.println("doit<T>(): t = "+t); } } declare parents: NonGenericClass implements Marker; declare parents: GenericClass implements Marker; pointcut nonGenericCall(): call (void NonGenericClass.doit(..)); pointcut genericCall(): call (void GenericClass.doit(..)); pointcut markerCall(): call (void Marker+.doit(..)); before(): nonGenericCall() { System.out.println("nonGenericCall: "+thisJoinPointStaticPart); } before(): genericCall() { System.out.println("genericCall: "+thisJoinPointStaticPart); } before(): markerCall() { System.out.println("markerCall: "+thisJoinPointStaticPart); } public static void main(String args[]) { new NonGenericClass().doit("message1"); new GenericClass<Integer>().doit(new Integer(2)); } } More information: The code pasted in the "steps" demonstrates the bug.
resolved fixed
11ebdd8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-06-17T04:02:05Z"
"2007-09-13T21:46:40Z"
tests/bugs161/pr203367/CantMatchOnInterfaceIntroducedToGenericClass.java
203,367
Bug 203367 ITD of interface on generic type; can't match calls to methods on interface+
Build ID: I20070621-1340 Steps To Reproduce: package bug; // I used a "bug" package under the "src" source folder. public aspect CantMatchOnInterfaceIntroducedToGenericClass { public static interface Marker {} public static class NonGenericClass { public void doit(String msg) { System.out.println("doit(): msg = "+msg); } } public static class GenericClass<T> { public void doit(T t) { System.out.println("doit<T>(): t = "+t); } } declare parents: NonGenericClass implements Marker; declare parents: GenericClass implements Marker; pointcut nonGenericCall(): call (void NonGenericClass.doit(..)); pointcut genericCall(): call (void GenericClass.doit(..)); pointcut markerCall(): call (void Marker+.doit(..)); before(): nonGenericCall() { System.out.println("nonGenericCall: "+thisJoinPointStaticPart); } before(): genericCall() { System.out.println("genericCall: "+thisJoinPointStaticPart); } before(): markerCall() { System.out.println("markerCall: "+thisJoinPointStaticPart); } public static void main(String args[]) { new NonGenericClass().doit("message1"); new GenericClass<Integer>().doit(new Integer(2)); } } More information: The code pasted in the "steps" demonstrates the bug.
resolved fixed
11ebdd8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-06-17T04:02:05Z"
"2007-09-13T21:46:40Z"
tests/src/org/aspectj/systemtest/ajc161/Ajc161Tests.java
/******************************************************************************* * Copyright (c) 2008 Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc161; import java.io.File; import java.util.Iterator; import java.util.Set; import junit.framework.Test; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IRelationshipMap; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc161Tests extends org.aspectj.testing.XMLBasedAjcTestCase { // AspectJ1.6.1 // public void testSuperItds_pr134425() { runTest("super itds"); } public void testSuperItds_pr198196_1() { runTest("super itds - 2"); } public void testSuperItds_pr198196_2() { runTest("super itds - 3"); } public void testSuperItds_pr198196_3() { runTest("super itds - 4"); } // public void testDeow_pr237381_1() { runTest("ataspectj deow - 1"); } // public void testDeow_pr237381_2() { runTest("ataspectj deow - 2"); } public void testRunningBrokenCode_pr102733_2() { runTest("running broken code - 2"); } public void testRunningBrokenCode_pr102733() { runTest("running broken code"); } public void testErrorOnNonabstractGenericAtAspectJAspect_pr168982() { runTest("error on non-abstract generic ataspectj aspect");} public void testIgnoringTypeLevelSuppression_pr234933() { runTest("ignoring type level suppress");} public void testDuplicateMethodSignature_pr223226_2() { runTest("duplicate method signature - 2"); } public void testDuplicateMethodSignature_pr223226() { runTest("duplicate method signature"); } public void testProtectedMethodsAroundAdvice_pr197719_2() { runTest("protected methods and around advice - again - 2");} public void testProtectedMethodsAroundAdvice_pr197719() { runTest("protected methods and around advice - again");} public void testProtectedMethodsAroundAdvice_pr230075() { runTest("protected methods and around advice");} public void testFinalStringsAnnotationPointcut_pr174385() { runTest("static strings in annotation pointcuts");} public void testComplexBoundsGenericAspect_pr199130_1() { runTest("complex bounds on generic aspect - 1");} public void testComplexBoundsGenericAspect_pr199130_2() { runTest("complex bounds on generic aspect - 2");} public void testComplexBoundsGenericAspect_pr199130_3() { runTest("complex bounds on generic aspect - 3");} public void testPrivilegedGenericAspect_pr235505() { runTest("privileged generic aspect");} public void testPrivilegedGenericAspect_pr235505_2() { runTest("privileged generic aspect - 2");} public void testParsingAroundNoReturn_pr64222() { runTest("parsing around advice no return");} public void testParsingBeforeArrayRef_pr159268() { runTest("before array name");} public void testGenericAspectAroundAdvice_pr226201() { runTest("generic aspect around advice");} public void testCrazyGenericsInnerTypes_pr235829() { runTest("crazy generics and inner types");} public void testAnnotationExposureGenerics_pr235597() { runTest("annotation exposure and generics");} public void testIncorrectRelationship_pr235204() { runTest("incorrect call relationship"); IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap(); Set entries = irm.getEntries(); boolean gotSomethingValid = false; String expected = "<recursivepackage{RecursiveCatcher.java}RecursiveCatcher~recursiveCall~I?method-call(void recursivepackage.RecursiveCatcher.recursiveCall(int))"; for (Iterator iterator = entries.iterator(); iterator.hasNext();) { String str = (String) iterator.next(); if (str.indexOf(expected)!=-1) gotSomethingValid = true; } if (!gotSomethingValid) { fail("Did not find a relationship with the expected data in '"+expected+"'"); } } public void testITDPrecedence_pr233838_1() { runTest("itd precedence - 1"); } public void testITDPrecedence_pr233838_2() { runTest("itd precedence - 2"); } public void testGetFieldGenerics_pr227401() { runTest("getfield problem with generics");} public void testGenericAbstractAspects_pr231478() { runTest("generic abstract aspects"); } public void testFieldJoinpointsAndAnnotationValues_pr227993() { runTest("field jp anno value"); } public void testGenericsBoundsDecp_pr231187() { runTest("generics bounds decp"); } public void testGenericsBoundsDecp_pr231187_2() { runTest("generics bounds decp - 2"); } public void testLtwInheritedCflow_pr230134() { runTest("ltw inherited cflow"); } public void testAroundAdviceOnFieldSet_pr229910() { runTest("around advice on field set"); } public void testPipelineCompilationGenericReturnType_pr226567() { runTest("pipeline compilation and generic return type"); } public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc161Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc161/ajc161.xml"); } }
237,962
Bug 237962 [migration] Unexpected problem loading an aspect built with 1.5.4
We always support processing of old aspects. It doesn't matter what level of AspectJ was used to build an aspect, as long as you use that version or a later version of the weaver, we can unpack it and don't require it to be rebuilt from source. However, I've just encountered a .class apparently built with 1.5.4 that 1.6.1 cannot load. It crashes deserializing a PointcutDeclaration. In the data stream we have just read the numbers 1 and 3 indicating 'kinded pointcut' and then 'method-execution' and the next digit is a 0 when it should be 1-9. We crash with a: org.aspectj.weaver.BCException: weird kind 0 when batch building BuildConfig[null] #Files=43 at org.aspectj.weaver.MemberKind.read(MemberKind.java:35) at org.aspectj.weaver.patterns.SignaturePattern.read(SignaturePattern.java:682) The memberkind is a typesafeenum and so can never be other than 1-9. It is the first part of a signaturepattern so hard to see how it got written out 'wrong' right now. I've been told 1.5.4 can load this, so about to try that. Wow....1.5.4 did load it back in, how the hell. I suspect we aren't consuming enough in 1.6.1 which then leaves us some extra that we interpret as a rogue pointcut. Ok, in a comparison we consume one extra byte from the stream when reading it with 1.6.1 that we do not consume with 1.6.0 - at position 260. As I got closer to it, I knew what it would be - especially when I knew it was just one byte difference. The version check for whether the byte for 'annotation pattern relates to a parameter match' was wrong (urgh).
resolved fixed
be03167
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-06-20T17:15:52Z"
"2008-06-20T16:40:00Z"
weaver/src/org/aspectj/weaver/patterns/AndAnnotationTypePattern.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; import org.aspectj.weaver.AjAttribute.WeaverVersionInfo; import org.aspectj.weaver.ResolvedType; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class AndAnnotationTypePattern extends AnnotationTypePattern { private AnnotationTypePattern left; private AnnotationTypePattern right; public AndAnnotationTypePattern(AnnotationTypePattern left, AnnotationTypePattern right) { this.left = left; this.right = right; setLocation(left.getSourceContext(), left.getStart(), right.getEnd()); } public FuzzyBoolean matches(AnnotatedElement annotated) { return left.matches(annotated).and(right.matches(annotated)); } public FuzzyBoolean matches(AnnotatedElement annotated, ResolvedType[] parameterAnnotations ) { return left.matches(annotated,parameterAnnotations).and(right.matches(annotated,parameterAnnotations)); } public void resolve(World world) { left.resolve(world); right.resolve(world); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings, boolean) */ public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { left = left.resolveBindings(scope,bindings,allowBinding); right =right.resolveBindings(scope,bindings,allowBinding); return this; } public AnnotationTypePattern parameterizeWith(Map typeVariableMap,World w) { AnnotationTypePattern newLeft = left.parameterizeWith(typeVariableMap,w); AnnotationTypePattern newRight = right.parameterizeWith(typeVariableMap,w); AndAnnotationTypePattern ret = new AndAnnotationTypePattern(newLeft,newRight); ret.copyLocationFrom(this); if (this.isForParameterAnnotationMatch()) ret.setForParameterAnnotationMatch(); return ret; } public static AnnotationTypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { AnnotationTypePattern p = new AndAnnotationTypePattern( AnnotationTypePattern.read(s,context), AnnotationTypePattern.read(s,context)); p.readLocation(context,s); if (s.getMajorVersion()>=WeaverVersionInfo.WEAVER_VERSION_MINOR_AJ160) { if (s.readBoolean()) p.setForParameterAnnotationMatch(); } return p; } public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.AND); left.write(s); right.write(s); writeLocation(s); s.writeBoolean(isForParameterAnnotationMatch()); } public boolean equals(Object obj) { if (!(obj instanceof AndAnnotationTypePattern)) return false; AndAnnotationTypePattern other = (AndAnnotationTypePattern) obj; return (left.equals(other.left) && right.equals(other.right) && left.isForParameterAnnotationMatch()==right.isForParameterAnnotationMatch()); } public int hashCode() { int result = 17; result = result*37 + left.hashCode(); result = result*37 + right.hashCode(); result = result*37 + (isForParameterAnnotationMatch()?0:1); return result; } public String toString() { return left.toString() + " " + right.toString(); } public AnnotationTypePattern getLeft() { return left; } public AnnotationTypePattern getRight() { return right; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public Object traverse(PatternNodeVisitor visitor, Object data) { Object ret = accept(visitor,data); left.traverse(visitor,ret); right.traverse(visitor,ret); return ret; } public void setForParameterAnnotationMatch() { left.setForParameterAnnotationMatch(); right.setForParameterAnnotationMatch(); } }
237,962
Bug 237962 [migration] Unexpected problem loading an aspect built with 1.5.4
We always support processing of old aspects. It doesn't matter what level of AspectJ was used to build an aspect, as long as you use that version or a later version of the weaver, we can unpack it and don't require it to be rebuilt from source. However, I've just encountered a .class apparently built with 1.5.4 that 1.6.1 cannot load. It crashes deserializing a PointcutDeclaration. In the data stream we have just read the numbers 1 and 3 indicating 'kinded pointcut' and then 'method-execution' and the next digit is a 0 when it should be 1-9. We crash with a: org.aspectj.weaver.BCException: weird kind 0 when batch building BuildConfig[null] #Files=43 at org.aspectj.weaver.MemberKind.read(MemberKind.java:35) at org.aspectj.weaver.patterns.SignaturePattern.read(SignaturePattern.java:682) The memberkind is a typesafeenum and so can never be other than 1-9. It is the first part of a signaturepattern so hard to see how it got written out 'wrong' right now. I've been told 1.5.4 can load this, so about to try that. Wow....1.5.4 did load it back in, how the hell. I suspect we aren't consuming enough in 1.6.1 which then leaves us some extra that we interpret as a rogue pointcut. Ok, in a comparison we consume one extra byte from the stream when reading it with 1.6.1 that we do not consume with 1.6.0 - at position 260. As I got closer to it, I knew what it would be - especially when I knew it was just one byte difference. The version check for whether the byte for 'annotation pattern relates to a parameter match' was wrong (urgh).
resolved fixed
be03167
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-06-20T17:15:52Z"
"2008-06-20T16:40:00Z"
weaver/src/org/aspectj/weaver/patterns/NotAnnotationTypePattern.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; import org.aspectj.weaver.AjAttribute.WeaverVersionInfo; public class NotAnnotationTypePattern extends AnnotationTypePattern { AnnotationTypePattern negatedPattern; public NotAnnotationTypePattern(AnnotationTypePattern pattern) { this.negatedPattern = pattern; setLocation(pattern.getSourceContext(), pattern.getStart(), pattern.getEnd()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#matches(org.aspectj.weaver.AnnotatedElement) */ public FuzzyBoolean matches(AnnotatedElement annotated) { return negatedPattern.matches(annotated).not(); } public FuzzyBoolean matches(AnnotatedElement annotated,ResolvedType[] parameterAnnotations) { return negatedPattern.matches(annotated,parameterAnnotations).not(); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#resolve(org.aspectj.weaver.World) */ public void resolve(World world) { negatedPattern.resolve(world); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings, boolean) */ public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { negatedPattern = negatedPattern.resolveBindings(scope,bindings,allowBinding); return this; } public AnnotationTypePattern parameterizeWith(Map typeVariableMap,World w) { AnnotationTypePattern newNegatedPattern = negatedPattern.parameterizeWith(typeVariableMap,w); NotAnnotationTypePattern ret = new NotAnnotationTypePattern(newNegatedPattern); ret.copyLocationFrom(this); if (this.isForParameterAnnotationMatch()) ret.setForParameterAnnotationMatch(); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.NOT); negatedPattern.write(s); writeLocation(s); s.writeBoolean(isForParameterAnnotationMatch()); } public static AnnotationTypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { AnnotationTypePattern ret = new NotAnnotationTypePattern(AnnotationTypePattern.read(s,context)); ret.readLocation(context,s); if (s.getMajorVersion()>=WeaverVersionInfo.WEAVER_VERSION_MINOR_AJ160) { if (s.readBoolean()) ret.setForParameterAnnotationMatch(); } return ret; } public boolean equals(Object obj) { if (!(obj instanceof NotAnnotationTypePattern)) return false; NotAnnotationTypePattern other = (NotAnnotationTypePattern) obj; return other.negatedPattern.equals(negatedPattern) && other.isForParameterAnnotationMatch()==isForParameterAnnotationMatch(); } public int hashCode() { int result = 17 + 37*negatedPattern.hashCode(); result = 37*result +(isForParameterAnnotationMatch()?0:1); return result; } public String toString() { return "!" + negatedPattern.toString(); } public AnnotationTypePattern getNegatedPattern() { return negatedPattern; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public Object traverse(PatternNodeVisitor visitor, Object data) { Object ret = accept(visitor,data); negatedPattern.traverse(visitor,ret); return ret; } public void setForParameterAnnotationMatch() { negatedPattern.setForParameterAnnotationMatch(); } }
237,962
Bug 237962 [migration] Unexpected problem loading an aspect built with 1.5.4
We always support processing of old aspects. It doesn't matter what level of AspectJ was used to build an aspect, as long as you use that version or a later version of the weaver, we can unpack it and don't require it to be rebuilt from source. However, I've just encountered a .class apparently built with 1.5.4 that 1.6.1 cannot load. It crashes deserializing a PointcutDeclaration. In the data stream we have just read the numbers 1 and 3 indicating 'kinded pointcut' and then 'method-execution' and the next digit is a 0 when it should be 1-9. We crash with a: org.aspectj.weaver.BCException: weird kind 0 when batch building BuildConfig[null] #Files=43 at org.aspectj.weaver.MemberKind.read(MemberKind.java:35) at org.aspectj.weaver.patterns.SignaturePattern.read(SignaturePattern.java:682) The memberkind is a typesafeenum and so can never be other than 1-9. It is the first part of a signaturepattern so hard to see how it got written out 'wrong' right now. I've been told 1.5.4 can load this, so about to try that. Wow....1.5.4 did load it back in, how the hell. I suspect we aren't consuming enough in 1.6.1 which then leaves us some extra that we interpret as a rogue pointcut. Ok, in a comparison we consume one extra byte from the stream when reading it with 1.6.1 that we do not consume with 1.6.0 - at position 260. As I got closer to it, I knew what it would be - especially when I knew it was just one byte difference. The version check for whether the byte for 'annotation pattern relates to a parameter match' was wrong (urgh).
resolved fixed
be03167
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-06-20T17:15:52Z"
"2008-06-20T16:40:00Z"
weaver/src/org/aspectj/weaver/patterns/OrAnnotationTypePattern.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; import org.aspectj.weaver.AjAttribute.WeaverVersionInfo; public class OrAnnotationTypePattern extends AnnotationTypePattern { private AnnotationTypePattern left; private AnnotationTypePattern right; public OrAnnotationTypePattern(AnnotationTypePattern left, AnnotationTypePattern right) { this.left = left; this.right = right; setLocation(left.getSourceContext(), left.getStart(), right.getEnd()); } public FuzzyBoolean matches(AnnotatedElement annotated) { return left.matches(annotated).or(right.matches(annotated)); } public FuzzyBoolean matches(AnnotatedElement annotated, ResolvedType[] parameterAnnotations ) { return left.matches(annotated,parameterAnnotations).or(right.matches(annotated,parameterAnnotations)); } public void resolve(World world) { left.resolve(world); right.resolve(world); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings, boolean) */ public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { left = left.resolveBindings(scope,bindings,allowBinding); right =right.resolveBindings(scope,bindings,allowBinding); return this; } public AnnotationTypePattern parameterizeWith(Map typeVariableMap,World w) { AnnotationTypePattern newLeft = left.parameterizeWith(typeVariableMap,w); AnnotationTypePattern newRight = right.parameterizeWith(typeVariableMap,w); OrAnnotationTypePattern ret = new OrAnnotationTypePattern(newLeft,newRight); ret.copyLocationFrom(this); if (isForParameterAnnotationMatch()) ret.setForParameterAnnotationMatch(); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } public Object traverse(PatternNodeVisitor visitor, Object data) { Object ret = accept(visitor,data); left.traverse(visitor,ret); right.traverse(visitor,ret); return ret; } public static AnnotationTypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { AnnotationTypePattern p = new OrAnnotationTypePattern( AnnotationTypePattern.read(s,context), AnnotationTypePattern.read(s,context)); p.readLocation(context,s); if (s.getMajorVersion()>=WeaverVersionInfo.WEAVER_VERSION_MINOR_AJ160) { if (s.readBoolean()) p.setForParameterAnnotationMatch(); } return p; } public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.OR); left.write(s); right.write(s); writeLocation(s); s.writeBoolean(isForParameterAnnotationMatch()); } public boolean equals(Object obj) { if (!(obj instanceof OrAnnotationTypePattern)) return false; OrAnnotationTypePattern other = (OrAnnotationTypePattern) obj; return (left.equals(other.left) && right.equals(other.right)) && isForParameterAnnotationMatch()==other.isForParameterAnnotationMatch(); } public int hashCode() { int result = 17; result = result*37 + left.hashCode(); result = result*37 + right.hashCode(); result = result*37 + (isForParameterAnnotationMatch()?0:1); return result; } public String toString() { return "(" + left.toString() + " || " + right.toString() + ")"; } public AnnotationTypePattern getLeft() { return left; } public AnnotationTypePattern getRight() { return right; } public void setForParameterAnnotationMatch() { left.setForParameterAnnotationMatch(); right.setForParameterAnnotationMatch(); } }
237,962
Bug 237962 [migration] Unexpected problem loading an aspect built with 1.5.4
We always support processing of old aspects. It doesn't matter what level of AspectJ was used to build an aspect, as long as you use that version or a later version of the weaver, we can unpack it and don't require it to be rebuilt from source. However, I've just encountered a .class apparently built with 1.5.4 that 1.6.1 cannot load. It crashes deserializing a PointcutDeclaration. In the data stream we have just read the numbers 1 and 3 indicating 'kinded pointcut' and then 'method-execution' and the next digit is a 0 when it should be 1-9. We crash with a: org.aspectj.weaver.BCException: weird kind 0 when batch building BuildConfig[null] #Files=43 at org.aspectj.weaver.MemberKind.read(MemberKind.java:35) at org.aspectj.weaver.patterns.SignaturePattern.read(SignaturePattern.java:682) The memberkind is a typesafeenum and so can never be other than 1-9. It is the first part of a signaturepattern so hard to see how it got written out 'wrong' right now. I've been told 1.5.4 can load this, so about to try that. Wow....1.5.4 did load it back in, how the hell. I suspect we aren't consuming enough in 1.6.1 which then leaves us some extra that we interpret as a rogue pointcut. Ok, in a comparison we consume one extra byte from the stream when reading it with 1.6.1 that we do not consume with 1.6.0 - at position 260. As I got closer to it, I knew what it would be - especially when I knew it was just one byte difference. The version check for whether the byte for 'annotation pattern relates to a parameter match' was wrong (urgh).
resolved fixed
be03167
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-06-20T17:15:52Z"
"2008-06-20T16:40:00Z"
weaver/src/org/aspectj/weaver/patterns/WildAnnotationTypePattern.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; import org.aspectj.weaver.AjAttribute.WeaverVersionInfo; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class WildAnnotationTypePattern extends AnnotationTypePattern { private TypePattern typePattern; private boolean resolved = false; Map annotationValues; /** * */ public WildAnnotationTypePattern(TypePattern typePattern) { super(); this.typePattern = typePattern; this.setLocation(typePattern.getSourceContext(), typePattern.start, typePattern.end); } public WildAnnotationTypePattern(TypePattern typePattern, Map annotationValues) { super(); this.typePattern = typePattern; this.annotationValues = annotationValues; // PVAL make the location be from start of type pattern to end of values this.setLocation(typePattern.getSourceContext(), typePattern.start, typePattern.end); } public TypePattern getTypePattern() { return typePattern; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#matches(org.aspectj.weaver.AnnotatedElement) */ public FuzzyBoolean matches(AnnotatedElement annotated) { return matches(annotated,null); } /** * Resolve any annotation values specified, checking they are all well formed (valid names, valid values) * @param annotationType the annotation type for which the values have been specified * @param scope the scope within which to resolve type references (eg. Color.GREEN) */ protected void resolveAnnotationValues(ResolvedType annotationType, IScope scope) { if (annotationValues == null) return; // Check any values specified are OK: // - the value names are for valid annotation fields // - the specified values are of the correct type // - for enums, check the specified values can be resolved in the specified scope Set keys = annotationValues.keySet(); ResolvedMember[] ms = annotationType.getDeclaredMethods(); for (Iterator kIter = keys.iterator(); kIter.hasNext();) { String k = (String) kIter.next(); String v = (String) annotationValues.get(k); boolean validKey = false; for (int i = 0; i < ms.length; i++) { ResolvedMember resolvedMember = ms[i]; if (resolvedMember.getName().equals(k) && resolvedMember.isAbstract()) { validKey = true; ResolvedType t = resolvedMember.getReturnType().resolve(scope.getWorld()); if (t.isEnum()) { // value must be an enum reference X.Y int pos = v.lastIndexOf("."); if (pos == -1) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE,v,"enum"), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } else { String typename = v.substring(0,pos); ResolvedType rt = scope.lookupType(typename, this).resolve(scope.getWorld()); v = rt.getSignature()+v.substring(pos+1); // from 'Color.RED' to 'Lp/Color;RED' annotationValues.put(k,v); } } else if (t.isPrimitiveType()) { if (t.getSignature()=="I") { try { int value = Integer.parseInt(v); annotationValues.put(k,Integer.toString(value)); } catch (NumberFormatException nfe) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE,v,"int"), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } } else if (t.getSignature()=="F") { try { float value = Float.parseFloat(v); annotationValues.put(k,Float.toString(value)); } catch (NumberFormatException nfe) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE,v,"float"), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } } else if (t.getSignature()=="Z") { if (v.equalsIgnoreCase("true") || v.equalsIgnoreCase("false")) { // is it ok ! } else { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE,v,"boolean"), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } } else if (t.getSignature()=="S") { try { short value = Short.parseShort(v); annotationValues.put(k,Short.toString(value)); } catch (NumberFormatException nfe) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE,v,"short"), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } } else if (t.getSignature()=="J") { try { long value = Long.parseLong(v); annotationValues.put(k,Long.toString(value)); } catch (NumberFormatException nfe) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE,v,"long"), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } } else if (t.getSignature()=="D") { try { double value = Double.parseDouble(v); annotationValues.put(k,Double.toString(value)); } catch (NumberFormatException nfe) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE,v,"double"), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } } else if (t.getSignature()=="B") { try { byte value = Byte.parseByte(v); annotationValues.put(k,Byte.toString(value)); } catch (NumberFormatException nfe) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE,v,"byte"), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } } else if (t.getSignature()=="C") { if (v.length()!=3) { // '?' IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE,v,"char"), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } else { annotationValues.put(k,v.substring(1,2)); } } else { throw new RuntimeException("Not implemented for "+t); } } else if (t.equals(ResolvedType.JAVA_LANG_STRING)) { // nothing to do, it will be OK } else { throw new RuntimeException("Compiler limitation: annotation value support not implemented for type "+t); } } } if (!validKey) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.UNKNOWN_ANNOTATION_VALUE,annotationType,k), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } } } public FuzzyBoolean matches(AnnotatedElement annotated,ResolvedType[] parameterAnnotations) { if (!resolved) { throw new IllegalStateException("Can't match on an unresolved annotation type pattern"); } if (annotationValues!=null) { // PVAL improve this restriction, would allow '*(value=Color.RED)' throw new IllegalStateException("Cannot use annotationvalues with a wild annotation pattern"); } if (isForParameterAnnotationMatch()) { if (parameterAnnotations!=null && parameterAnnotations.length!=0) { for (int i = 0; i < parameterAnnotations.length; i++) { if (typePattern.matches(parameterAnnotations[i],TypePattern.STATIC).alwaysTrue()) { return FuzzyBoolean.YES; } } } } else { // matches if the type of any of the annotations on the AnnotatedElement is // matched by the typePattern. ResolvedType[] annTypes = annotated.getAnnotationTypes(); if (annTypes!=null && annTypes.length!=0) { for (int i = 0; i < annTypes.length; i++) { if (typePattern.matches(annTypes[i],TypePattern.STATIC).alwaysTrue()) { return FuzzyBoolean.YES; } } } } return FuzzyBoolean.NO; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#resolve(org.aspectj.weaver.World) */ public void resolve(World world) { // nothing to do... resolved = true; } /** * This can modify in place, or return a new TypePattern if the type changes. */ public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { if (!scope.getWorld().isInJava5Mode()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.ANNOTATIONS_NEED_JAVA5), getSourceLocation())); return this; } if (resolved) return this; this.typePattern = typePattern.resolveBindings(scope,bindings,false,false); resolved = true; if (typePattern instanceof ExactTypePattern) { ExactTypePattern et = (ExactTypePattern)typePattern; if (!et.getExactType().resolve(scope.getWorld()).isAnnotation()) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.REFERENCE_TO_NON_ANNOTATION_TYPE,et.getExactType().getName()), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); resolved = false; } ResolvedType annotationType = et.getExactType().resolve(scope.getWorld()); resolveAnnotationValues(annotationType,scope); ExactAnnotationTypePattern eatp = new ExactAnnotationTypePattern(annotationType,annotationValues); eatp.copyLocationFrom(this); if (isForParameterAnnotationMatch()) eatp.setForParameterAnnotationMatch(); return eatp; } else { return this; } } public AnnotationTypePattern parameterizeWith(Map typeVariableMap,World w) { WildAnnotationTypePattern ret = new WildAnnotationTypePattern(typePattern.parameterizeWith(typeVariableMap,w)); ret.copyLocationFrom(this); ret.resolved = resolved; return ret; } private static final byte VERSION = 1; // rev if ser. form changes /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.WILD); s.writeByte(VERSION); typePattern.write(s); writeLocation(s); s.writeBoolean(isForParameterAnnotationMatch()); // PVAL if (annotationValues==null) { s.writeInt(0); } else { s.writeInt(annotationValues.size()); Set key = annotationValues.keySet(); for (Iterator keys = key.iterator(); keys.hasNext();) { String k = (String) keys.next(); s.writeUTF(k); s.writeUTF((String)annotationValues.get(k)); } } } public static AnnotationTypePattern read(VersionedDataInputStream s,ISourceContext context) throws IOException { WildAnnotationTypePattern ret; byte version = s.readByte(); if (version > VERSION) { throw new BCException("ExactAnnotationTypePattern was written by a newer version of AspectJ"); } TypePattern t = TypePattern.read(s,context); ret = new WildAnnotationTypePattern(t); ret.readLocation(context,s); if (s.getMajorVersion()>=WeaverVersionInfo.WEAVER_VERSION_MINOR_AJ160) { if (s.readBoolean()) ret.setForParameterAnnotationMatch(); } if (s.getMajorVersion()>=WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ160M2) { int annotationValueCount = s.readInt(); if (annotationValueCount>0) { Map aValues = new HashMap(); for (int i=0;i<annotationValueCount;i++) { String key = s.readUTF(); String val = s.readUTF(); aValues.put(key,val); } ret.annotationValues = aValues; } } return ret; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (!(obj instanceof WildAnnotationTypePattern)) return false; WildAnnotationTypePattern other = (WildAnnotationTypePattern) obj; return other.typePattern.equals(typePattern) && this.isForParameterAnnotationMatch()==other.isForParameterAnnotationMatch() && (annotationValues==null?other.annotationValues==null:annotationValues.equals(other.annotationValues)); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return (((17 + 37*typePattern.hashCode())*37+(isForParameterAnnotationMatch()?0:1))*37)+(annotationValues==null?0:annotationValues.hashCode()); } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { return "@(" + typePattern.toString() + ")"; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
229,829
Bug 229829 SourceTypeBinding.sourceStart() NPE
java.lang.NullPointerException at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding.sourceStart(SourceTypeBinding.java:1514) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding.sourceStart(MethodBinding.java:988) at org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceType.fillDeclaredMembers(EclipseSourceType.java:243) at org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceType.getDeclaredFiel ... IRETURN end public boolean isTracingModifications() end public class com.centricsoftware.pi.core.data.reflection.Attribute
resolved fixed
e9823aa
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-07-29T16:55:49Z"
"2008-05-01T16:40:00Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseSourceType.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur support for @AJ perClause * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.lookup; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration; import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration; import org.aspectj.ajdt.internal.compiler.ast.DeclareAnnotationDeclaration; import org.aspectj.ajdt.internal.compiler.ast.DeclareDeclaration; import org.aspectj.ajdt.internal.compiler.ast.InterTypeDeclaration; import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration; import org.aspectj.ajdt.internal.core.builder.EclipseSourceContext; import org.aspectj.bridge.IMessage; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ArrayInitializer; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MarkerAnnotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MemberValuePair; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.NameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.NormalAnnotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeParameter; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.Constant; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Binding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.weaver.AbstractReferenceTypeDelegate; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.AnnotationNameValuePair; import org.aspectj.weaver.AnnotationTargetKind; import org.aspectj.weaver.AnnotationValue; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.ArrayAnnotationValue; import org.aspectj.weaver.BCException; import org.aspectj.weaver.EnumAnnotationValue; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.AtAjAttributes.LazyResolvedPointcutDefinition; import org.aspectj.weaver.patterns.FormalBinding; import org.aspectj.weaver.patterns.ParserException; import org.aspectj.weaver.patterns.PatternParser; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.PerFromSuper; import org.aspectj.weaver.patterns.PerSingleton; import org.aspectj.weaver.patterns.Pointcut; /** * Supports viewing eclipse TypeDeclarations/SourceTypeBindings as a ResolvedType * * @author Jim Hugunin */ public class EclipseSourceType extends AbstractReferenceTypeDelegate { private static final char[] pointcutSig = "Lorg/aspectj/lang/annotation/Pointcut;".toCharArray(); private static final char[] aspectSig = "Lorg/aspectj/lang/annotation/Aspect;".toCharArray(); protected ResolvedPointcutDefinition[] declaredPointcuts = null; protected ResolvedMember[] declaredMethods = null; protected ResolvedMember[] declaredFields = null; public List declares = new ArrayList(); public List typeMungers = new ArrayList(); private EclipseFactory factory; private SourceTypeBinding binding; private TypeDeclaration declaration; private CompilationUnitDeclaration unit; private boolean annotationsResolved = false; private ResolvedType[] resolvedAnnotations = null; private boolean discoveredAnnotationTargetKinds = false; private AnnotationTargetKind[] annotationTargetKinds; private AnnotationX[] annotations = null; private final static ResolvedType[] NO_ANNOTATION_TYPES = new ResolvedType[0]; private final static AnnotationX[] NO_ANNOTATIONS = new AnnotationX[0]; protected EclipseFactory eclipseWorld() { return factory; } public EclipseSourceType(ReferenceType resolvedTypeX, EclipseFactory factory, SourceTypeBinding binding, TypeDeclaration declaration, CompilationUnitDeclaration unit) { super(resolvedTypeX, true); this.factory = factory; this.binding = binding; this.declaration = declaration; this.unit = unit; setSourceContext(new EclipseSourceContext(declaration.compilationResult)); resolvedTypeX.setStartPos(declaration.sourceStart); resolvedTypeX.setEndPos(declaration.sourceEnd); } public boolean isAspect() { final boolean isCodeStyle = declaration instanceof AspectDeclaration; return isCodeStyle?isCodeStyle:isAnnotationStyleAspect(); } public boolean isAnonymous() { if (declaration.binding != null) return declaration.binding.isAnonymousType(); return ((declaration.modifiers & (ASTNode.IsAnonymousType | ASTNode.IsLocalType)) != 0); } public boolean isNested() { if (declaration.binding!=null) return (declaration.binding.isMemberType()); return ((declaration.modifiers & ASTNode.IsMemberType) != 0); } public ResolvedType getOuterClass() { if (declaration.enclosingType==null) return null; return eclipseWorld().fromEclipse(declaration.enclosingType.binding); } public boolean isAnnotationStyleAspect() { if (declaration.annotations == null) { return false; } ResolvedType[] annotations = getAnnotationTypes(); for (int i = 0; i < annotations.length; i++) { if ("org.aspectj.lang.annotation.Aspect".equals(annotations[i].getName())) { return true; } } return false; } /** Returns "" if there is a problem */ private String getPointcutStringFromAnnotationStylePointcut(AbstractMethodDeclaration amd) { Annotation[] ans = amd.annotations; if (ans == null) return ""; for (int i = 0; i < ans.length; i++) { if (ans[i].resolvedType == null) continue; // XXX happens if we do this very early from buildInterTypeandPerClause // may prevent us from resolving references made in @Pointcuts to // an @Pointcut in a code-style aspect char[] sig = ans[i].resolvedType.signature(); if (CharOperation.equals(pointcutSig,sig)) { if (ans[i].memberValuePairs().length==0) return ""; // empty pointcut expression Expression expr = ans[i].memberValuePairs()[0].value; if (expr instanceof StringLiteral) { StringLiteral sLit = ((StringLiteral)expr); return new String(sLit.source()); } else if (expr instanceof NameReference && (((NameReference)expr).binding instanceof FieldBinding)) { Binding b = ((NameReference)expr).binding; Constant c = ((FieldBinding)b).constant; return c.stringValue(); } else { throw new BCException("Do not know how to recover pointcut definition from "+expr+" (type "+expr.getClass().getName()+")"); } } } return ""; } private boolean isAnnotationStylePointcut(Annotation[] annotations) { if (annotations == null) return false; for (int i = 0; i < annotations.length; i++) { if (annotations[i].resolvedType == null) continue; // XXX happens if we do this very early from buildInterTypeandPerClause // may prevent us from resolving references made in @Pointcuts to // an @Pointcut in a code-style aspect char[] sig = annotations[i].resolvedType.signature(); if (CharOperation.equals(pointcutSig,sig)) { return true; } } return false; } public WeaverStateInfo getWeaverState() { return null; } public ResolvedType getSuperclass() { if (binding.isInterface()) return getResolvedTypeX().getWorld().getCoreType(UnresolvedType.OBJECT); //XXX what about java.lang.Object return eclipseWorld().fromEclipse(binding.superclass()); } public ResolvedType[] getDeclaredInterfaces() { return eclipseWorld().fromEclipse(binding.superInterfaces()); } protected void fillDeclaredMembers() { List declaredPointcuts = new ArrayList(); List declaredMethods = new ArrayList(); List declaredFields = new ArrayList(); binding.methods(); // the important side-effect of this call is to make sure bindings are completed AbstractMethodDeclaration[] methods = declaration.methods; if (methods != null) { for (int i=0, len=methods.length; i < len; i++) { AbstractMethodDeclaration amd = methods[i]; if (amd == null || amd.ignoreFurtherInvestigation) continue; if (amd instanceof PointcutDeclaration) { PointcutDeclaration d = (PointcutDeclaration)amd; ResolvedPointcutDefinition df = d.makeResolvedPointcutDefinition(factory); declaredPointcuts.add(df); } else if (amd instanceof InterTypeDeclaration) { // these are handled in a separate pass continue; } else if (amd instanceof DeclareDeclaration && !(amd instanceof DeclareAnnotationDeclaration)) { // surfaces the annotated ajc$ method // these are handled in a separate pass continue; } else if (amd instanceof AdviceDeclaration) { // these are ignored during compilation and only used during weaving continue; } else if ((amd.annotations != null) && isAnnotationStylePointcut(amd.annotations)) { // consider pointcuts defined via annotations ResolvedPointcutDefinition df = makeResolvedPointcutDefinition(amd); if (df!=null) declaredPointcuts.add(df); } else { if (amd.binding == null || !amd.binding.isValidBinding()) continue; ResolvedMember member = factory.makeResolvedMember(amd.binding); if (unit != null) { member.setSourceContext(new EclipseSourceContext(unit.compilationResult,amd.binding.sourceStart())); member.setPosition(amd.binding.sourceStart(),amd.binding.sourceEnd()); } declaredMethods.add(member); } } } FieldBinding[] fields = binding.fields(); for (int i=0, len=fields.length; i < len; i++) { FieldBinding f = fields[i]; declaredFields.add(factory.makeResolvedMember(f)); } this.declaredPointcuts = (ResolvedPointcutDefinition[]) declaredPointcuts.toArray(new ResolvedPointcutDefinition[declaredPointcuts.size()]); this.declaredMethods = (ResolvedMember[]) declaredMethods.toArray(new ResolvedMember[declaredMethods.size()]); this.declaredFields = (ResolvedMember[]) declaredFields.toArray(new ResolvedMember[declaredFields.size()]); } private ResolvedPointcutDefinition makeResolvedPointcutDefinition(AbstractMethodDeclaration md) { if (md.binding==null) return null; // there is another error that has caused this... pr138143 EclipseSourceContext eSourceContext = new EclipseSourceContext(md.compilationResult); Pointcut pc = null; if (!md.isAbstract()) { String expression = getPointcutStringFromAnnotationStylePointcut(md); try { pc = new PatternParser(expression,eSourceContext).parsePointcut(); } catch (ParserException pe) { // error will be reported by other means... pc = Pointcut.makeMatchesNothing(Pointcut.SYMBOLIC); } } FormalBinding[] bindings = buildFormalAdviceBindingsFrom(md); ResolvedPointcutDefinition rpd = new LazyResolvedPointcutDefinition( factory.fromBinding(md.binding.declaringClass), md.modifiers, new String(md.selector), factory.fromBindings(md.binding.parameters), factory.fromBinding(md.binding.returnType), pc,new EclipseScope(bindings,md.scope)); rpd.setPosition(md.sourceStart, md.sourceEnd); rpd.setSourceContext(eSourceContext); return rpd; } private static final char[] joinPoint = "Lorg/aspectj/lang/JoinPoint;".toCharArray(); private static final char[] joinPointStaticPart = "Lorg/aspectj/lang/JoinPoint$StaticPart;".toCharArray(); private static final char[] joinPointEnclosingStaticPart = "Lorg/aspectj/lang/JoinPoint$EnclosingStaticPart;".toCharArray(); private static final char[] proceedingJoinPoint = "Lorg/aspectj/lang/ProceedingJoinPoint;".toCharArray(); private FormalBinding[] buildFormalAdviceBindingsFrom(AbstractMethodDeclaration mDecl) { if (mDecl.arguments == null) return new FormalBinding[0]; if (mDecl.binding == null) return new FormalBinding[0]; EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(mDecl.scope); String extraArgName = null;//maybeGetExtraArgName(); if (extraArgName == null) extraArgName = ""; FormalBinding[] ret = new FormalBinding[mDecl.arguments.length]; for (int i = 0; i < mDecl.arguments.length; i++) { Argument arg = mDecl.arguments[i]; String name = new String(arg.name); TypeBinding argTypeBinding = mDecl.binding.parameters[i]; UnresolvedType type = factory.fromBinding(argTypeBinding); if (CharOperation.equals(joinPoint,argTypeBinding.signature()) || CharOperation.equals(joinPointStaticPart,argTypeBinding.signature()) || CharOperation.equals(joinPointEnclosingStaticPart,argTypeBinding.signature()) || CharOperation.equals(proceedingJoinPoint,argTypeBinding.signature()) || name.equals(extraArgName)) { ret[i] = new FormalBinding.ImplicitFormalBinding(type,name,i); } else { ret[i] = new FormalBinding(type, name, i, arg.sourceStart, arg.sourceEnd, "unknown"); } } return ret; } /** * This method may not return all fields, for example it may * not include the ajc$initFailureCause or ajc$perSingletonInstance * fields - see bug 129613 */ public ResolvedMember[] getDeclaredFields() { if (declaredFields == null) fillDeclaredMembers(); return declaredFields; } /** * This method may not return all methods, for example it may * not include clinit, aspectOf, hasAspect or ajc$postClinit * methods - see bug 129613 */ public ResolvedMember[] getDeclaredMethods() { if (declaredMethods == null) fillDeclaredMembers(); return declaredMethods; } public ResolvedMember[] getDeclaredPointcuts() { if (declaredPointcuts == null) fillDeclaredMembers(); return declaredPointcuts; } public int getModifiers() { // only return the real Java modifiers, not the extra eclipse ones return binding.modifiers & ExtraCompilerModifiers.AccJustFlag; } public String toString() { return "EclipseSourceType(" + new String(binding.sourceName()) + ")"; } //XXX make sure this is applied to classes and interfaces public void checkPointcutDeclarations() { ResolvedMember[] pointcuts = getDeclaredPointcuts(); boolean sawError = false; for (int i=0, len=pointcuts.length; i < len; i++) { if (pointcuts[i].isAbstract()) { if (!this.isAspect()) { eclipseWorld().showMessage(IMessage.ERROR, "abstract pointcut only allowed in aspect" + pointcuts[i].getName(), pointcuts[i].getSourceLocation(), null); sawError = true; } else if (!binding.isAbstract()) { eclipseWorld().showMessage(IMessage.ERROR, "abstract pointcut in concrete aspect" + pointcuts[i], pointcuts[i].getSourceLocation(), null); sawError = true; } } for (int j=i+1; j < len; j++) { if (pointcuts[i].getName().equals(pointcuts[j].getName())) { eclipseWorld().showMessage(IMessage.ERROR, "duplicate pointcut name: " + pointcuts[j].getName(), pointcuts[i].getSourceLocation(), pointcuts[j].getSourceLocation()); sawError = true; } } } //now check all inherited pointcuts to be sure that they're handled reasonably if (sawError || !isAspect()) return; // find all pointcuts that override ones from super and check override is legal // i.e. same signatures and greater or equal visibility // find all inherited abstract pointcuts and make sure they're concretized if I'm concrete // find all inherited pointcuts and make sure they don't conflict getResolvedTypeX().getExposedPointcuts(); //??? this is an odd construction } //??? // public CrosscuttingMembers collectCrosscuttingMembers() { // return crosscuttingMembers; // } // public ISourceLocation getSourceLocation() { // TypeDeclaration dec = binding.scope.referenceContext; // return new EclipseSourceLocation(dec.compilationResult, dec.sourceStart, dec.sourceEnd); // } public boolean isInterface() { return binding.isInterface(); } // XXXAJ5: Should be constants in the eclipse compiler somewhere, once it supports 1.5 public final static short ACC_ANNOTATION = 0x2000; public final static short ACC_ENUM = 0x4000; public boolean isEnum() { return (binding.getAccessFlags() & ACC_ENUM)!=0; } public boolean isAnnotation() { return (binding.getAccessFlags() & ACC_ANNOTATION)!=0; } public void addAnnotation(AnnotationX annotationX) { // XXX Big hole here - annotationX holds a BCEL annotation but // we need an Eclipse one here, we haven't written the conversion utils // yet. Not sure if this method will be called in practice... throw new RuntimeException("EclipseSourceType.addAnnotation() not implemented"); } public boolean isAnnotationWithRuntimeRetention() { if (!isAnnotation()) { return false; } else { return (binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationRuntimeRetention; } } public String getRetentionPolicy() { if (isAnnotation()) { if ((binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationRuntimeRetention) return "RUNTIME"; if ((binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationSourceRetention) return "SOURCE"; if ((binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationClassRetention) return "CLASS"; } return null; } public boolean canAnnotationTargetType() { if (isAnnotation()) { return ((binding.getAnnotationTagBits() & TagBits.AnnotationForType) != 0 ); } return false; } public AnnotationTargetKind[] getAnnotationTargetKinds() { if (discoveredAnnotationTargetKinds) return annotationTargetKinds; discoveredAnnotationTargetKinds = true; annotationTargetKinds = null; // null means we have no idea or the @Target annotation hasn't been used // if (isAnnotation()) { // Annotation[] annotationsOnThisType = declaration.annotations; // if (annotationsOnThisType != null) { // for (int i = 0; i < annotationsOnThisType.length; i++) { // Annotation a = annotationsOnThisType[i]; // if (a.resolvedType != null) { // String packageName = new String(a.resolvedType.qualifiedPackageName()).concat("."); // String sourceName = new String(a.resolvedType.qualifiedSourceName()); // if ((packageName + sourceName).equals(UnresolvedType.AT_TARGET.getName())) { // MemberValuePair[] pairs = a.memberValuePairs(); // for (int j = 0; j < pairs.length; j++) { // MemberValuePair pair = pairs[j]; // targetKind = pair.value.toString(); // return targetKind; // } // } // } // } // } // } // return targetKind; if (isAnnotation()) { List targetKinds = new ArrayList(); if ((binding.getAnnotationTagBits() & TagBits.AnnotationForAnnotationType) != 0) targetKinds.add(AnnotationTargetKind.ANNOTATION_TYPE); if ((binding.getAnnotationTagBits() & TagBits.AnnotationForConstructor) != 0) targetKinds.add(AnnotationTargetKind.CONSTRUCTOR); if ((binding.getAnnotationTagBits() & TagBits.AnnotationForField) != 0) targetKinds.add(AnnotationTargetKind.FIELD); if ((binding.getAnnotationTagBits() & TagBits.AnnotationForLocalVariable) != 0) targetKinds.add(AnnotationTargetKind.LOCAL_VARIABLE); if ((binding.getAnnotationTagBits() & TagBits.AnnotationForMethod) != 0) targetKinds.add(AnnotationTargetKind.METHOD); if ((binding.getAnnotationTagBits() & TagBits.AnnotationForPackage) != 0) targetKinds.add(AnnotationTargetKind.PACKAGE); if ((binding.getAnnotationTagBits() & TagBits.AnnotationForParameter) != 0) targetKinds.add(AnnotationTargetKind.PARAMETER); if ((binding.getAnnotationTagBits() & TagBits.AnnotationForType) != 0) targetKinds.add(AnnotationTargetKind.TYPE); if (!targetKinds.isEmpty()) { annotationTargetKinds = new AnnotationTargetKind[targetKinds.size()]; return (AnnotationTargetKind[]) targetKinds.toArray(annotationTargetKinds); } } return annotationTargetKinds; } public boolean hasAnnotation(UnresolvedType ofType) { // Make sure they are resolved if (!annotationsResolved) { TypeDeclaration.resolveAnnotations(declaration.staticInitializerScope, declaration.annotations, binding); annotationsResolved = true; } Annotation[] as = declaration.annotations; if (as == null) return false; for (int i = 0; i < as.length; i++) { Annotation annotation = as[i]; if (annotation.resolvedType == null) { // Something has gone wrong - probably we have a 1.4 rt.jar around // which will result in a separate error message. return false; } String tname = CharOperation.charToString(annotation.resolvedType.constantPoolName()); if (UnresolvedType.forName(tname).equals(ofType)) { return true; } } return false; } /** * WARNING: This method does not have a complete implementation. * * The aim is that it converts Eclipse annotation objects to the AspectJ form of * annotations (the type AnnotationAJ). The AnnotationX objects returned are wrappers * over either a Bcel annotation type or the AspectJ AnnotationAJ type. * The minimal implementation provided here is for processing the RetentionPolicy and * Target annotation types - these are the only ones which the weaver will attempt to * process from an EclipseSourceType. * * More notes: * The pipeline has required us to implement this. With the pipeline we can be weaving * a type and asking questions of annotations before they have been turned into Bcel * objects - ie. when they are still in EclipseSourceType form. Without the pipeline we * would have converted everything to Bcel objects before proceeding with weaving. * Because the pipeline won't start weaving until all aspects have been compiled and * the fact that no AspectJ constructs match on the values within annotations, this code * only needs to deal with converting system annotations that the weaver needs to process * (RetentionPolicy, Target). */ public AnnotationX[] getAnnotations() { if (annotations!=null) return annotations; // only do this once getAnnotationTypes(); // forces resolution and sets resolvedAnnotations Annotation[] as = declaration.annotations; if (as==null || as.length==0) { annotations = NO_ANNOTATIONS; } else { annotations = new AnnotationX[as.length]; for (int i = 0; i < as.length; i++) { annotations[i]=convertEclipseAnnotation(as[i],factory.getWorld()); } } return annotations; } /** * Convert one eclipse annotation into an AnnotationX object containing an AnnotationAJ object. * * This code and the helper methods used by it will go *BANG* if they encounter anything * not currently supported - this is safer than limping along with a malformed annotation. When * the *BANG* is encountered the bug reporter should indicate the kind of annotation they * were working with and this code can be enhanced to support it. */ public AnnotationX convertEclipseAnnotation(Annotation eclipseAnnotation,World w) { // TODO if it is sourcevisible, we shouldn't let it through!!!!!!!!! testcase! ResolvedType annotationType = factory.fromTypeBindingToRTX(eclipseAnnotation.type.resolvedType); long bs = (eclipseAnnotation.bits & TagBits.AnnotationRetentionMASK); boolean isRuntimeVisible = (eclipseAnnotation.bits & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationRuntimeRetention; AnnotationAJ annotationAJ = new AnnotationAJ(annotationType.getSignature(),isRuntimeVisible); generateAnnotation(eclipseAnnotation,annotationAJ); return new AnnotationX(annotationAJ,w); } static class MissingImplementationException extends RuntimeException { MissingImplementationException(String reason) { super(reason); } } private void generateAnnotation(Annotation annotation,AnnotationAJ annotationAJ) { if (annotation instanceof NormalAnnotation) { NormalAnnotation normalAnnotation = (NormalAnnotation) annotation; MemberValuePair[] memberValuePairs = normalAnnotation.memberValuePairs; if (memberValuePairs != null) { int memberValuePairsLength = memberValuePairs.length; for (int i = 0; i < memberValuePairsLength; i++) { MemberValuePair memberValuePair = memberValuePairs[i]; MethodBinding methodBinding = memberValuePair.binding; if (methodBinding == null) { // is this just a marker annotation? throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation ["+annotation+"]"); } else { AnnotationValue av = generateElementValue(memberValuePair.value, methodBinding.returnType); AnnotationNameValuePair anvp = new AnnotationNameValuePair(new String(memberValuePair.name),av); annotationAJ.addNameValuePair(anvp); } } } else { throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation ["+annotation+"]"); } } else if (annotation instanceof SingleMemberAnnotation) { // this is a single member annotation (one member value) SingleMemberAnnotation singleMemberAnnotation = (SingleMemberAnnotation) annotation; MethodBinding methodBinding = singleMemberAnnotation.memberValuePairs()[0].binding; if (methodBinding == null) { throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation ["+annotation+"]"); } else { AnnotationValue av = generateElementValue(singleMemberAnnotation.memberValue, methodBinding.returnType); annotationAJ.addNameValuePair( new AnnotationNameValuePair(new String(singleMemberAnnotation.memberValuePairs()[0].name),av)); } } else if (annotation instanceof MarkerAnnotation) { return; } else { // this is something else... throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation ["+annotation+"]"); } } private AnnotationValue generateElementValue(Expression defaultValue,TypeBinding memberValuePairReturnType) { Constant constant = defaultValue.constant; TypeBinding defaultValueBinding = defaultValue.resolvedType; if (defaultValueBinding == null) { throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); } else { if (memberValuePairReturnType.isArrayType() && !defaultValueBinding.isArrayType()) { if (constant != null && constant != Constant.NotAConstant) { throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); // generateElementValue(attributeOffset, defaultValue, constant, memberValuePairReturnType.leafComponentType()); } else { AnnotationValue av = generateElementValueForNonConstantExpression(defaultValue, defaultValueBinding); return new ArrayAnnotationValue(new AnnotationValue[]{av}); } } else { if (constant != null && constant != Constant.NotAConstant) { AnnotationValue av = EclipseAnnotationConvertor.generateElementValueForConstantExpression(defaultValue,defaultValueBinding); if (av==null) { throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); } return av; // generateElementValue(attributeOffset, defaultValue, constant, memberValuePairReturnType.leafComponentType()); } else { AnnotationValue av = generateElementValueForNonConstantExpression(defaultValue, defaultValueBinding); return av; } } } } private AnnotationValue generateElementValueForNonConstantExpression(Expression defaultValue, TypeBinding defaultValueBinding) { if (defaultValueBinding != null) { if (defaultValueBinding.isEnum()) { FieldBinding fieldBinding = null; if (defaultValue instanceof QualifiedNameReference) { QualifiedNameReference nameReference = (QualifiedNameReference) defaultValue; fieldBinding = (FieldBinding) nameReference.binding; } else if (defaultValue instanceof SingleNameReference) { SingleNameReference nameReference = (SingleNameReference) defaultValue; fieldBinding = (FieldBinding) nameReference.binding; } else { throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); } if (fieldBinding != null) { String sig = new String(fieldBinding.type.signature()); AnnotationValue enumValue = new EnumAnnotationValue(sig,new String(fieldBinding.name)); return enumValue; } throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); } else if (defaultValueBinding.isAnnotationType()) { throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); // contents[contentsOffset++] = (byte) '@'; // generateAnnotation((Annotation) defaultValue, attributeOffset); } else if (defaultValueBinding.isArrayType()) { // array type if (defaultValue instanceof ArrayInitializer) { ArrayInitializer arrayInitializer = (ArrayInitializer) defaultValue; int arrayLength = arrayInitializer.expressions != null ? arrayInitializer.expressions.length : 0; AnnotationValue[] values = new AnnotationValue[arrayLength]; for (int i = 0; i < arrayLength; i++) { values[i] = generateElementValue(arrayInitializer.expressions[i], defaultValueBinding.leafComponentType());//, attributeOffset); } ArrayAnnotationValue aav = new ArrayAnnotationValue(values); return aav; } else { throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); } // } else if (defaultValue instanceof MagicLiteral) { // if (defaultValue instanceof FalseLiteral) { // new AnnotationValue // } else if (defaultValue instanceof TrueLiteral) { // // } else { // throw new MissingImplementationException( // "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); // } } else { // class type throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); // if (contentsOffset + 3 >= this.contents.length) { // resizeContents(3); // } // contents[contentsOffset++] = (byte) 'c'; // if (defaultValue instanceof ClassLiteralAccess) { // ClassLiteralAccess classLiteralAccess = (ClassLiteralAccess) defaultValue; // final int classInfoIndex = constantPool.literalIndex(classLiteralAccess.targetType.signature()); // contents[contentsOffset++] = (byte) (classInfoIndex >> 8); // contents[contentsOffset++] = (byte) classInfoIndex; // } else { // contentsOffset = attributeOffset; // } } } else { throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); // contentsOffset = attributeOffset; } } // --------------------------------- public ResolvedType[] getAnnotationTypes() { if (resolvedAnnotations!=null) return resolvedAnnotations; // Make sure they are resolved if (!annotationsResolved) { TypeDeclaration.resolveAnnotations(declaration.staticInitializerScope, declaration.annotations, binding); annotationsResolved = true; } if (declaration.annotations == null) { resolvedAnnotations = NO_ANNOTATION_TYPES;//new ResolvedType[0]; } else { resolvedAnnotations = new ResolvedType[declaration.annotations.length]; Annotation[] as = declaration.annotations; for (int i = 0; i < as.length; i++) { Annotation annotation = as[i]; resolvedAnnotations[i] =factory.fromTypeBindingToRTX(annotation.type.resolvedType); } } return resolvedAnnotations; } public PerClause getPerClause() { //should probably be: ((AspectDeclaration)declaration).perClause; // but we don't need this level of detail, and working with real per clauses // at this stage of compilation is not worth the trouble if (!isAnnotationStyleAspect()) { if(declaration instanceof AspectDeclaration) { PerClause pc = ((AspectDeclaration)declaration).perClause; if (pc != null) return pc; } return new PerSingleton(); } else { // for @Aspect, we do need the real kind though we don't need the real perClause // at least try to get the right perclause PerClause pc = null; if (declaration instanceof AspectDeclaration) pc = ((AspectDeclaration)declaration).perClause; if (pc==null) { PerClause.Kind kind = getPerClauseForTypeDeclaration(declaration); //returning a perFromSuper is enough to get the correct kind.. (that's really a hack - AV) return new PerFromSuper(kind); } return pc; } } PerClause.Kind getPerClauseForTypeDeclaration(TypeDeclaration typeDeclaration) { Annotation[] annotations = typeDeclaration.annotations; for (int i = 0; i < annotations.length; i++) { Annotation annotation = annotations[i]; if (CharOperation.equals(aspectSig, annotation.resolvedType.signature())) { // found @Aspect(...) if (annotation.memberValuePairs() == null || annotation.memberValuePairs().length == 0) { // it is an @Aspect or @Aspect() // needs to use PerFromSuper if declaration extends a super aspect PerClause.Kind kind = lookupPerClauseKind(typeDeclaration.binding.superclass); // if no super aspect, we have a @Aspect() means singleton if (kind == null) { return PerClause.SINGLETON; } else { return kind; } } else if (annotation instanceof SingleMemberAnnotation) { // it is an @Aspect(...something...) SingleMemberAnnotation theAnnotation = (SingleMemberAnnotation)annotation; String clause = new String(((StringLiteral)theAnnotation.memberValue).source());//TODO cast safe ? return determinePerClause(typeDeclaration, clause); } else if (annotation instanceof NormalAnnotation) { // this kind if it was added by the visitor ! // it is an @Aspect(...something...) NormalAnnotation theAnnotation = (NormalAnnotation)annotation; if (theAnnotation.memberValuePairs==null || theAnnotation.memberValuePairs.length<1) return PerClause.SINGLETON; String clause = new String(((StringLiteral)theAnnotation.memberValuePairs[0].value).source());//TODO cast safe ? return determinePerClause(typeDeclaration, clause); } else { eclipseWorld().showMessage(IMessage.ABORT, "@Aspect annotation is expected to be SingleMemberAnnotation with 'String value()' as unique element", new EclipseSourceLocation(typeDeclaration.compilationResult, typeDeclaration.sourceStart, typeDeclaration.sourceEnd), null); return PerClause.SINGLETON;//fallback strategy just to avoid NPE } } } return null;//no @Aspect annotation at all (not as aspect) } private PerClause.Kind determinePerClause(TypeDeclaration typeDeclaration, String clause) { if (clause.startsWith("perthis(")) { return PerClause.PEROBJECT; } else if (clause.startsWith("pertarget(")) { return PerClause.PEROBJECT; } else if (clause.startsWith("percflow(")) { return PerClause.PERCFLOW; } else if (clause.startsWith("percflowbelow(")) { return PerClause.PERCFLOW; } else if (clause.startsWith("pertypewithin(")) { return PerClause.PERTYPEWITHIN; } else if (clause.startsWith("issingleton(")) { return PerClause.SINGLETON; } else { eclipseWorld().showMessage(IMessage.ABORT, "cannot determine perClause '" + clause + "'", new EclipseSourceLocation(typeDeclaration.compilationResult, typeDeclaration.sourceStart, typeDeclaration.sourceEnd), null); return PerClause.SINGLETON;//fallback strategy just to avoid NPE } } // adapted from AspectDeclaration private PerClause.Kind lookupPerClauseKind(ReferenceBinding binding) { final PerClause.Kind kind; if (binding instanceof BinaryTypeBinding) { ResolvedType superTypeX = factory.fromEclipse(binding); PerClause perClause = superTypeX.getPerClause(); // clause is null for non aspect classes since coming from BCEL attributes if (perClause != null) { kind = superTypeX.getPerClause().getKind(); } else { kind = null; } } else if (binding instanceof SourceTypeBinding ) { SourceTypeBinding sourceSc = (SourceTypeBinding)binding; if (sourceSc.scope.referenceContext instanceof AspectDeclaration) { //code style kind = ((AspectDeclaration)sourceSc.scope.referenceContext).perClause.getKind(); } else if (sourceSc.scope.referenceContext instanceof TypeDeclaration) { // if @Aspect: perFromSuper, else if @Aspect(..) get from anno value, else null kind = getPerClauseForTypeDeclaration((TypeDeclaration)(sourceSc.scope.referenceContext)); } else { //XXX should not happen kind = null; } } else { //XXX need to handle this too kind = null; } return kind; } public Collection getDeclares() { return declares; } public Collection getPrivilegedAccesses() { return Collections.EMPTY_LIST; } public Collection getTypeMungers() { return typeMungers; } public boolean doesNotExposeShadowMungers() { return true; } public String getDeclaredGenericSignature() { return CharOperation.charToString(binding.genericSignature()); } public boolean isGeneric() { return binding.isGenericType(); } public TypeVariable[] getTypeVariables() { if (declaration.typeParameters == null) return new TypeVariable[0]; TypeVariable[] typeVariables = new TypeVariable[declaration.typeParameters.length]; for (int i = 0; i < typeVariables.length; i++) { typeVariables[i] = typeParameter2TypeVariable(declaration.typeParameters[i]); } return typeVariables; } private TypeVariable typeParameter2TypeVariable(TypeParameter aTypeParameter) { String name = new String(aTypeParameter.name); ReferenceBinding superclassBinding = aTypeParameter.binding.superclass; UnresolvedType superclass = UnresolvedType.forSignature(new String(superclassBinding.signature())); UnresolvedType[] superinterfaces = null; ReferenceBinding[] superInterfaceBindings = aTypeParameter.binding.superInterfaces; if (superInterfaceBindings != null) { superinterfaces = new UnresolvedType[superInterfaceBindings.length]; for (int i = 0; i < superInterfaceBindings.length; i++) { superinterfaces[i] = UnresolvedType.forSignature(new String(superInterfaceBindings[i].signature())); } } // XXX what about lower binding? TypeVariable tv = new TypeVariable(name,superclass,superinterfaces); tv.setDeclaringElement(factory.fromBinding(aTypeParameter.binding.declaringElement)); tv.setRank(aTypeParameter.binding.rank); return tv; } public void ensureDelegateConsistent() { // do nothing, currently these can't become inconsistent (phew) } }
238,666
Bug 238666 Allow the ltw configuration to be directly specified rather than discovered on the classpath
Currently the property: org.aspectj.weaver.loadtime.configuration can be set to name the ltw configuration file that the loadtime weaver searches for. The default value is: META-INF/aop.xml;META-INF/aop-ajc.xml;org/aspectj/aop.xml and the weaver searches the classpath for .xml files matching any of those three possibilities. A typical override might therefore be: -Dorg.aspectj.weaver.loadtime.configuration=META-INF/overhere.xml however the weaver will still only look for it on the classpath. In some environments the ltw user may just want to name the aop config file to use, and not be forced to include it on the classpath. We have had the suggestion to make it protocol based, which i like, but for now I would just allow support for 'file:'. If file: is the prefix, it will be treated as direct reference to the file to use, otherwise it will be searched for. This change would mean all existing uses of the override will be fine, but new users will be all to exploit the flexibility of naming their configuration directly.
resolved fixed
df49b5c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-08-06T18:10:47Z"
"2008-06-26T19:53:20Z"
loadtime/src/org/aspectj/weaver/loadtime/ClassLoaderWeavingAdaptor.java
/******************************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Alexandre Vasseur initial implementation * David Knibb weaving context enhancments *******************************************************************************/ package org.aspectj.weaver.loadtime; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.Constants; import org.aspectj.util.LangUtil; import org.aspectj.weaver.Lint; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeakClassLoaderReference; import org.aspectj.weaver.World; import org.aspectj.weaver.Lint.Kind; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.Utility; import org.aspectj.weaver.loadtime.definition.Definition; import org.aspectj.weaver.loadtime.definition.DocumentParser; import org.aspectj.weaver.ltw.LTWWorld; import org.aspectj.weaver.patterns.PatternParser; import org.aspectj.weaver.patterns.TypePattern; import org.aspectj.weaver.tools.GeneratedClassHandler; import org.aspectj.weaver.tools.Trace; import org.aspectj.weaver.tools.TraceFactory; import org.aspectj.weaver.tools.WeavingAdaptor; /** * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public class ClassLoaderWeavingAdaptor extends WeavingAdaptor { private final static String AOP_XML = Constants.AOP_USER_XML + ";" + Constants.AOP_AJC_XML + ";" + Constants.AOP_OSGI_XML; private boolean initialized; private List m_dumpTypePattern = new ArrayList(); private boolean m_dumpBefore = false; private List m_includeTypePattern = new ArrayList(); private List m_excludeTypePattern = new ArrayList(); private List m_includeStartsWith = new ArrayList(); private List m_excludeStartsWith = new ArrayList(); private List m_aspectExcludeTypePattern = new ArrayList(); private List m_aspectExcludeStartsWith = new ArrayList(); private List m_aspectIncludeTypePattern = new ArrayList(); private List m_aspectIncludeStartsWith = new ArrayList(); private StringBuffer namespace; private IWeavingContext weavingContext; private List concreteAspects = new ArrayList(); private static Trace trace = TraceFactory.getTraceFactory().getTrace(ClassLoaderWeavingAdaptor.class); public ClassLoaderWeavingAdaptor() { super(); if (trace.isTraceEnabled()) trace.enter("<init>",this); if (trace.isTraceEnabled()) trace.exit("<init>"); } /** * We don't need a reference to the class loader and using it during * construction can cause problems with recursion. It also makes sense * to supply the weaving context during initialization to. * @deprecated */ public ClassLoaderWeavingAdaptor(final ClassLoader deprecatedLoader, final IWeavingContext deprecatedContext) { super(); if (trace.isTraceEnabled()) trace.enter("<init>",this,new Object[] { deprecatedLoader, deprecatedContext }); if (trace.isTraceEnabled()) trace.exit("<init>"); } class SimpleGeneratedClassHandler implements GeneratedClassHandler { private WeakClassLoaderReference loaderRef; SimpleGeneratedClassHandler(ClassLoader loader) { loaderRef = new WeakClassLoaderReference(loader); } /** * Callback when we need to define a Closure in the JVM * */ public void acceptClass(String name, byte[] bytes) { try { if (shouldDump(name.replace('/', '.'), false)) { dump(name, bytes, false); } } catch (Throwable throwable) { throwable.printStackTrace(); } defineClass(loaderRef.getClassLoader(), name, bytes); // could be done lazily using the hook } }; protected void initialize (final ClassLoader classLoader, IWeavingContext context) { if (initialized) return; boolean success = true; // if (trace.isTraceEnabled()) trace.enter("initialize",this,new Object[] { classLoader, context }); this.weavingContext = context; if (weavingContext == null) { weavingContext = new DefaultWeavingContext(classLoader); } createMessageHandler(); this.generatedClassHandler = new SimpleGeneratedClassHandler(classLoader); List definitions = weavingContext.getDefinitions(classLoader,this); if (definitions.isEmpty()) { disable(); // TODO maw Needed to ensure messages are flushed if (trace.isTraceEnabled()) trace.exit("initialize",definitions); return; } bcelWorld = new LTWWorld( classLoader, weavingContext, // TODO when the world works in terms of the context, we can remove the loader... getMessageHandler(), null); weaver = new BcelWeaver(bcelWorld); // register the definitions success = registerDefinitions(weaver, classLoader, definitions); if (success) { // after adding aspects weaver.prepareForWeave(); enable(); // TODO maw Needed to ensure messages are flushed success = weaveAndDefineConceteAspects(); } if (success) { enable(); } else { disable(); bcelWorld = null; weaver = null; } initialized = true; if (trace.isTraceEnabled()) trace.exit("initialize",isEnabled()); } /** * Load and cache the aop.xml/properties according to the classloader visibility rules * * @param weaver * @param loader */ List parseDefinitions(final ClassLoader loader) { if (trace.isTraceEnabled()) trace.enter("parseDefinitions", this); List definitions = new ArrayList(); try { info("register classloader " + getClassLoaderName(loader)); //TODO av underoptimized: we will parse each XML once per CL that see it //TODO av dev mode needed ? TBD -Daj5.def=... if (loader.equals(ClassLoader.getSystemClassLoader())) { String file = System.getProperty("aj5.def", null); if (file != null) { info("using (-Daj5.def) " + file); definitions.add(DocumentParser.parse((new File(file)).toURL())); } } String resourcePath = System.getProperty("org.aspectj.weaver.loadtime.configuration",AOP_XML); if (trace.isTraceEnabled()) trace.event("parseDefinitions",this,resourcePath); StringTokenizer st = new StringTokenizer(resourcePath,";"); while(st.hasMoreTokens()){ Enumeration xmls = weavingContext.getResources(st.nextToken()); // System.out.println("? registerDefinitions: found-aop.xml=" + xmls.hasMoreElements() + ", loader=" + loader); Set seenBefore = new HashSet(); while (xmls.hasMoreElements()) { URL xml = (URL) xmls.nextElement(); if (trace.isTraceEnabled()) trace.event("parseDefinitions",this,xml); if (!seenBefore.contains(xml)) { info("using configuration " + weavingContext.getFile(xml)); definitions.add(DocumentParser.parse(xml)); seenBefore.add(xml); } else { warn("ignoring duplicate definition: " + xml); } } } if (definitions.isEmpty()) { info("no configuration found. Disabling weaver for class loader " + getClassLoaderName(loader)); } } catch (Exception e) { definitions.clear(); warn("parse definitions failed",e); } if (trace.isTraceEnabled()) trace.exit("parseDefinitions",definitions); return definitions; } private boolean registerDefinitions(final BcelWeaver weaver, final ClassLoader loader, List definitions) { if (trace.isTraceEnabled()) trace.enter("registerDefinitions",this,definitions); boolean success = true; try { registerOptions(weaver, loader, definitions); registerAspectExclude(weaver, loader, definitions); registerAspectInclude(weaver, loader, definitions); success = registerAspects(weaver, loader, definitions); registerIncludeExclude(weaver, loader, definitions); registerDump(weaver, loader, definitions); } catch (Exception ex) { trace.error("register definition failed",ex); success = false; warn("register definition failed",(ex instanceof AbortException)?null:ex); } if (trace.isTraceEnabled()) trace.exit("registerDefinitions",success); return success; } private String getClassLoaderName (ClassLoader loader) { return weavingContext.getClassLoaderName(); } /** * Configure the weaver according to the option directives * TODO av - don't know if it is that good to reuse, since we only allow a small subset of options in LTW * * @param weaver * @param loader * @param definitions */ private void registerOptions(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { StringBuffer allOptions = new StringBuffer(); for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); allOptions.append(definition.getWeaverOptions()).append(' '); } Options.WeaverOption weaverOption = Options.parse(allOptions.toString(), loader, getMessageHandler()); // configure the weaver and world // AV - code duplicates AspectJBuilder.initWorldAndWeaver() World world = weaver.getWorld(); setMessageHandler(weaverOption.messageHandler); world.setXlazyTjp(weaverOption.lazyTjp); world.setXHasMemberSupportEnabled(weaverOption.hasMember); world.setOptionalJoinpoints(weaverOption.optionalJoinpoints); world.setPinpointMode(weaverOption.pinpoint); weaver.setReweavableMode(weaverOption.notReWeavable); world.performExtraConfiguration(weaverOption.xSet); world.setXnoInline(weaverOption.noInline); // AMC - autodetect as per line below, needed for AtAjLTWTests.testLTWUnweavable world.setBehaveInJava5Way(LangUtil.is15VMOrGreater()); world.setAddSerialVerUID(weaverOption.addSerialVersionUID); /* First load defaults */ bcelWorld.getLint().loadDefaultProperties(); /* Second overlay LTW defaults */ bcelWorld.getLint().adviceDidNotMatch.setKind(null); /* Third load user file using -Xlintfile so that -Xlint wins */ if (weaverOption.lintFile != null) { InputStream resource = null; try { resource = loader.getResourceAsStream(weaverOption.lintFile); Exception failure = null; if (resource != null) { try { Properties properties = new Properties(); properties.load(resource); world.getLint().setFromProperties(properties); } catch (IOException e) { failure = e; } } if (failure != null || resource == null) { warn("Cannot access resource for -Xlintfile:"+weaverOption.lintFile,failure); // world.getMessageHandler().handleMessage(new Message( // "Cannot access resource for -Xlintfile:"+weaverOption.lintFile, // IMessage.WARNING, // failure, // null)); } } finally { try { resource.close(); } catch (Throwable t) {;} } } /* Fourth override with -Xlint */ if (weaverOption.lint != null) { if (weaverOption.lint.equals("default")) {//FIXME should be AjBuildConfig.AJLINT_DEFAULT but yetanother deps.. bcelWorld.getLint().loadDefaultProperties(); } else { bcelWorld.getLint().setAll(weaverOption.lint); } } //TODO proceedOnError option } private void registerAspectExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { String fastMatchInfo = null; for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); for (Iterator iterator1 = definition.getAspectExcludePatterns().iterator(); iterator1.hasNext();) { String exclude = (String) iterator1.next(); TypePattern excludePattern = new PatternParser(exclude).parseTypePattern(); m_aspectExcludeTypePattern.add(excludePattern); fastMatchInfo = looksLikeStartsWith(exclude); if (fastMatchInfo != null) { m_aspectExcludeStartsWith.add(fastMatchInfo); } } } } private void registerAspectInclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { String fastMatchInfo = null; for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); for (Iterator iterator1 = definition.getAspectIncludePatterns().iterator(); iterator1.hasNext();) { String include = (String) iterator1.next(); TypePattern includePattern = new PatternParser(include).parseTypePattern(); m_aspectIncludeTypePattern.add(includePattern); fastMatchInfo = looksLikeStartsWith(include); if (fastMatchInfo != null) { m_aspectIncludeStartsWith.add(fastMatchInfo); } } } } protected void lint (String name, String[] infos) { Lint lint = bcelWorld.getLint(); Kind kind = lint.getLintKind(name); kind.signal(infos,null,null); } public String getContextId () { return weavingContext.getId(); } /** * Register the aspect, following include / exclude rules * * @param weaver * @param loader * @param definitions */ private boolean registerAspects(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { if (trace.isTraceEnabled()) trace.enter("registerAspects",this, new Object[] { weaver, loader, definitions} ); boolean success = true; //TODO: the exclude aspect allow to exclude aspect defined upper in the CL hierarchy - is it what we want ?? // if not, review the getResource so that we track which resource is defined by which CL //iterate aspectClassNames //exclude if in any of the exclude list for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); for (Iterator aspects = definition.getAspectClassNames().iterator(); aspects.hasNext();) { String aspectClassName = (String) aspects.next(); if (acceptAspect(aspectClassName)) { info("register aspect " + aspectClassName); // System.err.println("? ClassLoaderWeavingAdaptor.registerAspects() aspectName=" + aspectClassName + ", loader=" + loader + ", bundle=" + weavingContext.getClassLoaderName()); /*ResolvedType aspect = */weaver.addLibraryAspect(aspectClassName); //generate key for SC if(namespace==null){ namespace=new StringBuffer(aspectClassName); }else{ namespace = namespace.append(";"+aspectClassName); } } else { // warn("aspect excluded: " + aspectClassName); lint("aspectExcludedByConfiguration", new String[] { aspectClassName, getClassLoaderName(loader) }); } } } //iterate concreteAspects //exclude if in any of the exclude list - note that the user defined name matters for that to happen for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); for (Iterator aspects = definition.getConcreteAspects().iterator(); aspects.hasNext();) { Definition.ConcreteAspect concreteAspect = (Definition.ConcreteAspect) aspects.next(); if (acceptAspect(concreteAspect.name)) { info("define aspect " + concreteAspect.name); ConcreteAspectCodeGen gen = new ConcreteAspectCodeGen(concreteAspect, weaver.getWorld()); if (!gen.validate()) { error("Concrete-aspect '"+concreteAspect.name+"' could not be registered"); success = false; break; } ((BcelWorld)weaver.getWorld()).addSourceObjectType(Utility.makeJavaClass(concreteAspect.name, gen.getBytes())); concreteAspects.add(gen); weaver.addLibraryAspect(concreteAspect.name); //generate key for SC if(namespace==null){ namespace=new StringBuffer(concreteAspect.name); }else{ namespace = namespace.append(";"+concreteAspect.name); } } } } /* We couldn't register one or more aspects so disable the adaptor */ if (!success) { warn("failure(s) registering aspects. Disabling weaver for class loader " + getClassLoaderName(loader)); } /* We didn't register any aspects so disable the adaptor */ else if (namespace == null) { success = false; info("no aspects registered. Disabling weaver for class loader " + getClassLoaderName(loader)); } if (trace.isTraceEnabled()) trace.exit("registerAspects",success); return success; } private boolean weaveAndDefineConceteAspects () { if (trace.isTraceEnabled()) trace.enter("weaveAndDefineConceteAspects",this,concreteAspects); boolean success = true; for (Iterator iterator = concreteAspects.iterator(); iterator.hasNext();) { ConcreteAspectCodeGen gen = (ConcreteAspectCodeGen)iterator.next(); String name = gen.getClassName(); byte[] bytes = gen.getBytes(); try { byte[] newBytes = weaveClass(name, bytes,true); this.generatedClassHandler.acceptClass(name,newBytes); } catch (IOException ex) { trace.error("weaveAndDefineConceteAspects",ex); error("exception weaving aspect '" + name + "'",ex); } } if (trace.isTraceEnabled()) trace.exit("weaveAndDefineConceteAspects",success); return success; } /** * Register the include / exclude filters * We duplicate simple patterns in startWith filters that will allow faster matching without ResolvedType * * @param weaver * @param loader * @param definitions */ private void registerIncludeExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { String fastMatchInfo = null; for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); for (Iterator iterator1 = definition.getIncludePatterns().iterator(); iterator1.hasNext();) { String include = (String) iterator1.next(); TypePattern includePattern = new PatternParser(include).parseTypePattern(); m_includeTypePattern.add(includePattern); fastMatchInfo = looksLikeStartsWith(include); if (fastMatchInfo != null) { m_includeStartsWith.add(fastMatchInfo); } } for (Iterator iterator1 = definition.getExcludePatterns().iterator(); iterator1.hasNext();) { String exclude = (String) iterator1.next(); TypePattern excludePattern = new PatternParser(exclude).parseTypePattern(); m_excludeTypePattern.add(excludePattern); fastMatchInfo = looksLikeStartsWith(exclude); if (fastMatchInfo != null) { m_excludeStartsWith.add(fastMatchInfo); } } } } /** * Checks if the type pattern can be handled as a startswith check * * TODO AV - enhance to support "char.sss" ie FQN direclty (match iff equals) * we could also add support for "*..*charss" endsWith style? * * @param typePattern * @return null if not possible, or the startWith sequence to test against */ private String looksLikeStartsWith(String typePattern) { if (typePattern.indexOf('@') >= 0 || typePattern.indexOf('+') >= 0 || typePattern.indexOf(' ') >= 0 || typePattern.charAt(typePattern.length()-1) != '*') { return null; } // now must looks like with "charsss..*" or "cha.rss..*" etc // note that "*" and "*..*" won't be fast matched // and that "charsss.*" will not neither int length = typePattern.length(); if (typePattern.endsWith("..*") && length > 3) { if (typePattern.indexOf("..") == length-3 // no ".." before last sequence && typePattern.indexOf('*') == length-1) { // no "*" before last sequence return typePattern.substring(0, length-2).replace('$', '.'); // ie "charsss." or "char.rss." etc } } return null; } /** * Register the dump filter * * @param weaver * @param loader * @param definitions */ private void registerDump(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); for (Iterator iterator1 = definition.getDumpPatterns().iterator(); iterator1.hasNext();) { String dump = (String) iterator1.next(); TypePattern pattern = new PatternParser(dump).parseTypePattern(); m_dumpTypePattern.add(pattern); } if (definition.shouldDumpBefore()) { m_dumpBefore = true; } } } protected boolean accept(String className, byte[] bytes) { // avoid ResolvedType if not needed if (m_excludeTypePattern.isEmpty() && m_includeTypePattern.isEmpty()) { return true; } // still try to avoid ResolvedType if we have simple patterns String fastClassName = className.replace('/', '.').replace('$', '.'); for (int i = 0; i < m_excludeStartsWith.size(); i++) { if (fastClassName.startsWith((String)m_excludeStartsWith.get(i))) { return false; } } /* * Bug 120363 * If we have an exclude pattern that cannot be matched using "starts with" * then we cannot fast accept */ if (m_excludeTypePattern.isEmpty()) { boolean fastAccept = false;//defaults to false if no fast include for (int i = 0; i < m_includeStartsWith.size(); i++) { fastAccept = fastClassName.startsWith((String)m_includeStartsWith.get(i)); if (fastAccept) { break; } } } // needs further analysis // TODO AV - needs refactoring // during LTW this calling resolve at that stage is BAD as we do have the bytecode from the classloader hook // but still go thru resolve that will do a getResourcesAsStream on disk // this is also problematic for jit stub which are not on disk - as often underlying infra // does returns null or some other info for getResourceAsStream (f.e. WLS 9 CR248491) // Instead I parse the given bytecode. But this also means it will be parsed again in // new WeavingClassFileProvider() from WeavingAdaptor.getWovenBytes()... ensureDelegateInitialized(className,bytes); ResolvedType classInfo = delegateForCurrentClass.getResolvedTypeX();//BAD: weaver.getWorld().resolve(UnresolvedType.forName(className), true); //exclude are "AND"ed for (Iterator iterator = m_excludeTypePattern.iterator(); iterator.hasNext();) { TypePattern typePattern = (TypePattern) iterator.next(); if (typePattern.matchesStatically(classInfo)) { // exclude match - skip return false; } } //include are "OR"ed boolean accept = true;//defaults to true if no include for (Iterator iterator = m_includeTypePattern.iterator(); iterator.hasNext();) { TypePattern typePattern = (TypePattern) iterator.next(); accept = typePattern.matchesStatically(classInfo); if (accept) { break; } // goes on if this include did not match ("OR"ed) } return accept; } //FIXME we don't use include/exclude of others aop.xml //this can be nice but very dangerous as well to change that private boolean acceptAspect(String aspectClassName) { // avoid ResolvedType if not needed if (m_aspectExcludeTypePattern.isEmpty() && m_aspectIncludeTypePattern.isEmpty()) { return true; } // still try to avoid ResolvedType if we have simple patterns // EXCLUDE: if one match then reject String fastClassName = aspectClassName.replace('/', '.').replace('.', '$'); for (int i = 0; i < m_aspectExcludeStartsWith.size(); i++) { if (fastClassName.startsWith((String)m_aspectExcludeStartsWith.get(i))) { return false; } } //INCLUDE: if one match then accept for (int i = 0; i < m_aspectIncludeStartsWith.size(); i++) { if (fastClassName.startsWith((String)m_aspectIncludeStartsWith.get(i))) { return true; } } // needs further analysis ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(aspectClassName), true); //exclude are "AND"ed for (Iterator iterator = m_aspectExcludeTypePattern.iterator(); iterator.hasNext();) { TypePattern typePattern = (TypePattern) iterator.next(); if (typePattern.matchesStatically(classInfo)) { // exclude match - skip return false; } } //include are "OR"ed boolean accept = true;//defaults to true if no include for (Iterator iterator = m_aspectIncludeTypePattern.iterator(); iterator.hasNext();) { TypePattern typePattern = (TypePattern) iterator.next(); accept = typePattern.matchesStatically(classInfo); if (accept) { break; } // goes on if this include did not match ("OR"ed) } return accept; } protected boolean shouldDump(String className, boolean before) { // Don't dump before weaving unless asked to if (before && !m_dumpBefore) { return false; } // avoid ResolvedType if not needed if (m_dumpTypePattern.isEmpty()) { return false; } //TODO AV - optimize for className.startWith only ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(className), true); //dump for (Iterator iterator = m_dumpTypePattern.iterator(); iterator.hasNext();) { TypePattern typePattern = (TypePattern) iterator.next(); if (typePattern.matchesStatically(classInfo)) { // dump match return true; } } return false; } /* * shared classes methods */ /** * @return Returns the key. */ public String getNamespace() { // System.out.println("ClassLoaderWeavingAdaptor.getNamespace() classloader=" + weavingContext.getClassLoaderName() + ", namespace=" + namespace); if(namespace==null) return ""; else return new String(namespace); } /** * Check to see if any classes are stored in the generated classes cache. * Then flush the cache if it is not empty * @param className TODO * @return true if a class has been generated and is stored in the cache */ public boolean generatedClassesExistFor (String className) { // System.err.println("? ClassLoaderWeavingAdaptor.generatedClassesExist() classname=" + className + ", size=" + generatedClasses); if (className == null) return !generatedClasses.isEmpty(); else return generatedClasses.containsKey(className); } /** * Flush the generated classes cache */ public void flushGeneratedClasses() { // System.err.println("? ClassLoaderWeavingAdaptor.flushGeneratedClasses() generatedClasses=" + generatedClasses); generatedClasses = new HashMap(); } private void defineClass(ClassLoader loader, String name, byte[] bytes) { if (trace.isTraceEnabled()) trace.enter("defineClass",this,new Object[] {loader,name,bytes}); Object clazz = null; debug("generating class '" + name + "'"); try { //TODO av protection domain, and optimize Method defineClass = ClassLoader.class.getDeclaredMethod( "defineClass", new Class[] { String.class, bytes.getClass(), int.class, int.class }); defineClass.setAccessible(true); clazz = defineClass.invoke(loader, new Object[] { name, bytes, new Integer(0), new Integer(bytes.length) }); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof LinkageError) { warn("define generated class failed",e.getTargetException()); //is already defined (happens for X$ajcMightHaveAspect interfaces since aspects are reweaved) // TODO maw I don't think this is OK and } else { warn("define generated class failed",e.getTargetException()); } } catch (Exception e) { warn("define generated class failed",e); } if (trace.isTraceEnabled()) trace.exit("defineClass",clazz); } }
216,067
Bug 216067 Typo in point example
null
resolved fixed
6d906dc
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-08-20T19:31:42Z"
"2008-01-22T02:46:40Z"
docs/dist/doc/examples/introduction/Point.java
/* Copyright (c) Xerox Corporation 1998-2002. All rights reserved. Use and copying of this software and preparation of derivative works based upon this software are permitted. Any distribution of this software or derivative works must comply with all applicable United States export control laws. This software is made available AS IS, and Xerox Corporation makes no warranty about the software, its performance or its conformity to any specification. */ package introduction; public class Point { protected double x = 0; protected double y = 0; protected double theta = 0; protected double rho = 0; protected boolean polar = true; protected boolean rectangular = true; public double getX(){ makeRectangular(); return x; } public double getY(){ makeRectangular(); return y; } public double getTheta(){ makePolar(); return theta; } public double getRho(){ makePolar(); return rho; } public void setRectangular(double newX, double newY){ x = newX; y = newY; rectangular = true; polar = false; } public void setPolar(double newTheta, double newRho){ theta = newTheta; rho = newRho; rectangular = false; polar = true; } public void rotate(double angle){ setPolar(theta + angle, rho); } public void offset(double deltaX, double deltaY){ setRectangular(x + deltaX, y + deltaY); } protected void makePolar(){ if (!polar){ theta = Math.atan2(y,x); rho = y / Math.sin(theta); polar = true; } } protected void makeRectangular(){ if (!rectangular) { x = rho * Math.sin(theta); y = rho * Math.cos(theta); rectangular = true; } } public String toString(){ return "(" + getX() + ", " + getY() + ")[" + getTheta() + " : " + getRho() + "]"; } public static void main(String[] args){ Point p1 = new Point(); System.out.println("p1 =" + p1); p1.setRectangular(5,2); System.out.println("p1 =" + p1); p1.setPolar( Math.PI / 4.0 , 1.0); System.out.println("p1 =" + p1); p1.setPolar( 0.3805 , 5.385); System.out.println("p1 =" + p1); } }
244,321
Bug 244321 I cannot aspect code written in SJPP-based encoding
null
resolved fixed
d5c2ead
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-08-29T20:08:59Z"
"2008-08-15T17:06:40Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildConfig.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Adrian Colyer added constructor to populate javaOptions with * default settings - 01.20.2003 * Bugzilla #29768, 29769 * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.ajdt.internal.compiler.CompilationResultDestinationManager; import org.aspectj.util.FileUtil; /** * All configuration information needed to run the AspectJ compiler. Compiler options (as opposed to path information) are held in * an AjCompilerOptions instance */ public class AjBuildConfig implements CompilerConfigurationChangeFlags { private boolean shouldProceed = true; public static final String AJLINT_IGNORE = "ignore"; public static final String AJLINT_WARN = "warn"; public static final String AJLINT_ERROR = "error"; public static final String AJLINT_DEFAULT = "default"; private File outputDir; private File outputJar; private String outxmlName; private CompilationResultDestinationManager compilationResultDestinationManager = null; private List/* File */sourceRoots = new ArrayList(); private List/* File */changedFiles; private List/* File */files = new ArrayList(); private List /* File */binaryFiles = new ArrayList(); // .class files in indirs... private List/* File */inJars = new ArrayList(); private List/* File */inPath = new ArrayList(); private Map/* String->File */sourcePathResources = new HashMap(); private List/* File */aspectpath = new ArrayList(); private List/* String */classpath = new ArrayList(); private List/* String */bootclasspath = new ArrayList(); private File configFile; private String lintMode = AJLINT_DEFAULT; private File lintSpecFile = null; private int changes = EVERYTHING; // bitflags, see CompilerConfigurationChangeFlags private AjCompilerOptions options; /** if true, then global values override local when joining */ private boolean override = true; // incremental variants handled by the compiler client, but parsed here private boolean incrementalMode; private File incrementalFile; public String toString() { StringBuffer sb = new StringBuffer(); sb.append("BuildConfig[" + (configFile == null ? "null" : configFile.getAbsoluteFile().toString()) + "] #Files=" + files.size()); return sb.toString(); } public static class BinarySourceFile { public BinarySourceFile(File dir, File src) { this.fromInPathDirectory = dir; this.binSrc = src; } public File fromInPathDirectory; public File binSrc; public boolean equals(Object obj) { if (obj != null && (obj instanceof BinarySourceFile)) { BinarySourceFile other = (BinarySourceFile) obj; return (binSrc.equals(other.binSrc)); } return false; } public int hashCode() { return binSrc != null ? binSrc.hashCode() : 0; } } /** * Intialises the javaOptions Map to hold the default JDT Compiler settings. Added by AMC 01.20.2003 in reponse to bug #29768 * and enh. 29769. The settings here are duplicated from those set in org.eclipse.jdt.internal.compiler.batch.Main, but I've * elected to copy them rather than refactor the JDT class since this keeps integration with future JDT releases easier (?). */ public AjBuildConfig() { options = new AjCompilerOptions(); } /** * returned files includes * <ul> * <li>files explicitly listed on command-line</li> * <li>files listed by reference in argument list files</li> * <li>files contained in sourceRootDir if that exists</li> * </ul> * * @return all source files that should be compiled. */ public List/* File */getFiles() { return files; } /** * returned files includes all .class files found in a directory on the inpath, but does not include .class files contained * within jars. */ public List/* BinarySourceFile */getBinaryFiles() { return binaryFiles; } public File getOutputDir() { return outputDir; } public CompilationResultDestinationManager getCompilationResultDestinationManager() { return this.compilationResultDestinationManager; } public void setCompilationResultDestinationManager(CompilationResultDestinationManager mgr) { this.compilationResultDestinationManager = mgr; } public void setFiles(List files) { this.files = files; } public void setOutputDir(File outputDir) { this.outputDir = outputDir; } public AjCompilerOptions getOptions() { return options; } /** * This does not include -bootclasspath but includes -extdirs and -classpath */ public List getClasspath() { // XXX setters don't respect javadoc contract... return classpath; } public void setClasspath(List classpath) { this.classpath = classpath; } public List getBootclasspath() { return bootclasspath; } public void setBootclasspath(List bootclasspath) { this.bootclasspath = bootclasspath; } public File getOutputJar() { return outputJar; } public String getOutxmlName() { return outxmlName; } public List/* File */getInpath() { // Elements of the list are either archives (jars/zips) or directories return inPath; } public List/* File */getInJars() { return inJars; } public Map getSourcePathResources() { return sourcePathResources; } public void setOutputJar(File outputJar) { this.outputJar = outputJar; } public void setOutxmlName(String name) { this.outxmlName = name; } public void setInJars(List sourceJars) { this.inJars = sourceJars; } public void setInPath(List dirsOrJars) { inPath = dirsOrJars; // remember all the class files in directories on the inpath binaryFiles = new ArrayList(); FileFilter filter = new FileFilter() { public boolean accept(File pathname) { return pathname.getPath().endsWith(".class"); } }; for (Iterator iter = dirsOrJars.iterator(); iter.hasNext();) { File inpathElement = (File) iter.next(); if (inpathElement.isDirectory()) { File[] files = FileUtil.listFiles(inpathElement, filter); for (int i = 0; i < files.length; i++) { binaryFiles.add(new BinarySourceFile(inpathElement, files[i])); } } } } public List getSourceRoots() { return sourceRoots; } public void setSourceRoots(List sourceRootDir) { this.sourceRoots = sourceRootDir; } public File getConfigFile() { return configFile; } public void setConfigFile(File configFile) { this.configFile = configFile; } public void setIncrementalMode(boolean incrementalMode) { this.incrementalMode = incrementalMode; } public boolean isIncrementalMode() { return incrementalMode; } public void setIncrementalFile(File incrementalFile) { this.incrementalFile = incrementalFile; } public boolean isIncrementalFileMode() { return (null != incrementalFile); } /** * @return List (String) classpath of bootclasspath, injars, inpath, aspectpath entries, specified classpath (extdirs, and * classpath), and output dir or jar */ public List getFullClasspath() { List full = new ArrayList(); full.addAll(getBootclasspath()); // XXX Is it OK that boot classpath overrides inpath/injars/aspectpath? for (Iterator i = inJars.iterator(); i.hasNext();) { full.add(((File) i.next()).getAbsolutePath()); } for (Iterator i = inPath.iterator(); i.hasNext();) { full.add(((File) i.next()).getAbsolutePath()); } for (Iterator i = aspectpath.iterator(); i.hasNext();) { full.add(((File) i.next()).getAbsolutePath()); } full.addAll(getClasspath()); // if (null != outputDir) { // full.add(outputDir.getAbsolutePath()); // } else if (null != outputJar) { // full.add(outputJar.getAbsolutePath()); // } return full; } public File getLintSpecFile() { return lintSpecFile; } public void setLintSpecFile(File lintSpecFile) { this.lintSpecFile = lintSpecFile; } public List getAspectpath() { return aspectpath; } public void setAspectpath(List aspectpath) { this.aspectpath = aspectpath; } /** @return true if any config file, sourceroots, sourcefiles, injars or inpath */ public boolean hasSources() { return ((null != configFile) || (0 < sourceRoots.size()) || (0 < files.size()) || (0 < inJars.size()) || (0 < inPath.size())); } // /** @return null if no errors, String errors otherwise */ // public String configErrors() { // StringBuffer result = new StringBuffer(); // // ok, permit both. sigh. // // if ((null != outputDir) && (null != outputJar)) { // // result.append("specified both outputDir and outputJar"); // // } // // incremental => only sourceroots // // // return (0 == result.length() ? null : result.toString()); // } /** * Install global values into local config unless values conflict: * <ul> * <li>Collections are unioned</li> * <li>values takes local value unless default and global set</li> * <li>this only sets one of outputDir and outputJar as needed</li> * <ul> * This also configures super if javaOptions change. * * @param global the AjBuildConfig to read globals from */ public void installGlobals(AjBuildConfig global) { // XXX relies on default values // don't join the options - they already have defaults taken care of. // Map optionsMap = options.getMap(); // join(optionsMap,global.getOptions().getMap()); // options.set(optionsMap); join(aspectpath, global.aspectpath); join(classpath, global.classpath); if (null == configFile) { configFile = global.configFile; // XXX correct? } if (!isEmacsSymMode() && global.isEmacsSymMode()) { setEmacsSymMode(true); } join(files, global.files); if (!isGenerateModelMode() && global.isGenerateModelMode()) { setGenerateModelMode(true); } if (null == incrementalFile) { incrementalFile = global.incrementalFile; } if (!incrementalMode && global.incrementalMode) { incrementalMode = true; } if (isCheckRuntimeVersion() && !global.isCheckRuntimeVersion()) { setCheckRuntimeVersion(false); } join(inJars, global.inJars); join(inPath, global.inPath); if ((null == lintMode) || (AJLINT_DEFAULT.equals(lintMode))) { setLintMode(global.lintMode); } if (null == lintSpecFile) { lintSpecFile = global.lintSpecFile; } if (!isTerminateAfterCompilation() && global.isTerminateAfterCompilation()) { setTerminateAfterCompilation(true); } if ((null == outputDir) && (null == outputJar)) { if (null != global.outputDir) { outputDir = global.outputDir; } if (null != global.outputJar) { outputJar = global.outputJar; } } join(sourceRoots, global.sourceRoots); if (!isXnoInline() && global.isXnoInline()) { setXnoInline(true); } if (!isXserializableAspects() && global.isXserializableAspects()) { setXserializableAspects(true); } if (!isXlazyTjp() && global.isXlazyTjp()) { setXlazyTjp(true); } if (!getProceedOnError() && global.getProceedOnError()) { setProceedOnError(true); } setTargetAspectjRuntimeLevel(global.getTargetAspectjRuntimeLevel()); setXJoinpoints(global.getXJoinpoints()); if (!isXHasMemberEnabled() && global.isXHasMemberEnabled()) { setXHasMemberSupport(true); } if (!isXNotReweavable() && global.isXNotReweavable()) { setXnotReweavable(true); } setOutxmlName(global.getOutxmlName()); setXconfigurationInfo(global.getXconfigurationInfo()); setAddSerialVerUID(global.isAddSerialVerUID()); } void join(Collection local, Collection global) { for (Iterator iter = global.iterator(); iter.hasNext();) { Object next = iter.next(); if (!local.contains(next)) { local.add(next); } } } void join(Map local, Map global) { for (Iterator iter = global.keySet().iterator(); iter.hasNext();) { Object key = iter.next(); if (override || (null == local.get(key))) { // Object value = global.get(key); if (null != value) { local.put(key, value); } } } } public void setSourcePathResources(Map map) { sourcePathResources = map; } /** * used to indicate whether to proceed after parsing config */ public boolean shouldProceed() { return shouldProceed; } public void doNotProceed() { shouldProceed = false; } public String getLintMode() { return lintMode; } // options... public void setLintMode(String lintMode) { this.lintMode = lintMode; String lintValue = null; if (AJLINT_IGNORE.equals(lintMode)) { lintValue = AjCompilerOptions.IGNORE; } else if (AJLINT_WARN.equals(lintMode)) { lintValue = AjCompilerOptions.WARNING; } else if (AJLINT_ERROR.equals(lintMode)) { lintValue = AjCompilerOptions.ERROR; } if (lintValue != null) { Map lintOptions = new HashMap(); lintOptions.put(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName, lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName, lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportUnresolvableMember, lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver, lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportShadowNotInStructure, lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall, lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP, lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField, lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion, lintValue); options.set(lintOptions); } } public boolean isTerminateAfterCompilation() { return options.terminateAfterCompilation; } public void setTerminateAfterCompilation(boolean b) { options.terminateAfterCompilation = b; } public boolean isXserializableAspects() { return options.xSerializableAspects; } public void setXserializableAspects(boolean xserializableAspects) { options.xSerializableAspects = xserializableAspects; } public void setXJoinpoints(String jps) { options.xOptionalJoinpoints = jps; } public String getXJoinpoints() { return options.xOptionalJoinpoints; } public boolean isXnoInline() { return options.xNoInline; } public void setXnoInline(boolean xnoInline) { options.xNoInline = xnoInline; } public boolean isXlazyTjp() { return options.xLazyThisJoinPoint; } public void setXlazyTjp(boolean b) { options.xLazyThisJoinPoint = b; } public void setXnotReweavable(boolean b) { options.xNotReweavable = b; } public void setXconfigurationInfo(String info) { options.xConfigurationInfo = info; } public String getXconfigurationInfo() { return options.xConfigurationInfo; } public void setXHasMemberSupport(boolean enabled) { options.xHasMember = enabled; } public boolean isXHasMemberEnabled() { return options.xHasMember; } public void setXdevPinpointMode(boolean enabled) { options.xdevPinpoint = enabled; } public boolean isXdevPinpoint() { return options.xdevPinpoint; } public void setAddSerialVerUID(boolean b) { options.addSerialVerUID = b; } public boolean isAddSerialVerUID() { return options.addSerialVerUID; } public boolean isXNotReweavable() { return options.xNotReweavable; } public boolean isGenerateJavadocsInModelMode() { return options.generateJavaDocsInModel; } public void setGenerateJavadocsInModelMode(boolean generateJavadocsInModelMode) { options.generateJavaDocsInModel = generateJavadocsInModelMode; } public boolean isGenerateCrossRefsMode() { return options.generateCrossRefs; } public void setGenerateCrossRefsMode(boolean on) { options.generateCrossRefs = on; } public boolean isCheckRuntimeVersion() { return options.checkRuntimeVersion; } public void setCheckRuntimeVersion(boolean on) { options.checkRuntimeVersion = on; } public boolean isEmacsSymMode() { return options.generateEmacsSymFiles; } public void setEmacsSymMode(boolean emacsSymMode) { options.generateEmacsSymFiles = emacsSymMode; } public boolean isGenerateModelMode() { return options.generateModel; } public void setGenerateModelMode(boolean structureModelMode) { options.generateModel = structureModelMode; } public boolean isNoAtAspectJAnnotationProcessing() { return options.noAtAspectJProcessing; } public void setNoAtAspectJAnnotationProcessing(boolean noProcess) { options.noAtAspectJProcessing = noProcess; } public void setShowWeavingInformation(boolean b) { options.showWeavingInformation = true; } public boolean getShowWeavingInformation() { return options.showWeavingInformation; } public void setProceedOnError(boolean b) { options.proceedOnError = b; } public boolean getProceedOnError() { return options.proceedOnError; } public void setBehaveInJava5Way(boolean b) { options.behaveInJava5Way = b; } public boolean getBehaveInJava5Way() { return options.behaveInJava5Way; } public void setTargetAspectjRuntimeLevel(String level) { options.targetAspectjRuntimeLevel = level; } public String getTargetAspectjRuntimeLevel() { return options.targetAspectjRuntimeLevel; } /** * Indicates what has changed in this configuration compared to the last time it was used, allowing the state management logic * to make intelligent optimizations and skip unnecessary work. * * @param changes set of bitflags, see {@link CompilerConfigurationChangeFlags} for flags */ public void setChanged(int changes) { this.changes = changes; } /** * Return the bit flags indicating what has changed since the last time this config was used. * * @return the bitflags according too {@link CompilerConfigurationChangeFlags} */ public int getChanged() { return this.changes; } public void setModifiedFiles(List projectSourceFilesChanged) { this.changedFiles = projectSourceFilesChanged; } public List getModifiedFiles() { return this.changedFiles; } }
244,321
Bug 244321 I cannot aspect code written in SJPP-based encoding
null
resolved fixed
d5c2ead
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-08-29T20:08:59Z"
"2008-08-15T17:06:40Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import org.aspectj.ajdt.internal.compiler.AjCompilerAdapter; import org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter; import org.aspectj.ajdt.internal.compiler.IBinarySourceProvider; import org.aspectj.ajdt.internal.compiler.ICompilerAdapter; import org.aspectj.ajdt.internal.compiler.ICompilerAdapterFactory; import org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor; import org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider; import org.aspectj.ajdt.internal.compiler.InterimCompilationResult; import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment; import org.aspectj.ajdt.internal.compiler.lookup.AnonymousClassPublisher; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.internal.ProgramElement; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.CountingMessageHandler; import org.aspectj.bridge.ILifecycleAware; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.SourceLocation; import org.aspectj.bridge.Version; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextFormatter; import org.aspectj.bridge.context.ContextToken; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies; import org.aspectj.org.eclipse.jdt.internal.compiler.ICompilerRequestor; import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.ClasspathLocation; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.CompilationUnit; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.FileSystem; import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilation; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.aspectj.tools.ajc.Main; import org.aspectj.util.FileUtil; import org.aspectj.weaver.CustomMungerFactory; import org.aspectj.weaver.Dump; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.UnwovenClassFile; import org.eclipse.core.runtime.OperationCanceledException; public class AjBuildManager implements IOutputClassFileNameProvider,IBinarySourceProvider,ICompilerAdapterFactory { private static final String CROSSREFS_FILE_NAME = "build.lst"; private static final String CANT_WRITE_RESULT = "unable to write compilation result"; private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; public static boolean COPY_INPATH_DIR_RESOURCES = false; // AJDT doesn't want this check, so Main enables it. private static boolean DO_RUNTIME_VERSION_CHECK = false; // If runtime version check fails, warn or fail? (unset?) static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false; private static final FileFilter binarySourceFilter = new FileFilter() { public boolean accept(File f) { return f.getName().endsWith(".class"); }}; /** * This builder is static so that it can be subclassed and reset. However, note * that there is only one builder present, so if two extendsion reset it, only * the latter will get used. */ public static AsmHierarchyBuilder asmHierarchyBuilder = new AsmHierarchyBuilder(); static { CompilationAndWeavingContext.setMultiThreaded(false); CompilationAndWeavingContext.registerFormatter( CompilationAndWeavingContext.BATCH_BUILD, new AjBuildContexFormatter()); CompilationAndWeavingContext.registerFormatter( CompilationAndWeavingContext.INCREMENTAL_BUILD, new AjBuildContexFormatter()); } private IProgressListener progressListener = null; private boolean environmentSupportsIncrementalCompilation = false; private int compiledCount; private int sourceFileCount; private JarOutputStream zos; private boolean batchCompile = true; private INameEnvironment environment; private Map /* String -> List<UCF>*/ binarySourcesForTheNextCompile = new HashMap(); // FIXME asc should this really be in here? private IHierarchy structureModel; public AjBuildConfig buildConfig; private boolean ignoreOutxml; private boolean wasFullBuild = true; // true if last build was a full build rather than an incremental build AjState state = new AjState(this); /** * Enable check for runtime version, used only by Ant/command-line Main. * @param main Main unused except to limit to non-null clients. */ public static void enableRuntimeVersionCheck(Main caller) { DO_RUNTIME_VERSION_CHECK = null != caller; } public BcelWeaver getWeaver() { return state.getWeaver();} public BcelWorld getBcelWorld() { return state.getBcelWorld();} public CountingMessageHandler handler; private CustomMungerFactory customMungerFactory; public AjBuildManager(IMessageHandler holder) { super(); this.handler = CountingMessageHandler.makeCountingMessageHandler(holder); } public void environmentSupportsIncrementalCompilation(boolean itDoes) { this.environmentSupportsIncrementalCompilation = itDoes; } /** @return true if we should generate a model as a side-effect */ public boolean doGenerateModel() { return buildConfig.isGenerateModelMode(); } public boolean batchBuild( AjBuildConfig buildConfig, IMessageHandler baseHandler) throws IOException, AbortException { return doBuild(buildConfig, baseHandler, true); } public boolean incrementalBuild( AjBuildConfig buildConfig, IMessageHandler baseHandler) throws IOException, AbortException { return doBuild(buildConfig, baseHandler, false); } /** @throws AbortException if check for runtime fails */ protected boolean doBuild( AjBuildConfig buildConfig, IMessageHandler baseHandler, boolean batch) throws IOException, AbortException { boolean ret = true; batchCompile = batch; wasFullBuild = batch; if (baseHandler instanceof ILifecycleAware) { ((ILifecycleAware)baseHandler).buildStarting(!batch); } CompilationAndWeavingContext.reset(); int phase = batch ? CompilationAndWeavingContext.BATCH_BUILD : CompilationAndWeavingContext.INCREMENTAL_BUILD; ContextToken ct = CompilationAndWeavingContext.enteringPhase(phase ,buildConfig); try { if (batch) { this.state = new AjState(this); } this.state.setCouldBeSubsequentIncrementalBuild(this.environmentSupportsIncrementalCompilation); boolean canIncremental = state.prepareForNextBuild(buildConfig); if (!canIncremental && !batch) { // retry as batch? CompilationAndWeavingContext.leavingPhase(ct); if (state.listenerDefined()) state.getListener().recordDecision("Falling back to batch compilation"); return doBuild(buildConfig, baseHandler, true); } this.handler = CountingMessageHandler.makeCountingMessageHandler(baseHandler); if (buildConfig==null || buildConfig.isCheckRuntimeVersion()) { if (DO_RUNTIME_VERSION_CHECK) { String check = checkRtJar(buildConfig); if (check != null) { if (FAIL_IF_RUNTIME_NOT_FOUND) { MessageUtil.error(handler, check); CompilationAndWeavingContext.leavingPhase(ct); return false; } else { MessageUtil.warn(handler, check); } } } } // if (batch) { setBuildConfig(buildConfig); //} if (batch || !AsmManager.attemptIncrementalModelRepairs) { // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { setupModel(buildConfig); // } } if (batch) { initBcelWorld(handler); } if (handler.hasErrors()) { CompilationAndWeavingContext.leavingPhase(ct); return false; } if (buildConfig.getOutputJar() != null) { if (!openOutputStream(buildConfig.getOutputJar())) { CompilationAndWeavingContext.leavingPhase(ct); return false; } } if (batch) { // System.err.println("XXXX batch: " + buildConfig.getFiles()); if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { getWorld().setModel(AsmManager.getDefault().getHierarchy()); // in incremental build, only get updated model? } binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true); performCompilation(buildConfig.getFiles()); state.clearBinarySourceFiles(); // we don't want these hanging around... if (!proceedOnError() && handler.hasErrors()) { CompilationAndWeavingContext.leavingPhase(ct); if (AsmManager.isReporting()) AsmManager.getDefault().reportModelInfo("After a batch build"); return false; } if (AsmManager.isReporting()) AsmManager.getDefault().reportModelInfo("After a batch build"); } else { // done already? // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { // bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel()); // } // System.err.println("XXXX start inc "); binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true); Set files = state.getFilesToCompile(true); if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) if (AsmManager.attemptIncrementalModelRepairs) AsmManager.getDefault().processDelta(files,state.getAddedFiles(),state.getDeletedFiles()); boolean hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty()); for (int i = 0; (i < 5) && hereWeGoAgain; i++) { if (state.listenerDefined()) state.getListener().recordInformation("Starting incremental compilation loop "+(i+1)+" of possibly 5"); // System.err.println("XXXX inc: " + files); performCompilation(files); if ((!proceedOnError() && handler.hasErrors()) || (progressListener!=null && progressListener.isCancelledRequested())) { CompilationAndWeavingContext.leavingPhase(ct); return false; } if (state.requiresFullBatchBuild()) { if (state.listenerDefined()) state.getListener().recordInformation(" Dropping back to full build"); return batchBuild(buildConfig, baseHandler); } binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(false); files = state.getFilesToCompile(false); hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty()); // TODO Andy - Needs some thought here... // I think here we might want to pass empty addedFiles/deletedFiles as they were // dealt with on the first call to processDelta - we are going through this loop // again because in compiling something we found something else we needed to // rebuild. But what case causes this? if (hereWeGoAgain) { if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) if (AsmManager.attemptIncrementalModelRepairs) AsmManager.getDefault().processDelta(files,state.getAddedFiles(),state.getDeletedFiles()); } } if (!files.isEmpty()) { CompilationAndWeavingContext.leavingPhase(ct); return batchBuild(buildConfig, baseHandler); } else { if (AsmManager.isReporting()) AsmManager.getDefault().reportModelInfo("After an incremental build"); } } // XXX not in Mik's incremental if (buildConfig.isEmacsSymMode()) { new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel(); } // for bug 113554: support ajsym file generation for command line builds if (buildConfig.isGenerateCrossRefsMode()) { File configFileProxy = new File(buildConfig.getOutputDir(),CROSSREFS_FILE_NAME); AsmManager.getDefault().writeStructureModel(configFileProxy.getAbsolutePath()); } // have to tell state we succeeded or next is not incremental state.successfulCompile(buildConfig,batch); // For a full compile, copy resources to the destination // - they should not get deleted on incremental and AJDT // will handle changes to them that require a recopying if (batch) { copyResourcesToDestination(); } if (buildConfig.getOutxmlName() != null) { writeOutxmlFile(); } /*boolean weaved = *///weaveAndGenerateClassFiles(); // if not weaved, then no-op build, no model changes // but always returns true // XXX weaved not in Mik's incremental if (buildConfig.isGenerateModelMode()) { AsmManager.getDefault().fireModelUpdated(); } CompilationAndWeavingContext.leavingPhase(ct); } finally { if (baseHandler instanceof ILifecycleAware) { ((ILifecycleAware)baseHandler).buildFinished(!batch); } if (zos != null) { closeOutputStream(buildConfig.getOutputJar()); } ret = !handler.hasErrors(); if (getBcelWorld()!=null) getBcelWorld().tidyUp(); if (getWeaver()!=null) getWeaver().tidyUp(); // bug 59895, don't release reference to handler as may be needed by a nested call //handler = null; } return ret; } private boolean openOutputStream(File outJar) { try { OutputStream os = FileUtil.makeOutputStream(buildConfig.getOutputJar()); zos = new JarOutputStream(os,getWeaver().getManifest(true)); } catch (IOException ex) { IMessage message = new Message("Unable to open outjar " + outJar.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(outJar,0), true); handler.handleMessage(message); return false; } return true; } private void closeOutputStream(File outJar) { try { if (zos != null) zos.close(); zos = null; /* Ensure we don't write an incomplete JAR bug-71339 */ if (handler.hasErrors()) { outJar.delete(); } } catch (IOException ex) { IMessage message = new Message("Unable to write outjar " + outJar.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(outJar,0), true); handler.handleMessage(message); } } private void copyResourcesToDestination() throws IOException { // resources that we need to copy are contained in the injars and inpath only for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) { File inJar = (File)i.next(); copyResourcesFromJarFile(inJar); } for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) { File inPathElement = (File)i.next(); if (inPathElement.isDirectory()) { copyResourcesFromDirectory(inPathElement); } else { copyResourcesFromJarFile(inPathElement); } } if (buildConfig.getSourcePathResources() != null) { for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) { String resource = (String)i.next(); File from = (File)buildConfig.getSourcePathResources().get(resource); copyResourcesFromFile(from,resource,from); } } writeManifest(); } private void copyResourcesFromJarFile(File jarFile) throws IOException { JarInputStream inStream = null; try { inStream = new JarInputStream(new FileInputStream(jarFile)); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; String filename = entry.getName(); // System.out.println("? copyResourcesFromJarFile() filename='" + filename +"'"); if (entry.isDirectory()) { writeDirectory(filename,jarFile); } else if (acceptResource(filename,false)) { byte[] bytes = FileUtil.readAsByteArray(inStream); writeResource(filename,bytes,jarFile); } inStream.closeEntry(); } } finally { if (inStream != null) inStream.close(); } } private void copyResourcesFromDirectory(File dir) throws IOException { if (!COPY_INPATH_DIR_RESOURCES) return; // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(dir,new FileFilter() { public boolean accept(File f) { boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")) ; return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = files[i].getAbsolutePath().substring( dir.getAbsolutePath().length()+1); copyResourcesFromFile(files[i],filename,dir); } } private void copyResourcesFromFile(File f,String filename,File src) throws IOException { if (!acceptResource(filename,true)) return; FileInputStream fis = null; try { fis = new FileInputStream(f); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); writeResource(filename,bytes,src); } finally { if (fis != null) fis.close(); } } /** * Add a directory entry to the output zip file. Don't do anything if not writing out to * a zip file. A directory entry is one whose filename ends with '/' * * @param directory the directory path * @param srcloc the src of the directory entry, for use when creating a warning message * @throws IOException if something goes wrong creating the new zip entry */ private void writeDirectory(String directory, File srcloc) throws IOException { if (state.hasResource(directory)) { IMessage msg = new Message("duplicate resource: '" + directory + "'", IMessage.WARNING, null, new SourceLocation(srcloc,0)); handler.handleMessage(msg); return; } if (zos != null) { ZipEntry newEntry = new ZipEntry(directory); zos.putNextEntry(newEntry); zos.closeEntry(); state.recordResource(directory); } // Nothing to do if not writing to a zip file } private void writeResource(String filename, byte[] content, File srcLocation) throws IOException { if (state.hasResource(filename)) { IMessage msg = new Message("duplicate resource: '" + filename + "'", IMessage.WARNING, null, new SourceLocation(srcLocation,0)); handler.handleMessage(msg); return; } if (filename.equals(buildConfig.getOutxmlName())) { ignoreOutxml = true; IMessage msg = new Message("-outxml/-outxmlfile option ignored because resource already exists: '" + filename + "'", IMessage.WARNING, null, new SourceLocation(srcLocation,0)); handler.handleMessage(msg); } if (zos != null) { ZipEntry newEntry = new ZipEntry(filename); //??? get compression scheme right zos.putNextEntry(newEntry); zos.write(content); zos.closeEntry(); } else { File destDir = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { destDir = buildConfig.getCompilationResultDestinationManager().getOutputLocationForResource(srcLocation); } try { OutputStream fos = FileUtil.makeOutputStream(new File(destDir,filename)); fos.write(content); fos.close(); } catch (FileNotFoundException fnfe) { IMessage msg = new Message("unable to copy resource to output folder: '" + filename + "' - reason: "+fnfe.getMessage(), IMessage.ERROR, null, new SourceLocation(srcLocation,0)); handler.handleMessage(msg); } } state.recordResource(filename); } /* * If we are writing to an output directory copy the manifest but only * if we already have one */ private void writeManifest () throws IOException { Manifest manifest = getWeaver().getManifest(false); if (manifest != null && zos == null) { File outputDir = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { // Manifests are only written if we have a jar on the inpath. Therefore, // we write the manifest to the defaultOutputLocation because this is // where we sent the classes that were on the inpath outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation(); } if (outputDir == null) return; OutputStream fos = FileUtil.makeOutputStream(new File(outputDir,MANIFEST_NAME)); manifest.write(fos); fos.close(); } } private boolean acceptResource(String resourceName,boolean fromFile) { if ( (resourceName.startsWith("CVS/")) || (resourceName.indexOf("/CVS/") != -1) || (resourceName.endsWith("/CVS")) || (resourceName.endsWith(".class")) || (resourceName.startsWith(".svn/")) || (resourceName.indexOf("/.svn/")!=-1) || (resourceName.endsWith("/.svn")) || // Do not copy manifests if either they are coming from a jar or we are writing to a jar (resourceName.toUpperCase().equals(MANIFEST_NAME) && (!fromFile || zos!=null)) ) { return false; } else { return true; } } private void writeOutxmlFile () throws IOException { if (ignoreOutxml) return; String filename = buildConfig.getOutxmlName(); // System.err.println("? AjBuildManager.writeOutxmlFile() outxml=" + filename); Map outputDirsAndAspects = findOutputDirsForAspects(); Set outputDirs = outputDirsAndAspects.entrySet(); for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); File outputDir = (File) entry.getKey(); List aspects = (List) entry.getValue(); ByteArrayOutputStream baos = getOutxmlContents(aspects); if (zos != null) { ZipEntry newEntry = new ZipEntry(filename); zos.putNextEntry(newEntry); zos.write(baos.toByteArray()); zos.closeEntry(); } else { OutputStream fos = FileUtil.makeOutputStream(new File(outputDir, filename)); fos.write(baos.toByteArray()); fos.close(); } } } private ByteArrayOutputStream getOutxmlContents(List aspectNames) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); ps.println("<aspectj>"); ps.println("<aspects>"); if (aspectNames != null) { for (Iterator i = aspectNames.iterator(); i.hasNext();) { String name = (String) i.next(); ps.println("<aspect name=\"" + name + "\"/>"); } } ps.println("</aspects>"); ps.println("</aspectj>"); ps.println(); ps.close(); return baos; } /** * Returns a map where the keys are File objects corresponding to * all the output directories and the values are a list of aspects * which are sent to that ouptut directory */ private Map /* File --> List (String) */findOutputDirsForAspects() { Map outputDirsToAspects = new HashMap(); Map aspectNamesToFileNames = state.getAspectNamesToFileNameMap(); if (buildConfig.getCompilationResultDestinationManager() == null || buildConfig.getCompilationResultDestinationManager().getAllOutputLocations().size() == 1) { // we only have one output directory...which simplifies things File outputDir = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation(); } List aspectNames = new ArrayList(); if (aspectNamesToFileNames != null) { Set keys = aspectNamesToFileNames.keySet(); for (Iterator iterator = keys.iterator(); iterator.hasNext();) { String name = (String) iterator.next(); aspectNames.add(name); } } outputDirsToAspects.put(outputDir, aspectNames); } else { List outputDirs = buildConfig.getCompilationResultDestinationManager().getAllOutputLocations(); for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) { File outputDir = (File) iterator.next(); outputDirsToAspects.put(outputDir,new ArrayList()); } Set entrySet = aspectNamesToFileNames.entrySet(); for (Iterator iterator = entrySet.iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String aspectName = (String) entry.getKey(); char[] fileName = (char[]) entry.getValue(); File outputDir = buildConfig.getCompilationResultDestinationManager() .getOutputLocationForClass(new File(new String(fileName))); if(!outputDirsToAspects.containsKey(outputDir)) { outputDirsToAspects.put(outputDir,new ArrayList()); } ((List)outputDirsToAspects.get(outputDir)).add(aspectName); } } return outputDirsToAspects; } // public static void dumprels() { // IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap(); // int ctr = 1; // Set entries = irm.getEntries(); // for (Iterator iter = entries.iterator(); iter.hasNext();) { // String hid = (String) iter.next(); // List rels = irm.get(hid); // for (Iterator iterator = rels.iterator(); iterator.hasNext();) { // IRelationship ir = (IRelationship) iterator.next(); // List targets = ir.getTargets(); // for (Iterator iterator2 = targets.iterator(); // iterator2.hasNext(); // ) { // String thid = (String) iterator2.next(); // System.err.println("Hid:"+(ctr++)+":(targets="+targets.size()+") "+hid+" ("+ir.getName()+") "+thid); // } // } // } // } /** * Responsible for managing the ASM model between builds. Contains the policy for * maintaining the persistance of elements in the model. * * This code is driven before each 'fresh' (batch) build to create * a new model. */ private void setupModel(AjBuildConfig config) { AsmManager.setCreatingModel(config.isEmacsSymMode() || config.isGenerateModelMode()); if (!AsmManager.isCreatingModel()) return; AsmManager.getDefault().createNewASM(); // AsmManager.getDefault().getRelationshipMap().clear(); IHierarchy model = AsmManager.getDefault().getHierarchy(); String rootLabel = "<root>"; IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA; if (buildConfig.getConfigFile() != null) { rootLabel = buildConfig.getConfigFile().getName(); model.setConfigFile(buildConfig.getConfigFile().getAbsolutePath()); kind = IProgramElement.Kind.FILE_LST; } model.setRoot(new ProgramElement(rootLabel, kind, new ArrayList())); model.setFileMap(new HashMap()); setStructureModel(model); state.setStructureModel(model); state.setRelationshipMap(AsmManager.getDefault().getRelationshipMap()); } // // private void dumplist(List l) { // System.err.println("---- "+l.size()); // for (int i =0 ;i<l.size();i++) System.err.println(i+"\t "+l.get(i)); // } // private void accumulateFileNodes(IProgramElement ipe,List store) { // if (ipe.getKind()==IProgramElement.Kind.FILE_JAVA || // ipe.getKind()==IProgramElement.Kind.FILE_ASPECTJ) { // if (!ipe.getName().equals("<root>")) { // store.add(ipe); // return; // } // } // for (Iterator i = ipe.getChildren().iterator();i.hasNext();) { // accumulateFileNodes((IProgramElement)i.next(),store); // } // } //LTODO delegate to BcelWeaver? // XXX hideous, should not be Object public void setCustomMungerFactory(Object o) { customMungerFactory = (CustomMungerFactory)o; } public Object getCustomMungerFactory() { return customMungerFactory; } /** init only on initial batch compile? no file-specific options */ private void initBcelWorld(IMessageHandler handler) throws IOException { List cp = buildConfig.getFullClasspath(); // pr145693 //buildConfig.getBootclasspath(); //cp.addAll(buildConfig.getClasspath()); BcelWorld bcelWorld = new BcelWorld(cp, handler, null); bcelWorld.setBehaveInJava5Way(buildConfig.getBehaveInJava5Way()); bcelWorld.setAddSerialVerUID(buildConfig.isAddSerialVerUID()); bcelWorld.performExtraConfiguration(buildConfig.getXconfigurationInfo()); bcelWorld.setTargetAspectjRuntimeLevel(buildConfig.getTargetAspectjRuntimeLevel()); bcelWorld.setOptionalJoinpoints(buildConfig.getXJoinpoints()); bcelWorld.setXnoInline(buildConfig.isXnoInline()); bcelWorld.setXlazyTjp(buildConfig.isXlazyTjp()); bcelWorld.setXHasMemberSupportEnabled(buildConfig.isXHasMemberEnabled()); bcelWorld.setPinpointMode(buildConfig.isXdevPinpoint()); bcelWorld.setErrorAndWarningThreshold(buildConfig.getOptions().errorThreshold,buildConfig.getOptions().warningThreshold); BcelWeaver bcelWeaver = new BcelWeaver(bcelWorld); bcelWeaver.setCustomMungerFactory(customMungerFactory); state.setWorld(bcelWorld); state.setWeaver(bcelWeaver); state.clearBinarySourceFiles(); if (buildConfig.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT)) { bcelWorld.getLint().loadDefaultProperties(); } else { bcelWorld.getLint().setAll(buildConfig.getLintMode()); } if (buildConfig.getLintSpecFile() != null) { bcelWorld.getLint().setFromProperties(buildConfig.getLintSpecFile()); } for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext();) { File f = (File) i.next(); if (!f.exists()) { IMessage message = new Message("invalid aspectpath entry: "+f.getName(),null,true); handler.handleMessage(message); } else { bcelWeaver.addLibraryJarFile(f); } } // String lintMode = buildConfig.getLintMode(); File outputDir = buildConfig.getOutputDir(); if (outputDir == null && buildConfig.getCompilationResultDestinationManager() != null) { // send all output from injars and inpath to the default output location // (will also later send the manifest there too) outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation(); } // ??? incremental issues for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext();) { File inJar = (File) i.next(); List unwovenClasses = bcelWeaver.addJarFile(inJar, outputDir, false); state.recordBinarySource(inJar.getPath(), unwovenClasses); } for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) { File inPathElement = (File)i.next(); if (!inPathElement.isDirectory()) { // its a jar file on the inpath // the weaver method can actually handle dirs, but we don't call it, see next block List unwovenClasses = bcelWeaver.addJarFile(inPathElement,outputDir,true); state.recordBinarySource(inPathElement.getPath(),unwovenClasses); } else { // add each class file in an in-dir individually, this gives us the best error reporting // (they are like 'source' files then), and enables a cleaner incremental treatment of // class file changes in indirs. File[] binSrcs = FileUtil.listFiles(inPathElement, binarySourceFilter); for (int j = 0; j < binSrcs.length; j++) { UnwovenClassFile ucf = bcelWeaver.addClassFile(binSrcs[j], inPathElement, outputDir); List ucfl = new ArrayList(); ucfl.add(ucf); state.recordBinarySource(binSrcs[j].getPath(),ucfl); } } } bcelWeaver.setReweavableMode(buildConfig.isXNotReweavable()); //check for org.aspectj.runtime.JoinPoint ResolvedType joinPoint = bcelWorld.resolve("org.aspectj.lang.JoinPoint"); if (joinPoint.isMissing()) { IMessage message = new Message("classpath error: unable to find org.aspectj.lang.JoinPoint (check that aspectjrt.jar is in your classpath)", null, true); handler.handleMessage(message); } } public World getWorld() { return getBcelWorld(); } void addAspectClassFilesToWeaver(List addedClassFiles) throws IOException { for (Iterator i = addedClassFiles.iterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile) i.next(); getWeaver().addClassFile(classFile); } } // public boolean weaveAndGenerateClassFiles() throws IOException { // handler.handleMessage(MessageUtil.info("weaving")); // if (progressListener != null) progressListener.setText("weaving aspects"); // bcelWeaver.setProgressListener(progressListener, 0.5, 0.5/state.addedClassFiles.size()); // //!!! doesn't provide intermediate progress during weaving // // XXX add all aspects even during incremental builds? // addAspectClassFilesToWeaver(state.addedClassFiles); // if (buildConfig.isNoWeave()) { // if (buildConfig.getOutputJar() != null) { // bcelWeaver.dumpUnwoven(buildConfig.getOutputJar()); // } else { // bcelWeaver.dumpUnwoven(); // bcelWeaver.dumpResourcesToOutPath(); // } // } else { // if (buildConfig.getOutputJar() != null) { // bcelWeaver.weave(buildConfig.getOutputJar()); // } else { // bcelWeaver.weave(); // bcelWeaver.dumpResourcesToOutPath(); // } // } // if (progressListener != null) progressListener.setProgress(1.0); // return true; // //return messageAdapter.getErrorCount() == 0; //!javaBuilder.notifier.anyErrors(); // } public FileSystem getLibraryAccess(String[] classpaths, String[] filenames) { String defaultEncoding = buildConfig.getOptions().defaultEncoding; if ("".equals(defaultEncoding)) //$NON-NLS-1$ defaultEncoding = null; //$NON-NLS-1$ // Bug 46671: We need an array as long as the number of elements in the classpath - *even though* not every // element of the classpath is likely to be a directory. If we ensure every element of the array is set to // only look for BINARY, then we make sure that for any classpath element that is a directory, we won't build // a classpathDirectory object that will attempt to look for source when it can't find binary. // int[] classpathModes = new int[classpaths.length]; // for (int i =0 ;i<classpaths.length;i++) classpathModes[i]=ClasspathDirectory.BINARY; return new FileSystem(classpaths, filenames, defaultEncoding,ClasspathLocation.BINARY); } public IProblemFactory getProblemFactory() { return new DefaultProblemFactory(Locale.getDefault()); } /* * Build the set of compilation source units */ public CompilationUnit[] getCompilationUnits(String[] filenames, String[] encodings) { int fileCount = filenames.length; CompilationUnit[] units = new CompilationUnit[fileCount]; // HashtableOfObject knownFileNames = new HashtableOfObject(fileCount); String defaultEncoding = buildConfig.getOptions().defaultEncoding; if ("".equals(defaultEncoding)) //$NON-NLS-1$ defaultEncoding = null; //$NON-NLS-1$ for (int i = 0; i < fileCount; i++) { String encoding = encodings[i]; if (encoding == null) encoding = defaultEncoding; units[i] = new CompilationUnit(null, filenames[i], encoding); } return units; } public String extractDestinationPathFromSourceFile(CompilationResult result) { ICompilationUnit compilationUnit = result.compilationUnit; if (compilationUnit != null) { char[] fileName = compilationUnit.getFileName(); int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName); if (lastIndex == -1) { return System.getProperty("user.dir"); //$NON-NLS-1$ } return new String(CharOperation.subarray(fileName, 0, lastIndex)); } return System.getProperty("user.dir"); //$NON-NLS-1$ } public void performCompilation(Collection files) { if (progressListener != null) { compiledCount=0; sourceFileCount = files.size(); progressListener.setText("compiling source files"); } //System.err.println("got files: " + files); String[] filenames = new String[files.size()]; String[] encodings = new String[files.size()]; //System.err.println("filename: " + this.filenames); int ii = 0; for (Iterator fIterator = files.iterator(); fIterator.hasNext();) { File f = (File) fIterator.next(); filenames[ii++] = f.getPath(); } List cps = buildConfig.getFullClasspath(); Dump.saveFullClasspath(cps); String[] classpaths = new String[cps.size()]; for (int i=0; i < cps.size(); i++) { classpaths[i] = (String)cps.get(i); } //System.out.println("compiling"); environment = getLibraryAccess(classpaths, filenames); //if (!state.getClassNameToFileMap().isEmpty()) { // see pr133532 (disabled to state can be used to answer questions) environment = new StatefulNameEnvironment(environment, state.getClassNameToFileMap(),state); //} org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(this); org.aspectj.org.eclipse.jdt.internal.compiler.Compiler compiler = new org.aspectj.org.eclipse.jdt.internal.compiler.Compiler(environment, DefaultErrorHandlingPolicies.proceedWithAllProblems(), buildConfig.getOptions().getMap(), getBatchRequestor(), getProblemFactory()); CompilerOptions options = compiler.options; options.produceReferenceInfo = true; //TODO turn off when not needed try { compiler.compile(getCompilationUnits(filenames, encodings)); } catch (OperationCanceledException oce) { handler.handleMessage(new Message("build cancelled:"+oce.getMessage(),IMessage.WARNING,null,null)); } // cleanup org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(null); AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(null); environment.cleanup(); environment = null; } /* * Answer the component to which will be handed back compilation results from the compiler */ public IIntermediateResultsRequestor getInterimResultRequestor() { return new IIntermediateResultsRequestor() { public void acceptResult(InterimCompilationResult result) { if (progressListener != null) { compiledCount++; progressListener.setProgress((compiledCount/2.0)/sourceFileCount); progressListener.setText("compiled: " + result.fileName()); } state.noteResult(result); if (progressListener!=null && progressListener.isCancelledRequested()) { throw new AbortCompilation(true, new OperationCanceledException("Compilation cancelled as requested")); } } }; } public ICompilerRequestor getBatchRequestor() { return new ICompilerRequestor() { public void acceptResult(CompilationResult unitResult) { // end of compile, must now write the results to the output destination // this is either a jar file or a file in a directory if (!unitResult.hasErrors() || proceedOnError()) { Collection classFiles = unitResult.compiledTypes.values(); boolean shouldAddAspectName = (buildConfig.getOutxmlName() != null); for (Iterator iter = classFiles.iterator(); iter.hasNext();) { ClassFile classFile = (ClassFile) iter.next(); String filename = new String(classFile.fileName()); String classname = filename.replace('/', '.'); filename = filename.replace('/', File.separatorChar) + ".class"; try { if (buildConfig.getOutputJar() == null) { writeDirectoryEntry(unitResult, classFile,filename); } else { writeZipEntry(classFile,filename); } if (shouldAddAspectName) addAspectName(classname, unitResult.getFileName()); } catch (IOException ex) { IMessage message = EclipseAdapterUtils.makeErrorMessage( new String(unitResult.fileName), CANT_WRITE_RESULT, ex); handler.handleMessage(message); } } unitResult.compiledTypes.clear(); // free up references to AjClassFile instances } if (unitResult.hasProblems() || unitResult.hasTasks()) { IProblem[] problems = unitResult.getAllProblems(); for (int i=0; i < problems.length; i++) { IMessage message = EclipseAdapterUtils.makeMessage(unitResult.compilationUnit, problems[i],getBcelWorld()); handler.handleMessage(message); } } } private void writeDirectoryEntry( CompilationResult unitResult, ClassFile classFile, String filename) throws IOException { File destinationPath = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { destinationPath = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass(new File(new String(unitResult.fileName))); } String outFile; if (destinationPath == null) { outFile = new File(filename).getName(); outFile = new File(extractDestinationPathFromSourceFile(unitResult), outFile).getPath(); } else { outFile = new File(destinationPath, filename).getPath(); } BufferedOutputStream os = FileUtil.makeOutputStream(new File(outFile)); os.write(classFile.getBytes()); os.close(); } private void writeZipEntry(ClassFile classFile, String name) throws IOException { name = name.replace(File.separatorChar,'/'); ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right zos.putNextEntry(newEntry); zos.write(classFile.getBytes()); zos.closeEntry(); } private void addAspectName (String name, char[] fileContainingAspect) { BcelWorld world = getBcelWorld(); ResolvedType type = world.resolve(name); // System.err.println("? writeAspectName() type=" + type); if (type.isAspect()) { if (state.getAspectNamesToFileNameMap() == null) { state.initializeAspectNamesToFileNameMap(); } if (!state.getAspectNamesToFileNameMap().containsKey(name)) { state.getAspectNamesToFileNameMap().put(name, fileContainingAspect); } } } }; } protected boolean proceedOnError() { return buildConfig.getProceedOnError(); } // public void noteClassFiles(AjCompiler.InterimResult result) { // if (result == null) return; // CompilationResult unitResult = result.result; // String sourceFileName = result.fileName(); // if (!(unitResult.hasErrors() && !proceedOnError())) { // List unwovenClassFiles = new ArrayList(); // Enumeration classFiles = unitResult.compiledTypes.elements(); // while (classFiles.hasMoreElements()) { // ClassFile classFile = (ClassFile) classFiles.nextElement(); // String filename = new String(classFile.fileName()); // filename = filename.replace('/', File.separatorChar) + ".class"; // // File destinationPath = buildConfig.getOutputDir(); // if (destinationPath == null) { // filename = new File(filename).getName(); // filename = new File(extractDestinationPathFromSourceFile(unitResult), filename).getPath(); // } else { // filename = new File(destinationPath, filename).getPath(); // } // // //System.out.println("classfile: " + filename); // unwovenClassFiles.add(new UnwovenClassFile(filename, classFile.getBytes())); // } // state.noteClassesFromFile(unitResult, sourceFileName, unwovenClassFiles); //// System.out.println("file: " + sourceFileName); //// for (int i=0; i < unitResult.simpleNameReferences.length; i++) { //// System.out.println("simple: " + new String(unitResult.simpleNameReferences[i])); //// } //// for (int i=0; i < unitResult.qualifiedReferences.length; i++) { //// System.out.println("qualified: " + //// new String(CharOperation.concatWith(unitResult.qualifiedReferences[i], '/'))); //// } // } else { // state.noteClassesFromFile(null, sourceFileName, Collections.EMPTY_LIST); // } // } // private void setBuildConfig(AjBuildConfig buildConfig) { this.buildConfig = buildConfig; if (!this.environmentSupportsIncrementalCompilation) { this.environmentSupportsIncrementalCompilation = (buildConfig.isIncrementalMode() || buildConfig.isIncrementalFileMode()); } handler.reset(); } String makeClasspathString(AjBuildConfig buildConfig) { if (buildConfig == null || buildConfig.getFullClasspath() == null) return ""; StringBuffer buf = new StringBuffer(); boolean first = true; for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) { if (first) { first = false; } else { buf.append(File.pathSeparator); } buf.append(it.next().toString()); } return buf.toString(); } /** * This will return null if aspectjrt.jar is present and has the correct version. * Otherwise it will return a string message indicating the problem. */ private String checkRtJar(AjBuildConfig buildConfig) { // omitting dev info if (Version.text.equals(Version.DEVELOPMENT)) { // in the development version we can't do this test usefully // MessageUtil.info(holder, "running development version of aspectj compiler"); return null; } if (buildConfig == null || buildConfig.getFullClasspath() == null) return "no classpath specified"; String ret = null; for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) { File p = new File( (String)it.next() ); // pr112830, allow variations on aspectjrt.jar of the form aspectjrtXXXXXX.jar if (p.isFile() && p.getName().startsWith("aspectjrt") && p.getName().endsWith(".jar")) { try { String version = null; Manifest manifest = new JarFile(p).getManifest(); if (manifest == null) { ret = "no manifest found in " + p.getAbsolutePath() + ", expected " + Version.text; continue; } Attributes attr = manifest.getAttributes("org/aspectj/lang/"); if (null != attr) { version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION); if (null != version) { version = version.trim(); } } // assume that users of development aspectjrt.jar know what they're doing if (Version.DEVELOPMENT.equals(version)) { // MessageUtil.info(holder, // "running with development version of aspectjrt.jar in " + // p.getAbsolutePath()); return null; } else if (!Version.text.equals(version)) { ret = "bad version number found in " + p.getAbsolutePath() + " expected " + Version.text + " found " + version; continue; } } catch (IOException ioe) { ret = "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe; } return null; // this is the "OK" return value! } else { // might want to catch other classpath errors } } if (ret != null) return ret; // last error found in potentially matching jars... return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString(buildConfig); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("AjBuildManager("); buf.append(")"); return buf.toString(); } public void setStructureModel(IHierarchy structureModel) { this.structureModel = structureModel; } /** * Returns null if there is no structure model */ public IHierarchy getStructureModel() { return structureModel; } public IProgressListener getProgressListener() { return progressListener; } public void setProgressListener(IProgressListener progressListener) { this.progressListener = progressListener; } /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.AjCompiler.IOutputClassFileNameProvider#getOutputClassFileName(char[]) */ public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) { String filename = new String(eclipseClassFileName); filename = filename.replace('/', File.separatorChar) + ".class"; File destinationPath = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { File f = new File(new String(result.getFileName())); destinationPath = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass(f); } String outFile; if (destinationPath == null) { outFile = new File(filename).getName(); outFile = new File(extractDestinationPathFromSourceFile(result), outFile).getPath(); } else { outFile = new File(destinationPath, filename).getPath(); } return outFile; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler) */ public ICompilerAdapter getAdapter(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) { // complete compiler config and return a suitable adapter... populateCompilerOptionsFromLintSettings(forCompiler); AjProblemReporter pr = new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(), forCompiler.options, getProblemFactory()); forCompiler.problemReporter = pr; AjLookupEnvironment le = new AjLookupEnvironment(forCompiler, forCompiler.options, pr, environment); EclipseFactory factory = new EclipseFactory(le,this); le.factory = factory; pr.factory = factory; forCompiler.lookupEnvironment = le; forCompiler.parser = new Parser( pr, forCompiler.options.parseLiteralExpressionsAsConstants); if (getBcelWorld().shouldPipelineCompilation()) { IMessage message = MessageUtil.info("Pipelining compilation"); handler.handleMessage(message); return new AjPipeliningCompilerAdapter(forCompiler,batchCompile,getBcelWorld(),getWeaver(), factory, getInterimResultRequestor(), progressListener, this, // IOutputFilenameProvider this, // IBinarySourceProvider state.getBinarySourceMap(), buildConfig.isTerminateAfterCompilation(), buildConfig.getProceedOnError(), buildConfig.isNoAtAspectJAnnotationProcessing(), state); } else { return new AjCompilerAdapter(forCompiler,batchCompile,getBcelWorld(),getWeaver(), factory, getInterimResultRequestor(), progressListener, this, // IOutputFilenameProvider this, // IBinarySourceProvider state.getBinarySourceMap(), buildConfig.isTerminateAfterCompilation(), buildConfig.getProceedOnError(), buildConfig.isNoAtAspectJAnnotationProcessing(), state); } } /** * Some AspectJ lint options need to be known about in the compiler. This is * how we pass them over... * @param forCompiler */ private void populateCompilerOptionsFromLintSettings(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) { BcelWorld world = this.state.getBcelWorld(); IMessage.Kind swallowedExceptionKind = world.getLint().swallowedExceptionInCatchBlock.getKind(); Map optionsMap = new HashMap(); optionsMap.put(CompilerOptions.OPTION_ReportSwallowedExceptionInCatchBlock, swallowedExceptionKind == null ? "ignore" : swallowedExceptionKind.toString()); forCompiler.options.set(optionsMap); } /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.IBinarySourceProvider#getBinarySourcesForThisWeave() */ public Map getBinarySourcesForThisWeave() { return binarySourcesForTheNextCompile; } public static AsmHierarchyBuilder getAsmHierarchyBuilder() { return asmHierarchyBuilder; } /** * Override the the default hierarchy builder. */ public static void setAsmHierarchyBuilder(AsmHierarchyBuilder newBuilder) { asmHierarchyBuilder = newBuilder; } public AjState getState() { return state; } public void setState(AjState buildState) { state = buildState; } private static class AjBuildContexFormatter implements ContextFormatter { public String formatEntry(int phaseId, Object data) { StringBuffer sb = new StringBuffer(); if (phaseId == CompilationAndWeavingContext.BATCH_BUILD) { sb.append("batch building "); } else { sb.append("incrementally building "); } AjBuildConfig config = (AjBuildConfig) data; List classpath = config.getClasspath(); sb.append("with classpath: "); for (Iterator iter = classpath.iterator(); iter.hasNext();) { sb.append(iter.next().toString()); sb.append(File.pathSeparator); } return sb.toString(); } } public boolean wasFullBuild() { return wasFullBuild; } }
246,021
Bug 246021 FindBugs reporting another optimization
Ben Hale reported that FindBugs was producing a warning about a dead store to a local variable (a variable that is never then read within the method). This bug is to investigate and hopefully remove the dead store.
resolved fixed
78a483d
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-09-03T00:28:44Z"
"2008-09-02T21:13:20Z"
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.ConstantPool; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.generic.ArrayType; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.INVOKEINTERFACE; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionBranch; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionLV; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InstructionTargeter; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.LineNumberTag; import org.aspectj.apache.bcel.generic.LocalVariableTag; import org.aspectj.apache.bcel.generic.MULTIANEWARRAY; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.TargetLostException; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.BCException; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.MemberImpl; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Var; import org.aspectj.weaver.patterns.AbstractPatternNodeVisitor; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.NotPointcut; import org.aspectj.weaver.patterns.OrPointcut; import org.aspectj.weaver.patterns.ThisOrTargetPointcut; /* * Some fun implementation stuff: * * * expressionKind advice is non-execution advice * * may have a target. * * if the body is extracted, it will be extracted into * a static method. The first argument to the static * method is the target * * advice may expose a this object, but that's the advice's * consideration, not ours. This object will NOT be cached in another * local, but will always come from frame zero. * * * non-expressionKind advice is execution advice * * may have a this. * * target is same as this, and is exposed that way to advice * (i.e., target will not be cached, will always come from frame zero) * * if the body is extracted, it will be extracted into a method * with same static/dynamic modifier as enclosing method. If non-static, * target of callback call will be this. * * * because of these two facts, the setup of the actual arguments (including * possible target) callback method is the same for both kinds of advice: * push the targetVar, if it exists (it will not exist for advice on static * things), then push all the argVars. * * Protected things: * * * the above is sufficient for non-expressionKind advice for protected things, * since the target will always be this. * * * For expressionKind things, we have to modify the signature of the callback * method slightly. For non-static expressionKind things, we modify * the first argument of the callback method NOT to be the type specified * by the method/field signature (the owner), but rather we type it to * the currentlyEnclosing type. We are guaranteed this will be fine, * since the verifier verifies that the target is a subtype of the currently * enclosingType. * * Worries: * * * ConstructorCalls will be weirder than all of these, since they * supposedly don't have a target (according to AspectJ), but they clearly * do have a target of sorts, just one that needs to be pushed on the stack, * dupped, and not touched otherwise until the constructor runs. * * @author Jim Hugunin * @author Erik Hilsdale * */ public class BcelShadow extends Shadow { private ShadowRange range; private final BcelWorld world; private final LazyMethodGen enclosingMethod; // SECRETAPI - for testing, this will tell us if the optimization succeeded *on the last shadow processed* public static boolean appliedLazyTjpOptimization; // Some instructions have a target type that will vary // from the signature (pr109728) (1.4 declaring type issue) private String actualInstructionTargetType; /** * This generates an unassociated shadow, rooted in a particular method but not rooted to any particular point in the code. It * should be given to a rooted ShadowRange in the {@link ShadowRange#associateWithShadow(BcelShadow)} method. */ public BcelShadow(BcelWorld world, Kind kind, Member signature, LazyMethodGen enclosingMethod, BcelShadow enclosingShadow) { super(kind, signature, enclosingShadow); this.world = world; this.enclosingMethod = enclosingMethod; } // ---- copies all state, including Shadow's mungers... public BcelShadow copyInto(LazyMethodGen recipient, BcelShadow enclosing) { BcelShadow s = new BcelShadow(world, getKind(), getSignature(), recipient, enclosing); if (mungers.size() > 0) { List src = mungers; if (s.mungers == Collections.EMPTY_LIST) s.mungers = new ArrayList(); List dest = s.mungers; for (Iterator i = src.iterator(); i.hasNext();) { dest.add(i.next()); } } return s; } // ---- overridden behaviour public World getIWorld() { return world; } private void deleteNewAndDup() { final ConstantPool cpg = getEnclosingClass().getConstantPool(); int depth = 1; InstructionHandle ih = range.getStart(); // Go back from where we are looking for 'NEW' that takes us to a stack depth of 0. INVOKESPECIAL <init> while (true) { Instruction inst = ih.getInstruction(); if (inst.opcode == Constants.INVOKESPECIAL && ((InvokeInstruction) inst).getName(cpg).equals("<init>")) { depth++; } else if (inst.opcode == Constants.NEW) { depth--; if (depth == 0) break; } else if (inst.opcode == Constants.DUP_X2) { // This code seen in the wild (by Brad): // 40: new #12; //class java/lang/StringBuffer // STACK: STRINGBUFFER // 43: dup // STACK: STRINGBUFFER/STRINGBUFFER // 44: aload_0 // STACK: STRINGBUFFER/STRINGBUFFER/THIS // 45: dup_x2 // STACK: THIS/STRINGBUFFER/STRINGBUFFER/THIS // 46: getfield #36; //Field value:Ljava/lang/String; // STACK: THIS/STRINGBUFFER/STRINGBUFFER/STRING<value> // 49: invokestatic #37; //Method java/lang/String.valueOf:(Ljava/lang/Object;)Ljava/lang/String; // STACK: THIS/STRINGBUFFER/STRINGBUFFER/STRING // 52: invokespecial #19; //Method java/lang/StringBuffer."<init>":(Ljava/lang/String;)V // STACK: THIS/STRINGBUFFER // 55: aload_1 // STACK: THIS/STRINGBUFFER/LOCAL1 // 56: invokevirtual #22; //Method java/lang/StringBuffer.append:(Ljava/lang/String;)Ljava/lang/StringBuffer; // STACK: THIS/STRINGBUFFER // 59: invokevirtual #34; //Method java/lang/StringBuffer.toString:()Ljava/lang/String; // STACK: THIS/STRING // 62: putfield #36; //Field value:Ljava/lang/String; // STACK: <empty> // 65: return // if we attempt to match on the ctor call to StringBuffer.<init> then we get into trouble. // if we simply delete the new/dup pair without fixing up the dup_x2 then the dup_x2 will fail due to there // not being 3 elements on the stack for it to work with. The fix *in this situation* is to change it to // a simple 'dup' // this fix is *not* very clean - but a general purpose decent solution will take much longer and this // bytecode sequence has only been seen once in the wild. ih.setInstruction(InstructionConstants.DUP); } ih = ih.getPrev(); } // now IH points to the NEW. We're followed by the DUP, and that is followed // by the actual instruction we care about. InstructionHandle newHandle = ih; InstructionHandle endHandle = newHandle.getNext(); InstructionHandle nextHandle; if (endHandle.getInstruction().opcode == Constants.DUP) { nextHandle = endHandle.getNext(); retargetFrom(newHandle, nextHandle); retargetFrom(endHandle, nextHandle); } else if (endHandle.getInstruction().opcode == Constants.DUP_X1) { InstructionHandle dupHandle = endHandle; endHandle = endHandle.getNext(); nextHandle = endHandle.getNext(); if (endHandle.getInstruction().opcode == Constants.SWAP) { } else { // XXX see next XXX comment throw new RuntimeException("Unhandled kind of new " + endHandle); } // Now make any jumps to the 'new', the 'dup' or the 'end' now target the nextHandle retargetFrom(newHandle, nextHandle); retargetFrom(dupHandle, nextHandle); retargetFrom(endHandle, nextHandle); } else { endHandle = newHandle; nextHandle = endHandle.getNext(); retargetFrom(newHandle, nextHandle); // add a POP here... we found a NEW w/o a dup or anything else, so // we must be in statement context. getRange().insert(InstructionConstants.POP, Range.OutsideAfter); } // assert (dupHandle.getInstruction() instanceof DUP); try { range.getBody().delete(newHandle, endHandle); } catch (TargetLostException e) { throw new BCException("shouldn't happen"); } } private void retargetFrom(InstructionHandle old, InstructionHandle fresh) { InstructionTargeter[] sources = old.getTargetersArray(); if (sources != null) { for (int i = sources.length - 1; i >= 0; i--) { if (sources[i] instanceof ExceptionRange) { ExceptionRange it = (ExceptionRange) sources[i]; System.err.println("..."); it.updateTarget(old, fresh, it.getBody()); } else { sources[i].updateTarget(old, fresh); } } } } // records advice that is stopping us doing the lazyTjp optimization private List badAdvice = null; public void addAdvicePreventingLazyTjp(BcelAdvice advice) { if (badAdvice == null) badAdvice = new ArrayList(); badAdvice.add(advice); } protected void prepareForMungers() { // if we're a constructor call, we need to remove the new:dup or the new:dup_x1:swap, // and store all our // arguments on the frame. // ??? This is a bit of a hack (for the Java langauge). We do this because // we sometime add code "outsideBefore" when dealing with weaving join points. We only // do this for exposing state that is on the stack. It turns out to just work for // everything except for constructor calls and exception handlers. If we were to clean // this up, every ShadowRange would have three instructionHandle points, the start of // the arg-setup code, the start of the running code, and the end of the running code. if (getKind() == ConstructorCall) { if (!world.isJoinpointArrayConstructionEnabled() || !this.getSignature().getDeclaringType().isArray()) deleteNewAndDup(); // no new/dup for new array construction initializeArgVars(); } else if (getKind() == PreInitialization) { // pr74952 ShadowRange range = getRange(); range.insert(InstructionConstants.NOP, Range.InsideAfter); } else if (getKind() == ExceptionHandler) { ShadowRange range = getRange(); InstructionList body = range.getBody(); InstructionHandle start = range.getStart(); // Create a store instruction to put the value from the top of the // stack into a local variable slot. This is a trimmed version of // what is in initializeArgVars() (since there is only one argument // at a handler jp and only before advice is supported) (pr46298) argVars = new BcelVar[1]; // int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0); UnresolvedType tx = getArgType(0); argVars[0] = genTempVar(tx, "ajc$arg0"); InstructionHandle insertedInstruction = range.insert(argVars[0].createStore(getFactory()), Range.OutsideBefore); // Now the exception range starts just after our new instruction. // The next bit of code changes the exception range to point at // the store instruction InstructionTargeter[] targeters = start.getTargetersArray(); for (int i = 0; i < targeters.length; i++) { InstructionTargeter t = targeters[i]; if (t instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) t; er.updateTarget(start, insertedInstruction, body); } } } // now we ask each munger to request our state isThisJoinPointLazy = true;// world.isXlazyTjp(); // lazy is default now badAdvice = null; for (Iterator iter = mungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); munger.specializeOn(this); } initializeThisJoinPoint(); if (thisJoinPointVar != null && !isThisJoinPointLazy && badAdvice != null && badAdvice.size() > 1) { // something stopped us making it a lazy tjp // can't build tjp lazily, no suitable test... int valid = 0; for (Iterator iter = badAdvice.iterator(); iter.hasNext();) { BcelAdvice element = (BcelAdvice) iter.next(); ISourceLocation sLoc = element.getSourceLocation(); if (sLoc != null && sLoc.getLine() > 0) valid++; } if (valid != 0) { ISourceLocation[] badLocs = new ISourceLocation[valid]; int i = 0; for (Iterator iter = badAdvice.iterator(); iter.hasNext();) { BcelAdvice element = (BcelAdvice) iter.next(); ISourceLocation sLoc = element.getSourceLocation(); if (sLoc != null) badLocs[i++] = sLoc; } world.getLint().multipleAdviceStoppingLazyTjp .signal(new String[] { this.toString() }, getSourceLocation(), badLocs); } } badAdvice = null; // If we are an expression kind, we require our target/arguments on the stack // before we do our actual thing. However, they may have been removed // from the stack as the shadowMungers have requested state. // if any of our shadowMungers requested either the arguments or target, // the munger will have added code // to pop the target/arguments into temporary variables, represented by // targetVar and argVars. In such a case, we must make sure to re-push the // values. // If we are nonExpressionKind, we don't expect arguments on the stack // so this is moot. If our argVars happen to be null, then we know that // no ShadowMunger has squirrelled away our arguments, so they're still // on the stack. InstructionFactory fact = getFactory(); if (getKind().argsOnStack() && argVars != null) { // Special case first (pr46298). If we are an exception handler and the instruction // just after the shadow is a POP then we should remove the pop. The code // above which generated the store instruction has already cleared the stack. // We also don't generate any code for the arguments in this case as it would be // an incorrect aload. if (getKind() == ExceptionHandler && range.getEnd().getNext().getInstruction().equals(InstructionConstants.POP)) { // easier than deleting it ... range.getEnd().getNext().setInstruction(InstructionConstants.NOP); } else { range.insert(BcelRenderer.renderExprs(fact, world, argVars), Range.InsideBefore); if (targetVar != null) { range.insert(BcelRenderer.renderExpr(fact, world, targetVar), Range.InsideBefore); } if (getKind() == ConstructorCall) { if (!world.isJoinpointArrayConstructionEnabled() || !this.getSignature().getDeclaringType().isArray()) { range.insert(InstructionFactory.createDup(1), Range.InsideBefore); range.insert(fact.createNew((ObjectType) BcelWorld.makeBcelType(getSignature().getDeclaringType())), Range.InsideBefore); } } } } } // ---- getters public ShadowRange getRange() { return range; } public void setRange(ShadowRange range) { this.range = range; } private int sourceline = -1; public int getSourceLine() { // if the kind of join point for which we are a shadow represents // a method or constructor execution, then the best source line is // the one from the enclosingMethod declarationLineNumber if available. if (sourceline != -1) return sourceline; Kind kind = getKind(); if ((kind == MethodExecution) || (kind == ConstructorExecution) || (kind == AdviceExecution) || (kind == StaticInitialization) || (kind == PreInitialization) || (kind == Initialization)) { if (getEnclosingMethod().hasDeclaredLineNumberInfo()) { sourceline = getEnclosingMethod().getDeclarationLineNumber(); return sourceline; } } if (range == null) { if (getEnclosingMethod().hasBody()) { sourceline = Utility.getSourceLine(getEnclosingMethod().getBody().getStart()); return sourceline; } else { sourceline = 0; return sourceline; } } sourceline = Utility.getSourceLine(range.getStart()); if (sourceline < 0) sourceline = 0; return sourceline; } // overrides public UnresolvedType getEnclosingType() { return getEnclosingClass().getType(); } public LazyClassGen getEnclosingClass() { return enclosingMethod.getEnclosingClass(); } public BcelWorld getWorld() { return world; } // ---- factory methods public static BcelShadow makeConstructorExecution(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle justBeforeStart) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow(world, ConstructorExecution, world.makeJoinPointSignatureFromMethod(enclosingMethod, Member.CONSTRUCTOR), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body, justBeforeStart.getNext()), Range.genEnd(body)); return s; } public static BcelShadow makeStaticInitialization(BcelWorld world, LazyMethodGen enclosingMethod) { InstructionList body = enclosingMethod.getBody(); // move the start past ajc$preClinit InstructionHandle clinitStart = body.getStart(); if (clinitStart.getInstruction() instanceof InvokeInstruction) { InvokeInstruction ii = (InvokeInstruction) clinitStart.getInstruction(); if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPool()).equals(NameMangler.AJC_PRE_CLINIT_NAME)) { clinitStart = clinitStart.getNext(); } } InstructionHandle clinitEnd = body.getEnd(); // XXX should move the end before the postClinit, but the return is then tricky... // if (clinitEnd.getInstruction() instanceof InvokeInstruction) { // InvokeInstruction ii = (InvokeInstruction)clinitEnd.getInstruction(); // if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPool()).equals(NameMangler.AJC_POST_CLINIT_NAME)) { // clinitEnd = clinitEnd.getPrev(); // } // } BcelShadow s = new BcelShadow(world, StaticInitialization, world.makeJoinPointSignatureFromMethod(enclosingMethod, Member.STATIC_INITIALIZATION), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body, clinitStart), Range.genEnd(body, clinitEnd)); return s; } /** * Make the shadow for an exception handler. Currently makes an empty shadow that only allows before advice to be woven into it. */ public static BcelShadow makeExceptionHandler(BcelWorld world, ExceptionRange exceptionRange, LazyMethodGen enclosingMethod, InstructionHandle startOfHandler, BcelShadow enclosingShadow) { InstructionList body = enclosingMethod.getBody(); UnresolvedType catchType = exceptionRange.getCatchType(); UnresolvedType inType = enclosingMethod.getEnclosingClass().getType(); ResolvedMemberImpl sig = MemberImpl.makeExceptionHandlerSignature(inType, catchType); sig.setParameterNames(new String[] { findHandlerParamName(startOfHandler) }); BcelShadow s = new BcelShadow(world, ExceptionHandler, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); InstructionHandle start = Range.genStart(body, startOfHandler); InstructionHandle end = Range.genEnd(body, start); r.associateWithTargets(start, end); exceptionRange.updateTarget(startOfHandler, start, body); return s; } private static String findHandlerParamName(InstructionHandle startOfHandler) { if (startOfHandler.getInstruction().isStoreInstruction() && startOfHandler.getNext() != null) { int slot = startOfHandler.getInstruction().getIndex(); // System.out.println("got store: " + startOfHandler.getInstruction() + ", " + index); Iterator tIter = startOfHandler.getNext().getTargeters().iterator(); while (tIter.hasNext()) { InstructionTargeter targeter = (InstructionTargeter) tIter.next(); if (targeter instanceof LocalVariableTag) { LocalVariableTag t = (LocalVariableTag) targeter; if (t.getSlot() == slot) { return t.getName(); } } } } return "<missing>"; } /** create an init join point associated w/ an interface in the body of a constructor */ public static BcelShadow makeIfaceInitialization(BcelWorld world, LazyMethodGen constructor, Member interfaceConstructorSignature) { // this call marks the instruction list as changed constructor.getBody(); // UnresolvedType inType = constructor.getEnclosingClass().getType(); BcelShadow s = new BcelShadow(world, Initialization, interfaceConstructorSignature, constructor, null); // s.fallsThrough = true; // ShadowRange r = new ShadowRange(body); // r.associateWithShadow(s); // InstructionHandle start = Range.genStart(body, handle); // InstructionHandle end = Range.genEnd(body, handle); // // r.associateWithTargets(start, end); return s; } public void initIfaceInitializer(InstructionHandle end) { final InstructionList body = enclosingMethod.getBody(); ShadowRange r = new ShadowRange(body); r.associateWithShadow(this); InstructionHandle nop = body.insert(end, InstructionConstants.NOP); r.associateWithTargets(Range.genStart(body, nop), Range.genEnd(body, nop)); } // public static BcelShadow makeIfaceConstructorExecution( // BcelWorld world, // LazyMethodGen constructor, // InstructionHandle next, // Member interfaceConstructorSignature) // { // // final InstructionFactory fact = constructor.getEnclosingClass().getFactory(); // InstructionList body = constructor.getBody(); // // UnresolvedType inType = constructor.getEnclosingClass().getType(); // BcelShadow s = // new BcelShadow( // world, // ConstructorExecution, // interfaceConstructorSignature, // constructor, // null); // s.fallsThrough = true; // ShadowRange r = new ShadowRange(body); // r.associateWithShadow(s); // // ??? this may or may not work // InstructionHandle start = Range.genStart(body, next); // //InstructionHandle end = Range.genEnd(body, body.append(start, fact.NOP)); // InstructionHandle end = Range.genStart(body, next); // //body.append(start, fact.NOP); // // r.associateWithTargets(start, end); // return s; // } /** * Create an initialization join point associated with a constructor, but not with any body of code yet. If this is actually * matched, it's range will be set when we inline self constructors. * * @param constructor The constructor starting this initialization. */ public static BcelShadow makeUnfinishedInitialization(BcelWorld world, LazyMethodGen constructor) { BcelShadow ret = new BcelShadow(world, Initialization, world.makeJoinPointSignatureFromMethod(constructor, Member.CONSTRUCTOR), constructor, null); if (constructor.getEffectiveSignature() != null) { ret.setMatchingSignature(constructor.getEffectiveSignature().getEffectiveSignature()); } return ret; } public static BcelShadow makeUnfinishedPreinitialization(BcelWorld world, LazyMethodGen constructor) { BcelShadow ret = new BcelShadow(world, PreInitialization, world.makeJoinPointSignatureFromMethod(constructor, Member.CONSTRUCTOR), constructor, null); if (constructor.getEffectiveSignature() != null) { ret.setMatchingSignature(constructor.getEffectiveSignature().getEffectiveSignature()); } return ret; } public static BcelShadow makeMethodExecution(BcelWorld world, LazyMethodGen enclosingMethod, boolean lazyInit) { if (!lazyInit) return makeMethodExecution(world, enclosingMethod); BcelShadow s = new BcelShadow(world, MethodExecution, enclosingMethod.getMemberView(), enclosingMethod, null); return s; } public void init() { if (range != null) return; final InstructionList body = enclosingMethod.getBody(); ShadowRange r = new ShadowRange(body); r.associateWithShadow(this); r.associateWithTargets(Range.genStart(body), Range.genEnd(body)); } public static BcelShadow makeMethodExecution(BcelWorld world, LazyMethodGen enclosingMethod) { return makeShadowForMethod(world, enclosingMethod, MethodExecution, enclosingMethod.getMemberView()); // world. // makeMethodSignature // ( // enclosingMethod)) // ; } public static BcelShadow makeShadowForMethod(BcelWorld world, LazyMethodGen enclosingMethod, Shadow.Kind kind, Member sig) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow(world, kind, sig, enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(// OPTIMIZE this occurs lots of times for all jp kinds... Range.genStart(body), Range.genEnd(body)); return s; } public static BcelShadow makeAdviceExecution(BcelWorld world, LazyMethodGen enclosingMethod) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow(world, AdviceExecution, world .makeJoinPointSignatureFromMethod(enclosingMethod, Member.ADVICE), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body), Range.genEnd(body)); return s; } // constructor call shadows are <em>initially</em> just around the // call to the constructor. If ANY advice gets put on it, we move // the NEW instruction inside the join point, which involves putting // all the arguments in temps. public static BcelShadow makeConstructorCall(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); Member sig = world.makeJoinPointSignatureForMethodInvocation(enclosingMethod.getEnclosingClass(), (InvokeInstruction) callHandle.getInstruction()); BcelShadow s = new BcelShadow(world, ConstructorCall, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeArrayConstructorCall(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle arrayInstruction, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); Member sig = world.makeJoinPointSignatureForArrayConstruction(enclosingMethod.getEnclosingClass(), arrayInstruction); BcelShadow s = new BcelShadow(world, ConstructorCall, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body, arrayInstruction), Range.genEnd(body, arrayInstruction)); retargetAllBranches(arrayInstruction, r.getStart()); return s; } public static BcelShadow makeMonitorEnter(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle monitorInstruction, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); Member sig = world.makeJoinPointSignatureForMonitorEnter(enclosingMethod.getEnclosingClass(), monitorInstruction); BcelShadow s = new BcelShadow(world, SynchronizationLock, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body, monitorInstruction), Range.genEnd(body, monitorInstruction)); retargetAllBranches(monitorInstruction, r.getStart()); return s; } public static BcelShadow makeMonitorExit(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle monitorInstruction, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); Member sig = world.makeJoinPointSignatureForMonitorExit(enclosingMethod.getEnclosingClass(), monitorInstruction); BcelShadow s = new BcelShadow(world, SynchronizationUnlock, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body, monitorInstruction), Range.genEnd(body, monitorInstruction)); retargetAllBranches(monitorInstruction, r.getStart()); return s; } // see pr77166 // public static BcelShadow makeArrayLoadCall( // BcelWorld world, // LazyMethodGen enclosingMethod, // InstructionHandle arrayInstruction, // BcelShadow enclosingShadow) // { // final InstructionList body = enclosingMethod.getBody(); // Member sig = world.makeJoinPointSignatureForArrayLoad(enclosingMethod.getEnclosingClass(),arrayInstruction); // BcelShadow s = // new BcelShadow( // world, // MethodCall, // sig, // enclosingMethod, // enclosingShadow); // ShadowRange r = new ShadowRange(body); // r.associateWithShadow(s); // r.associateWithTargets( // Range.genStart(body, arrayInstruction), // Range.genEnd(body, arrayInstruction)); // retargetAllBranches(arrayInstruction, r.getStart()); // return s; // } public static BcelShadow makeMethodCall(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow(world, MethodCall, world.makeJoinPointSignatureForMethodInvocation(enclosingMethod .getEnclosingClass(), (InvokeInstruction) callHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeShadowForMethodCall(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow, Kind kind, ResolvedMember sig) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow(world, kind, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeFieldGet(BcelWorld world, ResolvedMember field, LazyMethodGen enclosingMethod, InstructionHandle getHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow(world, FieldGet, field, // BcelWorld.makeFieldSignature( // enclosingMethod.getEnclosingClass(), // (FieldInstruction) getHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body, getHandle), Range.genEnd(body, getHandle)); retargetAllBranches(getHandle, r.getStart()); return s; } public static BcelShadow makeFieldSet(BcelWorld world, ResolvedMember field, LazyMethodGen enclosingMethod, InstructionHandle setHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow(world, FieldSet, field, // BcelWorld.makeFieldJoinPointSignature( // enclosingMethod.getEnclosingClass(), // (FieldInstruction) setHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body, setHandle), Range.genEnd(body, setHandle)); retargetAllBranches(setHandle, r.getStart()); return s; } public static void retargetAllBranches(InstructionHandle from, InstructionHandle to) { InstructionTargeter[] sources = from.getTargetersArray(); if (sources != null) { for (int i = sources.length - 1; i >= 0; i--) { InstructionTargeter source = sources[i]; if (source instanceof InstructionBranch) { source.updateTarget(from, to); } } } } // // ---- type access methods // private ObjectType getTargetBcelType() { // return (ObjectType) BcelWorld.makeBcelType(getTargetType()); // } // private Type getArgBcelType(int arg) { // return BcelWorld.makeBcelType(getArgType(arg)); // } // ---- kinding /** * If the end of my range has no real instructions following then my context needs a return at the end. */ public boolean terminatesWithReturn() { return getRange().getRealNext() == null; } /** * Is arg0 occupied with the value of this */ public boolean arg0HoldsThis() { if (getKind().isEnclosingKind()) { return !getSignature().isStatic(); } else if (enclosingShadow == null) { // XXX this is mostly right // this doesn't do the right thing for calls in the pre part of introduced constructors. return !enclosingMethod.isStatic(); } else { return ((BcelShadow) enclosingShadow).arg0HoldsThis(); } } // ---- argument getting methods private BcelVar thisVar = null; private BcelVar targetVar = null; private BcelVar[] argVars = null; private Map/* <UnresolvedType,BcelVar> */kindedAnnotationVars = null; private Map/* <UnresolvedType,BcelVar> */thisAnnotationVars = null; private Map/* <UnresolvedType,BcelVar> */targetAnnotationVars = null; private Map/* <UnresolvedType,BcelVar> */[] argAnnotationVars = null; private Map/* <UnresolvedType,BcelVar> */withinAnnotationVars = null; private Map/* <UnresolvedType,BcelVar> */withincodeAnnotationVars = null; public Var getThisVar() { if (!hasThis()) { throw new IllegalStateException("no this"); } initializeThisVar(); return thisVar; } public Var getThisAnnotationVar(UnresolvedType forAnnotationType) { if (!hasThis()) { throw new IllegalStateException("no this"); } initializeThisAnnotationVars(); // FIXME asc Why bother with this if we always return one? // Even if we can't find one, we have to return one as we might have this annotation at runtime Var v = (Var) thisAnnotationVars.get(forAnnotationType); if (v == null) v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world), (BcelVar) getThisVar()); return v; } public Var getTargetVar() { if (!hasTarget()) { throw new IllegalStateException("no target"); } initializeTargetVar(); return targetVar; } public Var getTargetAnnotationVar(UnresolvedType forAnnotationType) { if (!hasTarget()) { throw new IllegalStateException("no target"); } initializeTargetAnnotationVars(); // FIXME asc why bother with this if we always return one? Var v = (Var) targetAnnotationVars.get(forAnnotationType); // Even if we can't find one, we have to return one as we might have this annotation at runtime if (v == null) v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world), (BcelVar) getTargetVar()); return v; } public Var getArgVar(int i) { initializeArgVars(); return argVars[i]; } public Var getArgAnnotationVar(int i, UnresolvedType forAnnotationType) { initializeArgAnnotationVars(); Var v = (Var) argAnnotationVars[i].get(forAnnotationType); if (v == null) v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world), (BcelVar) getArgVar(i)); return v; } public Var getKindedAnnotationVar(UnresolvedType forAnnotationType) { initializeKindedAnnotationVars(); return (Var) kindedAnnotationVars.get(forAnnotationType); } public Var getWithinAnnotationVar(UnresolvedType forAnnotationType) { initializeWithinAnnotationVars(); return (Var) withinAnnotationVars.get(forAnnotationType); } public Var getWithinCodeAnnotationVar(UnresolvedType forAnnotationType) { initializeWithinCodeAnnotationVars(); return (Var) withincodeAnnotationVars.get(forAnnotationType); } // reflective thisJoinPoint support private BcelVar thisJoinPointVar = null; private boolean isThisJoinPointLazy; private int lazyTjpConsumers = 0; private BcelVar thisJoinPointStaticPartVar = null; // private BcelVar thisEnclosingJoinPointStaticPartVar = null; public final Var getThisJoinPointStaticPartVar() { return getThisJoinPointStaticPartBcelVar(); } public final Var getThisEnclosingJoinPointStaticPartVar() { return getThisEnclosingJoinPointStaticPartBcelVar(); } public void requireThisJoinPoint(boolean hasGuardTest, boolean isAround) { if (!isAround) { if (!hasGuardTest) { isThisJoinPointLazy = false; } else { lazyTjpConsumers++; } } // if (!hasGuardTest) { // isThisJoinPointLazy = false; // } else { // lazyTjpConsumers++; // } if (thisJoinPointVar == null) { thisJoinPointVar = genTempVar(UnresolvedType.forName("org.aspectj.lang.JoinPoint")); } } public Var getThisJoinPointVar() { requireThisJoinPoint(false, false); return thisJoinPointVar; } void initializeThisJoinPoint() { if (thisJoinPointVar == null) return; if (isThisJoinPointLazy) { isThisJoinPointLazy = checkLazyTjp(); } if (isThisJoinPointLazy) { appliedLazyTjpOptimization = true; createThisJoinPoint(); // make sure any state needed is initialized, but throw the instructions out if (lazyTjpConsumers == 1) return; // special case only one lazyTjpUser InstructionFactory fact = getFactory(); InstructionList il = new InstructionList(); il.append(InstructionConstants.ACONST_NULL); il.append(thisJoinPointVar.createStore(fact)); range.insert(il, Range.OutsideBefore); } else { appliedLazyTjpOptimization = false; InstructionFactory fact = getFactory(); InstructionList il = createThisJoinPoint(); il.append(thisJoinPointVar.createStore(fact)); range.insert(il, Range.OutsideBefore); } } private boolean checkLazyTjp() { // check for around advice for (Iterator i = mungers.iterator(); i.hasNext();) { ShadowMunger munger = (ShadowMunger) i.next(); if (munger instanceof Advice) { if (((Advice) munger).getKind() == AdviceKind.Around) { if (munger.getSourceLocation() != null) { // do we know enough to bother reporting? if (world.getLint().canNotImplementLazyTjp.isEnabled()) { world.getLint().canNotImplementLazyTjp.signal(new String[] { toString() }, getSourceLocation(), new ISourceLocation[] { munger.getSourceLocation() }); } } return false; } } } return true; } InstructionList loadThisJoinPoint() { InstructionFactory fact = getFactory(); InstructionList il = new InstructionList(); if (isThisJoinPointLazy) { // If we're lazy, build the join point right here. il.append(createThisJoinPoint()); // Does someone else need it? If so, store it for later retrieval if (lazyTjpConsumers > 1) { il.append(thisJoinPointVar.createStore(fact)); InstructionHandle end = il.append(thisJoinPointVar.createLoad(fact)); il.insert(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, end)); il.insert(thisJoinPointVar.createLoad(fact)); } } else { // If not lazy, its already been built and stored, just retrieve it thisJoinPointVar.appendLoad(il, fact); } return il; } InstructionList createThisJoinPoint() { InstructionFactory fact = getFactory(); InstructionList il = new InstructionList(); BcelVar staticPart = getThisJoinPointStaticPartBcelVar(); staticPart.appendLoad(il, fact); if (hasThis()) { ((BcelVar) getThisVar()).appendLoad(il, fact); } else { il.append(InstructionConstants.ACONST_NULL); } if (hasTarget()) { ((BcelVar) getTargetVar()).appendLoad(il, fact); } else { il.append(InstructionConstants.ACONST_NULL); } switch (getArgCount()) { case 0: il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT }, Constants.INVOKESTATIC)); break; case 1: ((BcelVar) getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT)); il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, Type.OBJECT }, Constants.INVOKESTATIC)); break; case 2: ((BcelVar) getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT)); ((BcelVar) getArgVar(1)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT)); il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, Type.OBJECT, Type.OBJECT }, Constants.INVOKESTATIC)); break; default: il.append(makeArgsObjectArray()); il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, new ArrayType(Type.OBJECT, 1) }, Constants.INVOKESTATIC)); break; } return il; } /** * Get the Var for the jpStaticPart * * @return */ public BcelVar getThisJoinPointStaticPartBcelVar() { return getThisJoinPointStaticPartBcelVar(false); } /** * Get the Var for the xxxxJpStaticPart, xxx = this or enclosing * * @param isEnclosingJp true to have the enclosingJpStaticPart * @return */ public BcelVar getThisJoinPointStaticPartBcelVar(final boolean isEnclosingJp) { if (thisJoinPointStaticPartVar == null) { Field field = getEnclosingClass().getTjpField(this, isEnclosingJp); ResolvedType sjpType = null; if (world.isTargettingAspectJRuntime12()) { // TAG:SUPPORTING12: We didn't have different jpsp types in 1.2 sjpType = world.getCoreType(UnresolvedType.JOINPOINT_STATICPART); } else { sjpType = isEnclosingJp ? world.getCoreType(UnresolvedType.JOINPOINT_ENCLOSINGSTATICPART) : world .getCoreType(UnresolvedType.JOINPOINT_STATICPART); } thisJoinPointStaticPartVar = new BcelFieldRef(sjpType, getEnclosingClass().getClassName(), field.getName()); // getEnclosingClass().warnOnAddedStaticInitializer(this,munger.getSourceLocation()); } return thisJoinPointStaticPartVar; } /** * Get the Var for the enclosingJpStaticPart * * @return */ public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() { if (enclosingShadow == null) { // the enclosing of an execution is itself return getThisJoinPointStaticPartBcelVar(true); } else { return ((BcelShadow) enclosingShadow).getThisJoinPointStaticPartBcelVar(true); } } // ??? need to better understand all the enclosing variants public Member getEnclosingCodeSignature() { if (getKind().isEnclosingKind()) { return getSignature(); } else if (getKind() == Shadow.PreInitialization) { // PreInit doesn't enclose code but its signature // is correctly the signature of the ctor. return getSignature(); } else if (enclosingShadow == null) { return getEnclosingMethod().getMemberView(); } else { return enclosingShadow.getSignature(); } } private InstructionList makeArgsObjectArray() { InstructionFactory fact = getFactory(); BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY); final InstructionList il = new InstructionList(); int alen = getArgCount(); il.append(Utility.createConstant(fact, alen)); il.append(fact.createNewArray(Type.OBJECT, (short) 1)); arrayVar.appendStore(il, fact); int stateIndex = 0; for (int i = 0, len = getArgCount(); i < len; i++) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, (BcelVar) getArgVar(i)); stateIndex++; } arrayVar.appendLoad(il, fact); return il; } // ---- initializing var tables /* * initializing this is doesn't do anything, because this is protected from side-effects, so we don't need to copy its location */ private void initializeThisVar() { if (thisVar != null) return; thisVar = new BcelVar(getThisType().resolve(world), 0); thisVar.setPositionInAroundState(0); } public void initializeTargetVar() { InstructionFactory fact = getFactory(); if (targetVar != null) return; if (getKind().isTargetSameAsThis()) { if (hasThis()) initializeThisVar(); targetVar = thisVar; } else { initializeArgVars(); // gotta pop off the args before we find the target UnresolvedType type = getTargetType(); type = ensureTargetTypeIsCorrect(type); targetVar = genTempVar(type, "ajc$target"); range.insert(targetVar.createStore(fact), Range.OutsideBefore); targetVar.setPositionInAroundState(hasThis() ? 1 : 0); } } /* * PR 72528 This method double checks the target type under certain conditions. The Java 1.4 compilers seem to take calls to * clone methods on array types and create bytecode that looks like clone is being called on Object. If we advise a clone call * with around advice we extract the call into a helper method which we can then refer to. Because the type in the bytecode for * the call to clone is Object we create a helper method with an Object parameter - this is not correct as we have lost the fact * that the actual type is an array type. If we don't do the check below we will create code that fails java verification. This * method checks for the peculiar set of conditions and if they are true, it has a sneak peek at the code before the call to see * what is on the stack. */ public UnresolvedType ensureTargetTypeIsCorrect(UnresolvedType tx) { Member msig = getSignature(); if (msig.getArity() == 0 && getKind() == MethodCall && msig.getName().charAt(0) == 'c' && tx.equals(ResolvedType.OBJECT) && msig.getReturnType().equals(ResolvedType.OBJECT) && msig.getName().equals("clone")) { // Lets go back through the code from the start of the shadow InstructionHandle searchPtr = range.getStart().getPrev(); while (Range.isRangeHandle(searchPtr) || searchPtr.getInstruction().isStoreInstruction()) { // ignore this instruction - // it doesnt give us the // info we want searchPtr = searchPtr.getPrev(); } // A load instruction may tell us the real type of what the clone() call is on if (searchPtr.getInstruction().isLoadInstruction()) { LocalVariableTag lvt = LazyMethodGen.getLocalVariableTag(searchPtr, searchPtr.getInstruction().getIndex()); if (lvt != null) return UnresolvedType.forSignature(lvt.getType()); } // A field access instruction may tell us the real type of what the clone() call is on if (searchPtr.getInstruction() instanceof FieldInstruction) { FieldInstruction si = (FieldInstruction) searchPtr.getInstruction(); Type t = si.getFieldType(getEnclosingClass().getConstantPool()); return BcelWorld.fromBcel(t); } // A new array instruction obviously tells us it is an array type ! if (searchPtr.getInstruction().opcode == Constants.ANEWARRAY) { // ANEWARRAY ana = (ANEWARRAY)searchPoint.getInstruction(); // Type t = ana.getType(getEnclosingClass().getConstantPool()); // Just use a standard java.lang.object array - that will work fine return BcelWorld.fromBcel(new ArrayType(Type.OBJECT, 1)); } // A multi new array instruction obviously tells us it is an array type ! if (searchPtr.getInstruction() instanceof MULTIANEWARRAY) { MULTIANEWARRAY ana = (MULTIANEWARRAY) searchPtr.getInstruction(); // Type t = ana.getType(getEnclosingClass().getConstantPool()); // t = new ArrayType(t,ana.getDimensions()); // Just use a standard java.lang.object array - that will work fine return BcelWorld.fromBcel(new ArrayType(Type.OBJECT, ana.getDimensions())); } throw new BCException("Can't determine real target of clone() when processing instruction " + searchPtr.getInstruction() + ". Perhaps avoid selecting clone with your pointcut?"); } return tx; } public void initializeArgVars() { if (argVars != null) return; InstructionFactory fact = getFactory(); int len = getArgCount(); argVars = new BcelVar[len]; int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0); if (getKind().argsOnStack()) { // we move backwards because we're popping off the stack for (int i = len - 1; i >= 0; i--) { UnresolvedType type = getArgType(i); BcelVar tmp = genTempVar(type, "ajc$arg" + i); range.insert(tmp.createStore(getFactory()), Range.OutsideBefore); int position = i; position += positionOffset; tmp.setPositionInAroundState(position); argVars[i] = tmp; } } else { int index = 0; if (arg0HoldsThis()) index++; for (int i = 0; i < len; i++) { UnresolvedType type = getArgType(i); BcelVar tmp = genTempVar(type, "ajc$arg" + i); range.insert(tmp.createCopyFrom(fact, index), Range.OutsideBefore); argVars[i] = tmp; int position = i; position += positionOffset; // System.out.println("set position: " + tmp + ", " + position + " in " + this); // System.out.println(" hasThis: " + hasThis() + ", hasTarget: " + hasTarget()); tmp.setPositionInAroundState(position); index += type.getSize(); } } } public void initializeForAroundClosure() { initializeArgVars(); if (hasTarget()) initializeTargetVar(); if (hasThis()) initializeThisVar(); // System.out.println("initialized: " + this + " thisVar = " + thisVar); } public void initializeThisAnnotationVars() { if (thisAnnotationVars != null) return; thisAnnotationVars = new HashMap(); // populate.. } public void initializeTargetAnnotationVars() { if (targetAnnotationVars != null) return; if (getKind().isTargetSameAsThis()) { if (hasThis()) initializeThisAnnotationVars(); targetAnnotationVars = thisAnnotationVars; } else { targetAnnotationVars = new HashMap(); ResolvedType[] rtx = this.getTargetType().resolve(world).getAnnotationTypes(); // what about annotations we havent // gotten yet but we will get in // subclasses? for (int i = 0; i < rtx.length; i++) { ResolvedType typeX = rtx[i]; targetAnnotationVars.put(typeX, new TypeAnnotationAccessVar(typeX, (BcelVar) getTargetVar())); } // populate. } } public void initializeArgAnnotationVars() { if (argAnnotationVars != null) return; int numArgs = getArgCount(); argAnnotationVars = new Map[numArgs]; for (int i = 0; i < argAnnotationVars.length; i++) { argAnnotationVars[i] = new HashMap(); // FIXME asc just delete this logic - we always build the Var on demand, as we don't know at weave time // what the full set of annotations could be (due to static/dynamic type differences...) } } protected ResolvedMember getRelevantMember(ResolvedMember foundMember, Member relevantMember, ResolvedType relevantType) { if (foundMember != null) { return foundMember; } foundMember = getSignature().resolve(world); if (foundMember == null && relevantMember != null) { foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember); } // check the ITD'd dooberries List mungers = relevantType.resolve(world).getInterTypeMungers(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next(); if (typeMunger.getMunger() instanceof NewMethodTypeMunger || typeMunger.getMunger() instanceof NewConstructorTypeMunger) { ResolvedMember fakerm = typeMunger.getSignature(); if (fakerm.getName().equals(getSignature().getName()) && fakerm.getParameterSignature().equals(getSignature().getParameterSignature())) { if (foundMember.getKind() == ResolvedMember.CONSTRUCTOR) { foundMember = AjcMemberMaker.interConstructor(relevantType, foundMember, typeMunger.getAspectType()); } else { foundMember = AjcMemberMaker.interMethod(foundMember, typeMunger.getAspectType(), false); } // in the above.. what about if it's on an Interface? Can that happen? // then the last arg of the above should be true return foundMember; } } } return foundMember; } protected ResolvedType[] getAnnotations(ResolvedMember foundMember, Member relevantMember, ResolvedType relevantType) { if (foundMember == null) { // check the ITD'd dooberries List mungers = relevantType.resolve(world).getInterTypeMungers(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next(); if (typeMunger.getMunger() instanceof NewMethodTypeMunger || typeMunger.getMunger() instanceof NewConstructorTypeMunger) { ResolvedMember fakerm = typeMunger.getSignature(); // if (fakerm.hasAnnotations()) ResolvedMember ajcMethod = (getSignature().getKind() == ResolvedMember.CONSTRUCTOR ? AjcMemberMaker .postIntroducedConstructor(typeMunger.getAspectType(), fakerm.getDeclaringType(), fakerm .getParameterTypes()) : AjcMemberMaker .interMethodDispatcher(fakerm, typeMunger.getAspectType())); // AjcMemberMaker.interMethodBody(fakerm,typeMunger.getAspectType())); ResolvedMember rmm = findMethod(typeMunger.getAspectType(), ajcMethod); if (fakerm.getName().equals(getSignature().getName()) && fakerm.getParameterSignature().equals(getSignature().getParameterSignature())) { relevantType = typeMunger.getAspectType(); foundMember = rmm; return foundMember.getAnnotationTypes(); } } } // didn't find in ITDs, look in supers foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember); if (foundMember == null) { throw new IllegalStateException("Couldn't find member " + relevantMember + " for type " + relevantType); } } return foundMember.getAnnotationTypes(); } /** * By determining what "kind" of shadow we are, we can find out the annotations on the appropriate element (method, field, * constructor, type). Then create one BcelVar entry in the map for each annotation, keyed by annotation type. */ public void initializeKindedAnnotationVars() { if (kindedAnnotationVars != null) return; kindedAnnotationVars = new HashMap(); // FIXME asc Refactor this code, there is duplication ResolvedType[] annotations = null; Member shadowSignature = getSignature(); Member annotationHolder = getSignature(); ResolvedType relevantType = shadowSignature.getDeclaringType().resolve(world); if (relevantType.isRawType() || relevantType.isParameterizedType()) relevantType = relevantType.getGenericType(); if (getKind() == Shadow.StaticInitialization) { annotations = relevantType.resolve(world).getAnnotationTypes(); } else if (getKind() == Shadow.MethodCall || getKind() == Shadow.ConstructorCall) { ResolvedMember foundMember = findMethod2(relevantType.resolve(world).getDeclaredMethods(), getSignature()); annotations = getAnnotations(foundMember, shadowSignature, relevantType); annotationHolder = getRelevantMember(foundMember, shadowSignature, relevantType); relevantType = annotationHolder.getDeclaringType().resolve(world); } else if (getKind() == Shadow.FieldSet || getKind() == Shadow.FieldGet) { annotationHolder = findField(relevantType.getDeclaredFields(), getSignature()); if (annotationHolder == null) { // check the ITD'd dooberries List mungers = relevantType.resolve(world).getInterTypeMungers(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next(); if (typeMunger.getMunger() instanceof NewFieldTypeMunger) { ResolvedMember fakerm = typeMunger.getSignature(); // if (fakerm.hasAnnotations()) ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm, typeMunger.getAspectType()); ResolvedMember rmm = findMethod(typeMunger.getAspectType(), ajcMethod); if (fakerm.equals(getSignature())) { relevantType = typeMunger.getAspectType(); annotationHolder = rmm; } } } } annotations = ((ResolvedMember) annotationHolder).getAnnotationTypes(); } else if (getKind() == Shadow.MethodExecution || getKind() == Shadow.ConstructorExecution || getKind() == Shadow.AdviceExecution) { // ResolvedMember rm[] = relevantType.getDeclaredMethods(); ResolvedMember foundMember = findMethod2(relevantType.getDeclaredMethods(), getSignature()); annotations = getAnnotations(foundMember, shadowSignature, relevantType); annotationHolder = foundMember; annotationHolder = getRelevantMember(foundMember, annotationHolder, relevantType); } else if (getKind() == Shadow.ExceptionHandler) { relevantType = getSignature().getParameterTypes()[0].resolve(world); annotations = relevantType.getAnnotationTypes(); } else if (getKind() == Shadow.PreInitialization || getKind() == Shadow.Initialization) { ResolvedMember found = findMethod2(relevantType.getDeclaredMethods(), getSignature()); annotations = found.getAnnotationTypes(); } if (annotations == null) { // We can't have recognized the shadow - should blow up now to be on the safe side throw new BCException("Could not discover annotations for shadow: " + getKind()); } for (int i = 0; i < annotations.length; i++) { ResolvedType annotationType = annotations[i]; AnnotationAccessVar accessVar = new AnnotationAccessVar(getKind(), annotationType.resolve(world), relevantType, annotationHolder); kindedAnnotationVars.put(annotationType, accessVar); } } // FIXME asc whats the real diff between this one and the version in findMethod()? ResolvedMember findMethod2(ResolvedMember rm[], Member sig) { ResolvedMember found = null; // String searchString = getSignature().getName()+getSignature().getParameterSignature(); for (int i = 0; i < rm.length && found == null; i++) { ResolvedMember member = rm[i]; if (member.getName().equals(sig.getName()) && member.getParameterSignature().equals(sig.getParameterSignature())) found = member; } return found; } private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) { ResolvedMember decMethods[] = aspectType.getDeclaredMethods(); for (int i = 0; i < decMethods.length; i++) { ResolvedMember member = decMethods[i]; if (member.equals(ajcMethod)) return member; } return null; } private ResolvedMember findField(ResolvedMember[] members, Member lookingFor) { for (int i = 0; i < members.length; i++) { ResolvedMember member = members[i]; if (member.getName().equals(getSignature().getName()) && member.getType().equals(getSignature().getType())) { return member; } } return null; } public void initializeWithinAnnotationVars() { if (withinAnnotationVars != null) return; withinAnnotationVars = new HashMap(); ResolvedType[] annotations = getEnclosingType().resolve(world).getAnnotationTypes(); for (int i = 0; i < annotations.length; i++) { ResolvedType ann = annotations[i]; Kind k = Shadow.StaticInitialization; withinAnnotationVars.put(ann, new AnnotationAccessVar(k, ann, getEnclosingType(), null)); } } public void initializeWithinCodeAnnotationVars() { if (withincodeAnnotationVars != null) return; withincodeAnnotationVars = new HashMap(); // For some shadow we are interested in annotations on the method containing that shadow. ResolvedType[] annotations = getEnclosingMethod().getMemberView().getAnnotationTypes(); for (int i = 0; i < annotations.length; i++) { ResolvedType ann = annotations[i]; Kind k = (getEnclosingMethod().getMemberView().getKind() == Member.CONSTRUCTOR ? Shadow.ConstructorExecution : Shadow.MethodExecution); withincodeAnnotationVars.put(ann, new AnnotationAccessVar(k, ann, getEnclosingType(), getEnclosingCodeSignature())); } } // ---- weave methods void weaveBefore(BcelAdvice munger) { range.insert(munger.getAdviceInstructions(this, null, range.getRealStart()), Range.InsideBefore); } public void weaveAfter(BcelAdvice munger) { weaveAfterThrowing(munger, UnresolvedType.THROWABLE); weaveAfterReturning(munger); } /** * The basic strategy here is to add a set of instructions at the end of the shadow range that dispatch the advice, and then * return whatever the shadow was going to return anyway. * * To achieve this, we note all the return statements in the advice, and replace them with code that: 1) stores the return value * on top of the stack in a temp var 2) jumps to the start of our advice block 3) restores the return value at the end of the * advice block before ultimately returning * * We also need to bind the return value into a returning parameter, if the advice specified one. */ public void weaveAfterReturning(BcelAdvice munger) { List returns = findReturnInstructions(); boolean hasReturnInstructions = !returns.isEmpty(); // list of instructions that handle the actual return from the join point InstructionList retList = new InstructionList(); // variable that holds the return value BcelVar returnValueVar = null; if (hasReturnInstructions) { returnValueVar = generateReturnInstructions(returns, retList); } else { // we need at least one instruction, as the target for jumps retList.append(InstructionConstants.NOP); } // list of instructions for dispatching to the advice itself InstructionList advice = getAfterReturningAdviceDispatchInstructions(munger, retList.getStart()); if (hasReturnInstructions) { InstructionHandle gotoTarget = advice.getStart(); for (Iterator i = returns.iterator(); i.hasNext();) { InstructionHandle ih = (InstructionHandle) i.next(); retargetReturnInstruction(munger.hasExtraParameter(), returnValueVar, gotoTarget, ih); } } range.append(advice); range.append(retList); } /** * @return a list of all the return instructions in the range of this shadow */ private List findReturnInstructions() { List returns = new ArrayList(); for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) { if (ih.getInstruction().isReturnInstruction()) { returns.add(ih); } } return returns; } /** * Given a list containing all the return instruction handles for this shadow, finds the last return instruction and copies it, * making this the ultimate return. If the shadow has a non-void return type, we also create a temporary variable to hold the * return value, and load the value from this var before returning (see pr148007 for why we do this - it works around a JRockit * bug, and is also closer to what javac generates) * * Sometimes the 'last return' isnt the right one - some rogue code can include the real return from the body of a subroutine * that exists at the end of the method. In this case the last return is RETURN but that may not be correct for a method with a * non-void return type... pr151673 * * @param returns list of all the return instructions in the shadow * @param returnInstructions instruction list into which the return instructions should be generated * @return the variable holding the return value, if needed */ private BcelVar generateReturnInstructions(List returns, InstructionList returnInstructions) { BcelVar returnValueVar = null; if (this.hasANonVoidReturnType()) { // Find the last *correct* return - this is a method with a non-void return type // so ignore RETURN Instruction newReturnInstruction = null; int i = returns.size() - 1; while (newReturnInstruction == null && i >= 0) { InstructionHandle ih = (InstructionHandle) returns.get(i); if (ih.getInstruction().opcode != Constants.RETURN) { newReturnInstruction = Utility.copyInstruction(ih.getInstruction()); } i--; } returnValueVar = genTempVar(this.getReturnType()); returnValueVar.appendLoad(returnInstructions, getFactory()); returnInstructions.append(newReturnInstruction); } else { InstructionHandle lastReturnHandle = (InstructionHandle) returns.get(returns.size() - 1); Instruction newReturnInstruction = Utility.copyInstruction(lastReturnHandle.getInstruction()); returnInstructions.append(newReturnInstruction); } return returnValueVar; } /** * @return true, iff this shadow returns a value */ private boolean hasANonVoidReturnType() { return this.getReturnType() != ResolvedType.VOID; } /** * Get the list of instructions used to dispatch to the after advice * * @param munger * @param firstInstructionInReturnSequence * @return */ private InstructionList getAfterReturningAdviceDispatchInstructions(BcelAdvice munger, InstructionHandle firstInstructionInReturnSequence) { InstructionList advice = new InstructionList(); BcelVar tempVar = null; if (munger.hasExtraParameter()) { tempVar = insertAdviceInstructionsForBindingReturningParameter(advice); } advice.append(munger.getAdviceInstructions(this, tempVar, firstInstructionInReturnSequence)); return advice; } /** * If the after() returning(Foo f) form is used, bind the return value to the parameter. If the shadow returns void, bind null. * * @param advice * @return */ private BcelVar insertAdviceInstructionsForBindingReturningParameter(InstructionList advice) { BcelVar tempVar; UnresolvedType tempVarType = getReturnType(); if (tempVarType.equals(ResolvedType.VOID)) { tempVar = genTempVar(UnresolvedType.OBJECT); advice.append(InstructionConstants.ACONST_NULL); tempVar.appendStore(advice, getFactory()); } else { tempVar = genTempVar(tempVarType); advice.append(InstructionFactory.createDup(tempVarType.getSize())); tempVar.appendStore(advice, getFactory()); } return tempVar; } /** * Helper method for weaveAfterReturning * * Each return instruction in the method body is retargeted by calling this method. The return instruction is replaced by up to * three instructions: 1) if the shadow returns a value, and that value is bound to an after returning parameter, then we DUP * the return value on the top of the stack 2) if the shadow returns a value, we store it in the returnValueVar (it will be * retrieved from here when we ultimately return after the advice dispatch) 3) if the return was the last instruction, we add a * NOP (it will fall through to the advice dispatch), otherwise we add a GOTO that branches to the supplied gotoTarget (start of * the advice dispatch) */ private void retargetReturnInstruction(boolean hasReturningParameter, BcelVar returnValueVar, InstructionHandle gotoTarget, InstructionHandle returnHandle) { // pr148007, work around JRockit bug // replace ret with store into returnValueVar, followed by goto if not // at the end of the instruction list... InstructionList newInstructions = new InstructionList(); if (returnValueVar != null) { if (hasReturningParameter) { // we have to dup the return val before consuming it... newInstructions.append(InstructionFactory.createDup(this.getReturnType().getSize())); } // store the return value into this var returnValueVar.appendStore(newInstructions, getFactory()); } if (!isLastInstructionInRange(returnHandle, range)) { newInstructions.append(InstructionFactory.createBranchInstruction(Constants.GOTO, gotoTarget)); } if (newInstructions.isEmpty()) { newInstructions.append(InstructionConstants.NOP); } Utility.replaceInstruction(returnHandle, newInstructions, enclosingMethod); } private boolean isLastInstructionInRange(InstructionHandle ih, ShadowRange aRange) { return ih.getNext() == aRange.getEnd(); } public void weaveAfterThrowing(BcelAdvice munger, UnresolvedType catchType) { // a good optimization would be not to generate anything here // if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even // a shadow, inside me). if (getRange().getStart().getNext() == getRange().getEnd()) return; InstructionFactory fact = getFactory(); InstructionList handler = new InstructionList(); BcelVar exceptionVar = genTempVar(catchType); exceptionVar.appendStore(handler, fact); // pr62642 // I will now jump through some firey BCEL hoops to generate a trivial bit of code: // if (exc instanceof ExceptionInInitializerError) // throw (ExceptionInInitializerError)exc; if (this.getEnclosingMethod().getName().equals("<clinit>")) { ResolvedType eiieType = world.resolve("java.lang.ExceptionInInitializerError"); ObjectType eiieBcelType = (ObjectType) BcelWorld.makeBcelType(eiieType); InstructionList ih = new InstructionList(InstructionConstants.NOP); handler.append(exceptionVar.createLoad(fact)); handler.append(fact.createInstanceOf(eiieBcelType)); InstructionBranch bi = InstructionFactory.createBranchInstruction(Constants.IFEQ, ih.getStart()); handler.append(bi); handler.append(exceptionVar.createLoad(fact)); handler.append(fact.createCheckCast(eiieBcelType)); handler.append(InstructionConstants.ATHROW); handler.append(ih); } InstructionList endHandler = new InstructionList(exceptionVar.createLoad(fact)); handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart())); handler.append(endHandler); handler.append(InstructionConstants.ATHROW); InstructionHandle handlerStart = handler.getStart(); if (isFallsThrough()) { InstructionHandle jumpTarget = handler.append(InstructionConstants.NOP); handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget)); } InstructionHandle protectedEnd = handler.getStart(); range.insert(handler, Range.InsideAfter); enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(), handlerStart, (ObjectType) BcelWorld.makeBcelType(catchType), // ???Type.THROWABLE, // high priority if our args are on the stack getKind().hasHighPriorityExceptions()); } // ??? this shares a lot of code with the above weaveAfterThrowing // ??? would be nice to abstract that to say things only once public void weaveSoftener(BcelAdvice munger, UnresolvedType catchType) { // a good optimization would be not to generate anything here // if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even // a shadow, inside me). if (getRange().getStart().getNext() == getRange().getEnd()) return; InstructionFactory fact = getFactory(); InstructionList handler = new InstructionList(); InstructionList rtExHandler = new InstructionList(); BcelVar exceptionVar = genTempVar(catchType); handler.append(fact.createNew(NameMangler.SOFT_EXCEPTION_TYPE)); handler.append(InstructionFactory.createDup(1)); handler.append(exceptionVar.createLoad(fact)); handler.append(fact.createInvoke(NameMangler.SOFT_EXCEPTION_TYPE, "<init>", Type.VOID, new Type[] { Type.THROWABLE }, Constants.INVOKESPECIAL)); // ??? special handler.append(InstructionConstants.ATHROW); // ENH 42737 exceptionVar.appendStore(rtExHandler, fact); // aload_1 rtExHandler.append(exceptionVar.createLoad(fact)); // instanceof class java/lang/RuntimeException rtExHandler.append(fact.createInstanceOf(new ObjectType("java.lang.RuntimeException"))); // ifeq go to new SOFT_EXCEPTION_TYPE instruction rtExHandler.append(InstructionFactory.createBranchInstruction(Constants.IFEQ, handler.getStart())); // aload_1 rtExHandler.append(exceptionVar.createLoad(fact)); // athrow rtExHandler.append(InstructionFactory.ATHROW); InstructionHandle handlerStart = rtExHandler.getStart(); if (isFallsThrough()) { InstructionHandle jumpTarget = range.getEnd();// handler.append(fact.NOP); rtExHandler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget)); } rtExHandler.append(handler); InstructionHandle protectedEnd = rtExHandler.getStart(); range.insert(rtExHandler, Range.InsideAfter); enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(), handlerStart, (ObjectType) BcelWorld.makeBcelType(catchType), // high priority if our args are on the stack getKind().hasHighPriorityExceptions()); } public void weavePerObjectEntry(final BcelAdvice munger, final BcelVar onVar) { final InstructionFactory fact = getFactory(); InstructionList entryInstructions = new InstructionList(); InstructionList entrySuccessInstructions = new InstructionList(); onVar.appendLoad(entrySuccessInstructions, fact); entrySuccessInstructions .append(Utility.createInvoke(fact, world, AjcMemberMaker.perObjectBind(munger.getConcreteAspect()))); InstructionList testInstructions = munger.getTestInstructions(this, entrySuccessInstructions.getStart(), range .getRealStart(), entrySuccessInstructions.getStart()); entryInstructions.append(testInstructions); entryInstructions.append(entrySuccessInstructions); range.insert(entryInstructions, Range.InsideBefore); } // PTWIMPL Create static initializer to call the aspect factory /** * Causes the aspect instance to be *set* for later retrievable through localAspectof()/aspectOf() */ public void weavePerTypeWithinAspectInitialization(final BcelAdvice munger, UnresolvedType t) { if (t.resolve(world).isInterface()) return; // Don't initialize statics in final InstructionFactory fact = getFactory(); InstructionList entryInstructions = new InstructionList(); InstructionList entrySuccessInstructions = new InstructionList(); BcelWorld.getBcelObjectType(munger.getConcreteAspect()); String aspectname = munger.getConcreteAspect().getName(); String ptwField = NameMangler.perTypeWithinFieldForTarget(munger.getConcreteAspect()); entrySuccessInstructions.append(InstructionFactory.PUSH(fact.getConstantPool(), t.getName())); entrySuccessInstructions.append(fact.createInvoke(aspectname, "ajc$createAspectInstance", new ObjectType(aspectname), new Type[] { new ObjectType("java.lang.String") }, Constants.INVOKESTATIC)); entrySuccessInstructions.append(fact.createPutStatic(t.getName(), ptwField, new ObjectType(aspectname))); entryInstructions.append(entrySuccessInstructions); range.insert(entryInstructions, Range.InsideBefore); } public void weaveCflowEntry(final BcelAdvice munger, final Member cflowField) { final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry || munger.getKind() == AdviceKind.PerCflowEntry; final Type objectArrayType = new ArrayType(Type.OBJECT, 1); final InstructionFactory fact = getFactory(); final BcelVar testResult = genTempVar(ResolvedType.BOOLEAN); InstructionList entryInstructions = new InstructionList(); { InstructionList entrySuccessInstructions = new InstructionList(); if (munger.hasDynamicTests()) { entryInstructions.append(Utility.createConstant(fact, 0)); testResult.appendStore(entryInstructions, fact); entrySuccessInstructions.append(Utility.createConstant(fact, 1)); testResult.appendStore(entrySuccessInstructions, fact); } if (isPer) { entrySuccessInstructions.append(fact.createInvoke(munger.getConcreteAspect().getName(), NameMangler.PERCFLOW_PUSH_METHOD, Type.VOID, new Type[] {}, Constants.INVOKESTATIC)); } else { BcelVar[] cflowStateVars = munger.getExposedStateAsBcelVars(false); if (cflowStateVars.length == 0) { // This should be getting managed by a counter - lets make sure. if (!cflowField.getType().getName().endsWith("CFlowCounter")) throw new RuntimeException("Incorrectly attempting counter operation on stacked cflow"); entrySuccessInstructions.append(Utility.createGet(fact, cflowField)); // arrayVar.appendLoad(entrySuccessInstructions, fact); entrySuccessInstructions.append(fact.createInvoke(NameMangler.CFLOW_COUNTER_TYPE, "inc", Type.VOID, new Type[] {}, Constants.INVOKEVIRTUAL)); } else { BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY); int alen = cflowStateVars.length; entrySuccessInstructions.append(Utility.createConstant(fact, alen)); entrySuccessInstructions.append(fact.createNewArray(Type.OBJECT, (short) 1)); arrayVar.appendStore(entrySuccessInstructions, fact); for (int i = 0; i < alen; i++) { arrayVar.appendConvertableArrayStore(entrySuccessInstructions, fact, i, cflowStateVars[i]); } entrySuccessInstructions.append(Utility.createGet(fact, cflowField)); arrayVar.appendLoad(entrySuccessInstructions, fact); entrySuccessInstructions.append(fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID, new Type[] { objectArrayType }, Constants.INVOKEVIRTUAL)); } } InstructionList testInstructions = munger.getTestInstructions(this, entrySuccessInstructions.getStart(), range .getRealStart(), entrySuccessInstructions.getStart()); entryInstructions.append(testInstructions); entryInstructions.append(entrySuccessInstructions); } // this is the same for both per and non-per weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) { public InstructionList getAdviceInstructions(BcelShadow s, BcelVar extraArgVar, InstructionHandle ifNoAdvice) { InstructionList exitInstructions = new InstructionList(); if (munger.hasDynamicTests()) { testResult.appendLoad(exitInstructions, fact); exitInstructions.append(InstructionFactory.createBranchInstruction(Constants.IFEQ, ifNoAdvice)); } exitInstructions.append(Utility.createGet(fact, cflowField)); if (munger.getKind() != AdviceKind.PerCflowEntry && munger.getKind() != AdviceKind.PerCflowBelowEntry && munger.getExposedStateAsBcelVars(false).length == 0) { exitInstructions.append(fact.createInvoke(NameMangler.CFLOW_COUNTER_TYPE, "dec", Type.VOID, new Type[] {}, Constants.INVOKEVIRTUAL)); } else { exitInstructions.append(fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "pop", Type.VOID, new Type[] {}, Constants.INVOKEVIRTUAL)); } return exitInstructions; } }); range.insert(entryInstructions, Range.InsideBefore); } /* * Implementation notes: * * AroundInline still extracts the instructions of the original shadow into an extracted method. This allows inlining of even * that advice that doesn't call proceed or calls proceed more than once. * * It extracts the instructions of the original shadow into a method. * * Then it extracts the instructions of the advice into a new method defined on this enclosing class. This new method can then * be specialized as below. * * Then it searches in the instructions of the advice for any call to the proceed method. * * At such a call, there is stuff on the stack representing the arguments to proceed. Pop these into the frame. * * Now build the stack for the call to the extracted method, taking values either from the join point state or from the new * frame locs from proceed. Now call the extracted method. The right return value should be on the stack, so no cast is * necessary. * * If only one call to proceed is made, we can re-inline the original shadow. We are not doing that presently. * * If the body of the advice can be determined to not alter the stack, or if this shadow doesn't care about the stack, i.e. * method-execution, then the new method for the advice can also be re-lined. We are not doing that presently. */ public void weaveAroundInline(BcelAdvice munger, boolean hasDynamicTest) { // !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...); Member mungerSig = munger.getSignature(); // Member originalSig = mungerSig; // If mungerSig is on a parameterized type, originalSig is the member on the generic type if (mungerSig instanceof ResolvedMember) { ResolvedMember rm = (ResolvedMember) mungerSig; if (rm.hasBackingGenericMember()) mungerSig = rm.getBackingGenericMember(); } ResolvedType declaringType = world.resolve(mungerSig.getDeclaringType(), true); if (declaringType.isMissing()) { world.getLint().cantFindType.signal(new String[] { WeaverMessages.format( WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE, declaringType.getClassName()) }, getSourceLocation(), new ISourceLocation[] { munger.getSourceLocation() }); // IMessage msg = new Message( // WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName()), // "",IMessage.ERROR,getSourceLocation(),null, // new ISourceLocation[]{ munger.getSourceLocation()}); // world.getMessageHandler().handleMessage(msg); } // ??? might want some checks here to give better errors ResolvedType rt = (declaringType.isParameterizedType() ? declaringType.getGenericType() : declaringType); BcelObjectType ot = BcelWorld.getBcelObjectType(rt); // if (ot==null) { // world.getMessageHandler().handleMessage( // MessageUtil.warn("Unable to find modifiable delegate for the aspect '"+rt.getName()+ // "' containing around advice - cannot implement inlining",munger.getSourceLocation())); // weaveAroundClosure(munger, hasDynamicTest); // return; // } LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig); if (!adviceMethod.getCanInline()) { weaveAroundClosure(munger, hasDynamicTest); return; } // specific test for @AJ proceedInInners if (munger.getConcreteAspect().isAnnotationStyleAspect()) { // if we can't find one proceed() we suspect that the call // is happening in an inner class so we don't inline it. // Note: for code style, this is done at Aspect compilation time. boolean canSeeProceedPassedToOther = false; InstructionHandle curr = adviceMethod.getBody().getStart(); InstructionHandle end = adviceMethod.getBody().getEnd(); ConstantPool cpg = adviceMethod.getEnclosingClass().getConstantPool(); while (curr != end) { InstructionHandle next = curr.getNext(); Instruction inst = curr.getInstruction(); if ((inst instanceof InvokeInstruction) && ((InvokeInstruction) inst).getSignature(cpg).indexOf("Lorg/aspectj/lang/ProceedingJoinPoint;") > 0) { // we may want to refine to exclude stuff returning jp ? // does code style skip inline if i write dump(thisJoinPoint) ? canSeeProceedPassedToOther = true;// we see one pjp passed around - dangerous break; } curr = next; } if (canSeeProceedPassedToOther) { // remember this decision to avoid re-analysis adviceMethod.setCanInline(false); weaveAroundClosure(munger, hasDynamicTest); return; } } // We can't inline around methods if they have around advice on them, this // is because the weaving will extract the body and hence the proceed call. // ??? should consider optimizations to recognize simple cases that don't require body extraction enclosingMethod.setCanInline(false); // start by exposing various useful things into the frame final InstructionFactory fact = getFactory(); // now generate the aroundBody method // eg. "private static final void method_aroundBody0(M, M, String, org.aspectj.lang.JoinPoint)" LazyMethodGen extractedMethod = extractMethod(NameMangler.aroundCallbackMethodName(getSignature(), getEnclosingClass()), Modifier.PRIVATE, munger); // now extract the advice into its own method String adviceMethodName = NameMangler.aroundCallbackMethodName(getSignature(), getEnclosingClass()) + "$advice"; List argVarList = new ArrayList(); List proceedVarList = new ArrayList(); int extraParamOffset = 0; // Create the extra parameters that are needed for passing to proceed // This code is very similar to that found in makeCallToCallback and should // be rationalized in the future if (thisVar != null) { argVarList.add(thisVar); proceedVarList.add(new BcelVar(thisVar.getType(), extraParamOffset)); extraParamOffset += thisVar.getType().getSize(); } if (targetVar != null && targetVar != thisVar) { argVarList.add(targetVar); proceedVarList.add(new BcelVar(targetVar.getType(), extraParamOffset)); extraParamOffset += targetVar.getType().getSize(); } for (int i = 0, len = getArgCount(); i < len; i++) { argVarList.add(argVars[i]); proceedVarList.add(new BcelVar(argVars[i].getType(), extraParamOffset)); extraParamOffset += argVars[i].getType().getSize(); } if (thisJoinPointVar != null) { argVarList.add(thisJoinPointVar); proceedVarList.add(new BcelVar(thisJoinPointVar.getType(), extraParamOffset)); extraParamOffset += thisJoinPointVar.getType().getSize(); } // We use the munger signature here because it allows for any parameterization of the mungers pointcut that // may have occurred ie. if the pointcut is p(T t) in the super aspect and that has become p(Foo t) in the sub aspect // then here the munger signature will have 'Foo' as an argument in it whilst the adviceMethod argument type will be // 'Object' - since // it represents the advice method in the superaspect which uses the erasure of the type variable p(Object t) - see // pr174449. Type[] adviceParameterTypes = BcelWorld.makeBcelTypes(munger.getSignature().getParameterTypes()); // adviceMethod.getArgumentTypes(); adviceMethod.getArgumentTypes(); // forces initialization ... dont like this but seems to be required for some tests to // pass, I think that means // there is a LazyMethodGen method that is not correctly setup to call initialize() when it is invoked - but I dont have // time right now to discover which Type[] extractedMethodParameterTypes = extractedMethod.getArgumentTypes(); Type[] parameterTypes = new Type[extractedMethodParameterTypes.length + adviceParameterTypes.length + 1]; int parameterIndex = 0; System.arraycopy(extractedMethodParameterTypes, 0, parameterTypes, parameterIndex, extractedMethodParameterTypes.length); parameterIndex += extractedMethodParameterTypes.length; parameterTypes[parameterIndex++] = BcelWorld.makeBcelType(adviceMethod.getEnclosingClass().getType()); System.arraycopy(adviceParameterTypes, 0, parameterTypes, parameterIndex, adviceParameterTypes.length); // parameterTypes is [Bug, C, org.aspectj.lang.JoinPoint, X, org.aspectj.lang.ProceedingJoinPoint, java.lang.Object, // java.lang.Object] LazyMethodGen localAdviceMethod = new LazyMethodGen(Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC, BcelWorld .makeBcelType(mungerSig.getReturnType()), adviceMethodName, parameterTypes, new String[0], getEnclosingClass()); String donorFileName = adviceMethod.getEnclosingClass().getInternalFileName(); String recipientFileName = getEnclosingClass().getInternalFileName(); // System.err.println("donor " + donorFileName); // System.err.println("recip " + recipientFileName); if (!donorFileName.equals(recipientFileName)) { localAdviceMethod.fromFilename = donorFileName; getEnclosingClass().addInlinedSourceFileInfo(donorFileName, adviceMethod.highestLineNumber); } getEnclosingClass().addMethodGen(localAdviceMethod); // create a map that will move all slots in advice method forward by extraParamOffset // in order to make room for the new proceed-required arguments that are added at // the beginning of the parameter list int nVars = adviceMethod.getMaxLocals() + extraParamOffset; IntMap varMap = IntMap.idMap(nVars); for (int i = extraParamOffset; i < nVars; i++) { varMap.put(i - extraParamOffset, i); } localAdviceMethod.getBody().insert( BcelClassWeaver.genInlineInstructions(adviceMethod, localAdviceMethod, varMap, fact, true)); localAdviceMethod.setMaxLocals(nVars); // System.err.println(localAdviceMethod); // the shadow is now empty. First, create a correct call // to the around advice. This includes both the call (which may involve // value conversion of the advice arguments) and the return // (which may involve value conversion of the return value). Right now // we push a null for the unused closure. It's sad, but there it is. InstructionList advice = new InstructionList(); // InstructionHandle adviceMethodInvocation; { for (Iterator i = argVarList.iterator(); i.hasNext();) { BcelVar var = (BcelVar) i.next(); var.appendLoad(advice, fact); } // ??? we don't actually need to push NULL for the closure if we take care advice.append(munger.getAdviceArgSetup(this, null, (munger.getConcreteAspect().isAnnotationStyleAspect() && munger.getDeclaringAspect() != null && munger .getDeclaringAspect().resolve(world).isAnnotationStyleAspect()) ? this.loadThisJoinPoint() : new InstructionList(InstructionConstants.ACONST_NULL))); // adviceMethodInvocation = advice.append(Utility.createInvoke(fact, localAdviceMethod)); // (fact, getWorld(), munger.getSignature())); advice.append(Utility.createConversion(getFactory(), BcelWorld.makeBcelType(mungerSig.getReturnType()), extractedMethod .getReturnType(), world.isInJava5Mode())); if (!isFallsThrough()) { advice.append(InstructionFactory.createReturn(extractedMethod.getReturnType())); } } // now, situate the call inside the possible dynamic tests, // and actually add the whole mess to the shadow if (!hasDynamicTest) { range.append(advice); } else { InstructionList afterThingie = new InstructionList(InstructionConstants.NOP); InstructionList callback = makeCallToCallback(extractedMethod); if (terminatesWithReturn()) { callback.append(InstructionFactory.createReturn(extractedMethod.getReturnType())); } else { // InstructionHandle endNop = range.insert(fact.NOP, Range.InsideAfter); advice.append(InstructionFactory.createBranchInstruction(Constants.GOTO, afterThingie.getStart())); } range.append(munger.getTestInstructions(this, advice.getStart(), callback.getStart(), advice.getStart())); range.append(advice); range.append(callback); range.append(afterThingie); } // now search through the advice, looking for a call to PROCEED. // Then we replace the call to proceed with some argument setup, and a // call to the extracted method. // inlining support for code style aspects if (!munger.getDeclaringType().isAnnotationStyleAspect()) { String proceedName = NameMangler.proceedMethodName(munger.getSignature().getName()); InstructionHandle curr = localAdviceMethod.getBody().getStart(); InstructionHandle end = localAdviceMethod.getBody().getEnd(); ConstantPool cpg = localAdviceMethod.getEnclosingClass().getConstantPool(); while (curr != end) { InstructionHandle next = curr.getNext(); Instruction inst = curr.getInstruction(); if ((inst.opcode == Constants.INVOKESTATIC) && proceedName.equals(((InvokeInstruction) inst).getMethodName(cpg))) { localAdviceMethod.getBody().append(curr, getRedoneProceedCall(fact, extractedMethod, munger, localAdviceMethod, proceedVarList)); Utility.deleteInstruction(curr, localAdviceMethod); } curr = next; } // and that's it. } else { // ATAJ inlining support for @AJ aspects // [TODO document @AJ code rule: don't manipulate 2 jps proceed at the same time.. in an advice body] InstructionHandle curr = localAdviceMethod.getBody().getStart(); InstructionHandle end = localAdviceMethod.getBody().getEnd(); ConstantPool cpg = localAdviceMethod.getEnclosingClass().getConstantPool(); while (curr != end) { InstructionHandle next = curr.getNext(); Instruction inst = curr.getInstruction(); if ((inst instanceof INVOKEINTERFACE) && "proceed".equals(((INVOKEINTERFACE) inst).getMethodName(cpg))) { final boolean isProceedWithArgs; if (((INVOKEINTERFACE) inst).getArgumentTypes(cpg).length == 1) { // proceed with args as a boxed Object[] isProceedWithArgs = true; } else { isProceedWithArgs = false; } InstructionList insteadProceedIl = getRedoneProceedCallForAnnotationStyle(fact, extractedMethod, munger, localAdviceMethod, proceedVarList, isProceedWithArgs); localAdviceMethod.getBody().append(curr, insteadProceedIl); Utility.deleteInstruction(curr, localAdviceMethod); } curr = next; } } } private InstructionList getRedoneProceedCall(InstructionFactory fact, LazyMethodGen callbackMethod, BcelAdvice munger, LazyMethodGen localAdviceMethod, List argVarList) { InstructionList ret = new InstructionList(); // we have on stack all the arguments for the ADVICE call. // we have in frame somewhere all the arguments for the non-advice call. BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(true); IntMap proceedMap = makeProceedArgumentMap(adviceVars); // System.out.println(proceedMap + " for " + this); // System.out.println(argVarList); ResolvedType[] proceedParamTypes = world.resolve(munger.getSignature().getParameterTypes()); // remove this*JoinPoint* as arguments to proceed if (munger.getBaseParameterCount() + 1 < proceedParamTypes.length) { int len = munger.getBaseParameterCount() + 1; ResolvedType[] newTypes = new ResolvedType[len]; System.arraycopy(proceedParamTypes, 0, newTypes, 0, len); proceedParamTypes = newTypes; } // System.out.println("stateTypes: " + Arrays.asList(stateTypes)); BcelVar[] proceedVars = Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod); Type[] stateTypes = callbackMethod.getArgumentTypes(); // System.out.println("stateTypes: " + Arrays.asList(stateTypes)); for (int i = 0, len = stateTypes.length; i < len; i++) { Type stateType = stateTypes[i]; ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world); if (proceedMap.hasKey(i)) { // throw new RuntimeException("unimplemented"); proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX); } else { ((BcelVar) argVarList.get(i)).appendLoad(ret, fact); } } ret.append(Utility.createInvoke(fact, callbackMethod)); ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), BcelWorld.makeBcelType(munger.getSignature() .getReturnType()))); return ret; } // private static boolean bindsThisOrTarget(Pointcut pointcut) { // ThisTargetFinder visitor = new ThisTargetFinder(); // pointcut.accept(visitor, null); // return visitor.bindsThisOrTarget; // } // private static class ThisTargetFinder extends IdentityPointcutVisitor { // boolean bindsThisOrTarget = false; // // public Object visit(ThisOrTargetPointcut node, Object data) { // if (node.isBinding()) { // bindsThisOrTarget = true; // } // return node; // } // // public Object visit(AndPointcut node, Object data) { // if (!bindsThisOrTarget) node.getLeft().accept(this, data); // if (!bindsThisOrTarget) node.getRight().accept(this, data); // return node; // } // // public Object visit(NotPointcut node, Object data) { // if (!bindsThisOrTarget) node.getNegatedPointcut().accept(this, data); // return node; // } // // public Object visit(OrPointcut node, Object data) { // if (!bindsThisOrTarget) node.getLeft().accept(this, data); // if (!bindsThisOrTarget) node.getRight().accept(this, data); // return node; // } // } /** * Annotation style handling for inlining. * * Note: The proceedingjoinpoint is already on the stack (since the user was calling pjp.proceed(...) * * The proceed map is ignored (in terms of argument repositioning) since we have a fixed expected format for annotation style. * The aim here is to change the proceed() call into a call to the xxx_aroundBody0 method. * * */ private InstructionList getRedoneProceedCallForAnnotationStyle(InstructionFactory fact, LazyMethodGen callbackMethod, BcelAdvice munger, LazyMethodGen localAdviceMethod, List argVarList, boolean isProceedWithArgs) { InstructionList ret = new InstructionList(); // store the Object[] array on stack if proceed with args if (isProceedWithArgs) { // STORE the Object[] into a local variable Type objectArrayType = Type.OBJECT_ARRAY; int theObjectArrayLocalNumber = localAdviceMethod.allocateLocal(objectArrayType); ret.append(InstructionFactory.createStore(objectArrayType, theObjectArrayLocalNumber)); // STORE the ProceedingJoinPoint instance into a local variable Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;"); int pjpLocalNumber = localAdviceMethod.allocateLocal(proceedingJpType); ret.append(InstructionFactory.createStore(proceedingJpType, pjpLocalNumber)); // Aim here initially is to determine whether the user will have provided a new // this/target in the object array and consume them if they have, leaving us the rest of // the arguments to process as regular arguments to the invocation at the original join point boolean pointcutBindsThis = bindsThis(munger); boolean pointcutBindsTarget = bindsTarget(munger); boolean targetIsSameAsThis = getKind().isTargetSameAsThis(); int nextArgumentToProvideForCallback = 0; if (hasThis()) { if (!(pointcutBindsTarget && targetIsSameAsThis)) { if (pointcutBindsThis) { // they have supplied new this as first entry in object array, consume it ret.append(InstructionFactory.createLoad(objectArrayType, theObjectArrayLocalNumber)); ret.append(Utility.createConstant(fact, 0)); ret.append(InstructionFactory.createArrayLoad(Type.OBJECT)); ret.append(Utility.createConversion(fact, Type.OBJECT, callbackMethod.getArgumentTypes()[0])); } else { // use local variable 0 ret.append(InstructionFactory.createALOAD(0)); } nextArgumentToProvideForCallback++; } } if (hasTarget()) { if (pointcutBindsTarget) { if (getKind().isTargetSameAsThis()) { ret.append(InstructionFactory.createLoad(objectArrayType, theObjectArrayLocalNumber)); ret.append(Utility.createConstant(fact, pointcutBindsThis ? 1 : 0)); ret.append(InstructionFactory.createArrayLoad(Type.OBJECT)); ret.append(Utility.createConversion(fact, Type.OBJECT, callbackMethod.getArgumentTypes()[0])); } else { int position = (hasThis() && pointcutBindsThis ? 1 : 0); ret.append(InstructionFactory.createLoad(objectArrayType, theObjectArrayLocalNumber)); ret.append(Utility.createConstant(fact, position)); ret.append(InstructionFactory.createArrayLoad(Type.OBJECT)); ret.append(Utility.createConversion(fact, Type.OBJECT, callbackMethod.getArgumentTypes()[position])); } nextArgumentToProvideForCallback++; } else { if (getKind().isTargetSameAsThis()) { // ret.append(new ALOAD(0)); } else { ret.append(InstructionFactory.createLoad(localAdviceMethod.getArgumentTypes()[0], hasThis() ? 1 : 0)); nextArgumentToProvideForCallback++; } } } // Where to start in the object array in order to pick up arguments int indexIntoObjectArrayForArguments = (pointcutBindsThis ? 1 : 0) + (pointcutBindsTarget ? 1 : 0); int len = callbackMethod.getArgumentTypes().length; for (int i = nextArgumentToProvideForCallback; i < len; i++) { Type stateType = callbackMethod.getArgumentTypes()[i]; BcelWorld.fromBcel(stateType).resolve(world); if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) { ret.append(new InstructionLV(Constants.ALOAD, pjpLocalNumber)); } else { ret.append(InstructionFactory.createLoad(objectArrayType, theObjectArrayLocalNumber)); ret.append(Utility .createConstant(fact, i - nextArgumentToProvideForCallback + indexIntoObjectArrayForArguments)); ret.append(InstructionFactory.createArrayLoad(Type.OBJECT)); ret.append(Utility.createConversion(fact, Type.OBJECT, stateType)); } } } else { Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;"); int localJp = localAdviceMethod.allocateLocal(proceedingJpType); ret.append(InstructionFactory.createStore(proceedingJpType, localJp)); for (int i = 0, len = callbackMethod.getArgumentTypes().length; i < len; i++) { Type stateType = callbackMethod.getArgumentTypes()[i]; /* ResolvedType stateTypeX = */ BcelWorld.fromBcel(stateType).resolve(world); if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) { ret.append(InstructionFactory.createALOAD(localJp));// from localAdvice signature // } else if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(stateType.getSignature())) { // //FIXME ALEX? // ret.append(new ALOAD(localJp));// from localAdvice signature // // ret.append(fact.createCheckCast( // // (ReferenceType) BcelWorld.makeBcelType(stateTypeX) // // )); // // cast ? // } else { ret.append(InstructionFactory.createLoad(stateType, i)); } } } // do the callback invoke ret.append(Utility.createInvoke(fact, callbackMethod)); // box it again. Handles cases where around advice does return something else than Object if (!UnresolvedType.OBJECT.equals(munger.getSignature().getReturnType())) { ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), Type.OBJECT)); } ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), BcelWorld.makeBcelType(munger.getSignature() .getReturnType()))); return ret; // // // // if (proceedMap.hasKey(i)) { // ret.append(new ALOAD(i)); // //throw new RuntimeException("unimplemented"); // //proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX); // } else { // //((BcelVar) argVarList.get(i)).appendLoad(ret, fact); // //ret.append(new ALOAD(i)); // if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) { // ret.append(new ALOAD(i)); // } else { // ret.append(new ALOAD(i)); // } // } // } // // ret.append(Utility.createInvoke(fact, callbackMethod)); // ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), // BcelWorld.makeBcelType(munger.getSignature().getReturnType()))); // // //ret.append(new ACONST_NULL());//will be POPed // if (true) return ret; // // // // // we have on stack all the arguments for the ADVICE call. // // we have in frame somewhere all the arguments for the non-advice call. // // BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(); // IntMap proceedMap = makeProceedArgumentMap(adviceVars); // // System.out.println(proceedMap + " for " + this); // System.out.println(argVarList); // // ResolvedType[] proceedParamTypes = // world.resolve(munger.getSignature().getParameterTypes()); // // remove this*JoinPoint* as arguments to proceed // if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) { // int len = munger.getBaseParameterCount()+1; // ResolvedType[] newTypes = new ResolvedType[len]; // System.arraycopy(proceedParamTypes, 0, newTypes, 0, len); // proceedParamTypes = newTypes; // } // // //System.out.println("stateTypes: " + Arrays.asList(stateTypes)); // BcelVar[] proceedVars = // Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod); // // Type[] stateTypes = callbackMethod.getArgumentTypes(); // // System.out.println("stateTypes: " + Arrays.asList(stateTypes)); // // for (int i=0, len=stateTypes.length; i < len; i++) { // Type stateType = stateTypes[i]; // ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world); // if (proceedMap.hasKey(i)) { // //throw new RuntimeException("unimplemented"); // proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX); // } else { // ((BcelVar) argVarList.get(i)).appendLoad(ret, fact); // } // } // // ret.append(Utility.createInvoke(fact, callbackMethod)); // ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), // BcelWorld.makeBcelType(munger.getSignature().getReturnType()))); // return ret; } private boolean bindsThis(BcelAdvice munger) { UsesThisVisitor utv = new UsesThisVisitor(); munger.getPointcut().accept(utv, null); return utv.usesThis; } private boolean bindsTarget(BcelAdvice munger) { UsesTargetVisitor utv = new UsesTargetVisitor(); munger.getPointcut().accept(utv, null); return utv.usesTarget; } private static class UsesThisVisitor extends AbstractPatternNodeVisitor { boolean usesThis = false; public Object visit(ThisOrTargetPointcut node, Object data) { if (node.isThis() && node.isBinding()) usesThis = true; return node; } public Object visit(AndPointcut node, Object data) { if (!usesThis) node.getLeft().accept(this, data); if (!usesThis) node.getRight().accept(this, data); return node; } public Object visit(NotPointcut node, Object data) { if (!usesThis) node.getNegatedPointcut().accept(this, data); return node; } public Object visit(OrPointcut node, Object data) { if (!usesThis) node.getLeft().accept(this, data); if (!usesThis) node.getRight().accept(this, data); return node; } } private static class UsesTargetVisitor extends AbstractPatternNodeVisitor { boolean usesTarget = false; public Object visit(ThisOrTargetPointcut node, Object data) { if (!node.isThis() && node.isBinding()) usesTarget = true; return node; } public Object visit(AndPointcut node, Object data) { if (!usesTarget) node.getLeft().accept(this, data); if (!usesTarget) node.getRight().accept(this, data); return node; } public Object visit(NotPointcut node, Object data) { if (!usesTarget) node.getNegatedPointcut().accept(this, data); return node; } public Object visit(OrPointcut node, Object data) { if (!usesTarget) node.getLeft().accept(this, data); if (!usesTarget) node.getRight().accept(this, data); return node; } } public void weaveAroundClosure(BcelAdvice munger, boolean hasDynamicTest) { InstructionFactory fact = getFactory(); enclosingMethod.setCanInline(false); int linenumber = getSourceLine(); // MOVE OUT ALL THE INSTRUCTIONS IN MY SHADOW INTO ANOTHER METHOD! LazyMethodGen callbackMethod = extractMethod(NameMangler.aroundCallbackMethodName(getSignature(), getEnclosingClass()), 0, munger); BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(true); String closureClassName = NameMangler.makeClosureClassName(getEnclosingClass().getType(), getEnclosingClass() .getNewGeneratedNameTag()); Member constructorSig = new MemberImpl(Member.CONSTRUCTOR, UnresolvedType.forName(closureClassName), 0, "<init>", "([Ljava/lang/Object;)V"); BcelVar closureHolder = null; // This is not being used currently since getKind() == preinitializaiton // cannot happen in around advice if (getKind() == PreInitialization) { closureHolder = genTempVar(AjcMemberMaker.AROUND_CLOSURE_TYPE); } InstructionList closureInstantiation = makeClosureInstantiation(constructorSig, closureHolder); /* LazyMethodGen constructor = */ makeClosureClassAndReturnConstructor(closureClassName, callbackMethod, makeProceedArgumentMap(adviceVars)); InstructionList returnConversionCode; if (getKind() == PreInitialization) { returnConversionCode = new InstructionList(); BcelVar stateTempVar = genTempVar(UnresolvedType.OBJECTARRAY); closureHolder.appendLoad(returnConversionCode, fact); returnConversionCode.append(Utility.createInvoke(fact, world, AjcMemberMaker.aroundClosurePreInitializationGetter())); stateTempVar.appendStore(returnConversionCode, fact); Type[] stateTypes = getSuperConstructorParameterTypes(); returnConversionCode.append(InstructionConstants.ALOAD_0); // put "this" back on the stack for (int i = 0, len = stateTypes.length; i < len; i++) { UnresolvedType bcelTX = BcelWorld.fromBcel(stateTypes[i]); ResolvedType stateRTX = world.resolve(bcelTX, true); if (stateRTX.isMissing()) { world.getLint().cantFindType.signal(new String[] { WeaverMessages.format( WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT, bcelTX.getClassName()) }, getSourceLocation(), new ISourceLocation[] { munger.getSourceLocation() }); // IMessage msg = new Message( // WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName()), // "",IMessage.ERROR,getSourceLocation(),null, // new ISourceLocation[]{ munger.getSourceLocation()}); // world.getMessageHandler().handleMessage(msg); } stateTempVar.appendConvertableArrayLoad(returnConversionCode, fact, i, stateRTX); } } else { // pr226201 Member mungerSignature = munger.getSignature(); if (munger.getSignature() instanceof ResolvedMember) { if (((ResolvedMember) mungerSignature).hasBackingGenericMember()) { mungerSignature = ((ResolvedMember) mungerSignature).getBackingGenericMember(); } } UnresolvedType returnType = mungerSignature.getReturnType(); returnConversionCode = Utility.createConversion(getFactory(), BcelWorld.makeBcelType(returnType), callbackMethod .getReturnType(), world.isInJava5Mode()); if (!isFallsThrough()) { returnConversionCode.append(InstructionFactory.createReturn(callbackMethod.getReturnType())); } } // initialize the bit flags for this shadow int bitflags = 0x000000; if (getKind().isTargetSameAsThis()) bitflags |= 0x010000; if (hasThis()) bitflags |= 0x001000; if (bindsThis(munger)) bitflags |= 0x000100; if (hasTarget()) bitflags |= 0x000010; if (bindsTarget(munger)) bitflags |= 0x000001; // ATAJ for @AJ aspect we need to link the closure with the joinpoint instance if (munger.getConcreteAspect() != null && munger.getConcreteAspect().isAnnotationStyleAspect() && munger.getDeclaringAspect() != null && munger.getDeclaringAspect().resolve(world).isAnnotationStyleAspect()) { // stick the bitflags on the stack and call the variant of linkClosureAndJoinPoint that takes an int closureInstantiation.append(fact.createConstant(Integer.valueOf(bitflags))); closureInstantiation.append(Utility.createInvoke(getFactory(), getWorld(), new MemberImpl(Member.METHOD, UnresolvedType .forName("org.aspectj.runtime.internal.AroundClosure"), Modifier.PUBLIC, "linkClosureAndJoinPoint", "(I)Lorg/aspectj/lang/ProceedingJoinPoint;"))); } InstructionList advice = new InstructionList(); advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation)); // invoke the advice advice.append(munger.getNonTestAdviceInstructions(this)); advice.append(returnConversionCode); if (getKind() == Shadow.MethodExecution && linenumber > 0) { advice.getStart().addTargeter(new LineNumberTag(linenumber)); } if (!hasDynamicTest) { range.append(advice); } else { InstructionList callback = makeCallToCallback(callbackMethod); InstructionList postCallback = new InstructionList(); if (terminatesWithReturn()) { callback.append(InstructionFactory.createReturn(callbackMethod.getReturnType())); } else { advice.append(InstructionFactory.createBranchInstruction(Constants.GOTO, postCallback .append(InstructionConstants.NOP))); } range.append(munger.getTestInstructions(this, advice.getStart(), callback.getStart(), advice.getStart())); range.append(advice); range.append(callback); range.append(postCallback); } } // exposed for testing InstructionList makeCallToCallback(LazyMethodGen callbackMethod) { InstructionFactory fact = getFactory(); InstructionList callback = new InstructionList(); if (thisVar != null) { callback.append(InstructionConstants.ALOAD_0); } if (targetVar != null && targetVar != thisVar) { callback.append(BcelRenderer.renderExpr(fact, world, targetVar)); } callback.append(BcelRenderer.renderExprs(fact, world, argVars)); // remember to render tjps if (thisJoinPointVar != null) { callback.append(BcelRenderer.renderExpr(fact, world, thisJoinPointVar)); } callback.append(Utility.createInvoke(fact, callbackMethod)); return callback; } /** side-effect-free */ private InstructionList makeClosureInstantiation(Member constructor, BcelVar holder) { // LazyMethodGen constructor) { InstructionFactory fact = getFactory(); BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY); // final Type objectArrayType = new ArrayType(Type.OBJECT, 1); final InstructionList il = new InstructionList(); int alen = getArgCount() + (thisVar == null ? 0 : 1) + ((targetVar != null && targetVar != thisVar) ? 1 : 0) + (thisJoinPointVar == null ? 0 : 1); il.append(Utility.createConstant(fact, alen)); il.append(fact.createNewArray(Type.OBJECT, (short) 1)); arrayVar.appendStore(il, fact); int stateIndex = 0; if (thisVar != null) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisVar); thisVar.setPositionInAroundState(stateIndex); stateIndex++; } if (targetVar != null && targetVar != thisVar) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, targetVar); targetVar.setPositionInAroundState(stateIndex); stateIndex++; } for (int i = 0, len = getArgCount(); i < len; i++) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, argVars[i]); argVars[i].setPositionInAroundState(stateIndex); stateIndex++; } if (thisJoinPointVar != null) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisJoinPointVar); thisJoinPointVar.setPositionInAroundState(stateIndex); stateIndex++; } il.append(fact.createNew(new ObjectType(constructor.getDeclaringType().getName()))); il.append(InstructionConstants.DUP); arrayVar.appendLoad(il, fact); il.append(Utility.createInvoke(fact, world, constructor)); if (getKind() == PreInitialization) { il.append(InstructionConstants.DUP); holder.appendStore(il, fact); } return il; } private IntMap makeProceedArgumentMap(BcelVar[] adviceArgs) { // System.err.println("coming in with " + Arrays.asList(adviceArgs)); IntMap ret = new IntMap(); for (int i = 0, len = adviceArgs.length; i < len; i++) { BcelVar v = adviceArgs[i]; if (v == null) continue; // XXX we don't know why this is required int pos = v.getPositionInAroundState(); if (pos >= 0) { // need this test to avoid args bound via cflow ret.put(pos, i); } } // System.err.println("returning " + ret); return ret; } /** * * * @param callbackMethod the method we will call back to when our run method gets called. * * @param proceedMap A map from state position to proceed argument position. May be non covering on state position. */ private LazyMethodGen makeClosureClassAndReturnConstructor(String closureClassName, LazyMethodGen callbackMethod, IntMap proceedMap) { String superClassName = "org.aspectj.runtime.internal.AroundClosure"; Type objectArrayType = new ArrayType(Type.OBJECT, 1); LazyClassGen closureClass = new LazyClassGen(closureClassName, superClassName, getEnclosingClass().getFileName(), Modifier.PUBLIC, new String[] {}, getWorld()); InstructionFactory fact = new InstructionFactory(closureClass.getConstantPool()); // constructor LazyMethodGen constructor = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, "<init>", new Type[] { objectArrayType }, new String[] {}, closureClass); InstructionList cbody = constructor.getBody(); cbody.append(InstructionFactory.createLoad(Type.OBJECT, 0)); cbody.append(InstructionFactory.createLoad(objectArrayType, 1)); cbody.append(fact .createInvoke(superClassName, "<init>", Type.VOID, new Type[] { objectArrayType }, Constants.INVOKESPECIAL)); cbody.append(InstructionFactory.createReturn(Type.VOID)); closureClass.addMethodGen(constructor); // method LazyMethodGen runMethod = new LazyMethodGen(Modifier.PUBLIC, Type.OBJECT, "run", new Type[] { objectArrayType }, new String[] {}, closureClass); InstructionList mbody = runMethod.getBody(); BcelVar proceedVar = new BcelVar(UnresolvedType.OBJECTARRAY.resolve(world), 1); // int proceedVarIndex = 1; BcelVar stateVar = new BcelVar(UnresolvedType.OBJECTARRAY.resolve(world), runMethod.allocateLocal(1)); // int stateVarIndex = runMethod.allocateLocal(1); mbody.append(InstructionFactory.createThis()); mbody.append(fact.createGetField(superClassName, "state", objectArrayType)); mbody.append(stateVar.createStore(fact)); // mbody.append(fact.createStore(objectArrayType, stateVarIndex)); Type[] stateTypes = callbackMethod.getArgumentTypes(); for (int i = 0, len = stateTypes.length; i < len; i++) { Type stateType = stateTypes[i]; ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world); if (proceedMap.hasKey(i)) { mbody.append(proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i), stateTypeX)); } else { mbody.append(stateVar.createConvertableArrayLoad(fact, i, stateTypeX)); } } mbody.append(Utility.createInvoke(fact, callbackMethod)); if (getKind() == PreInitialization) { mbody.append(Utility.createSet(fact, AjcMemberMaker.aroundClosurePreInitializationField())); mbody.append(InstructionConstants.ACONST_NULL); } else { mbody.append(Utility.createConversion(fact, callbackMethod.getReturnType(), Type.OBJECT)); } mbody.append(InstructionFactory.createReturn(Type.OBJECT)); closureClass.addMethodGen(runMethod); // class getEnclosingClass().addGeneratedInner(closureClass); return constructor; } // ---- extraction methods public LazyMethodGen extractMethod(String newMethodName, int visibilityModifier, ShadowMunger munger) { LazyMethodGen.assertGoodBody(range.getBody(), newMethodName); if (!getKind().allowsExtraction()) throw new BCException("Attempt to extract method from a shadow kind that does not support this operation (" + getKind() + ")"); LazyMethodGen freshMethod = createMethodGen(newMethodName, visibilityModifier); // System.err.println("******"); // System.err.println("ABOUT TO EXTRACT METHOD for" + this); // enclosingMethod.print(System.err); // System.err.println("INTO"); // freshMethod.print(System.err); // System.err.println("WITH REMAP"); // System.err.println(makeRemap()); range.extractInstructionsInto(freshMethod, makeRemap(), (getKind() != PreInitialization) && isFallsThrough()); if (getKind() == PreInitialization) { addPreInitializationReturnCode(freshMethod, getSuperConstructorParameterTypes()); } getEnclosingClass().addMethodGen(freshMethod, munger.getSourceLocation()); return freshMethod; } private void addPreInitializationReturnCode(LazyMethodGen extractedMethod, Type[] superConstructorTypes) { InstructionList body = extractedMethod.getBody(); final InstructionFactory fact = getFactory(); BcelVar arrayVar = new BcelVar(world.getCoreType(UnresolvedType.OBJECTARRAY), extractedMethod.allocateLocal(1)); int len = superConstructorTypes.length; body.append(Utility.createConstant(fact, len)); body.append(fact.createNewArray(Type.OBJECT, (short) 1)); arrayVar.appendStore(body, fact); for (int i = len - 1; i >= 0; i++) { // convert thing on top of stack to object body.append(Utility.createConversion(fact, superConstructorTypes[i], Type.OBJECT)); // push object array arrayVar.appendLoad(body, fact); // swap body.append(InstructionConstants.SWAP); // do object array store. body.append(Utility.createConstant(fact, i)); body.append(InstructionConstants.SWAP); body.append(InstructionFactory.createArrayStore(Type.OBJECT)); } arrayVar.appendLoad(body, fact); body.append(InstructionConstants.ARETURN); } private Type[] getSuperConstructorParameterTypes() { // assert getKind() == PreInitialization InstructionHandle superCallHandle = getRange().getEnd().getNext(); InvokeInstruction superCallInstruction = (InvokeInstruction) superCallHandle.getInstruction(); return superCallInstruction.getArgumentTypes(getEnclosingClass().getConstantPool()); } /** * make a map from old frame location to new frame location. Any unkeyed frame location picks out a copied local */ private IntMap makeRemap() { IntMap ret = new IntMap(5); int reti = 0; if (thisVar != null) { ret.put(0, reti++); // thisVar guaranteed to be 0 } if (targetVar != null && targetVar != thisVar) { ret.put(targetVar.getSlot(), reti++); } for (int i = 0, len = argVars.length; i < len; i++) { ret.put(argVars[i].getSlot(), reti); reti += argVars[i].getType().getSize(); } if (thisJoinPointVar != null) { ret.put(thisJoinPointVar.getSlot(), reti++); } // we not only need to put the arguments, we also need to remap their // aliases, which we so helpfully put into temps at the beginning of this join // point. if (!getKind().argsOnStack()) { int oldi = 0; int newi = 0; // if we're passing in a this and we're not argsOnStack we're always // passing in a target too if (arg0HoldsThis()) { ret.put(0, 0); oldi++; newi += 1; } // assert targetVar == thisVar for (int i = 0; i < getArgCount(); i++) { UnresolvedType type = getArgType(i); ret.put(oldi, newi); oldi += type.getSize(); newi += type.getSize(); } } // System.err.println("making remap for : " + this); // if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot()); // if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot()); // System.err.println(ret); return ret; } /** * The new method always static. It may take some extra arguments: this, target. If it's argsOnStack, then it must take both * this/target If it's argsOnFrame, it shares this and target. ??? rewrite this to do less array munging, please */ private LazyMethodGen createMethodGen(String newMethodName, int visibilityModifier) { Type[] parameterTypes = BcelWorld.makeBcelTypes(getArgTypes()); int modifiers = Modifier.FINAL | visibilityModifier; // XXX some bug // if (! isExpressionKind() && getSignature().isStrict(world)) { // modifiers |= Modifier.STRICT; // } modifiers |= Modifier.STATIC; if (targetVar != null && targetVar != thisVar) { UnresolvedType targetType = getTargetType(); targetType = ensureTargetTypeIsCorrect(targetType); // see pr109728,pr229910 - this fixes the case when the declaring class is sometype 'X' but the (gs)etfield // in the bytecode refers to a subtype of 'X'. This makes sure we use the type originally // mentioned in the fieldget instruction as the method parameter and *not* the type upon which the // field is declared because when the instructions are extracted into the new around body, // they will still refer to the subtype. if ((getKind() == FieldGet || getKind() == FieldSet) && getActualTargetType() != null && !getActualTargetType().equals(targetType.getName())) { targetType = UnresolvedType.forName(getActualTargetType()).resolve(world); } ResolvedMember resolvedMember = getSignature().resolve(world); // pr230075, pr197719 if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) && !samePackage(resolvedMember.getDeclaringType().getPackageName(), getEnclosingType().getPackageName()) && !resolvedMember.getName().equals("clone")) { if (!hasThis()) { // pr197719 - static accessor has been created to handle the call if (Modifier.isStatic(enclosingMethod.getAccessFlags()) && enclosingMethod.getName().startsWith("access$")) { targetType = BcelWorld.fromBcel(enclosingMethod.getArgumentTypes()[0]); } } else { if (!targetType.resolve(world).isAssignableFrom(getThisType().resolve(world))) { throw new BCException("bad bytecode"); } targetType = getThisType(); } } parameterTypes = addType(BcelWorld.makeBcelType(targetType), parameterTypes); } if (thisVar != null) { UnresolvedType thisType = getThisType(); parameterTypes = addType(BcelWorld.makeBcelType(thisType), parameterTypes); } // We always want to pass down thisJoinPoint in case we have already woven // some advice in here. If we only have a single piece of around advice on a // join point, it is unnecessary to accept (and pass) tjp. if (thisJoinPointVar != null) { parameterTypes = addTypeToEnd(LazyClassGen.tjpType, parameterTypes); // FIXME ALEX? which one // parameterTypes = addTypeToEnd(LazyClassGen.proceedingTjpType, parameterTypes); } UnresolvedType returnType; if (getKind() == PreInitialization) { returnType = UnresolvedType.OBJECTARRAY; } else { if (getKind() == ConstructorCall) returnType = getSignature().getDeclaringType(); else if (getKind() == FieldSet) returnType = ResolvedType.VOID; else returnType = getSignature().getReturnType().resolve(world); // returnType = getReturnType(); // for this and above lines, see pr137496 } return new LazyMethodGen(modifiers, BcelWorld.makeBcelType(returnType), newMethodName, parameterTypes, new String[0], // XXX again, we need to look up methods! // UnresolvedType.getNames(getSignature().getExceptions(world)), getEnclosingClass()); } private boolean samePackage(String p1, String p2) { if (p1 == null) return p2 == null; if (p2 == null) return false; return p1.equals(p2); } private Type[] addType(Type type, Type[] types) { int len = types.length; Type[] ret = new Type[len + 1]; ret[0] = type; System.arraycopy(types, 0, ret, 1, len); return ret; } private Type[] addTypeToEnd(Type type, Type[] types) { int len = types.length; Type[] ret = new Type[len + 1]; ret[len] = type; System.arraycopy(types, 0, ret, 0, len); return ret; } public BcelVar genTempVar(UnresolvedType typeX) { return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize())); } // public static final boolean CREATE_TEMP_NAMES = true; public BcelVar genTempVar(UnresolvedType typeX, String localName) { BcelVar tv = genTempVar(typeX); // if (CREATE_TEMP_NAMES) { // for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) { // if (Range.isRangeHandle(ih)) continue; // ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot())); // } // } return tv; } // eh doesn't think we need to garbage collect these (64K is a big number...) private int genTempVarIndex(int size) { return enclosingMethod.allocateLocal(size); } public InstructionFactory getFactory() { return getEnclosingClass().getFactory(); } public ISourceLocation getSourceLocation() { int sourceLine = getSourceLine(); if (sourceLine == 0 || sourceLine == -1) { // Thread.currentThread().dumpStack(); // System.err.println(this + ": " + range); return getEnclosingClass().getType().getSourceLocation(); } else { // For staticinitialization, if we have a nice offset, don't build a new source loc if (getKind() == Shadow.StaticInitialization && getEnclosingClass().getType().getSourceLocation().getOffset() != 0) { return getEnclosingClass().getType().getSourceLocation(); } else { int offset = 0; Kind kind = getKind(); if ((kind == MethodExecution) || (kind == ConstructorExecution) || (kind == AdviceExecution) || (kind == StaticInitialization) || (kind == PreInitialization) || (kind == Initialization)) { if (getEnclosingMethod().hasDeclaredLineNumberInfo()) { offset = getEnclosingMethod().getDeclarationOffset(); } } return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine, offset); } } } public Shadow getEnclosingShadow() { return enclosingShadow; } public LazyMethodGen getEnclosingMethod() { return enclosingMethod; } public boolean isFallsThrough() { return !terminatesWithReturn(); } public void setActualTargetType(String className) { this.actualInstructionTargetType = className; } public String getActualTargetType() { return actualInstructionTargetType; } }
245,734
Bug 245734 AJDT throws a RuntimeException from EclipseResolvedMember.getAnnotations
Build ID: N/A Steps To Reproduce: This exception is happening for us in both Eclipse 3.4 and 3.3 when we run an incremental build on one of our projects. We are using an aspect to declare an annotation on a class in the project, and we only started seeing this exception after we added it. A clean build on the project never throws the exception, only an incremental build. More information: The Exception Stack Trace: java.lang.RuntimeException at org.aspectj.ajdt.internal.compiler.lookup.EclipseResolvedMember.getAnnotations(EclipseResolvedMember.java:78) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.doDeclareAnnotations(AjLookupEnvironment.java:794) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:592) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironmen ... at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) Compile error: RuntimeException thrown: not yet implemented - please raise an AJ bug I was going to include the AJDT Event log for the build but it is very long, and mostly unremarkable, so I have included only the section for the project where the exception was thrown. 11:9:50 Build kind = INCREMENTALBUILD 11:9:50 Project=ICODES, kind of build requested=Incremental AspectJ compilation 11:9:50 build: Examined delta - source file changes in required project ICODES 11:9:51 Found state instance managing output location : C:\jnaylor\Java_Dev\workspace\ICDM 11:9:51 Failed to find a state instance managing output location : C:\jnaylor\Java_dev\workspace\Dependencies\MARVEL\resources 11:9:51 Failed to find a state instance managing output location : C:\jnaylor\Java_Dev\workspace\GSG 11:9:52 Failed to find a state instance managing output location : C:\jnaylor\Java_dev\.build\Launch4J 11:9:52 Preparing for build: planning to be an incremental build 11:9:52 Starting incremental compilation loop 1 of possibly 5 11:9:52 AJDE Callback: finish. Was full build: false 11:9:52 Timer event: 2172ms: Total time spent in AJDE 11:9:54 Timer event: 47ms: Create element map (0 rels in project: ICODES) 11:9:54 Types affected during build = 0 11:9:54 Timer event: 0ms: Add markers (0 markers) 11:9:54 Timer event: 3735ms: Total time spent in AJBuilder.build() 11:9:54 =========================================================================================== This is occurring frequently, but not every time so we haven't been able to narrow down a reasonable sized test case.
resolved fixed
f376a21
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-09-22T23:58:59Z"
"2008-08-29T17:13:20Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseResolvedMember.java
/* ******************************************************************* * Copyright (c) 2006 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.lookup; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AnnotationMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.FalseLiteral; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.IntLiteral; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TrueLiteral; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.IntConstant; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Binding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.BCException; import org.aspectj.weaver.MemberKind; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; /** * In the pipeline world, we can be weaving before all types have come through * from compilation. In some cases this means the weaver will want to ask * questions of eclipse types and this subtype of ResolvedMemberImpl is here to * answer some of those questions - it is backed by the real eclipse * MethodBinding object and can translate from Eclipse -> Weaver information. */ public class EclipseResolvedMember extends ResolvedMemberImpl { private static String[] NO_ARGS = new String[] {}; private Binding realBinding; private String[] argumentNames; private World w; private ResolvedType[] cachedAnnotationTypes; private EclipseFactory eclipseFactory; public EclipseResolvedMember(MethodBinding binding, MemberKind memberKind, ResolvedType realDeclaringType, int modifiers, UnresolvedType rettype, String name, UnresolvedType[] paramtypes, UnresolvedType[] extypes, EclipseFactory eclipseFactory) { super(memberKind, realDeclaringType, modifiers, rettype, name, paramtypes, extypes); this.realBinding = binding; this.eclipseFactory = eclipseFactory; this.w = realDeclaringType.getWorld(); } public EclipseResolvedMember(FieldBinding binding, MemberKind field, ResolvedType realDeclaringType, int modifiers, ResolvedType type, String string, UnresolvedType[] none) { super(field, realDeclaringType, modifiers, type, string, none); this.realBinding = binding; this.w = realDeclaringType.getWorld(); } public boolean hasAnnotation(UnresolvedType ofType) { ResolvedType[] annotationTypes = getAnnotationTypes(); if (annotationTypes == null) return false; for (int i = 0; i < annotationTypes.length; i++) { ResolvedType type = annotationTypes[i]; if (type.equals(ofType)) return true; } return false; } public AnnotationAJ[] getAnnotations() { // long abits = realBinding.getAnnotationTagBits(); // ensure resolved Annotation[] annos = getEclipseAnnotations(); if (annos == null) return null; // TODO errr missing in action - we need to implement this! Probably // using something like EclipseAnnotationConvertor - // itself not finished ;) throw new RuntimeException( "not yet implemented - please raise an AJ bug"); // return super.getAnnotations(); } public AnnotationAJ getAnnotationOfType(UnresolvedType ofType) { // long abits = realBinding.getAnnotationTagBits(); // ensure resolved Annotation[] annos = getEclipseAnnotations(); if (annos == null) return null; for (int i = 0; i < annos.length; i++) { Annotation anno = annos[i]; UnresolvedType ut = UnresolvedType.forSignature(new String( anno.resolvedType.signature())); if (w.resolve(ut).equals(ofType)) { // Found the one return EclipseAnnotationConvertor.convertEclipseAnnotation( anno, w, eclipseFactory); } } return null; } public String getAnnotationDefaultValue() { if (realBinding instanceof MethodBinding) { AbstractMethodDeclaration methodDecl = getTypeDeclaration() .declarationOf((MethodBinding) realBinding); if (methodDecl instanceof AnnotationMethodDeclaration) { AnnotationMethodDeclaration annoMethodDecl = (AnnotationMethodDeclaration) methodDecl; Expression e = annoMethodDecl.defaultValue; if (e.resolvedType == null) e.resolve(methodDecl.scope); // TODO does not cope with many cases... if (e instanceof QualifiedNameReference) { QualifiedNameReference qnr = (QualifiedNameReference) e; if (qnr.binding instanceof FieldBinding) { FieldBinding fb = (FieldBinding) qnr.binding; StringBuffer sb = new StringBuffer(); sb.append(fb.declaringClass.signature()); sb.append(fb.name); return sb.toString(); } } else if (e instanceof TrueLiteral) { return "true"; } else if (e instanceof FalseLiteral) { return "false"; } else if (e instanceof StringLiteral) { return new String(((StringLiteral) e).source()); } else if (e instanceof IntLiteral) { return Integer.toString(((IntConstant) e.constant) .intValue()); } else { throw new BCException( "EclipseResolvedMember.getAnnotationDefaultValue() not implemented for value of type '" + e.getClass() + "' - raise an AspectJ bug !"); } } } return null; } public ResolvedType[] getAnnotationTypes() { if (cachedAnnotationTypes == null) { // long abits = realBinding.getAnnotationTagBits(); // ensure resolved Annotation[] annos = getEclipseAnnotations(); if (annos == null) { cachedAnnotationTypes = ResolvedType.EMPTY_RESOLVED_TYPE_ARRAY; } else { cachedAnnotationTypes = new ResolvedType[annos.length]; for (int i = 0; i < annos.length; i++) { Annotation type = annos[i]; cachedAnnotationTypes[i] = w.resolve(UnresolvedType .forSignature(new String(type.resolvedType .signature()))); } } } return cachedAnnotationTypes; } public String[] getParameterNames() { if (argumentNames != null) return argumentNames; if (realBinding instanceof FieldBinding) { argumentNames = NO_ARGS; } else { TypeDeclaration typeDecl = getTypeDeclaration(); AbstractMethodDeclaration methodDecl = (typeDecl == null ? null : typeDecl.declarationOf((MethodBinding) realBinding)); Argument[] args = (methodDecl == null ? null : methodDecl.arguments); // dont // like // this // - // why // isnt // the // method // found // sometimes? is it because other errors are // being reported? if (args == null) { argumentNames = NO_ARGS; } else { argumentNames = new String[args.length]; for (int i = 0; i < argumentNames.length; i++) { argumentNames[i] = new String(methodDecl.arguments[i].name); } } } return argumentNames; } private Annotation[] getEclipseAnnotations() { if (realBinding instanceof MethodBinding) { AbstractMethodDeclaration methodDecl = getTypeDeclaration() .declarationOf((MethodBinding) realBinding); return methodDecl.annotations; } else if (realBinding instanceof FieldBinding) { FieldDeclaration fieldDecl = getTypeDeclaration().declarationOf( (FieldBinding) realBinding); return fieldDecl.annotations; } return null; } private TypeDeclaration getTypeDeclaration() { if (realBinding instanceof MethodBinding) { MethodBinding mb = (MethodBinding) realBinding; if (mb != null) { SourceTypeBinding stb = (SourceTypeBinding) mb.declaringClass; if (stb != null) { ClassScope cScope = stb.scope; if (cScope != null) return cScope.referenceContext; } } } else if (realBinding instanceof FieldBinding) { FieldBinding fb = (FieldBinding) realBinding; if (fb != null) { SourceTypeBinding stb = (SourceTypeBinding) fb.declaringClass; if (stb != null) { ClassScope cScope = stb.scope; if (cScope != null) return cScope.referenceContext; } } } return null; } }
192,877
Bug 192877 [ataspectj] @AspectJ style inter-type declaration causes false compiler error during incremental build
Build ID: M20070212-1330 Steps To Reproduce: Use @DeclareParents to introduce a default interface implementation to an existing type. A full build compiles cleanly and works as expected. An incremental build causes the following type of compile error: "The type FooImpl must implement the inherited abstract method Test.methodA()". In this example FooImpl is the class we are introducing a default implementation of the Test interface which defines the method "methodA". More information: See attached zip for a complete set of files to reproduce. I can repoduce this bug with AJDT 1.4.2.200705221209 for Eclipse 3.2.2 as well as AJDT 1.5RC1 for Eclipse 3.3RC1
resolved fixed
9b68a31
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-09-30T20:51:53Z"
"2007-06-15T15:06:40Z"
tests/multiIncremental/PR192877/base/src/DefaultTestImpl.java
192,877
Bug 192877 [ataspectj] @AspectJ style inter-type declaration causes false compiler error during incremental build
Build ID: M20070212-1330 Steps To Reproduce: Use @DeclareParents to introduce a default interface implementation to an existing type. A full build compiles cleanly and works as expected. An incremental build causes the following type of compile error: "The type FooImpl must implement the inherited abstract method Test.methodA()". In this example FooImpl is the class we are introducing a default implementation of the Test interface which defines the method "methodA". More information: See attached zip for a complete set of files to reproduce. I can repoduce this bug with AJDT 1.4.2.200705221209 for Eclipse 3.2.2 as well as AJDT 1.5RC1 for Eclipse 3.3RC1
resolved fixed
9b68a31
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-09-30T20:51:53Z"
"2007-06-15T15:06:40Z"
tests/multiIncremental/PR192877/base/src/Foo.java
192,877
Bug 192877 [ataspectj] @AspectJ style inter-type declaration causes false compiler error during incremental build
Build ID: M20070212-1330 Steps To Reproduce: Use @DeclareParents to introduce a default interface implementation to an existing type. A full build compiles cleanly and works as expected. An incremental build causes the following type of compile error: "The type FooImpl must implement the inherited abstract method Test.methodA()". In this example FooImpl is the class we are introducing a default implementation of the Test interface which defines the method "methodA". More information: See attached zip for a complete set of files to reproduce. I can repoduce this bug with AJDT 1.4.2.200705221209 for Eclipse 3.2.2 as well as AJDT 1.5RC1 for Eclipse 3.3RC1
resolved fixed
9b68a31
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-09-30T20:51:53Z"
"2007-06-15T15:06:40Z"
tests/multiIncremental/PR192877/base/src/FooImpl.java
192,877
Bug 192877 [ataspectj] @AspectJ style inter-type declaration causes false compiler error during incremental build
Build ID: M20070212-1330 Steps To Reproduce: Use @DeclareParents to introduce a default interface implementation to an existing type. A full build compiles cleanly and works as expected. An incremental build causes the following type of compile error: "The type FooImpl must implement the inherited abstract method Test.methodA()". In this example FooImpl is the class we are introducing a default implementation of the Test interface which defines the method "methodA". More information: See attached zip for a complete set of files to reproduce. I can repoduce this bug with AJDT 1.4.2.200705221209 for Eclipse 3.2.2 as well as AJDT 1.5RC1 for Eclipse 3.3RC1
resolved fixed
9b68a31
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-09-30T20:51:53Z"
"2007-06-15T15:06:40Z"
tests/multiIncremental/PR192877/base/src/Test.java
192,877
Bug 192877 [ataspectj] @AspectJ style inter-type declaration causes false compiler error during incremental build
Build ID: M20070212-1330 Steps To Reproduce: Use @DeclareParents to introduce a default interface implementation to an existing type. A full build compiles cleanly and works as expected. An incremental build causes the following type of compile error: "The type FooImpl must implement the inherited abstract method Test.methodA()". In this example FooImpl is the class we are introducing a default implementation of the Test interface which defines the method "methodA". More information: See attached zip for a complete set of files to reproduce. I can repoduce this bug with AJDT 1.4.2.200705221209 for Eclipse 3.2.2 as well as AJDT 1.5RC1 for Eclipse 3.3RC1
resolved fixed
9b68a31
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-09-30T20:51:53Z"
"2007-06-15T15:06:40Z"
tests/multiIncremental/PR192877/base/src/TestAspect.java
192,877
Bug 192877 [ataspectj] @AspectJ style inter-type declaration causes false compiler error during incremental build
Build ID: M20070212-1330 Steps To Reproduce: Use @DeclareParents to introduce a default interface implementation to an existing type. A full build compiles cleanly and works as expected. An incremental build causes the following type of compile error: "The type FooImpl must implement the inherited abstract method Test.methodA()". In this example FooImpl is the class we are introducing a default implementation of the Test interface which defines the method "methodA". More information: See attached zip for a complete set of files to reproduce. I can repoduce this bug with AJDT 1.4.2.200705221209 for Eclipse 3.2.2 as well as AJDT 1.5RC1 for Eclipse 3.3RC1
resolved fixed
9b68a31
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-09-30T20:51:53Z"
"2007-06-15T15:06:40Z"
tests/multiIncremental/PR192877/inc1/src/Test.java
192,877
Bug 192877 [ataspectj] @AspectJ style inter-type declaration causes false compiler error during incremental build
Build ID: M20070212-1330 Steps To Reproduce: Use @DeclareParents to introduce a default interface implementation to an existing type. A full build compiles cleanly and works as expected. An incremental build causes the following type of compile error: "The type FooImpl must implement the inherited abstract method Test.methodA()". In this example FooImpl is the class we are introducing a default implementation of the Test interface which defines the method "methodA". More information: See attached zip for a complete set of files to reproduce. I can repoduce this bug with AJDT 1.4.2.200705221209 for Eclipse 3.2.2 as well as AJDT 1.5RC1 for Eclipse 3.3RC1
resolved fixed
9b68a31
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-09-30T20:51:53Z"
"2007-06-15T15:06:40Z"
tests/src/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java
/******************************************************************** * Copyright (c) 2005 Contributors. All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement initial implementation * Helen Hawkins Converted to new interface (bug 148190) *******************************************************************/ package org.aspectj.systemtest.incremental.tools; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.ajde.core.ICompilerConfiguration; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.core.builder.AjState; import org.aspectj.ajdt.internal.core.builder.IncrementalStateManager; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IElementHandleProvider; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.IRelationship; import org.aspectj.asm.IRelationshipMap; import org.aspectj.asm.internal.JDTLikeHandleProvider; import org.aspectj.asm.internal.Relationship; import org.aspectj.bridge.IMessage; import org.aspectj.tools.ajc.Ajc; import org.aspectj.util.FileUtil; /** * The superclass knows all about talking through Ajde to the compiler. The superclass isn't in charge of knowing how to simulate * overlays for incremental builds, that is in here. As is the ability to generate valid build configs based on a directory * structure. To support this we just need access to a sandbox directory - this sandbox is managed by the superclass (it only * assumes all builds occur in <sandboxDir>/<projectName>/ ) * * The idea is you can initialize multiple projects in the sandbox and they can all be built independently, hopefully exploiting * incremental compilation. Between builds you can alter the contents of a project using the alter() method that overlays some set * of new files onto the current set (adding new files/changing existing ones) - you can then drive a new build and check it behaves * as expected. */ public class MultiProjectIncrementalTests extends AbstractMultiProjectIncrementalAjdeInteractionTestbed { /* * A.aj package pack; public aspect A { pointcut p() : call( C.method before() : p() { // line 7 } } * * C.java package pack; public class C { public void method1() { method2(); // line 6 } public void method2() { } public void * method3() { method2(); // line 13 } * * } */ public void testDontLoseAdviceMarkers_pr134471() { try { // see pr148027 AsmHierarchyBuilder.shouldAddUsesPointcut=false; initialiseProject("P4"); build("P4"); Ajc.dumpAJDEStructureModel("after full build where advice is applying"); // should be 4 relationship entries // In inc1 the first advised line is 'commented out' alter("P4", "inc1"); build("P4"); checkWasntFullBuild(); Ajc.dumpAJDEStructureModel("after inc build where first advised line is gone"); // should now be 2 relationship entries // This will be the line 6 entry in C.java IProgramElement codeElement = findCode(checkForNode("pack", "C", true)); // This will be the line 7 entry in A.java IProgramElement advice = findAdvice(checkForNode("pack", "A", true)); IRelationshipMap asmRelMap = AsmManager.getDefault().getRelationshipMap(); assertEquals("There should be two relationships in the relationship map", 2, asmRelMap.getEntries().size()); for (Iterator iter = asmRelMap.getEntries().iterator(); iter.hasNext();) { String sourceOfRelationship = (String) iter.next(); IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForHandle(sourceOfRelationship); assertNotNull("expected to find IProgramElement with handle " + sourceOfRelationship + " but didn't", ipe); if (ipe.getKind().equals(IProgramElement.Kind.ADVICE)) { assertEquals("expected source of relationship to be " + advice.toString() + " but found " + ipe.toString(), advice, ipe); } else if (ipe.getKind().equals(IProgramElement.Kind.CODE)) { assertEquals( "expected source of relationship to be " + codeElement.toString() + " but found " + ipe.toString(), codeElement, ipe); } else { fail("found unexpected relationship source " + ipe + " with kind " + ipe.getKind() + " when looking up handle: " + sourceOfRelationship); } List relationships = asmRelMap.get(ipe); assertNotNull("expected " + ipe.getName() + " to have some " + "relationships", relationships); for (Iterator iterator = relationships.iterator(); iterator.hasNext();) { Relationship rel = (Relationship) iterator.next(); List targets = rel.getTargets(); for (Iterator iterator2 = targets.iterator(); iterator2.hasNext();) { String t = (String) iterator2.next(); IProgramElement link = AsmManager.getDefault().getHierarchy().findElementForHandle(t); if (ipe.getKind().equals(IProgramElement.Kind.ADVICE)) { assertEquals("expected target of relationship to be " + codeElement.toString() + " but found " + link.toString(), codeElement, link); } else if (ipe.getKind().equals(IProgramElement.Kind.CODE)) { assertEquals("expected target of relationship to be " + advice.toString() + " but found " + link.toString(), advice, link); } else { fail("found unexpected relationship source " + ipe.getName() + " with kind " + ipe.getKind()); } } } } } finally { // see pr148027 AsmHierarchyBuilder.shouldAddUsesPointcut=true; // configureBuildStructureModel(false); } } public void testIncrementalAndAnnotations() { initialiseProject("Annos"); build("Annos"); checkWasFullBuild(); checkCompileWeaveCount("Annos", 4, 4); assertEquals("Should be 3 relationships ", 3, AsmManager.getDefault().getRelationshipMap().getEntries().size()); alter("Annos", "inc1"); // Comment out the annotation on Parent build("Annos"); checkWasntFullBuild(); assertEquals("Should be no relationships ", 0, AsmManager.getDefault().getRelationshipMap().getEntries().size()); checkCompileWeaveCount("Annos", 3, 3); alter("Annos", "inc2"); // Add the annotation back onto Parent build("Annos"); checkWasntFullBuild(); assertEquals("Should be 3 relationships ", 3, AsmManager.getDefault().getRelationshipMap().getEntries().size()); checkCompileWeaveCount("Annos", 3, 3); } public void testBrokenHandles_pr247742() { String p = "BrokenHandles"; initialiseProject(p); // alter(p, "inc1"); build(p); // alter(p, "inc2"); // build(p); dumptree(AsmManager.getDefault().getHierarchy().getRoot(), 0); IProgramElement root = AsmManager.getDefault().getHierarchy().getRoot(); IProgramElement ipe = findElementAtLine(root, 4); assertEquals("=BrokenHandles<p{GetInfo.java}GetInfo`declare warning", ipe.getHandleIdentifier()); ipe = findElementAtLine(root, 5); assertEquals("=BrokenHandles<p{GetInfo.java}GetInfo`declare warning!2", ipe.getHandleIdentifier()); ipe = findElementAtLine(root, 6); assertEquals("=BrokenHandles<p{GetInfo.java}GetInfo`declare parents!3", ipe.getHandleIdentifier()); } public void testSpacewarHandles() { // String p = "SpaceWar"; String p = "Simpler"; initialiseProject(p); build(p); dumptree(AsmManager.getDefault().getHierarchy().getRoot(), 0); // incomplete } public void testAdviceHandlesAreJDTCompatible() { String p = "AdviceHandles"; initialiseProject(p); addSourceFolderForSourceFile(p, getProjectRelativePath(p, "src/Handles.aj"), "src"); build(p); IProgramElement root = AsmManager.getDefault().getHierarchy().getRoot(); IProgramElement typeDecl = findElementAtLine(root, 4); assertEquals("=AdviceHandles/src<spacewar*Handles.aj}Handles", typeDecl.getHandleIdentifier()); IProgramElement advice1 = findElementAtLine(root, 7); assertEquals("=AdviceHandles/src<spacewar*Handles.aj}Handles&before", advice1.getHandleIdentifier()); IProgramElement advice2 = findElementAtLine(root, 11); assertEquals("=AdviceHandles/src<spacewar*Handles.aj}Handles&before!2", advice2.getHandleIdentifier()); IProgramElement advice3 = findElementAtLine(root, 15); assertEquals("=AdviceHandles/src<spacewar*Handles.aj}Handles&before&I", advice3.getHandleIdentifier()); IProgramElement advice4 = findElementAtLine(root, 20); assertEquals("=AdviceHandles/src<spacewar*Handles.aj}Handles&before&I!2", advice4.getHandleIdentifier()); IProgramElement advice5 = findElementAtLine(root, 25); assertEquals("=AdviceHandles/src<spacewar*Handles.aj}Handles&after", advice5.getHandleIdentifier()); IProgramElement advice6 = findElementAtLine(root, 30); assertEquals("=AdviceHandles/src<spacewar*Handles.aj}Handles&afterReturning", advice6.getHandleIdentifier()); IProgramElement advice7 = findElementAtLine(root, 35); assertEquals("=AdviceHandles/src<spacewar*Handles.aj}Handles&afterThrowing", advice7.getHandleIdentifier()); IProgramElement advice8 = findElementAtLine(root, 40); assertEquals("=AdviceHandles/src<spacewar*Handles.aj}Handles&afterThrowing&I", advice8.getHandleIdentifier()); IProgramElement namedInnerClass = findElementAtLine(root, 46); assertEquals("=AdviceHandles/src<spacewar*Handles.aj}Handles~x[NamedClass", namedInnerClass.getHandleIdentifier()); assertEquals("=AdviceHandles/src<spacewar*Handles.aj}Handles~foo[", findElementAtLine(root, 55).getHandleIdentifier()); assertEquals("=AdviceHandles/src<spacewar*Handles.aj}Handles~foo[!2", findElementAtLine(root, 56).getHandleIdentifier()); // From 247742: comment 3: two anon class declarations assertEquals("=AdviceHandles/src<spacewar*Handles.aj}Handles~b~QString;[", findElementAtLine(root, 62) .getHandleIdentifier()); assertEquals("=AdviceHandles/src<spacewar*Handles.aj}Handles~b~QString;[!2", findElementAtLine(root, 63) .getHandleIdentifier()); // From 247742: comment 6: two diff anon class declarations assertEquals("=AdviceHandles/src<spacewar*Handles.aj}Handles~c~QString;[", findElementAtLine(root, 66) .getHandleIdentifier()); assertEquals("=AdviceHandles/src<spacewar*Handles.aj}Handles~c~QString;[!2", findElementAtLine(root, 67) .getHandleIdentifier()); // // From 247742: comment 4 // assertEquals("=AdviceHandles/src<spacewar*Handles.aj}Foo&afterReturning&QString;", findElementAtLine(root, // 72).getHandleIdentifier()); // assertEquals("=AdviceHandles/src<spacewar*Handles.aj}Foo&afterReturning&QString;!2", findElementAtLine(root, // 73).getHandleIdentifier()); } // Testing code handles - should they included positional information? seems to be what AJDT wants but we // only have the declaration start position in the programelement // public void testHandlesForCodeElements() { // String p = "CodeHandles"; // initialiseProject(p); // addSourceFolderForSourceFile(p, getProjectRelativePath(p, "src/Handles.aj"), "src"); // build(p); // IProgramElement root = AsmManager.getDefault().getHierarchy().getRoot(); // IProgramElement typeDecl = findElementAtLine(root, 3); // assertEquals("=CodeHandles/src<spacewar*Handles.aj[C", typeDecl.getHandleIdentifier()); // // IProgramElement code = findElementAtLine(root, 6); // assertEquals("=CodeHandles/src<spacewar*Handles.aj[C~m?method-call(void spacewar.C.foo(int))", code.getHandleIdentifier()); // code = findElementAtLine(root, 7); // assertEquals("=CodeHandles/src<spacewar*Handles.aj[C~m?method-call(void spacewar.C.foo(int))!2", code.getHandleIdentifier()); // // } private IProgramElement findElementAtLine(IProgramElement whereToLook, int line) { if (whereToLook == null) { return null; } if (whereToLook.getSourceLocation() != null && whereToLook.getSourceLocation().getLine() == line) { return whereToLook; } List kids = whereToLook.getChildren(); for (Iterator iterator = kids.iterator(); iterator.hasNext();) { IProgramElement object = (IProgramElement) iterator.next(); if (object.getSourceLocation() != null && object.getSourceLocation().getLine() == line) { return object; } IProgramElement gotSomething = findElementAtLine(object, line); if (gotSomething != null) { return gotSomething; } } return null; } public void testModelWithMultipleSourceFolders() { initialiseProject("MultiSource"); // File sourceFolderOne = getProjectRelativePath("MultiSource", "src1"); // File sourceFolderTwo = getProjectRelativePath("MultiSource", "src2"); // File sourceFolderThree = getProjectRelativePath("MultiSource", // "src3"); addSourceFolderForSourceFile("MultiSource", getProjectRelativePath("MultiSource", "src1/CodeOne.java"), "src1"); addSourceFolderForSourceFile("MultiSource", getProjectRelativePath("MultiSource", "src2/CodeTwo.java"), "src2"); addSourceFolderForSourceFile("MultiSource", getProjectRelativePath("MultiSource", "src3/pkg/CodeThree.java"), "src3"); build("MultiSource"); IProgramElement srcOne = AsmManager.getDefault().getHierarchy().findElementForHandle("=MultiSource/src1"); IProgramElement CodeOneClass = AsmManager.getDefault().getHierarchy().findElementForHandle( "=MultiSource/src1{CodeOne.java[CodeOne"); IProgramElement srcTwoPackage = AsmManager.getDefault().getHierarchy().findElementForHandle("=MultiSource/src2<pkg"); IProgramElement srcThreePackage = AsmManager.getDefault().getHierarchy().findElementForHandle("=MultiSource/src3<pkg"); assertNotNull(srcOne); assertNotNull(CodeOneClass); assertNotNull(srcTwoPackage); assertNotNull(srcThreePackage); if (srcTwoPackage.equals(srcThreePackage)) { throw new RuntimeException( "Should not have found these package nodes to be the same, they are in different source folders"); } // dumptree(AsmManager.getDefault().getHierarchy().getRoot(), 0); } public static void dumptree(IProgramElement node, int indent) { for (int i = 0; i < indent; i++) System.out.print(" "); String loc = ""; if (node != null) { if (node.getSourceLocation() != null) loc = node.getSourceLocation().toString(); } System.out.println(node + " [" + (node == null ? "null" : node.getKind().toString()) + "] " + loc); if (node != null) { for (int i = 0; i < indent; i++) System.out.print(" "); System.out.println(" hid is " + node.getHandleIdentifier()); for (Iterator i = node.getChildren().iterator(); i.hasNext();) { dumptree((IProgramElement) i.next(), indent + 2); } } } public void testIncrementalItdsWithMultipleAspects_pr173729() { initialiseProject("PR173729"); build("PR173729"); checkWasFullBuild(); alter("PR173729", "inc1"); build("PR173729"); checkWasntFullBuild(); } // Compile a single simple project public void testTheBasics() { initialiseProject("P1"); build("P1"); // This first build will be batch build("P1"); checkWasntFullBuild(); checkCompileWeaveCount("P1", 0, 0); } // source code doesnt matter, we are checking invalid path handling public void testInvalidAspectpath_pr121395() { initialiseProject("P1"); File f = new File("foo.jar"); Set s = new HashSet(); s.add(f); configureAspectPath("P1", s); build("P1"); // This first build will be batch checkForError("P1", "invalid aspectpath entry"); } // incorrect use of '?' when it should be '*' public void testAspectPath_pr242797_c46() { String bug = "pr242797_1"; String bug2 = "pr242797_2"; initialiseProject(bug); initialiseProject(bug2); configureAspectPath(bug2, getProjectRelativePath(bug, "bin")); build(bug); build(bug2); } public void testAspectPath_pr247742_c16() throws IOException { String bug = "AspectPathOne"; String bug2 = "AspectPathTwo"; addSourceFolderForSourceFile(bug2, getProjectRelativePath(bug2, "src/C.java"), "src"); initialiseProject(bug); initialiseProject(bug2); configureAspectPath(bug2, getProjectRelativePath(bug, "bin")); build(bug); build(bug2); // dumptree(AsmManager.getDefault().getHierarchy().getRoot(), 0); // PrintWriter pw = new PrintWriter(System.out); // AsmManager.getDefault().dumprels(pw); // pw.flush(); IProgramElement root = AsmManager.getDefault().getHierarchy().getRoot(); assertEquals("=AspectPathTwo/binaries<pkg(Asp.class}Asp&before", findElementAtLine(root, 5).getHandleIdentifier()); assertEquals("=AspectPathTwo/binaries<(Asp2.class}Asp2&before", findElementAtLine(root, 16).getHandleIdentifier()); } // public void testAspectPath_pr242797_c41() { // String bug = "pr242797_3"; // String bug2 = "pr242797_4"; // initialiseProject(bug); // initialiseProject(bug2); // configureAspectPath(bug2, getProjectRelativePath(bug, "bin")); // build(bug); // build(bug2); // } /** * Build a project containing a resource - then mark the resource readOnly(), then do an inc-compile, it will report an error * about write access to the resource in the output folder being denied */ /* * public void testProblemCopyingResources_pr138171() { initialiseProject("PR138171"); * * File f=getProjectRelativePath("PR138171","res.txt"); Map m = new HashMap(); m.put("res.txt",f); * AjdeInteractionTestbed.MyProjectPropertiesAdapter .getInstance().setSourcePathResources(m); build("PR138171"); File f2 = * getProjectOutputRelativePath("PR138171","res.txt"); boolean successful = f2.setReadOnly(); * * alter("PR138171","inc1"); AjdeInteractionTestbed.MyProjectPropertiesAdapter .getInstance().setSourcePathResources(m); * build("PR138171"); List msgs = MyTaskListManager.getErrorMessages(); assertTrue("there should be one message but there are " * +(msgs==null?0:msgs.size())+":\n"+msgs,msgs!=null && msgs.size()==1); IMessage msg = (IMessage)msgs.get(0); String exp = * "unable to copy resource to output folder: 'res.txt'"; assertTrue("Expected message to include this text [" * +exp+"] but it does not: "+msg,msg.toString().indexOf(exp)!=-1); } */ // Make simple changes to a project, adding a class public void testSimpleChanges() { AjdeInteractionTestbed.VERBOSE = true; initialiseProject("P1"); build("P1"); // This first build will be batch alter("P1", "inc1"); // adds a single class build("P1"); checkCompileWeaveCount("P1", 1, -1); build("P1"); checkCompileWeaveCount("P1", 0, -1); } // Make simple changes to a project, adding a class and an aspect public void testAddingAnAspect() { initialiseProject("P1"); build("P1"); // build 1, weave 1 alter("P1", "inc1"); // adds a class alter("P1", "inc2"); // adds an aspect build("P1"); // build 1, long timeTakenForFullBuildAndWeave = getTimeTakenForBuild("P1"); checkWasFullBuild(); // it *will* be a full build under the new // "back-to-the-source strategy checkCompileWeaveCount("P1", 5, 3); // we compile X and A (the delta) // find out that // an aspect has changed, go back to the source // and compile X,A,C, then weave them all. build("P1"); long timeTakenForSimpleIncBuild = getTimeTakenForBuild("P1"); // I don't think this test will have timing issues as the times should // be *RADICALLY* different // On my config, first build time is 2093ms and the second is 30ms assertTrue("Should not take longer for the trivial incremental build! first=" + timeTakenForFullBuildAndWeave + "ms second=" + timeTakenForSimpleIncBuild + "ms", timeTakenForSimpleIncBuild < timeTakenForFullBuildAndWeave); } public void testBuildingTwoProjectsInTurns() { initialiseProject("P1"); initialiseProject("P2"); build("P1"); build("P2"); build("P1"); checkWasntFullBuild(); build("P2"); checkWasntFullBuild(); } public void testBuildingBrokenCode_pr240360() { AjdeInteractionTestbed.VERBOSE = true; initialiseProject("pr240360"); // configureNonStandardCompileOptions("pr240360","-proceedOnError"); build("pr240360"); checkWasFullBuild(); checkCompileWeaveCount("pr240360", 5, 4); assertTrue("There should be an error:\n" + getErrorMessages("pr240360"), !getErrorMessages("pr240360").isEmpty()); Set s = AsmManager.getDefault().getRelationshipMap().getEntries(); int relmapLength = s.size(); // Delete the erroneous type String f = getWorkingDir().getAbsolutePath() + File.separatorChar + "pr240360" + File.separatorChar + "src" + File.separatorChar + "test" + File.separatorChar + "Error.java"; (new File(f)).delete(); build("pr240360"); checkWasntFullBuild(); checkCompileWeaveCount("pr240360", 0, 0); assertEquals(relmapLength, AsmManager.getDefault().getRelationshipMap().getEntries().size()); // Readd the erroneous type alter("pr240360", "inc1"); build("pr240360"); checkWasntFullBuild(); checkCompileWeaveCount("pr240360", 1, 0); assertEquals(relmapLength, AsmManager.getDefault().getRelationshipMap().getEntries().size()); // Change the advice alter("pr240360", "inc2"); build("pr240360"); checkWasFullBuild(); checkCompileWeaveCount("pr240360", 6, 4); assertEquals(relmapLength, AsmManager.getDefault().getRelationshipMap().getEntries().size()); } public void testBrokenCodeCompilation() { initialiseProject("pr102733_1"); // configureNonStandardCompileOptions("pr102733_1","-proceedOnError"); build("pr102733_1"); checkWasFullBuild(); checkCompileWeaveCount("pr102733_1", 1, 0); assertTrue("There should be an error:\n" + getErrorMessages("pr102733_1"), !getErrorMessages("pr102733_1").isEmpty()); build("pr102733_1"); // incremental checkCompileWeaveCount("pr102733_1", 0, 0); checkWasntFullBuild(); alter("pr102733_1", "inc1"); // fix the error build("pr102733_1"); checkWasntFullBuild(); checkCompileWeaveCount("pr102733_1", 1, 1); assertTrue("There should be no errors:\n" + getErrorMessages("pr102733_1"), getErrorMessages("pr102733_1").isEmpty()); alter("pr102733_1", "inc2"); // break it again build("pr102733_1"); checkWasntFullBuild(); checkCompileWeaveCount("pr102733_1", 1, 0); assertTrue("There should be an error:\n" + getErrorMessages("pr102733_1"), !getErrorMessages("pr102733_1").isEmpty()); } // public void testDeclareAtType_pr149293() { // configureBuildStructureModel(true); // initialiseProject("PR149293_1"); // build("PR149293_1"); // checkCompileWeaveCount(4,5); // assertNoErrors(); // alter("PR149293_1","inc1"); // build("PR149293_1"); // assertNoErrors(); // } /* * public void testRefactoring_pr148285() { configureBuildStructureModel(true); initialiseProject("PR148285"); * build("PR148285"); System.err.println("xxx"); alter("PR148285","inc1"); build("PR148285"); } */ /** * In order for this next test to run, I had to move the weaver/world pair we keep in the AjBuildManager instance down into the * state object - this makes perfect sense - otherwise when reusing the state for another project we'd not be switching to the * right weaver/world for that project. */ public void testBuildingTwoProjectsMakingSmallChanges() { initialiseProject("P1"); initialiseProject("P2"); build("P1"); build("P2"); build("P1"); checkWasntFullBuild(); build("P2"); checkWasntFullBuild(); alter("P1", "inc1"); // adds a class alter("P1", "inc2"); // adds an aspect build("P1"); checkWasFullBuild(); // adding an aspect makes us go back to the source } public void testPr134371() { initialiseProject("PR134371"); build("PR134371"); alter("PR134371", "inc1"); build("PR134371"); assertTrue("There should be no exceptions handled:\n" + getErrorMessages("PR134371"), getErrorMessages("PR134371") .isEmpty()); } /** * Setup up two simple projects and build them in turn - check the structure model is right after each build */ public void testBuildingTwoProjectsAndVerifyingModel() { initialiseProject("P1"); initialiseProject("P2"); build("P1"); checkForNode("pkg", "C", true); build("P2"); checkForNode("pkg", "C", false); build("P1"); checkForNode("pkg", "C", true); build("P2"); checkForNode("pkg", "C", false); } // Setup up two simple projects and build them in turn - check the // structure model is right after each build public void testBuildingTwoProjectsAndVerifyingStuff() { initialiseProject("P1"); initialiseProject("P2"); build("P1"); checkForNode("pkg", "C", true); build("P2"); checkForNode("pkg", "C", false); build("P1"); checkForNode("pkg", "C", true); build("P2"); checkForNode("pkg", "C", false); } /** * Complex. Here we are testing that a state object records structural changes since the last full build correctly. We build a * simple project from scratch - this will be a full build and so the structural changes since last build count should be 0. We * then alter a class, adding a new method and check structural changes is 1. */ public void testStateManagement1() { File binDirectoryForP1 = new File(getFile("P1", "bin")); initialiseProject("P1"); build("P1"); // full build AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1); assertTrue("There should be a state object for project P1", ajs != null); assertTrue("Should be no structural changes as it was a full build but found: " + ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild() == 0); alter("P1", "inc3"); // adds a method to the class C.java build("P1"); checkWasntFullBuild(); ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1", "bin"))); assertTrue("There should be state for project P1", ajs != null); checkWasntFullBuild(); assertTrue("Should be one structural changes as it was a full build but found: " + ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild() == 1); } /** * Complex. Here we are testing that a state object records structural changes since the last full build correctly. We build a * simple project from scratch - this will be a full build and so the structural changes since last build count should be 0. We * then alter a class, changing body of a method, not the structure and check struc changes is still 0. */ public void testStateManagement2() { File binDirectoryForP1 = new File(getFile("P1", "bin")); initialiseProject("P1"); alter("P1", "inc3"); // need this change in here so 'inc4' can be // applied without making // it a structural change build("P1"); // full build AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1); assertTrue("There should be state for project P1", ajs != null); assertTrue("Should be no struc changes as its a full build: " + ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs .getNumberOfStructuralChangesSinceLastFullBuild() == 0); alter("P1", "inc4"); // changes body of main() method but does *not* // change the structure of C.java build("P1"); checkWasntFullBuild(); ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1", "bin"))); assertTrue("There should be state for project P1", ajs != null); checkWasntFullBuild(); assertTrue("Shouldn't be any structural changes but there were " + ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild() == 0); } /** * The C.java file modified in this test has an inner class - this means the inner class has a this$0 field and <init>(C) ctor * to watch out for when checking for structural changes * */ public void testStateManagement3() { File binDirForInterproject1 = new File(getFile("interprojectdeps1", "bin")); initialiseProject("interprojectdeps1"); build("interprojectdeps1"); // full build AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject1); assertTrue("There should be state for project P1", ajs != null); assertTrue("Should be no struc changes as its a full build: " + ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs .getNumberOfStructuralChangesSinceLastFullBuild() == 0); alter("interprojectdeps1", "inc1"); // adds a space to C.java build("interprojectdeps1"); checkWasntFullBuild(); ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps1", "bin"))); assertTrue("There should be state for project interprojectdeps1", ajs != null); checkWasntFullBuild(); assertTrue("Shouldn't be any structural changes but there were " + ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild() == 0); } /** * The C.java file modified in this test has an inner class - which has two ctors - this checks how they are mangled with an * instance of C. * */ public void testStateManagement4() { File binDirForInterproject2 = new File(getFile("interprojectdeps2", "bin")); initialiseProject("interprojectdeps2"); build("interprojectdeps2"); // full build AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject2); assertTrue("There should be state for project interprojectdeps2", ajs != null); assertTrue("Should be no struc changes as its a full build: " + ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs .getNumberOfStructuralChangesSinceLastFullBuild() == 0); alter("interprojectdeps2", "inc1"); // minor change to C.java build("interprojectdeps2"); checkWasntFullBuild(); ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps2", "bin"))); assertTrue("There should be state for project interprojectdeps1", ajs != null); checkWasntFullBuild(); assertTrue("Shouldn't be any structural changes but there were " + ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild() == 0); } /** * The C.java file modified in this test has an inner class - it has two ctors but also a reference to C.this in it - which will * give rise to an accessor being created in C * */ public void testStateManagement5() { File binDirForInterproject3 = new File(getFile("interprojectdeps3", "bin")); initialiseProject("interprojectdeps3"); build("interprojectdeps3"); // full build AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject3); assertTrue("There should be state for project interprojectdeps3", ajs != null); assertTrue("Should be no struc changes as its a full build: " + ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs .getNumberOfStructuralChangesSinceLastFullBuild() == 0); alter("interprojectdeps3", "inc1"); // minor change to C.java build("interprojectdeps3"); checkWasntFullBuild(); ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps3", "bin"))); assertTrue("There should be state for project interprojectdeps1", ajs != null); checkWasntFullBuild(); assertTrue("Shouldn't be any structural changes but there were " + ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild() == 0); } /** * Now the most complex test. Create a dependancy between two projects. Building one may affect whether the other does an * incremental or full build. The structural information recorded in the state object should be getting used to control whether * a full build is necessary... */ public void testBuildingDependantProjects() { initialiseProject("P1"); initialiseProject("P2"); configureNewProjectDependency("P2", "P1"); build("P1"); build("P2"); // now everything is consistent and compiled alter("P1", "inc1"); // adds a second class build("P1"); build("P2"); // although a second class was added - P2 can't be using // it, so we don't full build here :) checkWasntFullBuild(); alter("P1", "inc3"); // structurally changes one of the classes build("P1"); build("P2"); // build notices the structural change, but is incremental // of I and J as they depend on C checkWasntFullBuild(); alter("P1", "inc4"); build("P1"); build("P2"); // build sees a change but works out its not structural checkWasntFullBuild(); } public void testPr85132() { initialiseProject("PR85132"); build("PR85132"); alter("PR85132", "inc1"); build("PR85132"); } // parameterization of generic aspects public void testPr125405() { initialiseProject("PR125405"); build("PR125405"); checkCompileWeaveCount("PR125405", 1, 1); alter("PR125405", "inc1"); build("PR125405"); // "only abstract aspects can have type parameters" checkForError("PR125405", "only abstract aspects can have type parameters"); alter("PR125405", "inc2"); build("PR125405"); checkCompileWeaveCount("PR125405", 1, 1); assertTrue("Should be no errors, but got " + getErrorMessages("PR125405"), getErrorMessages("PR125405").size() == 0); } public void testPr128618() { initialiseProject("PR128618_1"); initialiseProject("PR128618_2"); configureNewProjectDependency("PR128618_2", "PR128618_1"); assertTrue("there should be no warning messages before we start", getWarningMessages("PR128618_1").isEmpty()); assertTrue("there should be no warning messages before we start", getWarningMessages("PR128618_2").isEmpty()); build("PR128618_1"); build("PR128618_2"); List l = getWarningMessages("PR128618_2"); // there should be one warning against "PR128618_2" List warnings = getWarningMessages("PR128618_2"); assertTrue("Should be one warning, but there are #" + warnings.size(), warnings.size() == 1); IMessage msg = (IMessage) (getWarningMessages("PR128618_2").get(0)); assertEquals("warning should be against the FFDC.aj resource", "FFDC.aj", msg.getSourceLocation().getSourceFile().getName()); alter("PR128618_2", "inc1"); build("PR128618_2"); checkWasntFullBuild(); IMessage msg2 = (IMessage) (getWarningMessages("PR128618_2").get(0)); assertEquals("warning should be against the FFDC.aj resource", "FFDC.aj", msg2.getSourceLocation().getSourceFile() .getName()); assertFalse("a new warning message should have been generated", msg.equals(msg2)); } public void testPr92837() { initialiseProject("PR92837"); build("PR92837"); alter("PR92837", "inc1"); build("PR92837"); } // See open generic itd bug mentioning 119570 // public void testPr119570() { // initialiseProject("PR119570"); // build("PR119570"); // assertNoErrors("PR119570"); // } // public void testPr119570_212783_2() { // initialiseProject("PR119570_2"); // build("PR119570_2"); // List l = getWarningMessages("PR119570_2"); // assertTrue("Should be no warnings, but got "+l,l.size()==0); // assertNoErrors("PR119570_2"); // } // // public void testPr119570_212783_3() { // initialiseProject("pr119570_3"); // build("pr119570_3"); // List l = getWarningMessages("pr119570_3"); // assertTrue("Should be no warnings, but got "+l,l.size()==0); // assertNoErrors("pr119570_3"); // } // If you fiddle with the compiler options - you must manually reset the // options at the end of the test public void testPr117209() { try { initialiseProject("pr117209"); configureNonStandardCompileOptions("pr117209", "-proceedOnError"); build("pr117209"); checkCompileWeaveCount("pr117209", 6, 5); } finally { // MyBuildOptionsAdapter.reset(); } } public void testPr114875() { // temporary problem with this on linux, think it is a filesystem // lastmodtime issue if (System.getProperty("os.name", "").toLowerCase().equals("linux")) return; initialiseProject("pr114875"); build("pr114875"); alter("pr114875", "inc1"); build("pr114875"); checkWasFullBuild(); alter("pr114875", "inc2"); build("pr114875"); checkWasFullBuild(); // back to the source for an aspect change } public void testPr117882() { // AjdeInteractionTestbed.VERBOSE=true; // AjdeInteractionTestbed.configureBuildStructureModel(true); initialiseProject("PR117882"); build("PR117882"); checkWasFullBuild(); alter("PR117882", "inc1"); build("PR117882"); checkWasFullBuild(); // back to the source for an aspect // AjdeInteractionTestbed.VERBOSE=false; // AjdeInteractionTestbed.configureBuildStructureModel(false); } public void testPr117882_2() { // AjdeInteractionTestbed.VERBOSE=true; // AjdeInteractionTestbed.configureBuildStructureModel(true); initialiseProject("PR117882_2"); build("PR117882_2"); checkWasFullBuild(); alter("PR117882_2", "inc1"); build("PR117882_2"); checkWasFullBuild(); // back to the source... // checkCompileWeaveCount(1,4); // fullBuild("PR117882_2"); // checkWasFullBuild(); // AjdeInteractionTestbed.VERBOSE=false; // AjdeInteractionTestbed.configureBuildStructureModel(false); } public void testPr115251() { // AjdeInteractionTestbed.VERBOSE=true; initialiseProject("PR115251"); build("PR115251"); checkWasFullBuild(); alter("PR115251", "inc1"); build("PR115251"); checkWasFullBuild(); // back to the source } public void testPr220255_InfiniteBuildHasMember() { AjdeInteractionTestbed.VERBOSE = true; initialiseProject("pr220255"); configureNonStandardCompileOptions("pr220255", "-XhasMember"); build("pr220255"); checkWasFullBuild(); alter("pr220255", "inc1"); build("pr220255"); checkWasntFullBuild(); } public void testPr157054() { initialiseProject("PR157054"); configureNonStandardCompileOptions("PR157054", "-showWeaveInfo"); configureShowWeaveInfoMessages("PR157054", true); build("PR157054"); checkWasFullBuild(); List weaveMessages = getWeavingMessages("PR157054"); assertTrue("Should be two weaving messages but there are " + weaveMessages.size(), weaveMessages.size() == 2); alter("PR157054", "inc1"); build("PR157054"); weaveMessages = getWeavingMessages("PR157054"); assertTrue("Should be three weaving messages but there are " + weaveMessages.size(), weaveMessages.size() == 3); checkWasntFullBuild(); fullBuild("PR157054"); weaveMessages = getWeavingMessages("PR157054"); assertTrue("Should be three weaving messages but there are " + weaveMessages.size(), weaveMessages.size() == 3); } /** * Checks we aren't leaking mungers across compiles (accumulating multiple instances of the same one that all do the same * thing). On the first compile the munger is added late on - so at the time we set the count it is still zero. On the * subsequent compiles we know about this extra one. */ public void testPr141956_IncrementallyCompilingAtAj() { initialiseProject("PR141956"); build("PR141956"); assertTrue("Should be zero but reports " + EclipseFactory.debug_mungerCount, EclipseFactory.debug_mungerCount == 0); alter("PR141956", "inc1"); build("PR141956"); assertTrue("Should be two but reports " + EclipseFactory.debug_mungerCount, EclipseFactory.debug_mungerCount == 2); alter("PR141956", "inc1"); build("PR141956"); assertTrue("Should be two but reports " + EclipseFactory.debug_mungerCount, EclipseFactory.debug_mungerCount == 2); alter("PR141956", "inc1"); build("PR141956"); assertTrue("Should be two but reports " + EclipseFactory.debug_mungerCount, EclipseFactory.debug_mungerCount == 2); alter("PR141956", "inc1"); build("PR141956"); assertTrue("Should be two but reports " + EclipseFactory.debug_mungerCount, EclipseFactory.debug_mungerCount == 2); } // public void testPr124399() { // AjdeInteractionTestbed.VERBOSE=true; // configureBuildStructureModel(true); // initialiseProject("PR124399"); // build("PR124399"); // checkWasFullBuild(); // alter("PR124399","inc1"); // build("PR124399"); // checkWasntFullBuild(); // } public void testPr121384() { // AjdeInteractionTestbed.VERBOSE=true; // AsmManager.setReporting("c:/foo.txt",true,true,true,false); initialiseProject("pr121384"); configureNonStandardCompileOptions("pr121384", "-showWeaveInfo"); build("pr121384"); checkWasFullBuild(); alter("pr121384", "inc1"); build("pr121384"); checkWasntFullBuild(); } /* * public void testPr111779() { super.VERBOSE=true; initialiseProject("PR111779"); build("PR111779"); alter("PR111779","inc1"); * build("PR111779"); } */ public void testPr93310_1() { initialiseProject("PR93310_1"); build("PR93310_1"); checkWasFullBuild(); String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_1" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java"; (new File(fileC2)).delete(); alter("PR93310_1", "inc1"); build("PR93310_1"); checkWasFullBuild(); int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size(); assertTrue("Expected one deleted file to be noticed, but detected: " + l, l == 1); String name = (String) AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0); assertTrue("Should end with C2.java but is " + name, name.endsWith("C2.java")); } public void testPr93310_2() { initialiseProject("PR93310_2"); build("PR93310_2"); checkWasFullBuild(); String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_2" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java"; (new File(fileC2)).delete(); alter("PR93310_2", "inc1"); build("PR93310_2"); checkWasFullBuild(); int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size(); assertTrue("Expected one deleted file to be noticed, but detected: " + l, l == 1); String name = (String) AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0); assertTrue("Should end with C2.java but is " + name, name.endsWith("C2.java")); } // Stage1: Compile two files, pack.A and pack.A1 - A1 sets a protected field // in A. // Stage2: make the field private in class A > gives compile error // Stage3: Add a new aspect whilst there is a compile error ! public void testPr113531() { initialiseProject("PR113531"); build("PR113531"); assertTrue("build should have compiled ok", getErrorMessages("PR113531").isEmpty()); alter("PR113531", "inc1"); build("PR113531"); assertEquals("error message should be 'foo cannot be resolved' ", "foo cannot be resolved", ((IMessage) getErrorMessages( "PR113531").get(0)).getMessage()); alter("PR113531", "inc2"); build("PR113531"); assertTrue("There should be no exceptions handled:\n" + getCompilerErrorMessages("PR113531"), getCompilerErrorMessages( "PR113531").isEmpty()); assertEquals("error message should be 'foo cannot be resolved' ", "foo cannot be resolved", ((IMessage) getErrorMessages( "PR113531").get(0)).getMessage()); } // Stage 1: Compile the 4 files, pack.A2 extends pack.A1 (aspects) where // A2 uses a protected field in A1 and pack.C2 extends pack.C1 (classes) // where C2 uses a protected field in C1 // Stage 2: make the field private in class C1 ==> compile errors in C2 // Stage 3: make the field private in aspect A1 whilst there's the compile // error. // There shouldn't be a BCExcpetion saying can't find delegate for pack.C2 public void testPr119882() { initialiseProject("PR119882"); build("PR119882"); assertTrue("build should have compiled ok", getErrorMessages("PR119882").isEmpty()); alter("PR119882", "inc1"); build("PR119882"); // fullBuild("PR119882"); List errors = getErrorMessages("PR119882"); assertTrue("Should be at least one error, but got none", errors.size() == 1); assertEquals("error message should be 'i cannot be resolved' ", "i cannot be resolved", ((IMessage) errors.get(0)) .getMessage()); alter("PR119882", "inc2"); build("PR119882"); assertTrue("There should be no exceptions handled:\n" + getCompilerErrorMessages("PR119882"), getCompilerErrorMessages( "PR119882").isEmpty()); assertEquals("error message should be 'i cannot be resolved' ", "i cannot be resolved", ((IMessage) errors.get(0)) .getMessage()); } public void testPr112736() { initialiseProject("PR112736"); build("PR112736"); checkWasFullBuild(); String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR112736" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "A.java"; (new File(fileC2)).delete(); alter("PR112736", "inc1"); build("PR112736"); checkWasFullBuild(); } /** * We have problems with multiple rewrites of a pointcut across incremental builds. */ public void testPr113257() { initialiseProject("PR113257"); build("PR113257"); alter("PR113257", "inc1"); build("PR113257"); checkWasFullBuild(); // back to the source alter("PR113257", "inc1"); build("PR113257"); } public void testPr123612() { initialiseProject("PR123612"); build("PR123612"); alter("PR123612", "inc1"); build("PR123612"); checkWasFullBuild(); // back to the source } // Bugzilla Bug 152257 - Incremental compiler doesn't handle exception // declaration correctly public void testPr152257() { initialiseProject("PR152257"); configureNonStandardCompileOptions("PR152257", "-XnoInline"); build("PR152257"); List errors = getErrorMessages("PR152257"); assertTrue("Should be no warnings, but there are #" + errors.size(), errors.size() == 0); checkWasFullBuild(); alter("PR152257", "inc1"); build("PR152257"); errors = getErrorMessages("PR152257"); assertTrue("Should be no warnings, but there are #" + errors.size(), errors.size() == 0); checkWasntFullBuild(); } public void testPr128655() { initialiseProject("pr128655"); configureNonStandardCompileOptions("pr128655", "-showWeaveInfo"); configureShowWeaveInfoMessages("pr128655", true); build("pr128655"); List firstBuildMessages = getWeavingMessages("pr128655"); assertTrue("Should be at least one message about the dec @type, but there were none", firstBuildMessages.size() > 0); alter("pr128655", "inc1"); build("pr128655"); checkWasntFullBuild(); // back to the source List secondBuildMessages = getWeavingMessages("pr128655"); // check they are the same for (int i = 0; i < firstBuildMessages.size(); i++) { IMessage m1 = (IMessage) firstBuildMessages.get(i); IMessage m2 = (IMessage) secondBuildMessages.get(i); if (!m1.toString().equals(m2.toString())) { System.err.println("Message during first build was: " + m1); System.err.println("Message during second build was: " + m1); fail("The two messages should be the same, but are not: \n" + m1 + "!=" + m2); } } } // Similar to above, but now the annotation is in the default package public void testPr128655_2() { initialiseProject("pr128655_2"); configureNonStandardCompileOptions("pr128655_2", "-showWeaveInfo"); configureShowWeaveInfoMessages("pr128655_2", true); build("pr128655_2"); List firstBuildMessages = getWeavingMessages("pr128655_2"); assertTrue("Should be at least one message about the dec @type, but there were none", firstBuildMessages.size() > 0); alter("pr128655_2", "inc1"); build("pr128655_2"); checkWasntFullBuild(); // back to the source List secondBuildMessages = getWeavingMessages("pr128655_2"); // check they are the same for (int i = 0; i < firstBuildMessages.size(); i++) { IMessage m1 = (IMessage) firstBuildMessages.get(i); IMessage m2 = (IMessage) secondBuildMessages.get(i); if (!m1.toString().equals(m2.toString())) { System.err.println("Message during first build was: " + m1); System.err.println("Message during second build was: " + m1); fail("The two messages should be the same, but are not: \n" + m1 + "!=" + m2); } } } // test for comment #31 - NPE public void testPr129163() { initialiseProject("PR129613"); build("PR129613"); alter("PR129613", "inc1"); build("PR129613"); assertTrue("There should be no exceptions handled:\n" + getCompilerErrorMessages("PR129613"), getCompilerErrorMessages( "PR129613").isEmpty()); assertEquals("warning message should be 'no match for this type name: File [Xlint:invalidAbsoluteTypeName]' ", "no match for this type name: File [Xlint:invalidAbsoluteTypeName]", ((IMessage) getWarningMessages("PR129613") .get(0)).getMessage()); } // test for comment #0 - adding a comment to a class file shouldn't // cause us to go back to source and recompile everything. To force this // to behave like AJDT we need to include the aspect in 'inc1' so that // when AjState looks at its timestamp it thinks the aspect has been // modified. // The logic within CrosscuttingMembers should then work out correctly // that there haven't really been any changes within the aspect and so // we shouldn't go back to source. public void testPr129163_2() { // want to behave like AJDT initialiseProject("pr129163_2"); build("pr129163_2"); checkWasFullBuild(); alter("pr129163_2", "inc1"); build("pr129163_2"); checkWasntFullBuild(); // shouldn't be a full build because the // aspect hasn't changed } public void testIncrementalIntelligence_Scenario01() { AjdeInteractionTestbed.VERBOSE = true; initialiseProject("Project1"); initialiseProject("Project2"); configureNewProjectDependency("Project2", "Project1"); build("Project1"); build("Project2"); alter("Project1", "inc1"); // white space change to ClassA - no impact build("Project1"); build("Project2"); checkWasntFullBuild(); // not a structural change so ignored alter("Project1", "inc2"); // structural change to ClassB - new method! build("Project1"); build("Project2"); checkWasntFullBuild(); // not a type that Project2 depends on so ignored alter("Project1", "inc3"); // structural change to ClassA build("Project1"); setNextChangeResponse("Project2", ICompilerConfiguration.EVERYTHING); // See // pr245566 // comment // 3 build("Project2"); checkWasntFullBuild(); // Just need to recompile ClassAExtender checkCompileWeaveCount("Project2", 1, 1); checkCompiled("Project2", "ClassAExtender"); alter("Project2", "inc1"); // New type that depends on ClassAExtender build("Project1"); build("Project2"); checkWasntFullBuild(); // Just build ClassAExtenderExtender alter("Project1", "inc4"); // another structural change to ClassA build("Project1"); setNextChangeResponse("Project2", ICompilerConfiguration.EVERYTHING); // See // pr245566 // comment // 3 build("Project2"); checkWasntFullBuild(); // Should rebuild ClassAExtender and // ClassAExtenderExtender checkCompileWeaveCount("Project2", 2, 2); checkCompiled("Project2", "ClassAExtenderExtender"); } private void checkCompiled(String projectName, String typeNameSubstring) { List files = getCompiledFiles(projectName); boolean found = false; for (Iterator iterator = files.iterator(); iterator.hasNext();) { String object = (String) iterator.next(); if (object.indexOf(typeNameSubstring) != -1) found = true; } assertTrue("Did not find '" + typeNameSubstring + "' in list of compiled files", found); } // Case001: renaming a private field in a type /* * public void testPrReducingDependentBuilds_001_221427() { AjdeInteractionTestbed.VERBOSE=true; * IncrementalStateManager.debugIncrementalStates=true; initialiseProject("P221427_1"); initialiseProject("P221427_2"); * configureNewProjectDependency("P221427_2","P221427_1"); * * build("P221427_1"); build("P221427_2"); alter("P221427_1","inc1"); // rename private class in super project * MyStateListener.reset(); build("P221427_1"); build("P221427_2"); * * AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P221427_1","bin"))); * assertTrue("There should be state for project P221427_1",ajs!=null); * //System.out.println(MyStateListener.getInstance().getDecisions()); checkWasntFullBuild(); * assertTrue("Should be one structural change but there were "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), * ajs.getNumberOfStructuralChangesSinceLastFullBuild()==1); * * } * * // Case002: changing a class to final that is extended in a dependent project public void * testPrReducingDependentBuilds_002_221427() { AjdeInteractionTestbed.VERBOSE=true; * IncrementalStateManager.debugIncrementalStates=true; initialiseProject("P221427_3"); initialiseProject("P221427_4"); * configureNewProjectDependency("P221427_4","P221427_3"); * * build("P221427_3"); build("P221427_4"); // build OK, type in super project is non-final alter("P221427_3","inc1"); // change * class declaration in super-project to final MyStateListener.reset(); build("P221427_3"); build("P221427_4"); // build FAIL, * type in super project is now final * * AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P221427_3","bin"))); * assertTrue("There should be state for project P221427_3",ajs!=null); * System.out.println(MyStateListener.getInstance().getDecisions()); * * List errors = getErrorMessages("P221427_4"); if (errors.size()!=1) { if (errors.size()==0) * fail("Expected error about not being able to extend final class"); for (Iterator iterator = errors.iterator(); * iterator.hasNext();) { Object object = (Object) iterator.next(); System.out.println(object); } * fail("Expected 1 error but got "+errors.size()); } // assertTrue("Shouldn't be one structural change but there were "+ // * ajs.getNumberOfStructuralChangesSinceLastFullBuild(), // ajs.getNumberOfStructuralChangesSinceLastFullBuild()==1); * * } */ // test for comment #6 - simulates AJDT core builder test testBug99133a - // changing the contents of a method within a class shouldn't force a // full build of a dependant project. To force this to behave like AJDT // 'inc1' of the dependant project should just be a copy of 'base' so that // AjState thinks somethings changed within the dependant project and // we do a build. Similarly, 'inc1' of the project depended on should // include the aspect even though nothing's changed within it. This causes // AjState to think that the aspect has changed. Together its then up to // logic within CrosscuttingMembers and various equals methods to decide // correctly that we don't have to go back to source. public void testPr129163_3() { initialiseProject("PR129163_4"); build("PR129163_4"); checkWasFullBuild(); // should be a full build because initializing // project initialiseProject("PR129163_3"); configureNewProjectDependency("PR129163_3", "PR129163_4"); build("PR129163_3"); checkWasFullBuild(); // should be a full build because initializing // project alter("PR129163_4", "inc1"); build("PR129163_4"); checkWasntFullBuild(); // should be an incremental build because // although // "inc1" includes the aspect A1.aj, it actually hasn't // changed so we shouldn't go back to source alter("PR129163_3", "inc1"); build("PR129163_3"); checkWasntFullBuild(); // should be an incremental build because nothing // has // changed within the class and no aspects have changed // within the running of the test } public void testPr133117() { // System.gc(); // System.exit(); initialiseProject("PR133117"); configureNonStandardCompileOptions("PR133117", "-Xlint:warning"); build("PR133117"); assertTrue("There should only be one xlint warning message reported:\n" + getWarningMessages("PR133117"), getWarningMessages("PR133117").size() == 1); alter("PR133117", "inc1"); build("PR133117"); List warnings = getWarningMessages("PR133117"); List noGuardWarnings = new ArrayList(); for (Iterator iter = warnings.iterator(); iter.hasNext();) { IMessage element = (IMessage) iter.next(); if (element.getMessage().indexOf("Xlint:noGuardForLazyTjp") != -1) { noGuardWarnings.add(element); } } assertTrue("There should only be two Xlint:noGuardForLazyTjp warning message reported:\n" + noGuardWarnings, noGuardWarnings.size() == 2); } public void testPr131505() { initialiseProject("PR131505"); configureNonStandardCompileOptions("PR131505", "-outxml"); build("PR131505"); checkWasFullBuild(); String outputDir = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR131505" + File.separatorChar + "bin"; // aop.xml file shouldn't contain any aspects checkXMLAspectCount("PR131505", "", 0, outputDir); // add a new aspect A which should be included in the aop.xml file alter("PR131505", "inc1"); build("PR131505"); checkWasFullBuild(); checkXMLAspectCount("PR131505", "", 1, outputDir); checkXMLAspectCount("PR131505", "A", 1, outputDir); // make changes to the class file which shouldn't affect the contents // of the aop.xml file alter("PR131505", "inc2"); build("PR131505"); checkWasntFullBuild(); checkXMLAspectCount("PR131505", "", 1, outputDir); checkXMLAspectCount("PR131505", "A", 1, outputDir); // add another new aspect A1 which should also be included in the // aop.xml file // ...there should be no duplicate entries in the file alter("PR131505", "inc3"); build("PR131505"); checkWasFullBuild(); checkXMLAspectCount("PR131505", "", 2, outputDir); checkXMLAspectCount("PR131505", "A1", 1, outputDir); checkXMLAspectCount("PR131505", "A", 1, outputDir); // delete aspect A1 which meanss that aop.xml file should only contain A File a1 = new File(getWorkingDir().getAbsolutePath() + File.separatorChar + "PR131505" + File.separatorChar + "A1.aj"); a1.delete(); build("PR131505"); checkWasFullBuild(); checkXMLAspectCount("PR131505", "", 1, outputDir); checkXMLAspectCount("PR131505", "A1", 0, outputDir); checkXMLAspectCount("PR131505", "A", 1, outputDir); // add another aspect called A which is in a different package, both A // and pkg.A should be included in the aop.xml file alter("PR131505", "inc4"); build("PR131505"); checkWasFullBuild(); checkXMLAspectCount("PR131505", "", 2, outputDir); checkXMLAspectCount("PR131505", "A", 1, outputDir); checkXMLAspectCount("PR131505", "pkg.A", 1, outputDir); } public void testPr136585() { initialiseProject("PR136585"); build("PR136585"); alter("PR136585", "inc1"); build("PR136585"); assertTrue("There should be no errors reported:\n" + getErrorMessages("PR136585"), getErrorMessages("PR136585").isEmpty()); } public void testPr133532() { initialiseProject("PR133532"); build("PR133532"); alter("PR133532", "inc1"); build("PR133532"); alter("PR133532", "inc2"); build("PR133532"); assertTrue("There should be no errors reported:\n" + getErrorMessages("PR133532"), getErrorMessages("PR133532").isEmpty()); } public void testPr133532_2() { initialiseProject("pr133532_2"); build("pr133532_2"); alter("pr133532_2", "inc2"); build("pr133532_2"); assertTrue("There should be no errors reported:\n" + getErrorMessages("pr133532_2"), getErrorMessages("pr133532_2") .isEmpty()); String decisions = AjdeInteractionTestbed.MyStateListener.getDecisions(); String expect = "Need to recompile 'A.aj'"; assertTrue("Couldn't find build decision: '" + expect + "' in the list of decisions made:\n" + decisions, decisions .indexOf(expect) != -1); } public void testPr133532_3() { initialiseProject("PR133532_3"); build("PR133532_3"); alter("PR133532_3", "inc1"); build("PR133532_3"); assertTrue("There should be no errors reported:\n" + getErrorMessages("PR133532_3"), getErrorMessages("PR133532_3") .isEmpty()); } public void testPr134541() { initialiseProject("PR134541"); build("PR134541"); assertEquals("[Xlint:adviceDidNotMatch] should be associated with line 5", 5, ((IMessage) getWarningMessages("PR134541") .get(0)).getSourceLocation().getLine()); alter("PR134541", "inc1"); build("PR134541"); if (AsmManager.getDefault().getHandleProvider().dependsOnLocation()) checkWasFullBuild(); // the line number has changed... but nothing // structural about the code else checkWasntFullBuild(); // the line number has changed... but nothing // structural about the code assertEquals("[Xlint:adviceDidNotMatch] should now be associated with line 7", 7, ((IMessage) getWarningMessages("PR134541").get(0)).getSourceLocation().getLine()); } public void testJDTLikeHandleProviderWithLstFile_pr141730() { IElementHandleProvider handleProvider = AsmManager.getDefault().getHandleProvider(); AsmManager.getDefault().setHandleProvider(new JDTLikeHandleProvider()); try { // The JDTLike-handles should start with the name // of the buildconfig file initialiseProject("JDTLikeHandleProvider"); build("JDTLikeHandleProvider"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement pe = top.findElementForType("pkg", "A"); String expectedHandle = "=JDTLikeHandleProvider<pkg*A.aj}A"; assertEquals("expected handle to be " + expectedHandle + ", but found " + pe.getHandleIdentifier(), expectedHandle, pe .getHandleIdentifier()); } finally { AsmManager.getDefault().setHandleProvider(handleProvider); } } public void testMovingAdviceDoesntChangeHandles_pr141730() { IElementHandleProvider handleProvider = AsmManager.getDefault().getHandleProvider(); AsmManager.getDefault().setHandleProvider(new JDTLikeHandleProvider()); try { initialiseProject("JDTLikeHandleProvider"); build("JDTLikeHandleProvider"); checkWasFullBuild(); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement pe = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE, "before(): <anonymous pointcut>"); // add a line which shouldn't change the handle alter("JDTLikeHandleProvider", "inc1"); build("JDTLikeHandleProvider"); checkWasntFullBuild(); IHierarchy top2 = AsmManager.getDefault().getHierarchy(); IProgramElement pe2 = top.findElementForLabel(top2.getRoot(), IProgramElement.Kind.ADVICE, "before(): <anonymous pointcut>"); assertEquals("expected advice to be on line " + pe.getSourceLocation().getLine() + 1 + " but was on " + pe2.getSourceLocation().getLine(), pe.getSourceLocation().getLine() + 1, pe2.getSourceLocation().getLine()); assertEquals("expected advice to have handle " + pe.getHandleIdentifier() + " but found handle " + pe2.getHandleIdentifier(), pe.getHandleIdentifier(), pe2.getHandleIdentifier()); } finally { AsmManager.getDefault().setHandleProvider(handleProvider); } } public void testSwappingAdviceAndHandles_pr141730() { IElementHandleProvider handleProvider = AsmManager.getDefault().getHandleProvider(); AsmManager.getDefault().setHandleProvider(new JDTLikeHandleProvider()); try { initialiseProject("JDTLikeHandleProvider"); build("JDTLikeHandleProvider"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement call = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE, "after(): callPCD.."); IProgramElement exec = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE, "after(): execPCD.."); // swap the two after advice statements over. This forces // a full build which means 'after(): callPCD..' will now // be the second after advice in the file and have the same // handle as 'after(): execPCD..' originally did. alter("JDTLikeHandleProvider", "inc2"); build("JDTLikeHandleProvider"); checkWasFullBuild(); IHierarchy top2 = AsmManager.getDefault().getHierarchy(); IProgramElement newCall = top2.findElementForLabel(top2.getRoot(), IProgramElement.Kind.ADVICE, "after(): callPCD.."); IProgramElement newExec = top2.findElementForLabel(top2.getRoot(), IProgramElement.Kind.ADVICE, "after(): execPCD.."); assertEquals("after swapping places, expected 'after(): callPCD..' " + "to be on line " + newExec.getSourceLocation().getLine() + " but was on line " + call.getSourceLocation().getLine(), newExec .getSourceLocation().getLine(), call.getSourceLocation().getLine()); assertEquals("after swapping places, expected 'after(): callPCD..' " + "to have handle " + exec.getHandleIdentifier() + " (because was full build) but had " + newCall.getHandleIdentifier(), exec.getHandleIdentifier(), newCall .getHandleIdentifier()); } finally { AsmManager.getDefault().setHandleProvider(handleProvider); } } public void testInitializerCountForJDTLikeHandleProvider_pr141730() { IElementHandleProvider handleProvider = AsmManager.getDefault().getHandleProvider(); AsmManager.getDefault().setHandleProvider(new JDTLikeHandleProvider()); try { initialiseProject("JDTLikeHandleProvider"); build("JDTLikeHandleProvider"); String expected = "=JDTLikeHandleProvider<pkg*A.aj[C|1"; IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement init = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.INITIALIZER, "..."); assertEquals("expected initializers handle to be " + expected + "," + " but found " + init.getHandleIdentifier(true), expected, init.getHandleIdentifier(true)); alter("JDTLikeHandleProvider", "inc2"); build("JDTLikeHandleProvider"); checkWasFullBuild(); IHierarchy top2 = AsmManager.getDefault().getHierarchy(); IProgramElement init2 = top2.findElementForLabel(top2.getRoot(), IProgramElement.Kind.INITIALIZER, "..."); assertEquals("expected initializers handle to still be " + expected + "," + " but found " + init2.getHandleIdentifier(true), expected, init2.getHandleIdentifier(true)); } finally { AsmManager.getDefault().setHandleProvider(handleProvider); } } // 134471 related tests perform incremental compilation and verify features // of the structure model post compile public void testPr134471_IncrementalCompilationAndModelUpdates() { try { // see pr148027 AsmHierarchyBuilder.shouldAddUsesPointcut=false; // Step1. Build the code, simple advice from aspect A onto class C initialiseProject("PR134471"); configureNonStandardCompileOptions("PR134471", "-showWeaveInfo -emacssym"); configureShowWeaveInfoMessages("PR134471", true); build("PR134471"); // Step2. Quick check that the advice points to something... IProgramElement nodeForTypeA = checkForNode("pkg", "A", true); IProgramElement nodeForAdvice = findAdvice(nodeForTypeA); List relatedElements = getRelatedElements(nodeForAdvice, 1); // Step3. Check the advice applying at the first 'code' join point // in pkg.C is from aspect pkg.A, line 7 IProgramElement programElement = getFirstRelatedElement(findCode(checkForNode("pkg", "C", true))); int line = programElement.getSourceLocation().getLine(); assertTrue("advice should be at line 7 - but is at line " + line, line == 7); // Step4. Simulate the aspect being saved but with no change at all // in it alter("PR134471", "inc1"); build("PR134471"); // Step5. Quick check that the advice points to something... nodeForTypeA = checkForNode("pkg", "A", true); nodeForAdvice = findAdvice(nodeForTypeA); relatedElements = getRelatedElements(nodeForAdvice, 1); // Step6. Check the advice applying at the first 'code' join point // in pkg.C is from aspect pkg.A, line 7 programElement = getFirstRelatedElement(findCode(checkForNode("pkg", "C", true))); line = programElement.getSourceLocation().getLine(); assertTrue("advice should be at line 7 - but is at line " + line, line == 7); } finally { // see pr148027 AsmHierarchyBuilder.shouldAddUsesPointcut=true; } } // now the advice moves down a few lines - hopefully the model will // notice... see discussion in 134471 public void testPr134471_MovingAdvice() { // Step1. build the project initialiseProject("PR134471_2"); configureNonStandardCompileOptions("PR134471_2", "-showWeaveInfo -emacssym"); configureShowWeaveInfoMessages("PR134471_2", true); build("PR134471_2"); // Step2. confirm advice is from correct location IProgramElement programElement = getFirstRelatedElement(findCode(checkForNode("pkg", "C", true))); int line = programElement.getSourceLocation().getLine(); assertTrue("advice should be at line 7 - but is at line " + line, line == 7); // Step3. No structural change to the aspect but the advice has moved // down a few lines... (change in source location) alter("PR134471_2", "inc1"); build("PR134471_2"); if (AsmManager.getDefault().getHandleProvider().dependsOnLocation()) checkWasFullBuild(); // the line number has changed... but nothing // structural about the code else checkWasntFullBuild(); // the line number has changed... but nothing // structural about the code // checkWasFullBuild(); // this is true whilst we consider // sourcelocation in the type/shadow munger equals() method - have // to until the handles are independent of location // Step4. Check we have correctly realised the advice moved to line 11 programElement = getFirstRelatedElement(findCode(checkForNode("pkg", "C", true))); line = programElement.getSourceLocation().getLine(); assertTrue("advice should be at line 11 - but is at line " + line, line == 11); } public void testAddingAndRemovingDecwWithStructureModel() { initialiseProject("P3"); build("P3"); alter("P3", "inc1"); build("P3"); assertTrue("There should be no exceptions handled:\n" + getCompilerErrorMessages("P3"), getCompilerErrorMessages("P3") .isEmpty()); alter("P3", "inc2"); build("P3"); assertTrue("There should be no exceptions handled:\n" + getCompilerErrorMessages("P3"), getCompilerErrorMessages("P3") .isEmpty()); } // same as first test with an extra stage that asks for C to be recompiled, // it should still be advised... public void testPr134471_IncrementallyRecompilingTheAffectedClass() { try { // see pr148027 AsmHierarchyBuilder.shouldAddUsesPointcut=false; // Step1. build the project initialiseProject("PR134471"); configureNonStandardCompileOptions("PR134471", "-showWeaveInfo -emacssym"); configureShowWeaveInfoMessages("PR134471", true); build("PR134471"); // Step2. confirm advice is from correct location IProgramElement programElement = getFirstRelatedElement(findCode(checkForNode("pkg", "C", true))); int line = programElement.getSourceLocation().getLine(); assertTrue("advice should be at line 7 - but is at line " + line, line == 7); // Step3. No change to the aspect at all alter("PR134471", "inc1"); build("PR134471"); // Step4. Quick check that the advice points to something... IProgramElement nodeForTypeA = checkForNode("pkg", "A", true); IProgramElement nodeForAdvice = findAdvice(nodeForTypeA); List relatedElements = getRelatedElements(nodeForAdvice, 1); // Step5. No change to the file C but it should still be advised // afterwards alter("PR134471", "inc2"); build("PR134471"); checkWasntFullBuild(); // Step6. confirm advice is from correct location programElement = getFirstRelatedElement(findCode(checkForNode("pkg", "C", true))); line = programElement.getSourceLocation().getLine(); assertTrue("advice should be at line 7 - but is at line " + line, line == 7); } finally { // see pr148027 AsmHierarchyBuilder.shouldAddUsesPointcut=true; } } // similar to previous test but with 'declare warning' as well as advice public void testPr134471_IncrementallyRecompilingAspectContainingDeclare() { // Step1. build the project initialiseProject("PR134471_3"); configureNonStandardCompileOptions("PR134471_3", "-showWeaveInfo -emacssym"); configureShowWeaveInfoMessages("PR134471_3", true); build("PR134471_3"); checkWasFullBuild(); // Step2. confirm declare warning is from correct location, decw matches // line 7 in pkg.C IProgramElement programElement = getFirstRelatedElement(findCode(checkForNode("pkg", "C", true), 7)); int line = programElement.getSourceLocation().getLine(); assertTrue("declare warning should be at line 10 - but is at line " + line, line == 10); // Step3. confirm advice is from correct location, advice matches line 6 // in pkg.C programElement = getFirstRelatedElement(findCode(checkForNode("pkg", "C", true), 6)); line = programElement.getSourceLocation().getLine(); assertTrue("advice should be at line 7 - but is at line " + line, line == 7); // Step4. Move declare warning in the aspect alter("PR134471_3", "inc1"); build("PR134471_3"); if (AsmManager.getDefault().getHandleProvider().dependsOnLocation()) checkWasFullBuild(); // the line number has changed... but nothing // structural about the code else checkWasntFullBuild(); // the line number has changed... but nothing // structural about the code // checkWasFullBuild(); // Step5. confirm declare warning is from correct location, decw (now at // line 12) in pkg.A matches line 7 in pkg.C programElement = getFirstRelatedElement(findCode(checkForNode("pkg", "C", true), 7)); line = programElement.getSourceLocation().getLine(); assertTrue("declare warning should be at line 12 - but is at line " + line, line == 12); // Step6. Now just simulate 'resave' of the aspect, nothing has changed alter("PR134471_3", "inc2"); build("PR134471_3"); checkWasntFullBuild(); // Step7. confirm declare warning is from correct location, decw (now at // line 12) in pkg.A matches line 7 in pkg.C programElement = getFirstRelatedElement(findCode(checkForNode("pkg", "C", true), 7)); line = programElement.getSourceLocation().getLine(); assertTrue("declare warning should be at line 12 - but is at line " + line, line == 12); } // similar to previous test but with 'declare warning' as well as advice public void testPr134471_IncrementallyRecompilingTheClassAffectedByDeclare() { // Step1. build the project initialiseProject("PR134471_3"); configureNonStandardCompileOptions("PR134471_3", "-showWeaveInfo -emacssym"); configureShowWeaveInfoMessages("PR134471_3", true); build("PR134471_3"); checkWasFullBuild(); // Step2. confirm declare warning is from correct location, decw matches // line 7 in pkg.C IProgramElement programElement = getFirstRelatedElement(findCode(checkForNode("pkg", "C", true), 7)); int line = programElement.getSourceLocation().getLine(); assertTrue("declare warning should be at line 10 - but is at line " + line, line == 10); // Step3. confirm advice is from correct location, advice matches line 6 // in pkg.C programElement = getFirstRelatedElement(findCode(checkForNode("pkg", "C", true), 6)); line = programElement.getSourceLocation().getLine(); assertTrue("advice should be at line 7 - but is at line " + line, line == 7); // Step4. Move declare warning in the aspect alter("PR134471_3", "inc1"); build("PR134471_3"); if (AsmManager.getDefault().getHandleProvider().dependsOnLocation()) checkWasFullBuild(); // the line number has changed... but nothing // structural about the code else checkWasntFullBuild(); // the line number has changed... but nothing // structural about the code // checkWasFullBuild(); // Step5. confirm declare warning is from correct location, decw (now at // line 12) in pkg.A matches line 7 in pkg.C programElement = getFirstRelatedElement(findCode(checkForNode("pkg", "C", true), 7)); line = programElement.getSourceLocation().getLine(); assertTrue("declare warning should be at line 12 - but is at line " + line, line == 12); // Step6. Now just simulate 'resave' of the aspect, nothing has changed alter("PR134471_3", "inc2"); build("PR134471_3"); checkWasntFullBuild(); // Step7. confirm declare warning is from correct location, decw (now at // line 12) in pkg.A matches line 7 in pkg.C programElement = getFirstRelatedElement(findCode(checkForNode("pkg", "C", true), 7)); line = programElement.getSourceLocation().getLine(); assertTrue("declare warning should be at line 12 - but is at line " + line, line == 12); // Step8. Now just simulate resave of the pkg.C type - no change at // all... are relationships gonna be repaired OK? alter("PR134471_3", "inc3"); build("PR134471_3"); checkWasntFullBuild(); // Step9. confirm declare warning is from correct location, decw (now at // line 12) in pkg.A matches line 7 in pkg.C programElement = getFirstRelatedElement(findCode(checkForNode("pkg", "C", true), 7)); line = programElement.getSourceLocation().getLine(); assertTrue("declare warning should be at line 12 - but is at line " + line, line == 12); } public void testDontLoseXlintWarnings_pr141556() { initialiseProject("PR141556"); configureNonStandardCompileOptions("PR141556", "-Xlint:warning"); build("PR141556"); checkWasFullBuild(); String warningMessage = "can not build thisJoinPoint " + "lazily for this advice since it has no suitable guard " + "[Xlint:noGuardForLazyTjp]"; assertEquals("warning message should be '" + warningMessage + "'", warningMessage, ((IMessage) getWarningMessages( "PR141556").get(0)).getMessage()); // add a space to the Aspect but dont do a build alter("PR141556", "inc1"); // remove the space so that the Aspect is exactly as it was alter("PR141556", "inc2"); // build the project and we should not have lost the xlint warning build("PR141556"); checkWasntFullBuild(); assertTrue("there should still be a warning message ", !getWarningMessages("PR141556").isEmpty()); assertEquals("warning message should be '" + warningMessage + "'", warningMessage, ((IMessage) getWarningMessages( "PR141556").get(0)).getMessage()); } public void testAdviceDidNotMatch_pr152589() { initialiseProject("PR152589"); build("PR152589"); List warnings = getWarningMessages("PR152589"); assertTrue("There should be no warnings:\n" + warnings, warnings.isEmpty()); alter("PR152589", "inc1"); build("PR152589"); if (AsmManager.getDefault().getHandleProvider().dependsOnLocation()) checkWasFullBuild(); // the line number has changed... but nothing // structural about the code else checkWasntFullBuild(); // the line number has changed... but nothing // structural about the code // checkWasFullBuild(); warnings = getWarningMessages("PR152589"); assertTrue("There should be no warnings after adding a whitespace:\n" + warnings, warnings.isEmpty()); } // see comment #11 of bug 154054 public void testNoFullBuildOnChangeInSysOutInAdviceBody_pr154054() { initialiseProject("PR154054"); build("PR154054"); alter("PR154054", "inc1"); build("PR154054"); checkWasntFullBuild(); } // change exception type in around advice, does it notice? public void testShouldFullBuildOnExceptionChange_pr154054() { initialiseProject("PR154054_2"); build("PR154054_2"); alter("PR154054_2", "inc1"); build("PR154054_2"); checkWasFullBuild(); } public void testPR158573() { IElementHandleProvider handleProvider = AsmManager.getDefault().getHandleProvider(); AsmManager.getDefault().setHandleProvider(new JDTLikeHandleProvider()); initialiseProject("PR158573"); build("PR158573"); List warnings = getWarningMessages("PR158573"); assertTrue("There should be no warnings:\n" + warnings, warnings.isEmpty()); alter("PR158573", "inc1"); build("PR158573"); checkWasntFullBuild(); warnings = getWarningMessages("PR158573"); assertTrue("There should be no warnings after changing the value of a " + "variable:\n" + warnings, warnings.isEmpty()); AsmManager.getDefault().setHandleProvider(handleProvider); } /** * If the user has specified that they want Java 6 compliance and kept the default classfile and source file level settings * (also 6.0) then expect an error saying that we don't support java 6. */ public void testPR164384_1() { initialiseProject("PR164384"); Hashtable javaOptions = new Hashtable(); javaOptions.put("org.eclipse.jdt.core.compiler.compliance", "1.6"); javaOptions.put("org.eclipse.jdt.core.compiler.codegen.targetPlatform", "1.6"); javaOptions.put("org.eclipse.jdt.core.compiler.source", "1.6"); configureJavaOptionsMap("PR164384", javaOptions); build("PR164384"); List errors = getErrorMessages("PR164384"); if (getCompilerForProjectWithName("PR164384").isJava6Compatible()) { assertTrue("There should be no errors:\n" + errors, errors.isEmpty()); } else { String expectedError = "Java 6.0 compliance level is unsupported"; String found = ((IMessage) errors.get(0)).getMessage(); assertEquals("Expected 'Java 6.0 compliance level is unsupported'" + " error message but found " + found, expectedError, found); // This is because the 'Java 6.0 compliance' error is an 'error' // rather than an 'abort'. Aborts are really for compiler // exceptions. assertTrue("expected there to be more than the one compliance level" + " error but only found that one", errors.size() > 1); } } /** * If the user has specified that they want Java 6 compliance and selected classfile and source file level settings to be 5.0 * then expect an error saying that we don't support java 6. */ public void testPR164384_2() { initialiseProject("PR164384"); Hashtable javaOptions = new Hashtable(); javaOptions.put("org.eclipse.jdt.core.compiler.compliance", "1.6"); javaOptions.put("org.eclipse.jdt.core.compiler.codegen.targetPlatform", "1.5"); javaOptions.put("org.eclipse.jdt.core.compiler.source", "1.5"); configureJavaOptionsMap("PR164384", javaOptions); build("PR164384"); List errors = getErrorMessages("PR164384"); if (getCompilerForProjectWithName("PR164384").isJava6Compatible()) { assertTrue("There should be no errors:\n" + errors, errors.isEmpty()); } else { String expectedError = "Java 6.0 compliance level is unsupported"; String found = ((IMessage) errors.get(0)).getMessage(); assertEquals("Expected 'Java 6.0 compliance level is unsupported'" + " error message but found " + found, expectedError, found); // This is because the 'Java 6.0 compliance' error is an 'error' // rather than an 'abort'. Aborts are really for compiler // exceptions. assertTrue("expected there to be more than the one compliance level" + " error but only found that one", errors.size() > 1); } } /** * If the user has specified that they want Java 6 compliance and set the classfile level to be 6.0 and source file level to be * 5.0 then expect an error saying that we don't support java 6. */ public void testPR164384_3() { initialiseProject("PR164384"); Hashtable javaOptions = new Hashtable(); javaOptions.put("org.eclipse.jdt.core.compiler.compliance", "1.6"); javaOptions.put("org.eclipse.jdt.core.compiler.codegen.targetPlatform", "1.6"); javaOptions.put("org.eclipse.jdt.core.compiler.source", "1.5"); configureJavaOptionsMap("PR164384", javaOptions); build("PR164384"); List errors = getErrorMessages("PR164384"); if (getCompilerForProjectWithName("PR164384").isJava6Compatible()) { assertTrue("There should be no errros:\n" + errors, errors.isEmpty()); } else { String expectedError = "Java 6.0 compliance level is unsupported"; String found = ((IMessage) errors.get(0)).getMessage(); assertEquals("Expected 'Java 6.0 compliance level is unsupported'" + " error message but found " + found, expectedError, found); // This is because the 'Java 6.0 compliance' error is an 'error' // rather than an 'abort'. Aborts are really for compiler // exceptions. assertTrue("expected there to be more than the one compliance level" + " error but only found that one", errors.size() > 1); } } public void testPr168840() throws Exception { initialiseProject("inpathTesting"); String inpathTestingDir = getWorkingDir() + File.separator + "inpathTesting"; String inpathDir = inpathTestingDir + File.separator + "injarBin" + File.separator + "pkg"; String expectedOutputDir = inpathTestingDir + File.separator + "bin"; // set up the inpath to have the directory on it's path File f = new File(inpathDir); Set s = new HashSet(); s.add(f); configureInPath("inpathTesting", s); build("inpathTesting"); // the declare warning matches one place so expect one warning message List warnings = getWarningMessages("inpathTesting"); assertTrue("Expected there to be one warning message but found " + warnings.size() + ": " + warnings, warnings.size() == 1); // copy over the updated version of the inpath class file File from = new File(testdataSrcDir + File.separatorChar + "inpathTesting" + File.separatorChar + "newInpathClass" + File.separatorChar + "InpathClass.class"); File destination = new File(inpathDir + File.separatorChar + "InpathClass.class"); FileUtil.copyFile(from, destination); build("inpathTesting"); checkWasntFullBuild(); // the newly copied inpath class means the declare warning now matches // two // places, therefore expect two warning messages warnings = getWarningMessages("inpathTesting"); assertTrue("Expected there to be two warning message but found " + warnings.size() + ": " + warnings, warnings.size() == 2); } // --- helper code --- /** * Retrieve program elements related to this one regardless of the relationship. A JUnit assertion is made that the number that * the 'expected' number are found. * * @param programElement Program element whose related elements are to be found * @param expected the number of expected related elements */ private List/* IProgramElement */getRelatedElements(IProgramElement programElement, int expected) { List relatedElements = getRelatedElements(programElement); StringBuffer debugString = new StringBuffer(); if (relatedElements != null) { for (Iterator iter = relatedElements.iterator(); iter.hasNext();) { String element = (String) iter.next(); debugString.append(AsmManager.getDefault().getHierarchy().findElementForHandle(element).toLabelString()).append( "\n"); } } assertTrue("Should be " + expected + " element" + (expected > 1 ? "s" : "") + " related to this one '" + programElement + "' but found :\n " + debugString, relatedElements != null && relatedElements.size() == 1); return relatedElements; } private IProgramElement getFirstRelatedElement(IProgramElement programElement) { List rels = getRelatedElements(programElement, 1); return AsmManager.getDefault().getHierarchy().findElementForHandle((String) rels.get(0)); } private List/* IProgramElement */getRelatedElements(IProgramElement advice) { List output = null; IRelationshipMap map = AsmManager.getDefault().getRelationshipMap(); List/* IRelationship */rels = map.get(advice); if (rels == null) fail("Did not find any related elements!"); for (Iterator iter = rels.iterator(); iter.hasNext();) { IRelationship element = (IRelationship) iter.next(); List/* String */targets = element.getTargets(); if (output == null) output = new ArrayList(); output.addAll(targets); } return output; } private IProgramElement findAdvice(IProgramElement ipe) { return findAdvice(ipe, 1); } private IProgramElement findAdvice(IProgramElement ipe, int whichOne) { if (ipe.getKind() == IProgramElement.Kind.ADVICE) { whichOne = whichOne - 1; if (whichOne == 0) return ipe; } List kids = ipe.getChildren(); for (Iterator iter = kids.iterator(); iter.hasNext();) { IProgramElement kid = (IProgramElement) iter.next(); IProgramElement found = findAdvice(kid, whichOne); if (found != null) return found; } return null; } /** * Finds the first 'code' program element below the element supplied - will return null if there aren't any */ private IProgramElement findCode(IProgramElement ipe) { return findCode(ipe, -1); } /** * Searches a hierarchy of program elements for a 'code' element at the specified line number, a line number of -1 means just * return the first one you find */ private IProgramElement findCode(IProgramElement ipe, int linenumber) { if (ipe.getKind() == IProgramElement.Kind.CODE) { if (linenumber == -1 || ipe.getSourceLocation().getLine() == linenumber) return ipe; } List kids = ipe.getChildren(); for (Iterator iter = kids.iterator(); iter.hasNext();) { IProgramElement kid = (IProgramElement) iter.next(); IProgramElement found = findCode(kid, linenumber); if (found != null) return found; } return null; } // other possible tests: // - memory usage (freemem calls?) // - relationship map // -------------------------------------------------------------------------- // ------------------------- private IProgramElement checkForNode(String packageName, String typeName, boolean shouldBeFound) { IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForType(packageName, typeName); if (shouldBeFound) { if (ipe == null) printModel(); assertTrue("Should have been able to find '" + packageName + "." + typeName + "' in the asm", ipe != null); } else { if (ipe != null) printModel(); assertTrue("Should have NOT been able to find '" + packageName + "." + typeName + "' in the asm", ipe == null); } return ipe; } private void printModel() { try { AsmManager.dumptree(AsmManager.getDefault().getHierarchy().getRoot(), 0); } catch (IOException e) { e.printStackTrace(); } } private static void log(String msg) { if (VERBOSE) System.out.println(msg); } private File getProjectRelativePath(String p, String filename) { File projDir = new File(getWorkingDir(), p); return new File(projDir, filename); } private File getProjectOutputRelativePath(String p, String filename) { File projDir = new File(getWorkingDir(), p); return new File(projDir, "bin" + File.separator + filename); } private void assertNoErrors(String projectName) { assertTrue("Should be no errors, but got " + getErrorMessages(projectName), getErrorMessages(projectName).size() == 0); } }
186,884
Bug 186884 Unhandled Kind of New Exception when have advice for Pointcut call(Throwable+.new(..))
null
resolved fixed
7a398a2
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-09-30T22:55:35Z"
"2007-05-14T22:00:00Z"
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.ConstantPool; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.generic.ArrayType; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.INVOKEINTERFACE; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionBranch; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionLV; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InstructionTargeter; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.LineNumberTag; import org.aspectj.apache.bcel.generic.LocalVariableTag; import org.aspectj.apache.bcel.generic.MULTIANEWARRAY; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.TargetLostException; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.BCException; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.MemberImpl; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Var; import org.aspectj.weaver.patterns.AbstractPatternNodeVisitor; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.NotPointcut; import org.aspectj.weaver.patterns.OrPointcut; import org.aspectj.weaver.patterns.ThisOrTargetPointcut; /* * Some fun implementation stuff: * * * expressionKind advice is non-execution advice * * may have a target. * * if the body is extracted, it will be extracted into * a static method. The first argument to the static * method is the target * * advice may expose a this object, but that's the advice's * consideration, not ours. This object will NOT be cached in another * local, but will always come from frame zero. * * * non-expressionKind advice is execution advice * * may have a this. * * target is same as this, and is exposed that way to advice * (i.e., target will not be cached, will always come from frame zero) * * if the body is extracted, it will be extracted into a method * with same static/dynamic modifier as enclosing method. If non-static, * target of callback call will be this. * * * because of these two facts, the setup of the actual arguments (including * possible target) callback method is the same for both kinds of advice: * push the targetVar, if it exists (it will not exist for advice on static * things), then push all the argVars. * * Protected things: * * * the above is sufficient for non-expressionKind advice for protected things, * since the target will always be this. * * * For expressionKind things, we have to modify the signature of the callback * method slightly. For non-static expressionKind things, we modify * the first argument of the callback method NOT to be the type specified * by the method/field signature (the owner), but rather we type it to * the currentlyEnclosing type. We are guaranteed this will be fine, * since the verifier verifies that the target is a subtype of the currently * enclosingType. * * Worries: * * * ConstructorCalls will be weirder than all of these, since they * supposedly don't have a target (according to AspectJ), but they clearly * do have a target of sorts, just one that needs to be pushed on the stack, * dupped, and not touched otherwise until the constructor runs. * * @author Jim Hugunin * @author Erik Hilsdale * */ public class BcelShadow extends Shadow { private ShadowRange range; private final BcelWorld world; private final LazyMethodGen enclosingMethod; // SECRETAPI - for testing, this will tell us if the optimization succeeded *on the last shadow processed* public static boolean appliedLazyTjpOptimization; // Some instructions have a target type that will vary // from the signature (pr109728) (1.4 declaring type issue) private String actualInstructionTargetType; /** * This generates an unassociated shadow, rooted in a particular method but not rooted to any particular point in the code. It * should be given to a rooted ShadowRange in the {@link ShadowRange#associateWithShadow(BcelShadow)} method. */ public BcelShadow(BcelWorld world, Kind kind, Member signature, LazyMethodGen enclosingMethod, BcelShadow enclosingShadow) { super(kind, signature, enclosingShadow); this.world = world; this.enclosingMethod = enclosingMethod; } // ---- copies all state, including Shadow's mungers... public BcelShadow copyInto(LazyMethodGen recipient, BcelShadow enclosing) { BcelShadow s = new BcelShadow(world, getKind(), getSignature(), recipient, enclosing); if (mungers.size() > 0) { List src = mungers; if (s.mungers == Collections.EMPTY_LIST) s.mungers = new ArrayList(); List dest = s.mungers; for (Iterator i = src.iterator(); i.hasNext();) { dest.add(i.next()); } } return s; } // ---- overridden behaviour public World getIWorld() { return world; } private void deleteNewAndDup() { final ConstantPool cpg = getEnclosingClass().getConstantPool(); int depth = 1; InstructionHandle ih = range.getStart(); // Go back from where we are looking for 'NEW' that takes us to a stack depth of 0. INVOKESPECIAL <init> while (true) { Instruction inst = ih.getInstruction(); if (inst.opcode == Constants.INVOKESPECIAL && ((InvokeInstruction) inst).getName(cpg).equals("<init>")) { depth++; } else if (inst.opcode == Constants.NEW) { depth--; if (depth == 0) break; } else if (inst.opcode == Constants.DUP_X2) { // This code seen in the wild (by Brad): // 40: new #12; //class java/lang/StringBuffer // STACK: STRINGBUFFER // 43: dup // STACK: STRINGBUFFER/STRINGBUFFER // 44: aload_0 // STACK: STRINGBUFFER/STRINGBUFFER/THIS // 45: dup_x2 // STACK: THIS/STRINGBUFFER/STRINGBUFFER/THIS // 46: getfield #36; //Field value:Ljava/lang/String; // STACK: THIS/STRINGBUFFER/STRINGBUFFER/STRING<value> // 49: invokestatic #37; //Method java/lang/String.valueOf:(Ljava/lang/Object;)Ljava/lang/String; // STACK: THIS/STRINGBUFFER/STRINGBUFFER/STRING // 52: invokespecial #19; //Method java/lang/StringBuffer."<init>":(Ljava/lang/String;)V // STACK: THIS/STRINGBUFFER // 55: aload_1 // STACK: THIS/STRINGBUFFER/LOCAL1 // 56: invokevirtual #22; //Method java/lang/StringBuffer.append:(Ljava/lang/String;)Ljava/lang/StringBuffer; // STACK: THIS/STRINGBUFFER // 59: invokevirtual #34; //Method java/lang/StringBuffer.toString:()Ljava/lang/String; // STACK: THIS/STRING // 62: putfield #36; //Field value:Ljava/lang/String; // STACK: <empty> // 65: return // if we attempt to match on the ctor call to StringBuffer.<init> then we get into trouble. // if we simply delete the new/dup pair without fixing up the dup_x2 then the dup_x2 will fail due to there // not being 3 elements on the stack for it to work with. The fix *in this situation* is to change it to // a simple 'dup' // this fix is *not* very clean - but a general purpose decent solution will take much longer and this // bytecode sequence has only been seen once in the wild. ih.setInstruction(InstructionConstants.DUP); } ih = ih.getPrev(); } // now IH points to the NEW. We're followed by the DUP, and that is followed // by the actual instruction we care about. InstructionHandle newHandle = ih; InstructionHandle endHandle = newHandle.getNext(); InstructionHandle nextHandle; if (endHandle.getInstruction().opcode == Constants.DUP) { nextHandle = endHandle.getNext(); retargetFrom(newHandle, nextHandle); retargetFrom(endHandle, nextHandle); } else if (endHandle.getInstruction().opcode == Constants.DUP_X1) { InstructionHandle dupHandle = endHandle; endHandle = endHandle.getNext(); nextHandle = endHandle.getNext(); if (endHandle.getInstruction().opcode == Constants.SWAP) { } else { // XXX see next XXX comment throw new RuntimeException("Unhandled kind of new " + endHandle); } // Now make any jumps to the 'new', the 'dup' or the 'end' now target the nextHandle retargetFrom(newHandle, nextHandle); retargetFrom(dupHandle, nextHandle); retargetFrom(endHandle, nextHandle); } else { endHandle = newHandle; nextHandle = endHandle.getNext(); retargetFrom(newHandle, nextHandle); // add a POP here... we found a NEW w/o a dup or anything else, so // we must be in statement context. getRange().insert(InstructionConstants.POP, Range.OutsideAfter); } // assert (dupHandle.getInstruction() instanceof DUP); try { range.getBody().delete(newHandle, endHandle); } catch (TargetLostException e) { throw new BCException("shouldn't happen"); } } private void retargetFrom(InstructionHandle old, InstructionHandle fresh) { InstructionTargeter[] sources = old.getTargetersArray(); if (sources != null) { for (int i = sources.length - 1; i >= 0; i--) { if (sources[i] instanceof ExceptionRange) { ExceptionRange it = (ExceptionRange) sources[i]; System.err.println("..."); it.updateTarget(old, fresh, it.getBody()); } else { sources[i].updateTarget(old, fresh); } } } } // records advice that is stopping us doing the lazyTjp optimization private List badAdvice = null; public void addAdvicePreventingLazyTjp(BcelAdvice advice) { if (badAdvice == null) badAdvice = new ArrayList(); badAdvice.add(advice); } protected void prepareForMungers() { // if we're a constructor call, we need to remove the new:dup or the new:dup_x1:swap, // and store all our // arguments on the frame. // ??? This is a bit of a hack (for the Java langauge). We do this because // we sometime add code "outsideBefore" when dealing with weaving join points. We only // do this for exposing state that is on the stack. It turns out to just work for // everything except for constructor calls and exception handlers. If we were to clean // this up, every ShadowRange would have three instructionHandle points, the start of // the arg-setup code, the start of the running code, and the end of the running code. if (getKind() == ConstructorCall) { if (!world.isJoinpointArrayConstructionEnabled() || !this.getSignature().getDeclaringType().isArray()) deleteNewAndDup(); // no new/dup for new array construction initializeArgVars(); } else if (getKind() == PreInitialization) { // pr74952 ShadowRange range = getRange(); range.insert(InstructionConstants.NOP, Range.InsideAfter); } else if (getKind() == ExceptionHandler) { ShadowRange range = getRange(); InstructionList body = range.getBody(); InstructionHandle start = range.getStart(); // Create a store instruction to put the value from the top of the // stack into a local variable slot. This is a trimmed version of // what is in initializeArgVars() (since there is only one argument // at a handler jp and only before advice is supported) (pr46298) argVars = new BcelVar[1]; // int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0); UnresolvedType tx = getArgType(0); argVars[0] = genTempVar(tx, "ajc$arg0"); InstructionHandle insertedInstruction = range.insert(argVars[0].createStore(getFactory()), Range.OutsideBefore); // Now the exception range starts just after our new instruction. // The next bit of code changes the exception range to point at // the store instruction InstructionTargeter[] targeters = start.getTargetersArray(); for (int i = 0; i < targeters.length; i++) { InstructionTargeter t = targeters[i]; if (t instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) t; er.updateTarget(start, insertedInstruction, body); } } } // now we ask each munger to request our state isThisJoinPointLazy = true;// world.isXlazyTjp(); // lazy is default now badAdvice = null; for (Iterator iter = mungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); munger.specializeOn(this); } initializeThisJoinPoint(); if (thisJoinPointVar != null && !isThisJoinPointLazy && badAdvice != null && badAdvice.size() > 1) { // something stopped us making it a lazy tjp // can't build tjp lazily, no suitable test... int valid = 0; for (Iterator iter = badAdvice.iterator(); iter.hasNext();) { BcelAdvice element = (BcelAdvice) iter.next(); ISourceLocation sLoc = element.getSourceLocation(); if (sLoc != null && sLoc.getLine() > 0) valid++; } if (valid != 0) { ISourceLocation[] badLocs = new ISourceLocation[valid]; int i = 0; for (Iterator iter = badAdvice.iterator(); iter.hasNext();) { BcelAdvice element = (BcelAdvice) iter.next(); ISourceLocation sLoc = element.getSourceLocation(); if (sLoc != null) badLocs[i++] = sLoc; } world.getLint().multipleAdviceStoppingLazyTjp .signal(new String[] { this.toString() }, getSourceLocation(), badLocs); } } badAdvice = null; // If we are an expression kind, we require our target/arguments on the stack // before we do our actual thing. However, they may have been removed // from the stack as the shadowMungers have requested state. // if any of our shadowMungers requested either the arguments or target, // the munger will have added code // to pop the target/arguments into temporary variables, represented by // targetVar and argVars. In such a case, we must make sure to re-push the // values. // If we are nonExpressionKind, we don't expect arguments on the stack // so this is moot. If our argVars happen to be null, then we know that // no ShadowMunger has squirrelled away our arguments, so they're still // on the stack. InstructionFactory fact = getFactory(); if (getKind().argsOnStack() && argVars != null) { // Special case first (pr46298). If we are an exception handler and the instruction // just after the shadow is a POP then we should remove the pop. The code // above which generated the store instruction has already cleared the stack. // We also don't generate any code for the arguments in this case as it would be // an incorrect aload. if (getKind() == ExceptionHandler && range.getEnd().getNext().getInstruction().equals(InstructionConstants.POP)) { // easier than deleting it ... range.getEnd().getNext().setInstruction(InstructionConstants.NOP); } else { range.insert(BcelRenderer.renderExprs(fact, world, argVars), Range.InsideBefore); if (targetVar != null) { range.insert(BcelRenderer.renderExpr(fact, world, targetVar), Range.InsideBefore); } if (getKind() == ConstructorCall) { if (!world.isJoinpointArrayConstructionEnabled() || !this.getSignature().getDeclaringType().isArray()) { range.insert(InstructionFactory.createDup(1), Range.InsideBefore); range.insert(fact.createNew((ObjectType) BcelWorld.makeBcelType(getSignature().getDeclaringType())), Range.InsideBefore); } } } } } // ---- getters public ShadowRange getRange() { return range; } public void setRange(ShadowRange range) { this.range = range; } private int sourceline = -1; public int getSourceLine() { // if the kind of join point for which we are a shadow represents // a method or constructor execution, then the best source line is // the one from the enclosingMethod declarationLineNumber if available. if (sourceline != -1) return sourceline; Kind kind = getKind(); if ((kind == MethodExecution) || (kind == ConstructorExecution) || (kind == AdviceExecution) || (kind == StaticInitialization) || (kind == PreInitialization) || (kind == Initialization)) { if (getEnclosingMethod().hasDeclaredLineNumberInfo()) { sourceline = getEnclosingMethod().getDeclarationLineNumber(); return sourceline; } } if (range == null) { if (getEnclosingMethod().hasBody()) { sourceline = Utility.getSourceLine(getEnclosingMethod().getBody().getStart()); return sourceline; } else { sourceline = 0; return sourceline; } } sourceline = Utility.getSourceLine(range.getStart()); if (sourceline < 0) sourceline = 0; return sourceline; } // overrides public UnresolvedType getEnclosingType() { return getEnclosingClass().getType(); } public LazyClassGen getEnclosingClass() { return enclosingMethod.getEnclosingClass(); } public BcelWorld getWorld() { return world; } // ---- factory methods public static BcelShadow makeConstructorExecution(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle justBeforeStart) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow(world, ConstructorExecution, world.makeJoinPointSignatureFromMethod(enclosingMethod, Member.CONSTRUCTOR), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body, justBeforeStart.getNext()), Range.genEnd(body)); return s; } public static BcelShadow makeStaticInitialization(BcelWorld world, LazyMethodGen enclosingMethod) { InstructionList body = enclosingMethod.getBody(); // move the start past ajc$preClinit InstructionHandle clinitStart = body.getStart(); if (clinitStart.getInstruction() instanceof InvokeInstruction) { InvokeInstruction ii = (InvokeInstruction) clinitStart.getInstruction(); if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPool()).equals(NameMangler.AJC_PRE_CLINIT_NAME)) { clinitStart = clinitStart.getNext(); } } InstructionHandle clinitEnd = body.getEnd(); // XXX should move the end before the postClinit, but the return is then tricky... // if (clinitEnd.getInstruction() instanceof InvokeInstruction) { // InvokeInstruction ii = (InvokeInstruction)clinitEnd.getInstruction(); // if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPool()).equals(NameMangler.AJC_POST_CLINIT_NAME)) { // clinitEnd = clinitEnd.getPrev(); // } // } BcelShadow s = new BcelShadow(world, StaticInitialization, world.makeJoinPointSignatureFromMethod(enclosingMethod, Member.STATIC_INITIALIZATION), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body, clinitStart), Range.genEnd(body, clinitEnd)); return s; } /** * Make the shadow for an exception handler. Currently makes an empty shadow that only allows before advice to be woven into it. */ public static BcelShadow makeExceptionHandler(BcelWorld world, ExceptionRange exceptionRange, LazyMethodGen enclosingMethod, InstructionHandle startOfHandler, BcelShadow enclosingShadow) { InstructionList body = enclosingMethod.getBody(); UnresolvedType catchType = exceptionRange.getCatchType(); UnresolvedType inType = enclosingMethod.getEnclosingClass().getType(); ResolvedMemberImpl sig = MemberImpl.makeExceptionHandlerSignature(inType, catchType); sig.setParameterNames(new String[] { findHandlerParamName(startOfHandler) }); BcelShadow s = new BcelShadow(world, ExceptionHandler, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); InstructionHandle start = Range.genStart(body, startOfHandler); InstructionHandle end = Range.genEnd(body, start); r.associateWithTargets(start, end); exceptionRange.updateTarget(startOfHandler, start, body); return s; } private static String findHandlerParamName(InstructionHandle startOfHandler) { if (startOfHandler.getInstruction().isStoreInstruction() && startOfHandler.getNext() != null) { int slot = startOfHandler.getInstruction().getIndex(); // System.out.println("got store: " + startOfHandler.getInstruction() + ", " + index); Iterator tIter = startOfHandler.getNext().getTargeters().iterator(); while (tIter.hasNext()) { InstructionTargeter targeter = (InstructionTargeter) tIter.next(); if (targeter instanceof LocalVariableTag) { LocalVariableTag t = (LocalVariableTag) targeter; if (t.getSlot() == slot) { return t.getName(); } } } } return "<missing>"; } /** create an init join point associated w/ an interface in the body of a constructor */ public static BcelShadow makeIfaceInitialization(BcelWorld world, LazyMethodGen constructor, Member interfaceConstructorSignature) { // this call marks the instruction list as changed constructor.getBody(); // UnresolvedType inType = constructor.getEnclosingClass().getType(); BcelShadow s = new BcelShadow(world, Initialization, interfaceConstructorSignature, constructor, null); // s.fallsThrough = true; // ShadowRange r = new ShadowRange(body); // r.associateWithShadow(s); // InstructionHandle start = Range.genStart(body, handle); // InstructionHandle end = Range.genEnd(body, handle); // // r.associateWithTargets(start, end); return s; } public void initIfaceInitializer(InstructionHandle end) { final InstructionList body = enclosingMethod.getBody(); ShadowRange r = new ShadowRange(body); r.associateWithShadow(this); InstructionHandle nop = body.insert(end, InstructionConstants.NOP); r.associateWithTargets(Range.genStart(body, nop), Range.genEnd(body, nop)); } // public static BcelShadow makeIfaceConstructorExecution( // BcelWorld world, // LazyMethodGen constructor, // InstructionHandle next, // Member interfaceConstructorSignature) // { // // final InstructionFactory fact = constructor.getEnclosingClass().getFactory(); // InstructionList body = constructor.getBody(); // // UnresolvedType inType = constructor.getEnclosingClass().getType(); // BcelShadow s = // new BcelShadow( // world, // ConstructorExecution, // interfaceConstructorSignature, // constructor, // null); // s.fallsThrough = true; // ShadowRange r = new ShadowRange(body); // r.associateWithShadow(s); // // ??? this may or may not work // InstructionHandle start = Range.genStart(body, next); // //InstructionHandle end = Range.genEnd(body, body.append(start, fact.NOP)); // InstructionHandle end = Range.genStart(body, next); // //body.append(start, fact.NOP); // // r.associateWithTargets(start, end); // return s; // } /** * Create an initialization join point associated with a constructor, but not with any body of code yet. If this is actually * matched, it's range will be set when we inline self constructors. * * @param constructor The constructor starting this initialization. */ public static BcelShadow makeUnfinishedInitialization(BcelWorld world, LazyMethodGen constructor) { BcelShadow ret = new BcelShadow(world, Initialization, world.makeJoinPointSignatureFromMethod(constructor, Member.CONSTRUCTOR), constructor, null); if (constructor.getEffectiveSignature() != null) { ret.setMatchingSignature(constructor.getEffectiveSignature().getEffectiveSignature()); } return ret; } public static BcelShadow makeUnfinishedPreinitialization(BcelWorld world, LazyMethodGen constructor) { BcelShadow ret = new BcelShadow(world, PreInitialization, world.makeJoinPointSignatureFromMethod(constructor, Member.CONSTRUCTOR), constructor, null); if (constructor.getEffectiveSignature() != null) { ret.setMatchingSignature(constructor.getEffectiveSignature().getEffectiveSignature()); } return ret; } public static BcelShadow makeMethodExecution(BcelWorld world, LazyMethodGen enclosingMethod, boolean lazyInit) { if (!lazyInit) return makeMethodExecution(world, enclosingMethod); BcelShadow s = new BcelShadow(world, MethodExecution, enclosingMethod.getMemberView(), enclosingMethod, null); return s; } public void init() { if (range != null) return; final InstructionList body = enclosingMethod.getBody(); ShadowRange r = new ShadowRange(body); r.associateWithShadow(this); r.associateWithTargets(Range.genStart(body), Range.genEnd(body)); } public static BcelShadow makeMethodExecution(BcelWorld world, LazyMethodGen enclosingMethod) { return makeShadowForMethod(world, enclosingMethod, MethodExecution, enclosingMethod.getMemberView()); } public static BcelShadow makeShadowForMethod(BcelWorld world, LazyMethodGen enclosingMethod, Shadow.Kind kind, Member sig) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow(world, kind, sig, enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(// OPTIMIZE this occurs lots of times for all jp kinds... Range.genStart(body), Range.genEnd(body)); return s; } public static BcelShadow makeAdviceExecution(BcelWorld world, LazyMethodGen enclosingMethod) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow(world, AdviceExecution, world .makeJoinPointSignatureFromMethod(enclosingMethod, Member.ADVICE), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body), Range.genEnd(body)); return s; } // constructor call shadows are <em>initially</em> just around the // call to the constructor. If ANY advice gets put on it, we move // the NEW instruction inside the join point, which involves putting // all the arguments in temps. public static BcelShadow makeConstructorCall(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); Member sig = world.makeJoinPointSignatureForMethodInvocation(enclosingMethod.getEnclosingClass(), (InvokeInstruction) callHandle.getInstruction()); BcelShadow s = new BcelShadow(world, ConstructorCall, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeArrayConstructorCall(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle arrayInstruction, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); Member sig = world.makeJoinPointSignatureForArrayConstruction(enclosingMethod.getEnclosingClass(), arrayInstruction); BcelShadow s = new BcelShadow(world, ConstructorCall, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body, arrayInstruction), Range.genEnd(body, arrayInstruction)); retargetAllBranches(arrayInstruction, r.getStart()); return s; } public static BcelShadow makeMonitorEnter(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle monitorInstruction, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); Member sig = world.makeJoinPointSignatureForMonitorEnter(enclosingMethod.getEnclosingClass(), monitorInstruction); BcelShadow s = new BcelShadow(world, SynchronizationLock, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body, monitorInstruction), Range.genEnd(body, monitorInstruction)); retargetAllBranches(monitorInstruction, r.getStart()); return s; } public static BcelShadow makeMonitorExit(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle monitorInstruction, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); Member sig = world.makeJoinPointSignatureForMonitorExit(enclosingMethod.getEnclosingClass(), monitorInstruction); BcelShadow s = new BcelShadow(world, SynchronizationUnlock, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body, monitorInstruction), Range.genEnd(body, monitorInstruction)); retargetAllBranches(monitorInstruction, r.getStart()); return s; } // see pr77166 // public static BcelShadow makeArrayLoadCall( // BcelWorld world, // LazyMethodGen enclosingMethod, // InstructionHandle arrayInstruction, // BcelShadow enclosingShadow) // { // final InstructionList body = enclosingMethod.getBody(); // Member sig = world.makeJoinPointSignatureForArrayLoad(enclosingMethod.getEnclosingClass(),arrayInstruction); // BcelShadow s = // new BcelShadow( // world, // MethodCall, // sig, // enclosingMethod, // enclosingShadow); // ShadowRange r = new ShadowRange(body); // r.associateWithShadow(s); // r.associateWithTargets( // Range.genStart(body, arrayInstruction), // Range.genEnd(body, arrayInstruction)); // retargetAllBranches(arrayInstruction, r.getStart()); // return s; // } public static BcelShadow makeMethodCall(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow(world, MethodCall, world.makeJoinPointSignatureForMethodInvocation(enclosingMethod .getEnclosingClass(), (InvokeInstruction) callHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeShadowForMethodCall(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow, Kind kind, ResolvedMember sig) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow(world, kind, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeFieldGet(BcelWorld world, ResolvedMember field, LazyMethodGen enclosingMethod, InstructionHandle getHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow(world, FieldGet, field, // BcelWorld.makeFieldSignature( // enclosingMethod.getEnclosingClass(), // (FieldInstruction) getHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body, getHandle), Range.genEnd(body, getHandle)); retargetAllBranches(getHandle, r.getStart()); return s; } public static BcelShadow makeFieldSet(BcelWorld world, ResolvedMember field, LazyMethodGen enclosingMethod, InstructionHandle setHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow(world, FieldSet, field, // BcelWorld.makeFieldJoinPointSignature( // enclosingMethod.getEnclosingClass(), // (FieldInstruction) setHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body, setHandle), Range.genEnd(body, setHandle)); retargetAllBranches(setHandle, r.getStart()); return s; } public static void retargetAllBranches(InstructionHandle from, InstructionHandle to) { InstructionTargeter[] sources = from.getTargetersArray(); if (sources != null) { for (int i = sources.length - 1; i >= 0; i--) { InstructionTargeter source = sources[i]; if (source instanceof InstructionBranch) { source.updateTarget(from, to); } } } } // // ---- type access methods // private ObjectType getTargetBcelType() { // return (ObjectType) BcelWorld.makeBcelType(getTargetType()); // } // private Type getArgBcelType(int arg) { // return BcelWorld.makeBcelType(getArgType(arg)); // } // ---- kinding /** * If the end of my range has no real instructions following then my context needs a return at the end. */ public boolean terminatesWithReturn() { return getRange().getRealNext() == null; } /** * Is arg0 occupied with the value of this */ public boolean arg0HoldsThis() { if (getKind().isEnclosingKind()) { return !getSignature().isStatic(); } else if (enclosingShadow == null) { // XXX this is mostly right // this doesn't do the right thing for calls in the pre part of introduced constructors. return !enclosingMethod.isStatic(); } else { return ((BcelShadow) enclosingShadow).arg0HoldsThis(); } } // ---- argument getting methods private BcelVar thisVar = null; private BcelVar targetVar = null; private BcelVar[] argVars = null; private Map/* <UnresolvedType,BcelVar> */kindedAnnotationVars = null; private Map/* <UnresolvedType,BcelVar> */thisAnnotationVars = null; private Map/* <UnresolvedType,BcelVar> */targetAnnotationVars = null; private Map/* <UnresolvedType,BcelVar> */[] argAnnotationVars = null; private Map/* <UnresolvedType,BcelVar> */withinAnnotationVars = null; private Map/* <UnresolvedType,BcelVar> */withincodeAnnotationVars = null; private boolean allArgVarsInitialized = false; public Var getThisVar() { if (!hasThis()) { throw new IllegalStateException("no this"); } initializeThisVar(); return thisVar; } public Var getThisAnnotationVar(UnresolvedType forAnnotationType) { if (!hasThis()) { throw new IllegalStateException("no this"); } initializeThisAnnotationVars(); // FIXME asc Why bother with this if we always return one? // Even if we can't find one, we have to return one as we might have this annotation at runtime Var v = (Var) thisAnnotationVars.get(forAnnotationType); if (v == null) v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world), (BcelVar) getThisVar()); return v; } public Var getTargetVar() { if (!hasTarget()) { throw new IllegalStateException("no target"); } initializeTargetVar(); return targetVar; } public Var getTargetAnnotationVar(UnresolvedType forAnnotationType) { if (!hasTarget()) { throw new IllegalStateException("no target"); } initializeTargetAnnotationVars(); // FIXME asc why bother with this if we always return one? Var v = (Var) targetAnnotationVars.get(forAnnotationType); // Even if we can't find one, we have to return one as we might have this annotation at runtime if (v == null) v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world), (BcelVar) getTargetVar()); return v; } public Var getArgVar(int i) { ensureInitializedArgVar(i); return argVars[i]; } public Var getArgAnnotationVar(int i, UnresolvedType forAnnotationType) { initializeArgAnnotationVars(); Var v = (Var) argAnnotationVars[i].get(forAnnotationType); if (v == null) v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world), (BcelVar) getArgVar(i)); return v; } public Var getKindedAnnotationVar(UnresolvedType forAnnotationType) { initializeKindedAnnotationVars(); return (Var) kindedAnnotationVars.get(forAnnotationType); } public Var getWithinAnnotationVar(UnresolvedType forAnnotationType) { initializeWithinAnnotationVars(); return (Var) withinAnnotationVars.get(forAnnotationType); } public Var getWithinCodeAnnotationVar(UnresolvedType forAnnotationType) { initializeWithinCodeAnnotationVars(); return (Var) withincodeAnnotationVars.get(forAnnotationType); } // reflective thisJoinPoint support private BcelVar thisJoinPointVar = null; private boolean isThisJoinPointLazy; private int lazyTjpConsumers = 0; private BcelVar thisJoinPointStaticPartVar = null; // private BcelVar thisEnclosingJoinPointStaticPartVar = null; public final Var getThisJoinPointStaticPartVar() { return getThisJoinPointStaticPartBcelVar(); } public final Var getThisEnclosingJoinPointStaticPartVar() { return getThisEnclosingJoinPointStaticPartBcelVar(); } public void requireThisJoinPoint(boolean hasGuardTest, boolean isAround) { if (!isAround) { if (!hasGuardTest) { isThisJoinPointLazy = false; } else { lazyTjpConsumers++; } } // if (!hasGuardTest) { // isThisJoinPointLazy = false; // } else { // lazyTjpConsumers++; // } if (thisJoinPointVar == null) { thisJoinPointVar = genTempVar(UnresolvedType.forName("org.aspectj.lang.JoinPoint")); } } public Var getThisJoinPointVar() { requireThisJoinPoint(false, false); return thisJoinPointVar; } void initializeThisJoinPoint() { if (thisJoinPointVar == null) return; if (isThisJoinPointLazy) { isThisJoinPointLazy = checkLazyTjp(); } if (isThisJoinPointLazy) { appliedLazyTjpOptimization = true; createThisJoinPoint(); // make sure any state needed is initialized, but throw the instructions out if (lazyTjpConsumers == 1) return; // special case only one lazyTjpUser InstructionFactory fact = getFactory(); InstructionList il = new InstructionList(); il.append(InstructionConstants.ACONST_NULL); il.append(thisJoinPointVar.createStore(fact)); range.insert(il, Range.OutsideBefore); } else { appliedLazyTjpOptimization = false; InstructionFactory fact = getFactory(); InstructionList il = createThisJoinPoint(); il.append(thisJoinPointVar.createStore(fact)); range.insert(il, Range.OutsideBefore); } } private boolean checkLazyTjp() { // check for around advice for (Iterator i = mungers.iterator(); i.hasNext();) { ShadowMunger munger = (ShadowMunger) i.next(); if (munger instanceof Advice) { if (((Advice) munger).getKind() == AdviceKind.Around) { if (munger.getSourceLocation() != null) { // do we know enough to bother reporting? if (world.getLint().canNotImplementLazyTjp.isEnabled()) { world.getLint().canNotImplementLazyTjp.signal(new String[] { toString() }, getSourceLocation(), new ISourceLocation[] { munger.getSourceLocation() }); } } return false; } } } return true; } InstructionList loadThisJoinPoint() { InstructionFactory fact = getFactory(); InstructionList il = new InstructionList(); if (isThisJoinPointLazy) { // If we're lazy, build the join point right here. il.append(createThisJoinPoint()); // Does someone else need it? If so, store it for later retrieval if (lazyTjpConsumers > 1) { il.append(thisJoinPointVar.createStore(fact)); InstructionHandle end = il.append(thisJoinPointVar.createLoad(fact)); il.insert(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, end)); il.insert(thisJoinPointVar.createLoad(fact)); } } else { // If not lazy, its already been built and stored, just retrieve it thisJoinPointVar.appendLoad(il, fact); } return il; } InstructionList createThisJoinPoint() { InstructionFactory fact = getFactory(); InstructionList il = new InstructionList(); BcelVar staticPart = getThisJoinPointStaticPartBcelVar(); staticPart.appendLoad(il, fact); if (hasThis()) { ((BcelVar) getThisVar()).appendLoad(il, fact); } else { il.append(InstructionConstants.ACONST_NULL); } if (hasTarget()) { ((BcelVar) getTargetVar()).appendLoad(il, fact); } else { il.append(InstructionConstants.ACONST_NULL); } switch (getArgCount()) { case 0: il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT }, Constants.INVOKESTATIC)); break; case 1: ((BcelVar) getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT)); il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, Type.OBJECT }, Constants.INVOKESTATIC)); break; case 2: ((BcelVar) getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT)); ((BcelVar) getArgVar(1)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT)); il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, Type.OBJECT, Type.OBJECT }, Constants.INVOKESTATIC)); break; default: il.append(makeArgsObjectArray()); il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, new ArrayType(Type.OBJECT, 1) }, Constants.INVOKESTATIC)); break; } return il; } /** * Get the Var for the jpStaticPart * * @return */ public BcelVar getThisJoinPointStaticPartBcelVar() { return getThisJoinPointStaticPartBcelVar(false); } /** * Get the Var for the xxxxJpStaticPart, xxx = this or enclosing * * @param isEnclosingJp true to have the enclosingJpStaticPart * @return */ public BcelVar getThisJoinPointStaticPartBcelVar(final boolean isEnclosingJp) { if (thisJoinPointStaticPartVar == null) { Field field = getEnclosingClass().getTjpField(this, isEnclosingJp); ResolvedType sjpType = null; if (world.isTargettingAspectJRuntime12()) { // TAG:SUPPORTING12: We didn't have different jpsp types in 1.2 sjpType = world.getCoreType(UnresolvedType.JOINPOINT_STATICPART); } else { sjpType = isEnclosingJp ? world.getCoreType(UnresolvedType.JOINPOINT_ENCLOSINGSTATICPART) : world .getCoreType(UnresolvedType.JOINPOINT_STATICPART); } thisJoinPointStaticPartVar = new BcelFieldRef(sjpType, getEnclosingClass().getClassName(), field.getName()); // getEnclosingClass().warnOnAddedStaticInitializer(this,munger.getSourceLocation()); } return thisJoinPointStaticPartVar; } /** * Get the Var for the enclosingJpStaticPart * * @return */ public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() { if (enclosingShadow == null) { // the enclosing of an execution is itself return getThisJoinPointStaticPartBcelVar(true); } else { return ((BcelShadow) enclosingShadow).getThisJoinPointStaticPartBcelVar(true); } } // ??? need to better understand all the enclosing variants public Member getEnclosingCodeSignature() { if (getKind().isEnclosingKind()) { return getSignature(); } else if (getKind() == Shadow.PreInitialization) { // PreInit doesn't enclose code but its signature // is correctly the signature of the ctor. return getSignature(); } else if (enclosingShadow == null) { return getEnclosingMethod().getMemberView(); } else { return enclosingShadow.getSignature(); } } private InstructionList makeArgsObjectArray() { InstructionFactory fact = getFactory(); BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY); final InstructionList il = new InstructionList(); int alen = getArgCount(); il.append(Utility.createConstant(fact, alen)); il.append(fact.createNewArray(Type.OBJECT, (short) 1)); arrayVar.appendStore(il, fact); int stateIndex = 0; for (int i = 0, len = getArgCount(); i < len; i++) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, (BcelVar) getArgVar(i)); stateIndex++; } arrayVar.appendLoad(il, fact); return il; } // ---- initializing var tables /* * initializing this is doesn't do anything, because this is protected from side-effects, so we don't need to copy its location */ private void initializeThisVar() { if (thisVar != null) return; thisVar = new BcelVar(getThisType().resolve(world), 0); thisVar.setPositionInAroundState(0); } public void initializeTargetVar() { InstructionFactory fact = getFactory(); if (targetVar != null) return; if (getKind().isTargetSameAsThis()) { if (hasThis()) initializeThisVar(); targetVar = thisVar; } else { initializeArgVars(); // gotta pop off the args before we find the target UnresolvedType type = getTargetType(); type = ensureTargetTypeIsCorrect(type); targetVar = genTempVar(type, "ajc$target"); range.insert(targetVar.createStore(fact), Range.OutsideBefore); targetVar.setPositionInAroundState(hasThis() ? 1 : 0); } } /* * PR 72528 This method double checks the target type under certain conditions. The Java 1.4 compilers seem to take calls to * clone methods on array types and create bytecode that looks like clone is being called on Object. If we advise a clone call * with around advice we extract the call into a helper method which we can then refer to. Because the type in the bytecode for * the call to clone is Object we create a helper method with an Object parameter - this is not correct as we have lost the fact * that the actual type is an array type. If we don't do the check below we will create code that fails java verification. This * method checks for the peculiar set of conditions and if they are true, it has a sneak peek at the code before the call to see * what is on the stack. */ public UnresolvedType ensureTargetTypeIsCorrect(UnresolvedType tx) { Member msig = getSignature(); if (msig.getArity() == 0 && getKind() == MethodCall && msig.getName().charAt(0) == 'c' && tx.equals(ResolvedType.OBJECT) && msig.getReturnType().equals(ResolvedType.OBJECT) && msig.getName().equals("clone")) { // Lets go back through the code from the start of the shadow InstructionHandle searchPtr = range.getStart().getPrev(); while (Range.isRangeHandle(searchPtr) || searchPtr.getInstruction().isStoreInstruction()) { // ignore this instruction - // it doesnt give us the // info we want searchPtr = searchPtr.getPrev(); } // A load instruction may tell us the real type of what the clone() call is on if (searchPtr.getInstruction().isLoadInstruction()) { LocalVariableTag lvt = LazyMethodGen.getLocalVariableTag(searchPtr, searchPtr.getInstruction().getIndex()); if (lvt != null) return UnresolvedType.forSignature(lvt.getType()); } // A field access instruction may tell us the real type of what the clone() call is on if (searchPtr.getInstruction() instanceof FieldInstruction) { FieldInstruction si = (FieldInstruction) searchPtr.getInstruction(); Type t = si.getFieldType(getEnclosingClass().getConstantPool()); return BcelWorld.fromBcel(t); } // A new array instruction obviously tells us it is an array type ! if (searchPtr.getInstruction().opcode == Constants.ANEWARRAY) { // ANEWARRAY ana = (ANEWARRAY)searchPoint.getInstruction(); // Type t = ana.getType(getEnclosingClass().getConstantPool()); // Just use a standard java.lang.object array - that will work fine return BcelWorld.fromBcel(new ArrayType(Type.OBJECT, 1)); } // A multi new array instruction obviously tells us it is an array type ! if (searchPtr.getInstruction() instanceof MULTIANEWARRAY) { MULTIANEWARRAY ana = (MULTIANEWARRAY) searchPtr.getInstruction(); // Type t = ana.getType(getEnclosingClass().getConstantPool()); // t = new ArrayType(t,ana.getDimensions()); // Just use a standard java.lang.object array - that will work fine return BcelWorld.fromBcel(new ArrayType(Type.OBJECT, ana.getDimensions())); } throw new BCException("Can't determine real target of clone() when processing instruction " + searchPtr.getInstruction() + ". Perhaps avoid selecting clone with your pointcut?"); } return tx; } public void ensureInitializedArgVar(int argNumber) { if (allArgVarsInitialized || (argVars != null && argVars[argNumber] != null)) { return; } InstructionFactory fact = getFactory(); int len = getArgCount(); if (argVars == null) { argVars = new BcelVar[len]; } // Need to initialize argument i int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0); if (getKind().argsOnStack()) { // Let's just do them all now since they are on the stack // we move backwards because we're popping off the stack for (int i = len - 1; i >= 0; i--) { UnresolvedType type = getArgType(i); BcelVar tmp = genTempVar(type, "ajc$arg" + i); range.insert(tmp.createStore(getFactory()), Range.OutsideBefore); int position = i; position += positionOffset; tmp.setPositionInAroundState(position); argVars[i] = tmp; } allArgVarsInitialized = true; } else { int index = 0; if (arg0HoldsThis()) { index++; } boolean allInited = true; for (int i = 0; i < len; i++) { UnresolvedType type = getArgType(i); if (i == argNumber) { argVars[argNumber] = genTempVar(type, "ajc$arg" + argNumber); range.insert(argVars[argNumber].createCopyFrom(fact, index), Range.OutsideBefore); argVars[argNumber].setPositionInAroundState(argNumber + positionOffset); } allInited = allInited && argVars[i] != null; index += type.getSize(); } if (allInited && (argNumber + 1) == len) { allArgVarsInitialized = true; } } } /** * Initialize all the available arguments at the shadow. This means creating a copy of them that we can then use for advice * calls (the copy ensures we are not affected by other advice changing the values). This method initializes all arguments * whereas the method ensureInitializedArgVar will only ensure a single argument is setup. */ public void initializeArgVars() { if (allArgVarsInitialized) { return; } InstructionFactory fact = getFactory(); int len = getArgCount(); if (argVars == null) { argVars = new BcelVar[len]; } int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0); if (getKind().argsOnStack()) { // we move backwards because we're popping off the stack for (int i = len - 1; i >= 0; i--) { UnresolvedType type = getArgType(i); BcelVar tmp = genTempVar(type, "ajc$arg" + i); range.insert(tmp.createStore(getFactory()), Range.OutsideBefore); int position = i; position += positionOffset; tmp.setPositionInAroundState(position); argVars[i] = tmp; } } else { int index = 0; if (arg0HoldsThis()) { index++; } for (int i = 0; i < len; i++) { UnresolvedType type = getArgType(i); if (argVars[i] == null) { BcelVar tmp = genTempVar(type, "ajc$arg" + i); range.insert(tmp.createCopyFrom(fact, index), Range.OutsideBefore); argVars[i] = tmp; tmp.setPositionInAroundState(i + positionOffset); } index += type.getSize(); } } allArgVarsInitialized = true; } public void initializeForAroundClosure() { initializeArgVars(); if (hasTarget()) initializeTargetVar(); if (hasThis()) initializeThisVar(); // System.out.println("initialized: " + this + " thisVar = " + thisVar); } public void initializeThisAnnotationVars() { if (thisAnnotationVars != null) return; thisAnnotationVars = new HashMap(); // populate.. } public void initializeTargetAnnotationVars() { if (targetAnnotationVars != null) return; if (getKind().isTargetSameAsThis()) { if (hasThis()) initializeThisAnnotationVars(); targetAnnotationVars = thisAnnotationVars; } else { targetAnnotationVars = new HashMap(); ResolvedType[] rtx = this.getTargetType().resolve(world).getAnnotationTypes(); // what about annotations we havent // gotten yet but we will get in // subclasses? for (int i = 0; i < rtx.length; i++) { ResolvedType typeX = rtx[i]; targetAnnotationVars.put(typeX, new TypeAnnotationAccessVar(typeX, (BcelVar) getTargetVar())); } // populate. } } public void initializeArgAnnotationVars() { if (argAnnotationVars != null) return; int numArgs = getArgCount(); argAnnotationVars = new Map[numArgs]; for (int i = 0; i < argAnnotationVars.length; i++) { argAnnotationVars[i] = new HashMap(); // FIXME asc just delete this logic - we always build the Var on demand, as we don't know at weave time // what the full set of annotations could be (due to static/dynamic type differences...) } } protected ResolvedMember getRelevantMember(ResolvedMember foundMember, Member relevantMember, ResolvedType relevantType) { if (foundMember != null) { return foundMember; } foundMember = getSignature().resolve(world); if (foundMember == null && relevantMember != null) { foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember); } // check the ITD'd dooberries List mungers = relevantType.resolve(world).getInterTypeMungers(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next(); if (typeMunger.getMunger() instanceof NewMethodTypeMunger || typeMunger.getMunger() instanceof NewConstructorTypeMunger) { ResolvedMember fakerm = typeMunger.getSignature(); if (fakerm.getName().equals(getSignature().getName()) && fakerm.getParameterSignature().equals(getSignature().getParameterSignature())) { if (foundMember.getKind() == ResolvedMember.CONSTRUCTOR) { foundMember = AjcMemberMaker.interConstructor(relevantType, foundMember, typeMunger.getAspectType()); } else { foundMember = AjcMemberMaker.interMethod(foundMember, typeMunger.getAspectType(), false); } // in the above.. what about if it's on an Interface? Can that happen? // then the last arg of the above should be true return foundMember; } } } return foundMember; } protected ResolvedType[] getAnnotations(ResolvedMember foundMember, Member relevantMember, ResolvedType relevantType) { if (foundMember == null) { // check the ITD'd dooberries List mungers = relevantType.resolve(world).getInterTypeMungers(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next(); if (typeMunger.getMunger() instanceof NewMethodTypeMunger || typeMunger.getMunger() instanceof NewConstructorTypeMunger) { ResolvedMember fakerm = typeMunger.getSignature(); // if (fakerm.hasAnnotations()) ResolvedMember ajcMethod = (getSignature().getKind() == ResolvedMember.CONSTRUCTOR ? AjcMemberMaker .postIntroducedConstructor(typeMunger.getAspectType(), fakerm.getDeclaringType(), fakerm .getParameterTypes()) : AjcMemberMaker .interMethodDispatcher(fakerm, typeMunger.getAspectType())); // AjcMemberMaker.interMethodBody(fakerm,typeMunger.getAspectType())); ResolvedMember rmm = findMethod(typeMunger.getAspectType(), ajcMethod); if (fakerm.getName().equals(getSignature().getName()) && fakerm.getParameterSignature().equals(getSignature().getParameterSignature())) { relevantType = typeMunger.getAspectType(); foundMember = rmm; return foundMember.getAnnotationTypes(); } } } // didn't find in ITDs, look in supers foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember); if (foundMember == null) { throw new IllegalStateException("Couldn't find member " + relevantMember + " for type " + relevantType); } } return foundMember.getAnnotationTypes(); } /** * By determining what "kind" of shadow we are, we can find out the annotations on the appropriate element (method, field, * constructor, type). Then create one BcelVar entry in the map for each annotation, keyed by annotation type. */ public void initializeKindedAnnotationVars() { if (kindedAnnotationVars != null) { return; } kindedAnnotationVars = new HashMap(); ResolvedType[] annotations = null; Member shadowSignature = getSignature(); Member annotationHolder = getSignature(); ResolvedType relevantType = shadowSignature.getDeclaringType().resolve(world); if (relevantType.isRawType() || relevantType.isParameterizedType()) { relevantType = relevantType.getGenericType(); } // Determine the annotations that are of interest if (getKind() == Shadow.StaticInitialization) { annotations = relevantType.resolve(world).getAnnotationTypes(); } else if (getKind() == Shadow.MethodCall || getKind() == Shadow.ConstructorCall) { ResolvedMember foundMember = findMethod2(relevantType.resolve(world).getDeclaredMethods(), getSignature()); annotations = getAnnotations(foundMember, shadowSignature, relevantType); annotationHolder = getRelevantMember(foundMember, shadowSignature, relevantType); relevantType = annotationHolder.getDeclaringType().resolve(world); } else if (getKind() == Shadow.FieldSet || getKind() == Shadow.FieldGet) { annotationHolder = findField(relevantType.getDeclaredFields(), getSignature()); if (annotationHolder == null) { // check the ITD'd dooberries List mungers = relevantType.resolve(world).getInterTypeMungers(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next(); if (typeMunger.getMunger() instanceof NewFieldTypeMunger) { ResolvedMember fakerm = typeMunger.getSignature(); // if (fakerm.hasAnnotations()) ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm, typeMunger.getAspectType()); ResolvedMember rmm = findMethod(typeMunger.getAspectType(), ajcMethod); if (fakerm.equals(getSignature())) { relevantType = typeMunger.getAspectType(); annotationHolder = rmm; } } } } annotations = ((ResolvedMember) annotationHolder).getAnnotationTypes(); } else if (getKind() == Shadow.MethodExecution || getKind() == Shadow.ConstructorExecution || getKind() == Shadow.AdviceExecution) { // ResolvedMember rm[] = relevantType.getDeclaredMethods(); ResolvedMember foundMember = findMethod2(relevantType.getDeclaredMethods(), getSignature()); annotations = getAnnotations(foundMember, shadowSignature, relevantType); annotationHolder = foundMember; annotationHolder = getRelevantMember(foundMember, annotationHolder, relevantType); } else if (getKind() == Shadow.ExceptionHandler) { relevantType = getSignature().getParameterTypes()[0].resolve(world); annotations = relevantType.getAnnotationTypes(); } else if (getKind() == Shadow.PreInitialization || getKind() == Shadow.Initialization) { ResolvedMember found = findMethod2(relevantType.getDeclaredMethods(), getSignature()); annotations = found.getAnnotationTypes(); } if (annotations == null) { // We can't have recognized the shadow - should blow up now to be on the safe side throw new BCException("Could not discover annotations for shadow: " + getKind()); } for (int i = 0; i < annotations.length; i++) { ResolvedType annotationType = annotations[i]; AnnotationAccessVar accessVar = new AnnotationAccessVar(getKind(), annotationType.resolve(world), relevantType, annotationHolder); kindedAnnotationVars.put(annotationType, accessVar); } } // FIXME asc whats the real diff between this one and the version in findMethod()? ResolvedMember findMethod2(ResolvedMember rm[], Member sig) { ResolvedMember found = null; // String searchString = getSignature().getName()+getSignature().getParameterSignature(); for (int i = 0; i < rm.length && found == null; i++) { ResolvedMember member = rm[i]; if (member.getName().equals(sig.getName()) && member.getParameterSignature().equals(sig.getParameterSignature())) found = member; } return found; } private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) { ResolvedMember decMethods[] = aspectType.getDeclaredMethods(); for (int i = 0; i < decMethods.length; i++) { ResolvedMember member = decMethods[i]; if (member.equals(ajcMethod)) return member; } return null; } private ResolvedMember findField(ResolvedMember[] members, Member lookingFor) { for (int i = 0; i < members.length; i++) { ResolvedMember member = members[i]; if (member.getName().equals(getSignature().getName()) && member.getType().equals(getSignature().getType())) { return member; } } return null; } public void initializeWithinAnnotationVars() { if (withinAnnotationVars != null) return; withinAnnotationVars = new HashMap(); ResolvedType[] annotations = getEnclosingType().resolve(world).getAnnotationTypes(); for (int i = 0; i < annotations.length; i++) { ResolvedType ann = annotations[i]; Kind k = Shadow.StaticInitialization; withinAnnotationVars.put(ann, new AnnotationAccessVar(k, ann, getEnclosingType(), null)); } } public void initializeWithinCodeAnnotationVars() { if (withincodeAnnotationVars != null) return; withincodeAnnotationVars = new HashMap(); // For some shadow we are interested in annotations on the method containing that shadow. ResolvedType[] annotations = getEnclosingMethod().getMemberView().getAnnotationTypes(); for (int i = 0; i < annotations.length; i++) { ResolvedType ann = annotations[i]; Kind k = (getEnclosingMethod().getMemberView().getKind() == Member.CONSTRUCTOR ? Shadow.ConstructorExecution : Shadow.MethodExecution); withincodeAnnotationVars.put(ann, new AnnotationAccessVar(k, ann, getEnclosingType(), getEnclosingCodeSignature())); } } // ---- weave methods void weaveBefore(BcelAdvice munger) { range.insert(munger.getAdviceInstructions(this, null, range.getRealStart()), Range.InsideBefore); } public void weaveAfter(BcelAdvice munger) { weaveAfterThrowing(munger, UnresolvedType.THROWABLE); weaveAfterReturning(munger); } /** * The basic strategy here is to add a set of instructions at the end of the shadow range that dispatch the advice, and then * return whatever the shadow was going to return anyway. * * To achieve this, we note all the return statements in the advice, and replace them with code that: 1) stores the return value * on top of the stack in a temp var 2) jumps to the start of our advice block 3) restores the return value at the end of the * advice block before ultimately returning * * We also need to bind the return value into a returning parameter, if the advice specified one. */ public void weaveAfterReturning(BcelAdvice munger) { List returns = findReturnInstructions(); boolean hasReturnInstructions = !returns.isEmpty(); // list of instructions that handle the actual return from the join point InstructionList retList = new InstructionList(); // variable that holds the return value BcelVar returnValueVar = null; if (hasReturnInstructions) { returnValueVar = generateReturnInstructions(returns, retList); } else { // we need at least one instruction, as the target for jumps retList.append(InstructionConstants.NOP); } // list of instructions for dispatching to the advice itself InstructionList advice = getAfterReturningAdviceDispatchInstructions(munger, retList.getStart()); if (hasReturnInstructions) { InstructionHandle gotoTarget = advice.getStart(); for (Iterator i = returns.iterator(); i.hasNext();) { InstructionHandle ih = (InstructionHandle) i.next(); retargetReturnInstruction(munger.hasExtraParameter(), returnValueVar, gotoTarget, ih); } } range.append(advice); range.append(retList); } /** * @return a list of all the return instructions in the range of this shadow */ private List findReturnInstructions() { List returns = new ArrayList(); for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) { if (ih.getInstruction().isReturnInstruction()) { returns.add(ih); } } return returns; } /** * Given a list containing all the return instruction handles for this shadow, finds the last return instruction and copies it, * making this the ultimate return. If the shadow has a non-void return type, we also create a temporary variable to hold the * return value, and load the value from this var before returning (see pr148007 for why we do this - it works around a JRockit * bug, and is also closer to what javac generates) * * Sometimes the 'last return' isnt the right one - some rogue code can include the real return from the body of a subroutine * that exists at the end of the method. In this case the last return is RETURN but that may not be correct for a method with a * non-void return type... pr151673 * * @param returns list of all the return instructions in the shadow * @param returnInstructions instruction list into which the return instructions should be generated * @return the variable holding the return value, if needed */ private BcelVar generateReturnInstructions(List returns, InstructionList returnInstructions) { BcelVar returnValueVar = null; if (this.hasANonVoidReturnType()) { // Find the last *correct* return - this is a method with a non-void return type // so ignore RETURN Instruction newReturnInstruction = null; int i = returns.size() - 1; while (newReturnInstruction == null && i >= 0) { InstructionHandle ih = (InstructionHandle) returns.get(i); if (ih.getInstruction().opcode != Constants.RETURN) { newReturnInstruction = Utility.copyInstruction(ih.getInstruction()); } i--; } returnValueVar = genTempVar(this.getReturnType()); returnValueVar.appendLoad(returnInstructions, getFactory()); returnInstructions.append(newReturnInstruction); } else { InstructionHandle lastReturnHandle = (InstructionHandle) returns.get(returns.size() - 1); Instruction newReturnInstruction = Utility.copyInstruction(lastReturnHandle.getInstruction()); returnInstructions.append(newReturnInstruction); } return returnValueVar; } /** * @return true, iff this shadow returns a value */ private boolean hasANonVoidReturnType() { return this.getReturnType() != ResolvedType.VOID; } /** * Get the list of instructions used to dispatch to the after advice * * @param munger * @param firstInstructionInReturnSequence * @return */ private InstructionList getAfterReturningAdviceDispatchInstructions(BcelAdvice munger, InstructionHandle firstInstructionInReturnSequence) { InstructionList advice = new InstructionList(); BcelVar tempVar = null; if (munger.hasExtraParameter()) { tempVar = insertAdviceInstructionsForBindingReturningParameter(advice); } advice.append(munger.getAdviceInstructions(this, tempVar, firstInstructionInReturnSequence)); return advice; } /** * If the after() returning(Foo f) form is used, bind the return value to the parameter. If the shadow returns void, bind null. * * @param advice * @return */ private BcelVar insertAdviceInstructionsForBindingReturningParameter(InstructionList advice) { BcelVar tempVar; UnresolvedType tempVarType = getReturnType(); if (tempVarType.equals(ResolvedType.VOID)) { tempVar = genTempVar(UnresolvedType.OBJECT); advice.append(InstructionConstants.ACONST_NULL); tempVar.appendStore(advice, getFactory()); } else { tempVar = genTempVar(tempVarType); advice.append(InstructionFactory.createDup(tempVarType.getSize())); tempVar.appendStore(advice, getFactory()); } return tempVar; } /** * Helper method for weaveAfterReturning * * Each return instruction in the method body is retargeted by calling this method. The return instruction is replaced by up to * three instructions: 1) if the shadow returns a value, and that value is bound to an after returning parameter, then we DUP * the return value on the top of the stack 2) if the shadow returns a value, we store it in the returnValueVar (it will be * retrieved from here when we ultimately return after the advice dispatch) 3) if the return was the last instruction, we add a * NOP (it will fall through to the advice dispatch), otherwise we add a GOTO that branches to the supplied gotoTarget (start of * the advice dispatch) */ private void retargetReturnInstruction(boolean hasReturningParameter, BcelVar returnValueVar, InstructionHandle gotoTarget, InstructionHandle returnHandle) { // pr148007, work around JRockit bug // replace ret with store into returnValueVar, followed by goto if not // at the end of the instruction list... InstructionList newInstructions = new InstructionList(); if (returnValueVar != null) { if (hasReturningParameter) { // we have to dup the return val before consuming it... newInstructions.append(InstructionFactory.createDup(this.getReturnType().getSize())); } // store the return value into this var returnValueVar.appendStore(newInstructions, getFactory()); } if (!isLastInstructionInRange(returnHandle, range)) { newInstructions.append(InstructionFactory.createBranchInstruction(Constants.GOTO, gotoTarget)); } if (newInstructions.isEmpty()) { newInstructions.append(InstructionConstants.NOP); } Utility.replaceInstruction(returnHandle, newInstructions, enclosingMethod); } private boolean isLastInstructionInRange(InstructionHandle ih, ShadowRange aRange) { return ih.getNext() == aRange.getEnd(); } public void weaveAfterThrowing(BcelAdvice munger, UnresolvedType catchType) { // a good optimization would be not to generate anything here // if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even // a shadow, inside me). if (getRange().getStart().getNext() == getRange().getEnd()) return; InstructionFactory fact = getFactory(); InstructionList handler = new InstructionList(); BcelVar exceptionVar = genTempVar(catchType); exceptionVar.appendStore(handler, fact); // pr62642 // I will now jump through some firey BCEL hoops to generate a trivial bit of code: // if (exc instanceof ExceptionInInitializerError) // throw (ExceptionInInitializerError)exc; if (this.getEnclosingMethod().getName().equals("<clinit>")) { ResolvedType eiieType = world.resolve("java.lang.ExceptionInInitializerError"); ObjectType eiieBcelType = (ObjectType) BcelWorld.makeBcelType(eiieType); InstructionList ih = new InstructionList(InstructionConstants.NOP); handler.append(exceptionVar.createLoad(fact)); handler.append(fact.createInstanceOf(eiieBcelType)); InstructionBranch bi = InstructionFactory.createBranchInstruction(Constants.IFEQ, ih.getStart()); handler.append(bi); handler.append(exceptionVar.createLoad(fact)); handler.append(fact.createCheckCast(eiieBcelType)); handler.append(InstructionConstants.ATHROW); handler.append(ih); } InstructionList endHandler = new InstructionList(exceptionVar.createLoad(fact)); handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart())); handler.append(endHandler); handler.append(InstructionConstants.ATHROW); InstructionHandle handlerStart = handler.getStart(); if (isFallsThrough()) { InstructionHandle jumpTarget = handler.append(InstructionConstants.NOP); handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget)); } InstructionHandle protectedEnd = handler.getStart(); range.insert(handler, Range.InsideAfter); enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(), handlerStart, (ObjectType) BcelWorld.makeBcelType(catchType), // ???Type.THROWABLE, // high priority if our args are on the stack getKind().hasHighPriorityExceptions()); } // ??? this shares a lot of code with the above weaveAfterThrowing // ??? would be nice to abstract that to say things only once public void weaveSoftener(BcelAdvice munger, UnresolvedType catchType) { // a good optimization would be not to generate anything here // if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even // a shadow, inside me). if (getRange().getStart().getNext() == getRange().getEnd()) return; InstructionFactory fact = getFactory(); InstructionList handler = new InstructionList(); InstructionList rtExHandler = new InstructionList(); BcelVar exceptionVar = genTempVar(catchType); handler.append(fact.createNew(NameMangler.SOFT_EXCEPTION_TYPE)); handler.append(InstructionFactory.createDup(1)); handler.append(exceptionVar.createLoad(fact)); handler.append(fact.createInvoke(NameMangler.SOFT_EXCEPTION_TYPE, "<init>", Type.VOID, new Type[] { Type.THROWABLE }, Constants.INVOKESPECIAL)); // ??? special handler.append(InstructionConstants.ATHROW); // ENH 42737 exceptionVar.appendStore(rtExHandler, fact); // aload_1 rtExHandler.append(exceptionVar.createLoad(fact)); // instanceof class java/lang/RuntimeException rtExHandler.append(fact.createInstanceOf(new ObjectType("java.lang.RuntimeException"))); // ifeq go to new SOFT_EXCEPTION_TYPE instruction rtExHandler.append(InstructionFactory.createBranchInstruction(Constants.IFEQ, handler.getStart())); // aload_1 rtExHandler.append(exceptionVar.createLoad(fact)); // athrow rtExHandler.append(InstructionFactory.ATHROW); InstructionHandle handlerStart = rtExHandler.getStart(); if (isFallsThrough()) { InstructionHandle jumpTarget = range.getEnd();// handler.append(fact.NOP); rtExHandler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget)); } rtExHandler.append(handler); InstructionHandle protectedEnd = rtExHandler.getStart(); range.insert(rtExHandler, Range.InsideAfter); enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(), handlerStart, (ObjectType) BcelWorld.makeBcelType(catchType), // high priority if our args are on the stack getKind().hasHighPriorityExceptions()); } public void weavePerObjectEntry(final BcelAdvice munger, final BcelVar onVar) { final InstructionFactory fact = getFactory(); InstructionList entryInstructions = new InstructionList(); InstructionList entrySuccessInstructions = new InstructionList(); onVar.appendLoad(entrySuccessInstructions, fact); entrySuccessInstructions .append(Utility.createInvoke(fact, world, AjcMemberMaker.perObjectBind(munger.getConcreteAspect()))); InstructionList testInstructions = munger.getTestInstructions(this, entrySuccessInstructions.getStart(), range .getRealStart(), entrySuccessInstructions.getStart()); entryInstructions.append(testInstructions); entryInstructions.append(entrySuccessInstructions); range.insert(entryInstructions, Range.InsideBefore); } // PTWIMPL Create static initializer to call the aspect factory /** * Causes the aspect instance to be *set* for later retrievable through localAspectof()/aspectOf() */ public void weavePerTypeWithinAspectInitialization(final BcelAdvice munger, UnresolvedType t) { if (t.resolve(world).isInterface()) return; // Don't initialize statics in final InstructionFactory fact = getFactory(); InstructionList entryInstructions = new InstructionList(); InstructionList entrySuccessInstructions = new InstructionList(); BcelWorld.getBcelObjectType(munger.getConcreteAspect()); String aspectname = munger.getConcreteAspect().getName(); String ptwField = NameMangler.perTypeWithinFieldForTarget(munger.getConcreteAspect()); entrySuccessInstructions.append(InstructionFactory.PUSH(fact.getConstantPool(), t.getName())); entrySuccessInstructions.append(fact.createInvoke(aspectname, "ajc$createAspectInstance", new ObjectType(aspectname), new Type[] { new ObjectType("java.lang.String") }, Constants.INVOKESTATIC)); entrySuccessInstructions.append(fact.createPutStatic(t.getName(), ptwField, new ObjectType(aspectname))); entryInstructions.append(entrySuccessInstructions); range.insert(entryInstructions, Range.InsideBefore); } public void weaveCflowEntry(final BcelAdvice munger, final Member cflowField) { final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry || munger.getKind() == AdviceKind.PerCflowEntry; final Type objectArrayType = new ArrayType(Type.OBJECT, 1); final InstructionFactory fact = getFactory(); final BcelVar testResult = genTempVar(ResolvedType.BOOLEAN); InstructionList entryInstructions = new InstructionList(); { InstructionList entrySuccessInstructions = new InstructionList(); if (munger.hasDynamicTests()) { entryInstructions.append(Utility.createConstant(fact, 0)); testResult.appendStore(entryInstructions, fact); entrySuccessInstructions.append(Utility.createConstant(fact, 1)); testResult.appendStore(entrySuccessInstructions, fact); } if (isPer) { entrySuccessInstructions.append(fact.createInvoke(munger.getConcreteAspect().getName(), NameMangler.PERCFLOW_PUSH_METHOD, Type.VOID, new Type[] {}, Constants.INVOKESTATIC)); } else { BcelVar[] cflowStateVars = munger.getExposedStateAsBcelVars(false); if (cflowStateVars.length == 0) { // This should be getting managed by a counter - lets make sure. if (!cflowField.getType().getName().endsWith("CFlowCounter")) throw new RuntimeException("Incorrectly attempting counter operation on stacked cflow"); entrySuccessInstructions.append(Utility.createGet(fact, cflowField)); // arrayVar.appendLoad(entrySuccessInstructions, fact); entrySuccessInstructions.append(fact.createInvoke(NameMangler.CFLOW_COUNTER_TYPE, "inc", Type.VOID, new Type[] {}, Constants.INVOKEVIRTUAL)); } else { BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY); int alen = cflowStateVars.length; entrySuccessInstructions.append(Utility.createConstant(fact, alen)); entrySuccessInstructions.append(fact.createNewArray(Type.OBJECT, (short) 1)); arrayVar.appendStore(entrySuccessInstructions, fact); for (int i = 0; i < alen; i++) { arrayVar.appendConvertableArrayStore(entrySuccessInstructions, fact, i, cflowStateVars[i]); } entrySuccessInstructions.append(Utility.createGet(fact, cflowField)); arrayVar.appendLoad(entrySuccessInstructions, fact); entrySuccessInstructions.append(fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID, new Type[] { objectArrayType }, Constants.INVOKEVIRTUAL)); } } InstructionList testInstructions = munger.getTestInstructions(this, entrySuccessInstructions.getStart(), range .getRealStart(), entrySuccessInstructions.getStart()); entryInstructions.append(testInstructions); entryInstructions.append(entrySuccessInstructions); } // this is the same for both per and non-per weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) { public InstructionList getAdviceInstructions(BcelShadow s, BcelVar extraArgVar, InstructionHandle ifNoAdvice) { InstructionList exitInstructions = new InstructionList(); if (munger.hasDynamicTests()) { testResult.appendLoad(exitInstructions, fact); exitInstructions.append(InstructionFactory.createBranchInstruction(Constants.IFEQ, ifNoAdvice)); } exitInstructions.append(Utility.createGet(fact, cflowField)); if (munger.getKind() != AdviceKind.PerCflowEntry && munger.getKind() != AdviceKind.PerCflowBelowEntry && munger.getExposedStateAsBcelVars(false).length == 0) { exitInstructions.append(fact.createInvoke(NameMangler.CFLOW_COUNTER_TYPE, "dec", Type.VOID, new Type[] {}, Constants.INVOKEVIRTUAL)); } else { exitInstructions.append(fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "pop", Type.VOID, new Type[] {}, Constants.INVOKEVIRTUAL)); } return exitInstructions; } }); range.insert(entryInstructions, Range.InsideBefore); } /* * Implementation notes: * * AroundInline still extracts the instructions of the original shadow into an extracted method. This allows inlining of even * that advice that doesn't call proceed or calls proceed more than once. * * It extracts the instructions of the original shadow into a method. * * Then it extracts the instructions of the advice into a new method defined on this enclosing class. This new method can then * be specialized as below. * * Then it searches in the instructions of the advice for any call to the proceed method. * * At such a call, there is stuff on the stack representing the arguments to proceed. Pop these into the frame. * * Now build the stack for the call to the extracted method, taking values either from the join point state or from the new * frame locs from proceed. Now call the extracted method. The right return value should be on the stack, so no cast is * necessary. * * If only one call to proceed is made, we can re-inline the original shadow. We are not doing that presently. * * If the body of the advice can be determined to not alter the stack, or if this shadow doesn't care about the stack, i.e. * method-execution, then the new method for the advice can also be re-lined. We are not doing that presently. */ public void weaveAroundInline(BcelAdvice munger, boolean hasDynamicTest) { // !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...); Member mungerSig = munger.getSignature(); // Member originalSig = mungerSig; // If mungerSig is on a parameterized type, originalSig is the member on the generic type if (mungerSig instanceof ResolvedMember) { ResolvedMember rm = (ResolvedMember) mungerSig; if (rm.hasBackingGenericMember()) mungerSig = rm.getBackingGenericMember(); } ResolvedType declaringType = world.resolve(mungerSig.getDeclaringType(), true); if (declaringType.isMissing()) { world.getLint().cantFindType.signal(new String[] { WeaverMessages.format( WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE, declaringType.getClassName()) }, getSourceLocation(), new ISourceLocation[] { munger.getSourceLocation() }); // IMessage msg = new Message( // WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName()), // "",IMessage.ERROR,getSourceLocation(),null, // new ISourceLocation[]{ munger.getSourceLocation()}); // world.getMessageHandler().handleMessage(msg); } // ??? might want some checks here to give better errors ResolvedType rt = (declaringType.isParameterizedType() ? declaringType.getGenericType() : declaringType); BcelObjectType ot = BcelWorld.getBcelObjectType(rt); // if (ot==null) { // world.getMessageHandler().handleMessage( // MessageUtil.warn("Unable to find modifiable delegate for the aspect '"+rt.getName()+ // "' containing around advice - cannot implement inlining",munger.getSourceLocation())); // weaveAroundClosure(munger, hasDynamicTest); // return; // } LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig); if (!adviceMethod.getCanInline()) { weaveAroundClosure(munger, hasDynamicTest); return; } // specific test for @AJ proceedInInners if (munger.getConcreteAspect().isAnnotationStyleAspect()) { // if we can't find one proceed() we suspect that the call // is happening in an inner class so we don't inline it. // Note: for code style, this is done at Aspect compilation time. boolean canSeeProceedPassedToOther = false; InstructionHandle curr = adviceMethod.getBody().getStart(); InstructionHandle end = adviceMethod.getBody().getEnd(); ConstantPool cpg = adviceMethod.getEnclosingClass().getConstantPool(); while (curr != end) { InstructionHandle next = curr.getNext(); Instruction inst = curr.getInstruction(); if ((inst instanceof InvokeInstruction) && ((InvokeInstruction) inst).getSignature(cpg).indexOf("Lorg/aspectj/lang/ProceedingJoinPoint;") > 0) { // we may want to refine to exclude stuff returning jp ? // does code style skip inline if i write dump(thisJoinPoint) ? canSeeProceedPassedToOther = true;// we see one pjp passed around - dangerous break; } curr = next; } if (canSeeProceedPassedToOther) { // remember this decision to avoid re-analysis adviceMethod.setCanInline(false); weaveAroundClosure(munger, hasDynamicTest); return; } } // We can't inline around methods if they have around advice on them, this // is because the weaving will extract the body and hence the proceed call. // ??? should consider optimizations to recognize simple cases that don't require body extraction enclosingMethod.setCanInline(false); // start by exposing various useful things into the frame final InstructionFactory fact = getFactory(); // now generate the aroundBody method // eg. "private static final void method_aroundBody0(M, M, String, org.aspectj.lang.JoinPoint)" LazyMethodGen extractedMethod = extractMethod(NameMangler.aroundCallbackMethodName(getSignature(), getEnclosingClass()), Modifier.PRIVATE, munger); // now extract the advice into its own method String adviceMethodName = NameMangler.aroundCallbackMethodName(getSignature(), getEnclosingClass()) + "$advice"; List argVarList = new ArrayList(); List proceedVarList = new ArrayList(); int extraParamOffset = 0; // Create the extra parameters that are needed for passing to proceed // This code is very similar to that found in makeCallToCallback and should // be rationalized in the future if (thisVar != null) { argVarList.add(thisVar); proceedVarList.add(new BcelVar(thisVar.getType(), extraParamOffset)); extraParamOffset += thisVar.getType().getSize(); } if (targetVar != null && targetVar != thisVar) { argVarList.add(targetVar); proceedVarList.add(new BcelVar(targetVar.getType(), extraParamOffset)); extraParamOffset += targetVar.getType().getSize(); } for (int i = 0, len = getArgCount(); i < len; i++) { argVarList.add(argVars[i]); proceedVarList.add(new BcelVar(argVars[i].getType(), extraParamOffset)); extraParamOffset += argVars[i].getType().getSize(); } if (thisJoinPointVar != null) { argVarList.add(thisJoinPointVar); proceedVarList.add(new BcelVar(thisJoinPointVar.getType(), extraParamOffset)); extraParamOffset += thisJoinPointVar.getType().getSize(); } // We use the munger signature here because it allows for any parameterization of the mungers pointcut that // may have occurred ie. if the pointcut is p(T t) in the super aspect and that has become p(Foo t) in the sub aspect // then here the munger signature will have 'Foo' as an argument in it whilst the adviceMethod argument type will be // 'Object' - since // it represents the advice method in the superaspect which uses the erasure of the type variable p(Object t) - see // pr174449. Type[] adviceParameterTypes = BcelWorld.makeBcelTypes(munger.getSignature().getParameterTypes()); // adviceMethod.getArgumentTypes(); adviceMethod.getArgumentTypes(); // forces initialization ... dont like this but seems to be required for some tests to // pass, I think that means // there is a LazyMethodGen method that is not correctly setup to call initialize() when it is invoked - but I dont have // time right now to discover which Type[] extractedMethodParameterTypes = extractedMethod.getArgumentTypes(); Type[] parameterTypes = new Type[extractedMethodParameterTypes.length + adviceParameterTypes.length + 1]; int parameterIndex = 0; System.arraycopy(extractedMethodParameterTypes, 0, parameterTypes, parameterIndex, extractedMethodParameterTypes.length); parameterIndex += extractedMethodParameterTypes.length; parameterTypes[parameterIndex++] = BcelWorld.makeBcelType(adviceMethod.getEnclosingClass().getType()); System.arraycopy(adviceParameterTypes, 0, parameterTypes, parameterIndex, adviceParameterTypes.length); // parameterTypes is [Bug, C, org.aspectj.lang.JoinPoint, X, org.aspectj.lang.ProceedingJoinPoint, java.lang.Object, // java.lang.Object] LazyMethodGen localAdviceMethod = new LazyMethodGen(Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC, BcelWorld .makeBcelType(mungerSig.getReturnType()), adviceMethodName, parameterTypes, new String[0], getEnclosingClass()); String donorFileName = adviceMethod.getEnclosingClass().getInternalFileName(); String recipientFileName = getEnclosingClass().getInternalFileName(); // System.err.println("donor " + donorFileName); // System.err.println("recip " + recipientFileName); if (!donorFileName.equals(recipientFileName)) { localAdviceMethod.fromFilename = donorFileName; getEnclosingClass().addInlinedSourceFileInfo(donorFileName, adviceMethod.highestLineNumber); } getEnclosingClass().addMethodGen(localAdviceMethod); // create a map that will move all slots in advice method forward by extraParamOffset // in order to make room for the new proceed-required arguments that are added at // the beginning of the parameter list int nVars = adviceMethod.getMaxLocals() + extraParamOffset; IntMap varMap = IntMap.idMap(nVars); for (int i = extraParamOffset; i < nVars; i++) { varMap.put(i - extraParamOffset, i); } localAdviceMethod.getBody().insert( BcelClassWeaver.genInlineInstructions(adviceMethod, localAdviceMethod, varMap, fact, true)); localAdviceMethod.setMaxLocals(nVars); // System.err.println(localAdviceMethod); // the shadow is now empty. First, create a correct call // to the around advice. This includes both the call (which may involve // value conversion of the advice arguments) and the return // (which may involve value conversion of the return value). Right now // we push a null for the unused closure. It's sad, but there it is. InstructionList advice = new InstructionList(); // InstructionHandle adviceMethodInvocation; { for (Iterator i = argVarList.iterator(); i.hasNext();) { BcelVar var = (BcelVar) i.next(); var.appendLoad(advice, fact); } // ??? we don't actually need to push NULL for the closure if we take care advice.append(munger.getAdviceArgSetup(this, null, (munger.getConcreteAspect().isAnnotationStyleAspect() && munger.getDeclaringAspect() != null && munger .getDeclaringAspect().resolve(world).isAnnotationStyleAspect()) ? this.loadThisJoinPoint() : new InstructionList(InstructionConstants.ACONST_NULL))); // adviceMethodInvocation = advice.append(Utility.createInvoke(fact, localAdviceMethod)); // (fact, getWorld(), munger.getSignature())); advice.append(Utility.createConversion(getFactory(), BcelWorld.makeBcelType(mungerSig.getReturnType()), extractedMethod .getReturnType(), world.isInJava5Mode())); if (!isFallsThrough()) { advice.append(InstructionFactory.createReturn(extractedMethod.getReturnType())); } } // now, situate the call inside the possible dynamic tests, // and actually add the whole mess to the shadow if (!hasDynamicTest) { range.append(advice); } else { InstructionList afterThingie = new InstructionList(InstructionConstants.NOP); InstructionList callback = makeCallToCallback(extractedMethod); if (terminatesWithReturn()) { callback.append(InstructionFactory.createReturn(extractedMethod.getReturnType())); } else { // InstructionHandle endNop = range.insert(fact.NOP, Range.InsideAfter); advice.append(InstructionFactory.createBranchInstruction(Constants.GOTO, afterThingie.getStart())); } range.append(munger.getTestInstructions(this, advice.getStart(), callback.getStart(), advice.getStart())); range.append(advice); range.append(callback); range.append(afterThingie); } // now search through the advice, looking for a call to PROCEED. // Then we replace the call to proceed with some argument setup, and a // call to the extracted method. // inlining support for code style aspects if (!munger.getDeclaringType().isAnnotationStyleAspect()) { String proceedName = NameMangler.proceedMethodName(munger.getSignature().getName()); InstructionHandle curr = localAdviceMethod.getBody().getStart(); InstructionHandle end = localAdviceMethod.getBody().getEnd(); ConstantPool cpg = localAdviceMethod.getEnclosingClass().getConstantPool(); while (curr != end) { InstructionHandle next = curr.getNext(); Instruction inst = curr.getInstruction(); if ((inst.opcode == Constants.INVOKESTATIC) && proceedName.equals(((InvokeInstruction) inst).getMethodName(cpg))) { localAdviceMethod.getBody().append(curr, getRedoneProceedCall(fact, extractedMethod, munger, localAdviceMethod, proceedVarList)); Utility.deleteInstruction(curr, localAdviceMethod); } curr = next; } // and that's it. } else { // ATAJ inlining support for @AJ aspects // [TODO document @AJ code rule: don't manipulate 2 jps proceed at the same time.. in an advice body] InstructionHandle curr = localAdviceMethod.getBody().getStart(); InstructionHandle end = localAdviceMethod.getBody().getEnd(); ConstantPool cpg = localAdviceMethod.getEnclosingClass().getConstantPool(); while (curr != end) { InstructionHandle next = curr.getNext(); Instruction inst = curr.getInstruction(); if ((inst instanceof INVOKEINTERFACE) && "proceed".equals(((INVOKEINTERFACE) inst).getMethodName(cpg))) { final boolean isProceedWithArgs; if (((INVOKEINTERFACE) inst).getArgumentTypes(cpg).length == 1) { // proceed with args as a boxed Object[] isProceedWithArgs = true; } else { isProceedWithArgs = false; } InstructionList insteadProceedIl = getRedoneProceedCallForAnnotationStyle(fact, extractedMethod, munger, localAdviceMethod, proceedVarList, isProceedWithArgs); localAdviceMethod.getBody().append(curr, insteadProceedIl); Utility.deleteInstruction(curr, localAdviceMethod); } curr = next; } } } private InstructionList getRedoneProceedCall(InstructionFactory fact, LazyMethodGen callbackMethod, BcelAdvice munger, LazyMethodGen localAdviceMethod, List argVarList) { InstructionList ret = new InstructionList(); // we have on stack all the arguments for the ADVICE call. // we have in frame somewhere all the arguments for the non-advice call. BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(true); IntMap proceedMap = makeProceedArgumentMap(adviceVars); // System.out.println(proceedMap + " for " + this); // System.out.println(argVarList); ResolvedType[] proceedParamTypes = world.resolve(munger.getSignature().getParameterTypes()); // remove this*JoinPoint* as arguments to proceed if (munger.getBaseParameterCount() + 1 < proceedParamTypes.length) { int len = munger.getBaseParameterCount() + 1; ResolvedType[] newTypes = new ResolvedType[len]; System.arraycopy(proceedParamTypes, 0, newTypes, 0, len); proceedParamTypes = newTypes; } // System.out.println("stateTypes: " + Arrays.asList(stateTypes)); BcelVar[] proceedVars = Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod); Type[] stateTypes = callbackMethod.getArgumentTypes(); // System.out.println("stateTypes: " + Arrays.asList(stateTypes)); for (int i = 0, len = stateTypes.length; i < len; i++) { Type stateType = stateTypes[i]; ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world); if (proceedMap.hasKey(i)) { // throw new RuntimeException("unimplemented"); proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX); } else { ((BcelVar) argVarList.get(i)).appendLoad(ret, fact); } } ret.append(Utility.createInvoke(fact, callbackMethod)); ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), BcelWorld.makeBcelType(munger.getSignature() .getReturnType()))); return ret; } // private static boolean bindsThisOrTarget(Pointcut pointcut) { // ThisTargetFinder visitor = new ThisTargetFinder(); // pointcut.accept(visitor, null); // return visitor.bindsThisOrTarget; // } // private static class ThisTargetFinder extends IdentityPointcutVisitor { // boolean bindsThisOrTarget = false; // // public Object visit(ThisOrTargetPointcut node, Object data) { // if (node.isBinding()) { // bindsThisOrTarget = true; // } // return node; // } // // public Object visit(AndPointcut node, Object data) { // if (!bindsThisOrTarget) node.getLeft().accept(this, data); // if (!bindsThisOrTarget) node.getRight().accept(this, data); // return node; // } // // public Object visit(NotPointcut node, Object data) { // if (!bindsThisOrTarget) node.getNegatedPointcut().accept(this, data); // return node; // } // // public Object visit(OrPointcut node, Object data) { // if (!bindsThisOrTarget) node.getLeft().accept(this, data); // if (!bindsThisOrTarget) node.getRight().accept(this, data); // return node; // } // } /** * Annotation style handling for inlining. * * Note: The proceedingjoinpoint is already on the stack (since the user was calling pjp.proceed(...) * * The proceed map is ignored (in terms of argument repositioning) since we have a fixed expected format for annotation style. * The aim here is to change the proceed() call into a call to the xxx_aroundBody0 method. * * */ private InstructionList getRedoneProceedCallForAnnotationStyle(InstructionFactory fact, LazyMethodGen callbackMethod, BcelAdvice munger, LazyMethodGen localAdviceMethod, List argVarList, boolean isProceedWithArgs) { InstructionList ret = new InstructionList(); // store the Object[] array on stack if proceed with args if (isProceedWithArgs) { // STORE the Object[] into a local variable Type objectArrayType = Type.OBJECT_ARRAY; int theObjectArrayLocalNumber = localAdviceMethod.allocateLocal(objectArrayType); ret.append(InstructionFactory.createStore(objectArrayType, theObjectArrayLocalNumber)); // STORE the ProceedingJoinPoint instance into a local variable Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;"); int pjpLocalNumber = localAdviceMethod.allocateLocal(proceedingJpType); ret.append(InstructionFactory.createStore(proceedingJpType, pjpLocalNumber)); // Aim here initially is to determine whether the user will have provided a new // this/target in the object array and consume them if they have, leaving us the rest of // the arguments to process as regular arguments to the invocation at the original join point boolean pointcutBindsThis = bindsThis(munger); boolean pointcutBindsTarget = bindsTarget(munger); boolean targetIsSameAsThis = getKind().isTargetSameAsThis(); int nextArgumentToProvideForCallback = 0; if (hasThis()) { if (!(pointcutBindsTarget && targetIsSameAsThis)) { if (pointcutBindsThis) { // they have supplied new this as first entry in object array, consume it ret.append(InstructionFactory.createLoad(objectArrayType, theObjectArrayLocalNumber)); ret.append(Utility.createConstant(fact, 0)); ret.append(InstructionFactory.createArrayLoad(Type.OBJECT)); ret.append(Utility.createConversion(fact, Type.OBJECT, callbackMethod.getArgumentTypes()[0])); } else { // use local variable 0 ret.append(InstructionFactory.createALOAD(0)); } nextArgumentToProvideForCallback++; } } if (hasTarget()) { if (pointcutBindsTarget) { if (getKind().isTargetSameAsThis()) { ret.append(InstructionFactory.createLoad(objectArrayType, theObjectArrayLocalNumber)); ret.append(Utility.createConstant(fact, pointcutBindsThis ? 1 : 0)); ret.append(InstructionFactory.createArrayLoad(Type.OBJECT)); ret.append(Utility.createConversion(fact, Type.OBJECT, callbackMethod.getArgumentTypes()[0])); } else { int position = (hasThis() && pointcutBindsThis ? 1 : 0); ret.append(InstructionFactory.createLoad(objectArrayType, theObjectArrayLocalNumber)); ret.append(Utility.createConstant(fact, position)); ret.append(InstructionFactory.createArrayLoad(Type.OBJECT)); ret.append(Utility.createConversion(fact, Type.OBJECT, callbackMethod.getArgumentTypes()[position])); } nextArgumentToProvideForCallback++; } else { if (getKind().isTargetSameAsThis()) { // ret.append(new ALOAD(0)); } else { ret.append(InstructionFactory.createLoad(localAdviceMethod.getArgumentTypes()[0], hasThis() ? 1 : 0)); nextArgumentToProvideForCallback++; } } } // Where to start in the object array in order to pick up arguments int indexIntoObjectArrayForArguments = (pointcutBindsThis ? 1 : 0) + (pointcutBindsTarget ? 1 : 0); int len = callbackMethod.getArgumentTypes().length; for (int i = nextArgumentToProvideForCallback; i < len; i++) { Type stateType = callbackMethod.getArgumentTypes()[i]; BcelWorld.fromBcel(stateType).resolve(world); if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) { ret.append(new InstructionLV(Constants.ALOAD, pjpLocalNumber)); } else { ret.append(InstructionFactory.createLoad(objectArrayType, theObjectArrayLocalNumber)); ret.append(Utility .createConstant(fact, i - nextArgumentToProvideForCallback + indexIntoObjectArrayForArguments)); ret.append(InstructionFactory.createArrayLoad(Type.OBJECT)); ret.append(Utility.createConversion(fact, Type.OBJECT, stateType)); } } } else { Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;"); int localJp = localAdviceMethod.allocateLocal(proceedingJpType); ret.append(InstructionFactory.createStore(proceedingJpType, localJp)); for (int i = 0, len = callbackMethod.getArgumentTypes().length; i < len; i++) { Type stateType = callbackMethod.getArgumentTypes()[i]; /* ResolvedType stateTypeX = */ BcelWorld.fromBcel(stateType).resolve(world); if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) { ret.append(InstructionFactory.createALOAD(localJp));// from localAdvice signature // } else if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(stateType.getSignature())) { // //FIXME ALEX? // ret.append(new ALOAD(localJp));// from localAdvice signature // // ret.append(fact.createCheckCast( // // (ReferenceType) BcelWorld.makeBcelType(stateTypeX) // // )); // // cast ? // } else { ret.append(InstructionFactory.createLoad(stateType, i)); } } } // do the callback invoke ret.append(Utility.createInvoke(fact, callbackMethod)); // box it again. Handles cases where around advice does return something else than Object if (!UnresolvedType.OBJECT.equals(munger.getSignature().getReturnType())) { ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), Type.OBJECT)); } ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), BcelWorld.makeBcelType(munger.getSignature() .getReturnType()))); return ret; // // // // if (proceedMap.hasKey(i)) { // ret.append(new ALOAD(i)); // //throw new RuntimeException("unimplemented"); // //proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX); // } else { // //((BcelVar) argVarList.get(i)).appendLoad(ret, fact); // //ret.append(new ALOAD(i)); // if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) { // ret.append(new ALOAD(i)); // } else { // ret.append(new ALOAD(i)); // } // } // } // // ret.append(Utility.createInvoke(fact, callbackMethod)); // ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), // BcelWorld.makeBcelType(munger.getSignature().getReturnType()))); // // //ret.append(new ACONST_NULL());//will be POPed // if (true) return ret; // // // // // we have on stack all the arguments for the ADVICE call. // // we have in frame somewhere all the arguments for the non-advice call. // // BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(); // IntMap proceedMap = makeProceedArgumentMap(adviceVars); // // System.out.println(proceedMap + " for " + this); // System.out.println(argVarList); // // ResolvedType[] proceedParamTypes = // world.resolve(munger.getSignature().getParameterTypes()); // // remove this*JoinPoint* as arguments to proceed // if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) { // int len = munger.getBaseParameterCount()+1; // ResolvedType[] newTypes = new ResolvedType[len]; // System.arraycopy(proceedParamTypes, 0, newTypes, 0, len); // proceedParamTypes = newTypes; // } // // //System.out.println("stateTypes: " + Arrays.asList(stateTypes)); // BcelVar[] proceedVars = // Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod); // // Type[] stateTypes = callbackMethod.getArgumentTypes(); // // System.out.println("stateTypes: " + Arrays.asList(stateTypes)); // // for (int i=0, len=stateTypes.length; i < len; i++) { // Type stateType = stateTypes[i]; // ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world); // if (proceedMap.hasKey(i)) { // //throw new RuntimeException("unimplemented"); // proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX); // } else { // ((BcelVar) argVarList.get(i)).appendLoad(ret, fact); // } // } // // ret.append(Utility.createInvoke(fact, callbackMethod)); // ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), // BcelWorld.makeBcelType(munger.getSignature().getReturnType()))); // return ret; } private boolean bindsThis(BcelAdvice munger) { UsesThisVisitor utv = new UsesThisVisitor(); munger.getPointcut().accept(utv, null); return utv.usesThis; } private boolean bindsTarget(BcelAdvice munger) { UsesTargetVisitor utv = new UsesTargetVisitor(); munger.getPointcut().accept(utv, null); return utv.usesTarget; } private static class UsesThisVisitor extends AbstractPatternNodeVisitor { boolean usesThis = false; public Object visit(ThisOrTargetPointcut node, Object data) { if (node.isThis() && node.isBinding()) usesThis = true; return node; } public Object visit(AndPointcut node, Object data) { if (!usesThis) node.getLeft().accept(this, data); if (!usesThis) node.getRight().accept(this, data); return node; } public Object visit(NotPointcut node, Object data) { if (!usesThis) node.getNegatedPointcut().accept(this, data); return node; } public Object visit(OrPointcut node, Object data) { if (!usesThis) node.getLeft().accept(this, data); if (!usesThis) node.getRight().accept(this, data); return node; } } private static class UsesTargetVisitor extends AbstractPatternNodeVisitor { boolean usesTarget = false; public Object visit(ThisOrTargetPointcut node, Object data) { if (!node.isThis() && node.isBinding()) usesTarget = true; return node; } public Object visit(AndPointcut node, Object data) { if (!usesTarget) node.getLeft().accept(this, data); if (!usesTarget) node.getRight().accept(this, data); return node; } public Object visit(NotPointcut node, Object data) { if (!usesTarget) node.getNegatedPointcut().accept(this, data); return node; } public Object visit(OrPointcut node, Object data) { if (!usesTarget) node.getLeft().accept(this, data); if (!usesTarget) node.getRight().accept(this, data); return node; } } public void weaveAroundClosure(BcelAdvice munger, boolean hasDynamicTest) { InstructionFactory fact = getFactory(); enclosingMethod.setCanInline(false); int linenumber = getSourceLine(); // MOVE OUT ALL THE INSTRUCTIONS IN MY SHADOW INTO ANOTHER METHOD! LazyMethodGen callbackMethod = extractMethod(NameMangler.aroundCallbackMethodName(getSignature(), getEnclosingClass()), 0, munger); BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(true); String closureClassName = NameMangler.makeClosureClassName(getEnclosingClass().getType(), getEnclosingClass() .getNewGeneratedNameTag()); Member constructorSig = new MemberImpl(Member.CONSTRUCTOR, UnresolvedType.forName(closureClassName), 0, "<init>", "([Ljava/lang/Object;)V"); BcelVar closureHolder = null; // This is not being used currently since getKind() == preinitializaiton // cannot happen in around advice if (getKind() == PreInitialization) { closureHolder = genTempVar(AjcMemberMaker.AROUND_CLOSURE_TYPE); } InstructionList closureInstantiation = makeClosureInstantiation(constructorSig, closureHolder); /* LazyMethodGen constructor = */ makeClosureClassAndReturnConstructor(closureClassName, callbackMethod, makeProceedArgumentMap(adviceVars)); InstructionList returnConversionCode; if (getKind() == PreInitialization) { returnConversionCode = new InstructionList(); BcelVar stateTempVar = genTempVar(UnresolvedType.OBJECTARRAY); closureHolder.appendLoad(returnConversionCode, fact); returnConversionCode.append(Utility.createInvoke(fact, world, AjcMemberMaker.aroundClosurePreInitializationGetter())); stateTempVar.appendStore(returnConversionCode, fact); Type[] stateTypes = getSuperConstructorParameterTypes(); returnConversionCode.append(InstructionConstants.ALOAD_0); // put "this" back on the stack for (int i = 0, len = stateTypes.length; i < len; i++) { UnresolvedType bcelTX = BcelWorld.fromBcel(stateTypes[i]); ResolvedType stateRTX = world.resolve(bcelTX, true); if (stateRTX.isMissing()) { world.getLint().cantFindType.signal(new String[] { WeaverMessages.format( WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT, bcelTX.getClassName()) }, getSourceLocation(), new ISourceLocation[] { munger.getSourceLocation() }); // IMessage msg = new Message( // WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName()), // "",IMessage.ERROR,getSourceLocation(),null, // new ISourceLocation[]{ munger.getSourceLocation()}); // world.getMessageHandler().handleMessage(msg); } stateTempVar.appendConvertableArrayLoad(returnConversionCode, fact, i, stateRTX); } } else { // pr226201 Member mungerSignature = munger.getSignature(); if (munger.getSignature() instanceof ResolvedMember) { if (((ResolvedMember) mungerSignature).hasBackingGenericMember()) { mungerSignature = ((ResolvedMember) mungerSignature).getBackingGenericMember(); } } UnresolvedType returnType = mungerSignature.getReturnType(); returnConversionCode = Utility.createConversion(getFactory(), BcelWorld.makeBcelType(returnType), callbackMethod .getReturnType(), world.isInJava5Mode()); if (!isFallsThrough()) { returnConversionCode.append(InstructionFactory.createReturn(callbackMethod.getReturnType())); } } // initialize the bit flags for this shadow int bitflags = 0x000000; if (getKind().isTargetSameAsThis()) bitflags |= 0x010000; if (hasThis()) bitflags |= 0x001000; if (bindsThis(munger)) bitflags |= 0x000100; if (hasTarget()) bitflags |= 0x000010; if (bindsTarget(munger)) bitflags |= 0x000001; // ATAJ for @AJ aspect we need to link the closure with the joinpoint instance if (munger.getConcreteAspect() != null && munger.getConcreteAspect().isAnnotationStyleAspect() && munger.getDeclaringAspect() != null && munger.getDeclaringAspect().resolve(world).isAnnotationStyleAspect()) { // stick the bitflags on the stack and call the variant of linkClosureAndJoinPoint that takes an int closureInstantiation.append(fact.createConstant(Integer.valueOf(bitflags))); closureInstantiation.append(Utility.createInvoke(getFactory(), getWorld(), new MemberImpl(Member.METHOD, UnresolvedType .forName("org.aspectj.runtime.internal.AroundClosure"), Modifier.PUBLIC, "linkClosureAndJoinPoint", "(I)Lorg/aspectj/lang/ProceedingJoinPoint;"))); } InstructionList advice = new InstructionList(); advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation)); // invoke the advice advice.append(munger.getNonTestAdviceInstructions(this)); advice.append(returnConversionCode); if (getKind() == Shadow.MethodExecution && linenumber > 0) { advice.getStart().addTargeter(new LineNumberTag(linenumber)); } if (!hasDynamicTest) { range.append(advice); } else { InstructionList callback = makeCallToCallback(callbackMethod); InstructionList postCallback = new InstructionList(); if (terminatesWithReturn()) { callback.append(InstructionFactory.createReturn(callbackMethod.getReturnType())); } else { advice.append(InstructionFactory.createBranchInstruction(Constants.GOTO, postCallback .append(InstructionConstants.NOP))); } range.append(munger.getTestInstructions(this, advice.getStart(), callback.getStart(), advice.getStart())); range.append(advice); range.append(callback); range.append(postCallback); } } // exposed for testing InstructionList makeCallToCallback(LazyMethodGen callbackMethod) { InstructionFactory fact = getFactory(); InstructionList callback = new InstructionList(); if (thisVar != null) { callback.append(InstructionConstants.ALOAD_0); } if (targetVar != null && targetVar != thisVar) { callback.append(BcelRenderer.renderExpr(fact, world, targetVar)); } callback.append(BcelRenderer.renderExprs(fact, world, argVars)); // remember to render tjps if (thisJoinPointVar != null) { callback.append(BcelRenderer.renderExpr(fact, world, thisJoinPointVar)); } callback.append(Utility.createInvoke(fact, callbackMethod)); return callback; } /** side-effect-free */ private InstructionList makeClosureInstantiation(Member constructor, BcelVar holder) { // LazyMethodGen constructor) { InstructionFactory fact = getFactory(); BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY); // final Type objectArrayType = new ArrayType(Type.OBJECT, 1); final InstructionList il = new InstructionList(); int alen = getArgCount() + (thisVar == null ? 0 : 1) + ((targetVar != null && targetVar != thisVar) ? 1 : 0) + (thisJoinPointVar == null ? 0 : 1); il.append(Utility.createConstant(fact, alen)); il.append(fact.createNewArray(Type.OBJECT, (short) 1)); arrayVar.appendStore(il, fact); int stateIndex = 0; if (thisVar != null) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisVar); thisVar.setPositionInAroundState(stateIndex); stateIndex++; } if (targetVar != null && targetVar != thisVar) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, targetVar); targetVar.setPositionInAroundState(stateIndex); stateIndex++; } for (int i = 0, len = getArgCount(); i < len; i++) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, argVars[i]); argVars[i].setPositionInAroundState(stateIndex); stateIndex++; } if (thisJoinPointVar != null) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisJoinPointVar); thisJoinPointVar.setPositionInAroundState(stateIndex); stateIndex++; } il.append(fact.createNew(new ObjectType(constructor.getDeclaringType().getName()))); il.append(InstructionConstants.DUP); arrayVar.appendLoad(il, fact); il.append(Utility.createInvoke(fact, world, constructor)); if (getKind() == PreInitialization) { il.append(InstructionConstants.DUP); holder.appendStore(il, fact); } return il; } private IntMap makeProceedArgumentMap(BcelVar[] adviceArgs) { // System.err.println("coming in with " + Arrays.asList(adviceArgs)); IntMap ret = new IntMap(); for (int i = 0, len = adviceArgs.length; i < len; i++) { BcelVar v = adviceArgs[i]; if (v == null) continue; // XXX we don't know why this is required int pos = v.getPositionInAroundState(); if (pos >= 0) { // need this test to avoid args bound via cflow ret.put(pos, i); } } // System.err.println("returning " + ret); return ret; } /** * * * @param callbackMethod the method we will call back to when our run method gets called. * * @param proceedMap A map from state position to proceed argument position. May be non covering on state position. */ private LazyMethodGen makeClosureClassAndReturnConstructor(String closureClassName, LazyMethodGen callbackMethod, IntMap proceedMap) { String superClassName = "org.aspectj.runtime.internal.AroundClosure"; Type objectArrayType = new ArrayType(Type.OBJECT, 1); LazyClassGen closureClass = new LazyClassGen(closureClassName, superClassName, getEnclosingClass().getFileName(), Modifier.PUBLIC, new String[] {}, getWorld()); InstructionFactory fact = new InstructionFactory(closureClass.getConstantPool()); // constructor LazyMethodGen constructor = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, "<init>", new Type[] { objectArrayType }, new String[] {}, closureClass); InstructionList cbody = constructor.getBody(); cbody.append(InstructionFactory.createLoad(Type.OBJECT, 0)); cbody.append(InstructionFactory.createLoad(objectArrayType, 1)); cbody.append(fact .createInvoke(superClassName, "<init>", Type.VOID, new Type[] { objectArrayType }, Constants.INVOKESPECIAL)); cbody.append(InstructionFactory.createReturn(Type.VOID)); closureClass.addMethodGen(constructor); // method LazyMethodGen runMethod = new LazyMethodGen(Modifier.PUBLIC, Type.OBJECT, "run", new Type[] { objectArrayType }, new String[] {}, closureClass); InstructionList mbody = runMethod.getBody(); BcelVar proceedVar = new BcelVar(UnresolvedType.OBJECTARRAY.resolve(world), 1); // int proceedVarIndex = 1; BcelVar stateVar = new BcelVar(UnresolvedType.OBJECTARRAY.resolve(world), runMethod.allocateLocal(1)); // int stateVarIndex = runMethod.allocateLocal(1); mbody.append(InstructionFactory.createThis()); mbody.append(fact.createGetField(superClassName, "state", objectArrayType)); mbody.append(stateVar.createStore(fact)); // mbody.append(fact.createStore(objectArrayType, stateVarIndex)); Type[] stateTypes = callbackMethod.getArgumentTypes(); for (int i = 0, len = stateTypes.length; i < len; i++) { Type stateType = stateTypes[i]; ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world); if (proceedMap.hasKey(i)) { mbody.append(proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i), stateTypeX)); } else { mbody.append(stateVar.createConvertableArrayLoad(fact, i, stateTypeX)); } } mbody.append(Utility.createInvoke(fact, callbackMethod)); if (getKind() == PreInitialization) { mbody.append(Utility.createSet(fact, AjcMemberMaker.aroundClosurePreInitializationField())); mbody.append(InstructionConstants.ACONST_NULL); } else { mbody.append(Utility.createConversion(fact, callbackMethod.getReturnType(), Type.OBJECT)); } mbody.append(InstructionFactory.createReturn(Type.OBJECT)); closureClass.addMethodGen(runMethod); // class getEnclosingClass().addGeneratedInner(closureClass); return constructor; } // ---- extraction methods public LazyMethodGen extractMethod(String newMethodName, int visibilityModifier, ShadowMunger munger) { LazyMethodGen.assertGoodBody(range.getBody(), newMethodName); if (!getKind().allowsExtraction()) throw new BCException("Attempt to extract method from a shadow kind that does not support this operation (" + getKind() + ")"); LazyMethodGen freshMethod = createMethodGen(newMethodName, visibilityModifier); // System.err.println("******"); // System.err.println("ABOUT TO EXTRACT METHOD for" + this); // enclosingMethod.print(System.err); // System.err.println("INTO"); // freshMethod.print(System.err); // System.err.println("WITH REMAP"); // System.err.println(makeRemap()); range.extractInstructionsInto(freshMethod, makeRemap(), (getKind() != PreInitialization) && isFallsThrough()); if (getKind() == PreInitialization) { addPreInitializationReturnCode(freshMethod, getSuperConstructorParameterTypes()); } getEnclosingClass().addMethodGen(freshMethod, munger.getSourceLocation()); return freshMethod; } private void addPreInitializationReturnCode(LazyMethodGen extractedMethod, Type[] superConstructorTypes) { InstructionList body = extractedMethod.getBody(); final InstructionFactory fact = getFactory(); BcelVar arrayVar = new BcelVar(world.getCoreType(UnresolvedType.OBJECTARRAY), extractedMethod.allocateLocal(1)); int len = superConstructorTypes.length; body.append(Utility.createConstant(fact, len)); body.append(fact.createNewArray(Type.OBJECT, (short) 1)); arrayVar.appendStore(body, fact); for (int i = len - 1; i >= 0; i++) { // convert thing on top of stack to object body.append(Utility.createConversion(fact, superConstructorTypes[i], Type.OBJECT)); // push object array arrayVar.appendLoad(body, fact); // swap body.append(InstructionConstants.SWAP); // do object array store. body.append(Utility.createConstant(fact, i)); body.append(InstructionConstants.SWAP); body.append(InstructionFactory.createArrayStore(Type.OBJECT)); } arrayVar.appendLoad(body, fact); body.append(InstructionConstants.ARETURN); } private Type[] getSuperConstructorParameterTypes() { // assert getKind() == PreInitialization InstructionHandle superCallHandle = getRange().getEnd().getNext(); InvokeInstruction superCallInstruction = (InvokeInstruction) superCallHandle.getInstruction(); return superCallInstruction.getArgumentTypes(getEnclosingClass().getConstantPool()); } /** * make a map from old frame location to new frame location. Any unkeyed frame location picks out a copied local */ private IntMap makeRemap() { IntMap ret = new IntMap(5); int reti = 0; if (thisVar != null) { ret.put(0, reti++); // thisVar guaranteed to be 0 } if (targetVar != null && targetVar != thisVar) { ret.put(targetVar.getSlot(), reti++); } for (int i = 0, len = argVars.length; i < len; i++) { ret.put(argVars[i].getSlot(), reti); reti += argVars[i].getType().getSize(); } if (thisJoinPointVar != null) { ret.put(thisJoinPointVar.getSlot(), reti++); } // we not only need to put the arguments, we also need to remap their // aliases, which we so helpfully put into temps at the beginning of this join // point. if (!getKind().argsOnStack()) { int oldi = 0; int newi = 0; // if we're passing in a this and we're not argsOnStack we're always // passing in a target too if (arg0HoldsThis()) { ret.put(0, 0); oldi++; newi += 1; } // assert targetVar == thisVar for (int i = 0; i < getArgCount(); i++) { UnresolvedType type = getArgType(i); ret.put(oldi, newi); oldi += type.getSize(); newi += type.getSize(); } } // System.err.println("making remap for : " + this); // if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot()); // if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot()); // System.err.println(ret); return ret; } /** * The new method always static. It may take some extra arguments: this, target. If it's argsOnStack, then it must take both * this/target If it's argsOnFrame, it shares this and target. ??? rewrite this to do less array munging, please */ private LazyMethodGen createMethodGen(String newMethodName, int visibilityModifier) { Type[] parameterTypes = BcelWorld.makeBcelTypes(getArgTypes()); int modifiers = Modifier.FINAL | visibilityModifier; // XXX some bug // if (! isExpressionKind() && getSignature().isStrict(world)) { // modifiers |= Modifier.STRICT; // } modifiers |= Modifier.STATIC; if (targetVar != null && targetVar != thisVar) { UnresolvedType targetType = getTargetType(); targetType = ensureTargetTypeIsCorrect(targetType); // see pr109728,pr229910 - this fixes the case when the declaring class is sometype 'X' but the (gs)etfield // in the bytecode refers to a subtype of 'X'. This makes sure we use the type originally // mentioned in the fieldget instruction as the method parameter and *not* the type upon which the // field is declared because when the instructions are extracted into the new around body, // they will still refer to the subtype. if ((getKind() == FieldGet || getKind() == FieldSet) && getActualTargetType() != null && !getActualTargetType().equals(targetType.getName())) { targetType = UnresolvedType.forName(getActualTargetType()).resolve(world); } ResolvedMember resolvedMember = getSignature().resolve(world); // pr230075, pr197719 if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) && !samePackage(resolvedMember.getDeclaringType().getPackageName(), getEnclosingType().getPackageName()) && !resolvedMember.getName().equals("clone")) { if (!hasThis()) { // pr197719 - static accessor has been created to handle the call if (Modifier.isStatic(enclosingMethod.getAccessFlags()) && enclosingMethod.getName().startsWith("access$")) { targetType = BcelWorld.fromBcel(enclosingMethod.getArgumentTypes()[0]); } } else { if (!targetType.resolve(world).isAssignableFrom(getThisType().resolve(world))) { throw new BCException("bad bytecode"); } targetType = getThisType(); } } parameterTypes = addType(BcelWorld.makeBcelType(targetType), parameterTypes); } if (thisVar != null) { UnresolvedType thisType = getThisType(); parameterTypes = addType(BcelWorld.makeBcelType(thisType), parameterTypes); } // We always want to pass down thisJoinPoint in case we have already woven // some advice in here. If we only have a single piece of around advice on a // join point, it is unnecessary to accept (and pass) tjp. if (thisJoinPointVar != null) { parameterTypes = addTypeToEnd(LazyClassGen.tjpType, parameterTypes); // FIXME ALEX? which one // parameterTypes = addTypeToEnd(LazyClassGen.proceedingTjpType, parameterTypes); } UnresolvedType returnType; if (getKind() == PreInitialization) { returnType = UnresolvedType.OBJECTARRAY; } else { if (getKind() == ConstructorCall) returnType = getSignature().getDeclaringType(); else if (getKind() == FieldSet) returnType = ResolvedType.VOID; else returnType = getSignature().getReturnType().resolve(world); // returnType = getReturnType(); // for this and above lines, see pr137496 } return new LazyMethodGen(modifiers, BcelWorld.makeBcelType(returnType), newMethodName, parameterTypes, new String[0], // XXX again, we need to look up methods! // UnresolvedType.getNames(getSignature().getExceptions(world)), getEnclosingClass()); } private boolean samePackage(String p1, String p2) { if (p1 == null) return p2 == null; if (p2 == null) return false; return p1.equals(p2); } private Type[] addType(Type type, Type[] types) { int len = types.length; Type[] ret = new Type[len + 1]; ret[0] = type; System.arraycopy(types, 0, ret, 1, len); return ret; } private Type[] addTypeToEnd(Type type, Type[] types) { int len = types.length; Type[] ret = new Type[len + 1]; ret[len] = type; System.arraycopy(types, 0, ret, 0, len); return ret; } public BcelVar genTempVar(UnresolvedType typeX) { return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize())); } // public static final boolean CREATE_TEMP_NAMES = true; public BcelVar genTempVar(UnresolvedType typeX, String localName) { BcelVar tv = genTempVar(typeX); // if (CREATE_TEMP_NAMES) { // for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) { // if (Range.isRangeHandle(ih)) continue; // ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot())); // } // } return tv; } // eh doesn't think we need to garbage collect these (64K is a big number...) private int genTempVarIndex(int size) { return enclosingMethod.allocateLocal(size); } public InstructionFactory getFactory() { return getEnclosingClass().getFactory(); } public ISourceLocation getSourceLocation() { int sourceLine = getSourceLine(); if (sourceLine == 0 || sourceLine == -1) { // Thread.currentThread().dumpStack(); // System.err.println(this + ": " + range); return getEnclosingClass().getType().getSourceLocation(); } else { // For staticinitialization, if we have a nice offset, don't build a new source loc if (getKind() == Shadow.StaticInitialization && getEnclosingClass().getType().getSourceLocation().getOffset() != 0) { return getEnclosingClass().getType().getSourceLocation(); } else { int offset = 0; Kind kind = getKind(); if ((kind == MethodExecution) || (kind == ConstructorExecution) || (kind == AdviceExecution) || (kind == StaticInitialization) || (kind == PreInitialization) || (kind == Initialization)) { if (getEnclosingMethod().hasDeclaredLineNumberInfo()) { offset = getEnclosingMethod().getDeclarationOffset(); } } return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine, offset); } } } public Shadow getEnclosingShadow() { return enclosingShadow; } public LazyMethodGen getEnclosingMethod() { return enclosingMethod; } public boolean isFallsThrough() { return !terminatesWithReturn(); } public void setActualTargetType(String className) { this.actualInstructionTargetType = className; } public String getActualTargetType() { return actualInstructionTargetType; } }
249,710
Bug 249710 [compiling] Problem with -XterminateAfterCompilation
null
resolved fixed
cffe291
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-10-29T19:08:05Z"
"2008-10-05T23:40:00Z"
tests/bugs163/pr249710/Foo.java
249,710
Bug 249710 [compiling] Problem with -XterminateAfterCompilation
null
resolved fixed
cffe291
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-10-29T19:08:05Z"
"2008-10-05T23:40:00Z"
tests/src/org/aspectj/systemtest/ajc163/Ajc163Tests.java
/******************************************************************************* * Copyright (c) 2008 Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc163; import java.io.File; import junit.framework.Test; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc163Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testItdCCE_pr250091() { runTest("itd cce"); } // class A from java.net.URLClassLoader@1e4853f extends class java.lang.Object (false) // class java.lang.ClassNotFoundException from null extends class java.lang.Exception (true) // class Base from java.net.URLClassLoader@1e4853f extends class java.lang.Object (false) public void testBreakingRecovery_pr226163() { runTest("breaking recovery"); } public void testGenericMethodConversions_pr250632() { runTest("type conversion in generic itd"); } public void testGenericMethodBridging_pr250493() { runTest("bridge methods for generic itds"); } public void testGenericFieldBridging_pr252285() { runTest("bridge methods for generic itd fields"); } public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc163Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc163/ajc163.xml"); } }
256,400
Bug 256400 An internal error occurred during: "Delete and update AspectJ markers for CoreSource".
this occured during a clean and build of the project i'm working on. The following was inthe details. An internal error occurred during: "Delete and update AspectJ markers for CoreSource". java.lang.NullPointerException
resolved fixed
155a888
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-11-27T17:59:09Z"
"2008-11-25T10:46:40Z"
asm/src/org/aspectj/asm/internal/JDTLikeHandleProvider.java
/******************************************************************** * Copyright (c) 2006 Contributors. All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: IBM Corporation - initial API and implementation * Helen Hawkins - initial version *******************************************************************/ package org.aspectj.asm.internal; import java.io.File; import java.util.Iterator; import java.util.List; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IElementHandleProvider; import org.aspectj.asm.IProgramElement; import org.aspectj.bridge.ISourceLocation; /** * Creates JDT-like handles, for example * * method with string argument: <tjp{Demo.java[Demo~main~\[QString; method with generic argument: * <pkg{MyClass.java[MyClass~myMethod~QList\<QString;>; an aspect: <pkg*A1.aj}A1 advice with Integer arg: * <pkg*A8.aj}A8&afterReturning&QInteger; method call: <pkg*A10.aj[C~m1?method-call(void pkg.C.m2()) * */ public class JDTLikeHandleProvider implements IElementHandleProvider { private final AsmManager asm; // Need to keep our own count of the number of initializers // because this information cannot be gained from the ipe. private int initializerCounter = 0; private final char[] empty = new char[] {}; private final char[] countDelim = new char[] { HandleProviderDelimiter.COUNT.getDelimiter() }; private final String backslash = "\\"; private final String emptyString = ""; public JDTLikeHandleProvider(AsmManager asm) { this.asm = asm; } public String createHandleIdentifier(IProgramElement ipe) { // AjBuildManager.setupModel --> top of the tree is either // <root> or the .lst file if (ipe == null || (ipe.getKind().equals(IProgramElement.Kind.FILE_JAVA) && ipe.getName().equals("<root>"))) { return ""; } else if (ipe.getHandleIdentifier(false) != null) { // have already created the handle for this ipe // therefore just return it return ipe.getHandleIdentifier(); } else if (ipe.getKind().equals(IProgramElement.Kind.FILE_LST)) { String configFile = asm.getHierarchy().getConfigFile(); int start = configFile.lastIndexOf(File.separator); int end = configFile.lastIndexOf(".lst"); if (end != -1) { configFile = configFile.substring(start + 1, end); } else { configFile = new StringBuffer("=").append(configFile.substring(start + 1)).toString(); } ipe.setHandleIdentifier(configFile); return configFile; } else if (ipe.getKind() == IProgramElement.Kind.SOURCE_FOLDER) { StringBuffer sb = new StringBuffer(); sb.append(createHandleIdentifier(ipe.getParent())).append("/"); sb.append(ipe.getName()); String handle = sb.toString(); ipe.setHandleIdentifier(handle); return handle; } IProgramElement parent = ipe.getParent(); if (parent != null && parent.getKind().equals(IProgramElement.Kind.IMPORT_REFERENCE)) { // want to miss out '#import declaration' in the handle parent = ipe.getParent().getParent(); } StringBuffer handle = new StringBuffer(); // add the handle for the parent handle.append(createHandleIdentifier(parent)); // add the correct delimiter for this ipe handle.append(HandleProviderDelimiter.getDelimiter(ipe)); // add the name and any parameters unless we're an initializer // (initializer's names are '...') if (!ipe.getKind().equals(IProgramElement.Kind.INITIALIZER)) { if (ipe.getKind() == IProgramElement.Kind.CLASS && ipe.getName().endsWith("{..}")) { // format: 'new Runnable() {..}' but its anon-y-mouse // dont append anything, there may be a count to follow though (!<n>) } else { if (ipe.getKind() == IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR) { handle.append(ipe.getName()).append("_new").append(getParameters(ipe)); } else { // if (ipe.getKind() == IProgramElement.Kind.PACKAGE && ipe.getName().equals("DEFAULT")) { // // the delimiter will be in there, but skip the word DEFAULT as it is just a placeholder // } else { handle.append(ipe.getName()).append(getParameters(ipe)); } // } } } // add the count, for example '!2' if its the second ipe of its // kind in the aspect handle.append(getCount(ipe)); ipe.setHandleIdentifier(handle.toString()); return handle.toString(); } private String getParameters(IProgramElement ipe) { if (ipe.getParameterSignatures() == null || ipe.getParameterSignatures().isEmpty()) { return ""; } StringBuffer sb = new StringBuffer(); List parameterTypes = ipe.getParameterSignatures(); for (Iterator iter = parameterTypes.iterator(); iter.hasNext();) { char[] element = (char[]) iter.next(); sb.append(HandleProviderDelimiter.getDelimiter(ipe)); if (element[0] == HandleProviderDelimiter.TYPE.getDelimiter()) { // its an array sb.append(HandleProviderDelimiter.ESCAPE.getDelimiter()); sb.append(HandleProviderDelimiter.TYPE.getDelimiter()); sb.append(NameConvertor.getTypeName(CharOperation.subarray(element, 1, element.length))); } else if (element[0] == NameConvertor.PARAMETERIZED) { // its a parameterized type sb.append(NameConvertor.createShortName(element)); } else { sb.append(NameConvertor.getTypeName(element)); } } return sb.toString(); } /** * Determine a count to be suffixed to the handle, this is only necessary for identical looking entries at the same level in the * model (for example two anonymous class declarations). The format is !<n> where n will be greater than 2. * * @param ipe the program element for which the handle is being constructed * @return a char suffix that will either be empty or of the form "!<n>" */ private char[] getCount(IProgramElement ipe) { // TODO could optimize this code char[] byteCodeName = ipe.getBytecodeName().toCharArray(); if (ipe.getKind().isDeclare()) { int index = CharOperation.lastIndexOf('_', byteCodeName); if (index != -1) { return convertCount(CharOperation.subarray(byteCodeName, index + 1, byteCodeName.length)); } } else if (ipe.getKind().equals(IProgramElement.Kind.ADVICE)) { // Look at any peer advice int count = 1; List kids = ipe.getParent().getChildren(); String ipeSig = ipe.getBytecodeSignature(); for (Iterator iterator = kids.iterator(); iterator.hasNext();) { IProgramElement object = (IProgramElement) iterator.next(); if (object.equals(ipe)) { break; } if (object.getKind() == ipe.getKind()) { if (object.getName().equals(ipe.getName())) { String sig1 = object.getBytecodeSignature(); if (sig1 == null && ipeSig == null || sig1.equals(ipeSig)) { String existingHandle = object.getHandleIdentifier(); int suffixPosition = existingHandle.indexOf('!'); if (suffixPosition != -1) { count = new Integer(existingHandle.substring(suffixPosition + 1)).intValue() + 1; } else { if (count == 1) { count = 2; } } } } } } if (count > 1) { return CharOperation.concat(countDelim, new Integer(count).toString().toCharArray()); } } else if (ipe.getKind().equals(IProgramElement.Kind.INITIALIZER)) { return String.valueOf(++initializerCounter).toCharArray(); } else if (ipe.getKind().equals(IProgramElement.Kind.CODE)) { int index = CharOperation.lastIndexOf('!', byteCodeName); if (index != -1) { return convertCount(CharOperation.subarray(byteCodeName, index + 1, byteCodeName.length)); } } else if (ipe.getKind() == IProgramElement.Kind.CLASS) { // depends on previous children int count = 1; List kids = ipe.getParent().getChildren(); if (ipe.getName().endsWith("{..}")) { // only depends on previous anonymous children, name irrelevant for (Iterator iterator = kids.iterator(); iterator.hasNext();) { IProgramElement object = (IProgramElement) iterator.next(); if (object.equals(ipe)) { break; } if (object.getKind() == ipe.getKind()) { if (object.getName().endsWith("{..}")) { String existingHandle = object.getHandleIdentifier(); int suffixPosition = existingHandle.indexOf('!'); if (suffixPosition != -1) { count = new Integer(existingHandle.substring(suffixPosition + 1)).intValue() + 1; } else { if (count == 1) { count = 2; } } } } } } else { for (Iterator iterator = kids.iterator(); iterator.hasNext();) { IProgramElement object = (IProgramElement) iterator.next(); if (object.equals(ipe)) { break; } if (object.getKind() == ipe.getKind()) { if (object.getName().equals(ipe.getName())) { String existingHandle = object.getHandleIdentifier(); int suffixPosition = existingHandle.indexOf('!'); if (suffixPosition != -1) { count = new Integer(existingHandle.substring(suffixPosition + 1)).intValue() + 1; } else { if (count == 1) { count = 2; } } } } } } if (count > 1) { return CharOperation.concat(countDelim, new Integer(count).toString().toCharArray()); } } return empty; } /** * Only returns the count if it's not equal to 1 */ private char[] convertCount(char[] c) { if ((c.length == 1 && c[0] != ' ' && c[0] != '1') || c.length > 1) { return CharOperation.concat(countDelim, c); } return empty; } public String getFileForHandle(String handle) { IProgramElement node = asm.getHierarchy().getElement(handle); if (node != null) { return asm.getCanonicalFilePath(node.getSourceLocation().getSourceFile()); } else if (handle.charAt(0) == HandleProviderDelimiter.ASPECT_CU.getDelimiter() || handle.charAt(0) == HandleProviderDelimiter.COMPILATIONUNIT.getDelimiter()) { // it's something like *MyAspect.aj or {MyClass.java. In other words // it's a file node that's been created with no children and no // parent return backslash + handle.substring(1); } return emptyString; } public int getLineNumberForHandle(String handle) { IProgramElement node = asm.getHierarchy().getElement(handle); if (node != null) { return node.getSourceLocation().getLine(); } else if (handle.charAt(0) == HandleProviderDelimiter.ASPECT_CU.getDelimiter() || handle.charAt(0) == HandleProviderDelimiter.COMPILATIONUNIT.getDelimiter()) { // it's something like *MyAspect.aj or {MyClass.java. In other words // it's a file node that's been created with no children and no // parent return 1; } return -1; } public int getOffSetForHandle(String handle) { IProgramElement node = asm.getHierarchy().getElement(handle); if (node != null) { return node.getSourceLocation().getOffset(); } else if (handle.charAt(0) == HandleProviderDelimiter.ASPECT_CU.getDelimiter() || handle.charAt(0) == HandleProviderDelimiter.COMPILATIONUNIT.getDelimiter()) { // it's something like *MyAspect.aj or {MyClass.java. In other words // it's a file node that's been created with no children and no // parent return 0; } return -1; } public String createHandleIdentifier(ISourceLocation location) { IProgramElement node = asm.getHierarchy().findElementForSourceLine(location); if (node != null) { return createHandleIdentifier(node); } return null; } public String createHandleIdentifier(File sourceFile, int line, int column, int offset) { IProgramElement node = asm.getHierarchy().findElementForOffSet(sourceFile.getAbsolutePath(), line, offset); if (node != null) { return createHandleIdentifier(node); } return null; } public boolean dependsOnLocation() { // handles are independent of soureLocations therefore return false return false; } public void initialize() { // reset the initializer count. This ensures we return the // same handle as JDT for initializers. initializerCounter = 0; } }
185,447
Bug 185447 [plan] [ataspectj] Abstract @Aspect causing problems
Trying to use an abstract @Aspect from a library jar file is causing problems. In the (soon to be) attached zip of eclipse projects: * logging-library: defines two abstract trivial logging aspects, one in code-style and one in @AspectJ style. * sample-system: uses the code-style abstract aspect successfully * sample-system2: uses the @AspectJ style abstract aspect and won't compile in Eclipse Exception: java.lang.NullPointerException at org.aspectj.weaver.bcel.AtAjAttributes$LazyResolvedPointcutDefinition.getPointcut(AtAjAttributes.java:1632) at org.aspectj.weaver.ShadowMunger.addChildNodes(ShadowMunger.java:258) at org.aspectj.weaver.ShadowMunger.createHierarchy(ShadowMunger.java:247) at org.aspectj.weaver.AsmRelationshipProvider.adviceMunger(AsmRelationshipProvider.java:180) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:717) a ... int;)Ljava/lang/String; ARETURN end public Object run(Object[])
resolved fixed
120b47f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-12-01T21:00:43Z"
"2007-05-03T22:06:40Z"
weaver/src/org/aspectj/weaver/bcel/AtAjAttributes.java
/******************************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * initial implementation Alexandre Vasseur *******************************************************************************/ package org.aspectj.weaver.bcel; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.Constant; import org.aspectj.apache.bcel.classfile.ConstantUtf8; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.LocalVariable; import org.aspectj.apache.bcel.classfile.LocalVariableTable; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen; import org.aspectj.apache.bcel.classfile.annotation.ClassElementValueGen; import org.aspectj.apache.bcel.classfile.annotation.ElementNameValuePairGen; import org.aspectj.apache.bcel.classfile.annotation.RuntimeAnnotations; import org.aspectj.apache.bcel.classfile.annotation.RuntimeVisibleAnnotations; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.BindingScope; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.MethodDelegateTypeMunger; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.patterns.Bindings; import org.aspectj.weaver.patterns.DeclareErrorOrWarning; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.FormalBinding; import org.aspectj.weaver.patterns.IScope; import org.aspectj.weaver.patterns.ParserException; import org.aspectj.weaver.patterns.PatternParser; import org.aspectj.weaver.patterns.PerCflow; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.PerFromSuper; import org.aspectj.weaver.patterns.PerObject; import org.aspectj.weaver.patterns.PerSingleton; import org.aspectj.weaver.patterns.PerTypeWithin; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.TypePattern; /** * Annotation defined aspect reader. Reads the Java 5 annotations and turns them into AjAttributes * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public class AtAjAttributes { private final static List EMPTY_LIST = new ArrayList(); private final static String[] EMPTY_STRINGS = new String[0]; private final static String VALUE = "value"; private final static String ARGNAMES = "argNames"; private final static String POINTCUT = "pointcut"; private final static String THROWING = "throwing"; private final static String RETURNING = "returning"; private final static String STRING_DESC = "Ljava/lang/String;"; /** * A struct that allows to add extra arguments without always breaking the API */ private static class AjAttributeStruct { /** * The list of AjAttribute.XXX that we are populating from the @AJ read */ List ajAttributes = new ArrayList(); /** * The resolved type (class) for which we are reading @AJ for (be it class, method, field annotations) */ final ResolvedType enclosingType; final ISourceContext context; final IMessageHandler handler; public AjAttributeStruct(ResolvedType type, ISourceContext sourceContext, IMessageHandler messageHandler) { enclosingType = type; context = sourceContext; handler = messageHandler; } } /** * A struct when we read @AJ on method * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ private static class AjAttributeMethodStruct extends AjAttributeStruct { // argument names used for formal binding private String[] m_argumentNamesLazy = null; public String unparsedArgumentNames = null; // Set only if discovered as argNames attribute of annotation final Method method; final BcelMethod bMethod; public AjAttributeMethodStruct(Method method, BcelMethod bMethod, ResolvedType type, ISourceContext sourceContext, IMessageHandler messageHandler) { super(type, sourceContext, messageHandler); this.method = method; this.bMethod = bMethod; } public String[] getArgumentNames() { if (m_argumentNamesLazy == null) { m_argumentNamesLazy = getMethodArgumentNames(method, unparsedArgumentNames, this); } return m_argumentNamesLazy; } } /** * A struct when we read @AJ on field */ private static class AjAttributeFieldStruct extends AjAttributeStruct { final Field field; final BcelField bField; public AjAttributeFieldStruct(Field field, BcelField bField, ResolvedType type, ISourceContext sourceContext, IMessageHandler messageHandler) { super(type, sourceContext, messageHandler); this.field = field; this.bField = bField; } } /** * Annotations are RuntimeVisible only. This allow us to not visit RuntimeInvisible ones. * * @param attribute * @return true if runtime visible annotation */ public static boolean acceptAttribute(Attribute attribute) { return (attribute instanceof RuntimeVisibleAnnotations); } /** * Extract class level annotations and turn them into AjAttributes. * * @param javaClass * @param type * @param context * @param msgHandler * @return list of AjAttributes */ public static List readAj5ClassAttributes(AsmManager model, JavaClass javaClass, ReferenceType type, ISourceContext context, IMessageHandler msgHandler, boolean isCodeStyleAspect) { boolean ignoreThisClass = javaClass.getClassName().charAt(0) == 'o' && javaClass.getClassName().startsWith("org.aspectj.lang.annotation"); if (ignoreThisClass) return EMPTY_LIST; boolean containsPointcut = false; boolean containsAnnotationClassReference = false; Constant[] cpool = javaClass.getConstantPool().getConstantPool(); for (int i = 0; i < cpool.length; i++) { Constant constant = cpool[i]; if (constant != null && constant.getTag() == Constants.CONSTANT_Utf8) { String constantValue = ((ConstantUtf8) constant).getBytes(); if (constantValue.length() > 28 && constantValue.charAt(1) == 'o') { if (constantValue.startsWith("Lorg/aspectj/lang/annotation")) { containsAnnotationClassReference = true; if ("Lorg/aspectj/lang/annotation/DeclareAnnotation;".equals(constantValue)) { msgHandler.handleMessage(new Message( "Found @DeclareAnnotation while current release does not support it (see '" + type.getName() + "')", IMessage.WARNING, null, type.getSourceLocation())); } if ("Lorg/aspectj/lang/annotation/Pointcut;".equals(constantValue)) { containsPointcut = true; } } } } } if (!containsAnnotationClassReference) return EMPTY_LIST; AjAttributeStruct struct = new AjAttributeStruct(type, context, msgHandler); Attribute[] attributes = javaClass.getAttributes(); boolean hasAtAspectAnnotation = false; boolean hasAtPrecedenceAnnotation = false; for (int i = 0; i < attributes.length; i++) { Attribute attribute = attributes[i]; if (acceptAttribute(attribute)) { RuntimeAnnotations rvs = (RuntimeAnnotations) attribute; // we don't need to look for several attribute occurrences since it cannot happen as per JSR175 if (!isCodeStyleAspect && !javaClass.isInterface()) { hasAtAspectAnnotation = handleAspectAnnotation(rvs, struct); // TODO AV - if put outside the if isCodeStyleAspect then we would enable mix style hasAtPrecedenceAnnotation = handlePrecedenceAnnotation(rvs, struct); } // there can only be one RuntimeVisible bytecode attribute break; } } // basic semantic check if (hasAtPrecedenceAnnotation && !hasAtAspectAnnotation) { msgHandler.handleMessage(new Message("Found @DeclarePrecedence on a non @Aspect type '" + type.getName() + "'", IMessage.WARNING, null, type.getSourceLocation())); // bypass what we have read return EMPTY_LIST; } // the following block will not detect @Pointcut in non @Aspect types for optimization purpose if (!(hasAtAspectAnnotation || isCodeStyleAspect) && !containsPointcut) { return EMPTY_LIST; } // FIXME AV - turn on when ajcMightHaveAspect // if (hasAtAspectAnnotation && type.isInterface()) { // msgHandler.handleMessage( // new Message( // "Found @Aspect on an interface type '" + type.getName() + "'", // IMessage.WARNING, // null, // type.getSourceLocation() // ) // ); // // bypass what we have read // return EMPTY_LIST; // } // semantic check: @Aspect must be public // FIXME AV - do we really want to enforce that? // if (hasAtAspectAnnotation && !javaClass.isPublic()) { // msgHandler.handleMessage( // new Message( // "Found @Aspect annotation on a non public class '" + javaClass.getClassName() + "'", // IMessage.ERROR, // null, // type.getSourceLocation() // ) // ); // return EMPTY_LIST; // } // code style pointcuts are class attributes // we need to gather the @AJ pointcut right now and not at method level annotation extraction time // in order to be able to resolve the pointcut references later on // we don't need to look in super class, the pointcut reference in the grammar will do it for (int i = 0; i < javaClass.getMethods().length; i++) { Method method = javaClass.getMethods()[i]; if (method.getName().startsWith(NameMangler.PREFIX)) continue; // already dealt with by ajc... // FIXME alex optimize, this method struct will gets recreated for advice extraction AjAttributeMethodStruct mstruct = null; boolean processedPointcut = false; Attribute[] mattributes = method.getAttributes(); for (int j = 0; j < mattributes.length; j++) { Attribute mattribute = mattributes[j]; if (acceptAttribute(mattribute)) { mstruct = new AjAttributeMethodStruct(method, null, type, context, msgHandler);// FIXME AVASM processedPointcut = handlePointcutAnnotation((RuntimeAnnotations) mattribute, mstruct); // there can only be one RuntimeVisible bytecode attribute break; } } if (processedPointcut) { // FIXME asc should check we aren't adding multiple versions... will do once I get the tests passing again... struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo()); struct.ajAttributes.addAll(mstruct.ajAttributes); } } // code style declare error / warning / implements / parents are field attributes Field[] fs = javaClass.getFields(); for (int i = 0; i < fs.length; i++) { Field field = fs[i]; if (field.getName().startsWith(NameMangler.PREFIX)) continue; // already dealt with by ajc... // FIXME alex optimize, this method struct will gets recreated for advice extraction AjAttributeFieldStruct fstruct = new AjAttributeFieldStruct(field, null, type, context, msgHandler); Attribute[] fattributes = field.getAttributes(); for (int j = 0; j < fattributes.length; j++) { Attribute fattribute = fattributes[j]; if (acceptAttribute(fattribute)) { RuntimeAnnotations frvs = (RuntimeAnnotations) fattribute; if (handleDeclareErrorOrWarningAnnotation(model, frvs, fstruct) || handleDeclareParentsAnnotation(frvs, fstruct)) { // semantic check - must be in an @Aspect [remove if previous block bypassed in advance] if (!type.isAnnotationStyleAspect() && !isCodeStyleAspect) { msgHandler.handleMessage(new Message("Found @AspectJ annotations in a non @Aspect type '" + type.getName() + "'", IMessage.WARNING, null, type.getSourceLocation())); // go ahead } } // there can only be one RuntimeVisible bytecode attribute break; } } struct.ajAttributes.addAll(fstruct.ajAttributes); } return struct.ajAttributes; } /** * Extract method level annotations and turn them into AjAttributes. * * @param method * @param type * @param context * @param msgHandler * @return list of AjAttributes */ public static List readAj5MethodAttributes(Method method, BcelMethod bMethod, ResolvedType type, ResolvedPointcutDefinition preResolvedPointcut, ISourceContext context, IMessageHandler msgHandler) { if (method.getName().startsWith(NameMangler.PREFIX)) return Collections.EMPTY_LIST; // already dealt with by ajc... AjAttributeMethodStruct struct = new AjAttributeMethodStruct(method, bMethod, type, context, msgHandler); Attribute[] attributes = method.getAttributes(); // we remember if we found one @AJ annotation for minimal semantic error reporting // the real reporting beeing done thru AJDT and the compiler mapping @AJ to AjAtttribute // or thru APT // // Note: we could actually skip the whole thing if type is not itself an @Aspect // but then we would not see any warning. We do bypass for pointcut but not for advice since it would // be too silent. boolean hasAtAspectJAnnotation = false; boolean hasAtAspectJAnnotationMustReturnVoid = false; for (int i = 0; i < attributes.length; i++) { Attribute attribute = attributes[i]; try { if (acceptAttribute(attribute)) { RuntimeAnnotations rvs = (RuntimeAnnotations) attribute; hasAtAspectJAnnotationMustReturnVoid = hasAtAspectJAnnotationMustReturnVoid || handleBeforeAnnotation(rvs, struct, preResolvedPointcut); hasAtAspectJAnnotationMustReturnVoid = hasAtAspectJAnnotationMustReturnVoid || handleAfterAnnotation(rvs, struct, preResolvedPointcut); hasAtAspectJAnnotationMustReturnVoid = hasAtAspectJAnnotationMustReturnVoid || handleAfterReturningAnnotation(rvs, struct, preResolvedPointcut, bMethod); hasAtAspectJAnnotationMustReturnVoid = hasAtAspectJAnnotationMustReturnVoid || handleAfterThrowingAnnotation(rvs, struct, preResolvedPointcut, bMethod); hasAtAspectJAnnotation = hasAtAspectJAnnotation || handleAroundAnnotation(rvs, struct, preResolvedPointcut); // there can only be one RuntimeVisible bytecode attribute break; } } catch (ReturningFormalNotDeclaredInAdviceSignatureException e) { msgHandler.handleMessage(new Message(WeaverMessages.format(WeaverMessages.RETURNING_FORMAL_NOT_DECLARED_IN_ADVICE, e.getFormalName()), IMessage.ERROR, null, bMethod.getSourceLocation())); } catch (ThrownFormalNotDeclaredInAdviceSignatureException e) { msgHandler.handleMessage(new Message(WeaverMessages.format(WeaverMessages.THROWN_FORMAL_NOT_DECLARED_IN_ADVICE, e .getFormalName()), IMessage.ERROR, null, bMethod.getSourceLocation())); } } hasAtAspectJAnnotation = hasAtAspectJAnnotation || hasAtAspectJAnnotationMustReturnVoid; // semantic check - must be in an @Aspect [remove if previous block bypassed in advance] if (hasAtAspectJAnnotation && !type.isAspect()) { // isAnnotationStyleAspect()) { msgHandler.handleMessage(new Message("Found @AspectJ annotations in a non @Aspect type '" + type.getName() + "'", IMessage.WARNING, null, type.getSourceLocation())); // go ahead } // semantic check - advice must be public if (hasAtAspectJAnnotation && !struct.method.isPublic()) { msgHandler.handleMessage(new Message("Found @AspectJ annotation on a non public advice '" + methodToString(struct.method) + "'", IMessage.ERROR, null, type.getSourceLocation())); // go ahead } // semantic check - advice must not be static if (hasAtAspectJAnnotation && struct.method.isStatic()) { msgHandler.handleMessage(MessageUtil.error("Advice cannot be declared static '" + methodToString(struct.method) + "'", type.getSourceLocation())); // new Message( // "Advice cannot be declared static '" + methodToString(struct.method) + "'", // IMessage.ERROR, // null, // type.getSourceLocation() // ) // ); // go ahead } // semantic check for non around advice must return void if (hasAtAspectJAnnotationMustReturnVoid && !Type.VOID.equals(struct.method.getReturnType())) { msgHandler.handleMessage(new Message("Found @AspectJ annotation on a non around advice not returning void '" + methodToString(struct.method) + "'", IMessage.ERROR, null, type.getSourceLocation())); // go ahead } return struct.ajAttributes; } /** * Extract field level annotations and turn them into AjAttributes. * * @param field * @param type * @param context * @param msgHandler * @return list of AjAttributes, always empty for now */ public static List readAj5FieldAttributes(Field field, BcelField bField, ResolvedType type, ISourceContext context, IMessageHandler msgHandler) { // Note: field annotation are for ITD and DEOW - processed at class level directly return Collections.EMPTY_LIST; } /** * Read @Aspect * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleAspectAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeStruct struct) { AnnotationGen aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.ASPECT_ANNOTATION); if (aspect != null) { // semantic check for inheritance (only one level up) boolean extendsAspect = false; if (!"java.lang.Object".equals(struct.enclosingType.getSuperclass().getName())) { if (!struct.enclosingType.getSuperclass().isAbstract() && struct.enclosingType.getSuperclass().isAspect()) { reportError("cannot extend a concrete aspect", struct); return false; } extendsAspect = struct.enclosingType.getSuperclass().isAspect(); } ElementNameValuePairGen aspectPerClause = getAnnotationElement(aspect, VALUE); final PerClause perClause; if (aspectPerClause == null) { // empty value means singleton unless inherited if (!extendsAspect) { perClause = new PerSingleton(); } else { perClause = new PerFromSuper(struct.enclosingType.getSuperclass().getPerClause().getKind()); } } else { String perX = aspectPerClause.getValue().stringifyValue(); if (perX == null || perX.length() <= 0) { perClause = new PerSingleton(); } else { perClause = parsePerClausePointcut(perX, struct); } } if (perClause == null) { // could not parse it, ignore the aspect return false; } else { perClause.setLocation(struct.context, -1, -1);// struct.context.getOffset(), struct.context.getOffset()+1);//FIXME // AVASM // FIXME asc see related comment way about about the version... struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo()); AjAttribute.Aspect aspectAttribute = new AjAttribute.Aspect(perClause); struct.ajAttributes.add(aspectAttribute); FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; final IScope binding; binding = new BindingScope(struct.enclosingType, struct.context, bindings); // // we can't resolve here since the perclause typically refers to pointcuts // // defined in the aspect that we haven't told the BcelObjectType about yet. // // perClause.resolve(binding); // so we prepare to do it later... aspectAttribute.setResolutionScope(binding); return true; } } return false; } /** * Read a perClause, returns null on failure and issue messages * * @param perClauseString like "pertarget(.....)" * @param struct for which we are parsing the per clause * @return a PerClause instance */ private static PerClause parsePerClausePointcut(String perClauseString, AjAttributeStruct struct) { final String pointcutString; Pointcut pointcut = null; TypePattern typePattern = null; final PerClause perClause; if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERCFLOW.getName())) { pointcutString = PerClause.KindAnnotationPrefix.PERCFLOW.extractPointcut(perClauseString); pointcut = parsePointcut(pointcutString, struct, false); perClause = new PerCflow(pointcut, false); } else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERCFLOWBELOW.getName())) { pointcutString = PerClause.KindAnnotationPrefix.PERCFLOWBELOW.extractPointcut(perClauseString); pointcut = parsePointcut(pointcutString, struct, false); perClause = new PerCflow(pointcut, true); } else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERTARGET.getName())) { pointcutString = PerClause.KindAnnotationPrefix.PERTARGET.extractPointcut(perClauseString); pointcut = parsePointcut(pointcutString, struct, false); perClause = new PerObject(pointcut, false); } else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERTHIS.getName())) { pointcutString = PerClause.KindAnnotationPrefix.PERTHIS.extractPointcut(perClauseString); pointcut = parsePointcut(pointcutString, struct, false); perClause = new PerObject(pointcut, true); } else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERTYPEWITHIN.getName())) { pointcutString = PerClause.KindAnnotationPrefix.PERTYPEWITHIN.extractPointcut(perClauseString); typePattern = parseTypePattern(pointcutString, struct); perClause = new PerTypeWithin(typePattern); } else if (perClauseString.equalsIgnoreCase(PerClause.SINGLETON.getName() + "()")) { perClause = new PerSingleton(); } else { // could not parse the @AJ perclause - fallback to singleton and issue an error reportError("@Aspect per clause cannot be read '" + perClauseString + "'", struct); return null; } if (!PerClause.SINGLETON.equals(perClause.getKind()) && !PerClause.PERTYPEWITHIN.equals(perClause.getKind()) && pointcut == null) { // we could not parse the pointcut return null; } if (PerClause.PERTYPEWITHIN.equals(perClause.getKind()) && typePattern == null) { // we could not parse the type pattern return null; } return perClause; } /** * Read @DeclarePrecedence * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handlePrecedenceAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeStruct struct) { AnnotationGen aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREPRECEDENCE_ANNOTATION); if (aspect != null) { ElementNameValuePairGen precedence = getAnnotationElement(aspect, VALUE); if (precedence != null) { String precedencePattern = precedence.getValue().stringifyValue(); PatternParser parser = new PatternParser(precedencePattern); DeclarePrecedence ajPrecedence = parser.parseDominates(); struct.ajAttributes.add(new AjAttribute.DeclareAttribute(ajPrecedence)); return true; } } return false; } // /** // * Read @DeclareImplements // * // * @param runtimeAnnotations // * @param struct // * @return true if found // */ // private static boolean handleDeclareImplementsAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeFieldStruct // struct) {//, ResolvedPointcutDefinition preResolvedPointcut) { // Annotation deci = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREIMPLEMENTS_ANNOTATION); // if (deci != null) { // ElementNameValuePairGen deciPatternNVP = getAnnotationElement(deci, VALUE); // String deciPattern = deciPatternNVP.getValue().stringifyValue(); // if (deciPattern != null) { // TypePattern typePattern = parseTypePattern(deciPattern, struct); // ResolvedType fieldType = UnresolvedType.forSignature(struct.field.getSignature()).resolve(struct.enclosingType.getWorld()); // if (fieldType.isPrimitiveType()) { // return false; // } else if (fieldType.isInterface()) { // TypePattern parent = new ExactTypePattern(UnresolvedType.forSignature(struct.field.getSignature()), false, false); // parent.resolve(struct.enclosingType.getWorld()); // List parents = new ArrayList(1); // parents.add(parent); // //TODO kick ISourceLocation sl = struct.bField.getSourceLocation(); ?? // struct.ajAttributes.add( // new AjAttribute.DeclareAttribute( // new DeclareParents( // typePattern, // parents, // false // ) // ) // ); // return true; // } else { // reportError("@DeclareImplements: can only be used on field whose type is an interface", struct); // return false; // } // } // } // return false; // } /** * Read @DeclareParents * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleDeclareParentsAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeFieldStruct struct) {// , // ResolvedPointcutDefinition // preResolvedPointcut) // { AnnotationGen decp = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREPARENTS_ANNOTATION); if (decp != null) { ElementNameValuePairGen decpPatternNVP = getAnnotationElement(decp, VALUE); String decpPattern = decpPatternNVP.getValue().stringifyValue(); if (decpPattern != null) { TypePattern typePattern = parseTypePattern(decpPattern, struct); ResolvedType fieldType = UnresolvedType.forSignature(struct.field.getSignature()).resolve( struct.enclosingType.getWorld()); if (fieldType.isInterface()) { TypePattern parent = parseTypePattern(fieldType.getName(), struct); FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings); // first add the declare implements like List parents = new ArrayList(1); parents.add(parent); DeclareParents dp = new DeclareParents(typePattern, parents, false); dp.resolve(binding); // resolves the parent and child parts of the decp // resolve this so that we can use it for the MethodDelegateMungers below. // eg. '@Coloured *' will change from a WildTypePattern to an 'AnyWithAnnotationTypePattern' after this // resolution typePattern = typePattern.resolveBindings(binding, Bindings.NONE, false, false); // TODO kick ISourceLocation sl = struct.bField.getSourceLocation(); ?? // dp.setLocation(dp.getDeclaringType().getSourceContext(), // dp.getDeclaringType().getSourceLocation().getOffset(), // dp.getDeclaringType().getSourceLocation().getOffset()); dp.setLocation(struct.context, -1, -1); // not ideal... struct.ajAttributes.add(new AjAttribute.DeclareAttribute(dp)); // do we have a defaultImpl=xxx.class (ie implementation) String defaultImplClassName = null; ElementNameValuePairGen defaultImplNVP = getAnnotationElement(decp, "defaultImpl"); if (defaultImplNVP != null) { ClassElementValueGen defaultImpl = (ClassElementValueGen) defaultImplNVP.getValue(); defaultImplClassName = UnresolvedType.forSignature(defaultImpl.getClassString()).getName(); if (defaultImplClassName.equals("org.aspectj.lang.annotation.DeclareParents")) { defaultImplClassName = null; } else { // check public no arg ctor ResolvedType impl = struct.enclosingType.getWorld().resolve(defaultImplClassName, false); ResolvedMember[] mm = impl.getDeclaredMethods(); boolean hasNoCtorOrANoArgOne = true; for (int i = 0; i < mm.length; i++) { ResolvedMember resolvedMember = mm[i]; if (resolvedMember.getName().equals("<init>")) { hasNoCtorOrANoArgOne = false; if (resolvedMember.getParameterTypes().length == 0 && resolvedMember.isPublic()) { hasNoCtorOrANoArgOne = true; } } if (hasNoCtorOrANoArgOne) { break; } } if (!hasNoCtorOrANoArgOne) { reportError("@DeclareParents: defaultImpl=\"" + defaultImplClassName + "\" has no public no-arg constructor", struct); } if (!fieldType.isAssignableFrom(impl)) { reportError("@DeclareParents: defaultImpl=\"" + defaultImplClassName + "\" does not implement the interface '" + fieldType.toString() + "'", struct); } } } // then iterate on field interface hierarchy (not object) boolean hasAtLeastOneMethod = false; ResolvedMember[] methods = (ResolvedMember[]) fieldType.getMethodsWithoutIterator(true, false).toArray( new ResolvedMember[0]); for (int i = 0; i < methods.length; i++) { ResolvedMember method = methods[i]; if (method.isAbstract()) { // moved to be detected at weave time if the target doesnt implement the methods // if (defaultImplClassName == null) { // // non marker interface with no default impl provided // reportError("@DeclareParents: used with a non marker interface and no defaultImpl=\"...\" provided", // struct); // return false; // } hasAtLeastOneMethod = true; MethodDelegateTypeMunger mdtm = new MethodDelegateTypeMunger(method, struct.enclosingType, defaultImplClassName, typePattern); mdtm.setSourceLocation(struct.enclosingType.getSourceLocation()); struct.ajAttributes.add(new AjAttribute.TypeMunger(mdtm)); } } // successfull so far, we thus need a bcel type munger to have // a field hosting the mixin in the target type if (hasAtLeastOneMethod && defaultImplClassName != null) { struct.ajAttributes.add(new AjAttribute.TypeMunger(new MethodDelegateTypeMunger.FieldHostTypeMunger( AjcMemberMaker.itdAtDeclareParentsField(null,// prototyped fieldType, struct.enclosingType), struct.enclosingType, typePattern))); } return true; } else { reportError("@DeclareParents: can only be used on a field whose type is an interface", struct); return false; } } } return false; } /** * Read @Before * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleBeforeAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeMethodStruct struct, ResolvedPointcutDefinition preResolvedPointcut) { AnnotationGen before = getAnnotation(runtimeAnnotations, AjcMemberMaker.BEFORE_ANNOTATION); if (before != null) { ElementNameValuePairGen beforeAdvice = getAnnotationElement(before, VALUE); if (beforeAdvice != null) { // this/target/args binding String argumentNames = getArgNamesValue(before); if (argumentNames != null) { struct.unparsedArgumentNames = argumentNames; } FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; try { bindings = extractBindings(struct); } catch (UnreadableDebugInfoException unreadableDebugInfoException) { return false; } IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings); // joinpoint, staticJoinpoint binding int extraArgument = extractExtraArgument(struct.method); Pointcut pc = null; if (preResolvedPointcut != null) { pc = preResolvedPointcut.getPointcut(); // pc.resolve(binding); } else { pc = parsePointcut(beforeAdvice.getValue().stringifyValue(), struct, false); if (pc == null) return false;// parse error pc = pc.resolve(binding); } setIgnoreUnboundBindingNames(pc, bindings); ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(), struct.bMethod .getDeclarationOffset()); struct.ajAttributes.add(new AjAttribute.AdviceAttribute(AdviceKind.Before, pc, extraArgument, sl.getOffset(), sl .getOffset() + 1,// FIXME AVASM struct.context)); return true; } } return false; } /** * Read @After * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleAfterAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeMethodStruct struct, ResolvedPointcutDefinition preResolvedPointcut) { AnnotationGen after = getAnnotation(runtimeAnnotations, AjcMemberMaker.AFTER_ANNOTATION); if (after != null) { ElementNameValuePairGen afterAdvice = getAnnotationElement(after, VALUE); if (afterAdvice != null) { // this/target/args binding FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; String argumentNames = getArgNamesValue(after); if (argumentNames != null) { struct.unparsedArgumentNames = argumentNames; } try { bindings = extractBindings(struct); } catch (UnreadableDebugInfoException unreadableDebugInfoException) { return false; } IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings); // joinpoint, staticJoinpoint binding int extraArgument = extractExtraArgument(struct.method); Pointcut pc = null; if (preResolvedPointcut != null) { pc = preResolvedPointcut.getPointcut(); } else { pc = parsePointcut(afterAdvice.getValue().stringifyValue(), struct, false); if (pc == null) return false;// parse error pc.resolve(binding); } setIgnoreUnboundBindingNames(pc, bindings); ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(), struct.bMethod .getDeclarationOffset()); struct.ajAttributes.add(new AjAttribute.AdviceAttribute(AdviceKind.After, pc, extraArgument, sl.getOffset(), sl .getOffset() + 1,// FIXME AVASM struct.context)); return true; } } return false; } /** * Read @AfterReturning * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleAfterReturningAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeMethodStruct struct, ResolvedPointcutDefinition preResolvedPointcut, BcelMethod owningMethod) throws ReturningFormalNotDeclaredInAdviceSignatureException { AnnotationGen after = getAnnotation(runtimeAnnotations, AjcMemberMaker.AFTERRETURNING_ANNOTATION); if (after != null) { ElementNameValuePairGen annValue = getAnnotationElement(after, VALUE); ElementNameValuePairGen annPointcut = getAnnotationElement(after, POINTCUT); ElementNameValuePairGen annReturned = getAnnotationElement(after, RETURNING); // extract the pointcut and returned type/binding - do some checks String pointcut = null; String returned = null; if ((annValue != null && annPointcut != null) || (annValue == null && annPointcut == null)) { reportError("@AfterReturning: either 'value' or 'poincut' must be provided, not both", struct); return false; } if (annValue != null) { pointcut = annValue.getValue().stringifyValue(); } else { pointcut = annPointcut.getValue().stringifyValue(); } if (isNullOrEmpty(pointcut)) { reportError("@AfterReturning: either 'value' or 'poincut' must be provided, not both", struct); return false; } if (annReturned != null) { returned = annReturned.getValue().stringifyValue(); if (isNullOrEmpty(returned)) { returned = null; } else { // check that thrownFormal exists as the last parameter in the advice String[] pNames = owningMethod.getParameterNames(); if (pNames == null || pNames.length == 0 || !Arrays.asList(pNames).contains(returned)) { throw new ReturningFormalNotDeclaredInAdviceSignatureException(returned); } } } String argumentNames = getArgNamesValue(after); if (argumentNames != null) { struct.unparsedArgumentNames = argumentNames; } // this/target/args binding // exclude the return binding from the pointcut binding since it is an extraArg binding FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; try { bindings = (returned == null ? extractBindings(struct) : extractBindings(struct, returned)); } catch (UnreadableDebugInfoException unreadableDebugInfoException) { return false; } IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings); // joinpoint, staticJoinpoint binding int extraArgument = extractExtraArgument(struct.method); // return binding if (returned != null) { extraArgument |= Advice.ExtraArgument; } Pointcut pc = null; if (preResolvedPointcut != null) { pc = preResolvedPointcut.getPointcut(); } else { pc = parsePointcut(pointcut, struct, false); if (pc == null) return false;// parse error pc.resolve(binding); } setIgnoreUnboundBindingNames(pc, bindings); ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(), struct.bMethod .getDeclarationOffset()); struct.ajAttributes.add(new AjAttribute.AdviceAttribute(AdviceKind.AfterReturning, pc, extraArgument, sl.getOffset(), sl.getOffset() + 1,// FIXME AVASM struct.context)); return true; } return false; } /** * Read @AfterThrowing * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleAfterThrowingAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeMethodStruct struct, ResolvedPointcutDefinition preResolvedPointcut, BcelMethod owningMethod) throws ThrownFormalNotDeclaredInAdviceSignatureException { AnnotationGen after = getAnnotation(runtimeAnnotations, AjcMemberMaker.AFTERTHROWING_ANNOTATION); if (after != null) { ElementNameValuePairGen annValue = getAnnotationElement(after, VALUE); ElementNameValuePairGen annPointcut = getAnnotationElement(after, POINTCUT); ElementNameValuePairGen annThrown = getAnnotationElement(after, THROWING); // extract the pointcut and throwned type/binding - do some checks String pointcut = null; String thrownFormal = null; if ((annValue != null && annPointcut != null) || (annValue == null && annPointcut == null)) { reportError("@AfterThrowing: either 'value' or 'poincut' must be provided, not both", struct); return false; } if (annValue != null) { pointcut = annValue.getValue().stringifyValue(); } else { pointcut = annPointcut.getValue().stringifyValue(); } if (isNullOrEmpty(pointcut)) { reportError("@AfterThrowing: either 'value' or 'poincut' must be provided, not both", struct); return false; } if (annThrown != null) { thrownFormal = annThrown.getValue().stringifyValue(); if (isNullOrEmpty(thrownFormal)) { thrownFormal = null; } else { // check that thrownFormal exists as the last parameter in the advice String[] pNames = owningMethod.getParameterNames(); if (pNames == null || pNames.length == 0 || !Arrays.asList(pNames).contains(thrownFormal)) { throw new ThrownFormalNotDeclaredInAdviceSignatureException(thrownFormal); } } } String argumentNames = getArgNamesValue(after); if (argumentNames != null) { struct.unparsedArgumentNames = argumentNames; } // this/target/args binding // exclude the throwned binding from the pointcut binding since it is an extraArg binding FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; try { bindings = (thrownFormal == null ? extractBindings(struct) : extractBindings(struct, thrownFormal)); } catch (UnreadableDebugInfoException unreadableDebugInfoException) { return false; } IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings); // joinpoint, staticJoinpoint binding int extraArgument = extractExtraArgument(struct.method); // return binding if (thrownFormal != null) { extraArgument |= Advice.ExtraArgument; } Pointcut pc = null; if (preResolvedPointcut != null) { pc = preResolvedPointcut.getPointcut(); } else { pc = parsePointcut(pointcut, struct, false); if (pc == null) return false;// parse error pc.resolve(binding); } setIgnoreUnboundBindingNames(pc, bindings); ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(), struct.bMethod .getDeclarationOffset()); struct.ajAttributes.add(new AjAttribute.AdviceAttribute(AdviceKind.AfterThrowing, pc, extraArgument, sl.getOffset(), sl .getOffset() + 1,// FIXME AVASM struct.context)); return true; } return false; } /** * Read @Around * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleAroundAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeMethodStruct struct, ResolvedPointcutDefinition preResolvedPointcut) { AnnotationGen around = getAnnotation(runtimeAnnotations, AjcMemberMaker.AROUND_ANNOTATION); if (around != null) { ElementNameValuePairGen aroundAdvice = getAnnotationElement(around, VALUE); if (aroundAdvice != null) { // this/target/args binding String argumentNames = getArgNamesValue(around); if (argumentNames != null) { struct.unparsedArgumentNames = argumentNames; } FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; try { bindings = extractBindings(struct); } catch (UnreadableDebugInfoException unreadableDebugInfoException) { return false; } IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings); // joinpoint, staticJoinpoint binding int extraArgument = extractExtraArgument(struct.method); Pointcut pc = null; if (preResolvedPointcut != null) { pc = preResolvedPointcut.getPointcut(); } else { pc = parsePointcut(aroundAdvice.getValue().stringifyValue(), struct, false); if (pc == null) return false;// parse error pc.resolve(binding); } setIgnoreUnboundBindingNames(pc, bindings); ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(), struct.bMethod .getDeclarationOffset()); struct.ajAttributes.add(new AjAttribute.AdviceAttribute(AdviceKind.Around, pc, extraArgument, sl.getOffset(), sl .getOffset() + 1,// FIXME AVASM struct.context)); return true; } } return false; } /** * Read @Pointcut and handle the resolving in a lazy way to deal with pointcut references * * @param runtimeAnnotations * @param struct * @return true if a pointcut was handled */ private static boolean handlePointcutAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeMethodStruct struct) { AnnotationGen pointcut = getAnnotation(runtimeAnnotations, AjcMemberMaker.POINTCUT_ANNOTATION); if (pointcut == null) return false; ElementNameValuePairGen pointcutExpr = getAnnotationElement(pointcut, VALUE); // semantic check: the method must return void, or be "public static boolean" for if() support if (!(Type.VOID.equals(struct.method.getReturnType()) || (Type.BOOLEAN.equals(struct.method.getReturnType()) && struct.method.isStatic() && struct.method.isPublic()))) { reportWarning("Found @Pointcut on a method not returning 'void' or not 'public static boolean'", struct); // no need to stop } // semantic check: the method must not throw anything if (struct.method.getExceptionTable() != null) { reportWarning("Found @Pointcut on a method throwing exception", struct); // no need to stop } String argumentNames = getArgNamesValue(pointcut); if (argumentNames != null) { struct.unparsedArgumentNames = argumentNames; } // this/target/args binding final IScope binding; try { if (struct.method.isAbstract()) { binding = null; } else { binding = new BindingScope(struct.enclosingType, struct.context, extractBindings(struct)); } } catch (UnreadableDebugInfoException e) { return false; } UnresolvedType[] argumentTypes = new UnresolvedType[struct.method.getArgumentTypes().length]; for (int i = 0; i < argumentTypes.length; i++) { argumentTypes[i] = UnresolvedType.forSignature(struct.method.getArgumentTypes()[i].getSignature()); } Pointcut pc = null; if (struct.method.isAbstract()) { if ((pointcutExpr != null && isNullOrEmpty(pointcutExpr.getValue().stringifyValue())) || pointcutExpr == null) { // abstract pointcut // leave pc = null } else { reportError("Found defined @Pointcut on an abstract method", struct); return false;// stop } } else { if (pointcutExpr == null || isNullOrEmpty(pointcutExpr.getValue().stringifyValue())) { // the matches nothing pointcut (125475/125480) - perhaps not as cleanly supported as it could be. } else { // if (pointcutExpr != null) { // use a LazyResolvedPointcutDefinition so that the pointcut is resolved lazily // since for it to be resolved, we will need other pointcuts to be registered as well pc = parsePointcut(pointcutExpr.getValue().stringifyValue(), struct, true); if (pc == null) return false;// parse error pc.setLocation(struct.context, -1, -1);// FIXME AVASM !! bMethod is null here.. // } else { // reportError("Found undefined @Pointcut on a non-abstract method", struct); // return false; // } } } // do not resolve binding now but lazily struct.ajAttributes.add(new AjAttribute.PointcutDeclarationAttribute(new LazyResolvedPointcutDefinition( struct.enclosingType, struct.method.getModifiers(), struct.method.getName(), argumentTypes, UnresolvedType .forSignature(struct.method.getReturnType().getSignature()), pc,// can be null for abstract pointcut binding // can be null for abstract pointcut ))); return true; } /** * Read @DeclareError, @DeclareWarning * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleDeclareErrorOrWarningAnnotation(AsmManager model, RuntimeAnnotations runtimeAnnotations, AjAttributeFieldStruct struct) { AnnotationGen error = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREERROR_ANNOTATION); boolean hasError = false; if (error != null) { ElementNameValuePairGen declareError = getAnnotationElement(error, VALUE); if (declareError != null) { if (!STRING_DESC.equals(struct.field.getSignature()) || struct.field.getConstantValue() == null) { reportError("@DeclareError used on a non String constant field", struct); return false; } Pointcut pc = parsePointcut(declareError.getValue().stringifyValue(), struct, false); if (pc == null) { hasError = false;// cannot parse pointcut } else { DeclareErrorOrWarning deow = new DeclareErrorOrWarning(true, pc, struct.field.getConstantValue().toString()); setDeclareErrorOrWarningLocation(model, deow, struct); struct.ajAttributes.add(new AjAttribute.DeclareAttribute(deow)); hasError = true; } } } AnnotationGen warning = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREWARNING_ANNOTATION); boolean hasWarning = false; if (warning != null) { ElementNameValuePairGen declareWarning = getAnnotationElement(warning, VALUE); if (declareWarning != null) { if (!STRING_DESC.equals(struct.field.getSignature()) || struct.field.getConstantValue() == null) { reportError("@DeclareWarning used on a non String constant field", struct); return false; } Pointcut pc = parsePointcut(declareWarning.getValue().stringifyValue(), struct, false); if (pc == null) { hasWarning = false;// cannot parse pointcut } else { DeclareErrorOrWarning deow = new DeclareErrorOrWarning(false, pc, struct.field.getConstantValue().toString()); setDeclareErrorOrWarningLocation(model, deow, struct); struct.ajAttributes.add(new AjAttribute.DeclareAttribute(deow)); return hasWarning = true; } } } return hasError || hasWarning; } /** * Sets the location for the declare error / warning using the corresponding IProgramElement in the structure model. This will * only fix bug 120356 if compiled with -emacssym, however, it does mean that the cross references view in AJDT will show the * correct information. * * Other possibilities for fix: 1. using the information in ajcDeclareSoft (if this is set correctly) which will fix the problem * if compiled with ajc but not if compiled with javac. 2. creating an AjAttribute called FieldDeclarationLineNumberAttribute * (much like MethodDeclarationLineNumberAttribute) which we can ask for the offset. This will again only fix bug 120356 when * compiled with ajc. * * @param deow * @param struct */ private static void setDeclareErrorOrWarningLocation(AsmManager model, DeclareErrorOrWarning deow, AjAttributeFieldStruct struct) { IHierarchy top = (model == null ? null : model.getHierarchy()); if (top != null && top.getRoot() != null) { IProgramElement ipe = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.FIELD, struct.field.getName()); if (ipe != null && ipe.getSourceLocation() != null) { ISourceLocation sourceLocation = ipe.getSourceLocation(); int start = sourceLocation.getOffset(); int end = start + struct.field.getName().length(); deow.setLocation(struct.context, start, end); return; } } deow.setLocation(struct.context, -1, -1); } /** * Returns a readable representation of a method. Method.toString() is not suitable. * * @param method * @return a readable representation of a method */ private static String methodToString(Method method) { StringBuffer sb = new StringBuffer(); sb.append(method.getName()); sb.append(method.getSignature()); return sb.toString(); } /** * Build the bindings for a given method (pointcut / advice) * * @param struct * @return null if no debug info is available */ private static FormalBinding[] extractBindings(AjAttributeMethodStruct struct) throws UnreadableDebugInfoException { Method method = struct.method; String[] argumentNames = struct.getArgumentNames(); // assert debug info was here if (argumentNames.length != method.getArgumentTypes().length) { reportError( "Cannot read debug info for @Aspect to handle formal binding in pointcuts (please compile with 'javac -g' or '<javac debug='true'.../>' in Ant)", struct); throw new UnreadableDebugInfoException(); } List bindings = new ArrayList(); for (int i = 0; i < argumentNames.length; i++) { String argumentName = argumentNames[i]; UnresolvedType argumentType = UnresolvedType.forSignature(method.getArgumentTypes()[i].getSignature()); // do not bind JoinPoint / StaticJoinPoint / EnclosingStaticJoinPoint // TODO solve me : this means that the JP/SJP/ESJP cannot appear as binding // f.e. when applying advice on advice etc if ((AjcMemberMaker.TYPEX_JOINPOINT.equals(argumentType) || AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.equals(argumentType) || AjcMemberMaker.TYPEX_STATICJOINPOINT.equals(argumentType) || AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.equals(argumentType) || AjcMemberMaker.AROUND_CLOSURE_TYPE .equals(argumentType))) { // continue;// skip bindings.add(new FormalBinding.ImplicitFormalBinding(argumentType, argumentName, i)); } else { bindings.add(new FormalBinding(argumentType, argumentName, i)); } } return (FormalBinding[]) bindings.toArray(new FormalBinding[] {}); } // FIXME alex deal with exclude index private static FormalBinding[] extractBindings(AjAttributeMethodStruct struct, String excludeFormal) throws UnreadableDebugInfoException { FormalBinding[] bindings = extractBindings(struct); // int excludeIndex = -1; for (int i = 0; i < bindings.length; i++) { FormalBinding binding = bindings[i]; if (binding.getName().equals(excludeFormal)) { // excludeIndex = i; bindings[i] = new FormalBinding.ImplicitFormalBinding(binding.getType(), binding.getName(), binding.getIndex()); break; } } return bindings; // // if (excludeIndex >= 0) { // FormalBinding[] bindingsFiltered = new FormalBinding[bindings.length-1]; // int k = 0; // for (int i = 0; i < bindings.length; i++) { // if (i == excludeIndex) { // ; // } else { // bindingsFiltered[k] = new FormalBinding(bindings[i].getType(), bindings[i].getName(), k); // k++; // } // } // return bindingsFiltered; // } else { // return bindings; // } } /** * Compute the flag for the xxxJoinPoint extra argument * * @param method * @return extra arg flag */ private static int extractExtraArgument(Method method) { Type[] methodArgs = method.getArgumentTypes(); String[] sigs = new String[methodArgs.length]; for (int i = 0; i < methodArgs.length; i++) { sigs[i] = methodArgs[i].getSignature(); } return extractExtraArgument(sigs); } /** * Compute the flag for the xxxJoinPoint extra argument * * @param argumentSignatures * @return extra arg flag */ public static int extractExtraArgument(String[] argumentSignatures) { int extraArgument = 0; for (int i = 0; i < argumentSignatures.length; i++) { if (AjcMemberMaker.TYPEX_JOINPOINT.getSignature().equals(argumentSignatures[i])) { extraArgument |= Advice.ThisJoinPoint; } else if (AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.getSignature().equals(argumentSignatures[i])) { extraArgument |= Advice.ThisJoinPoint; } else if (AjcMemberMaker.TYPEX_STATICJOINPOINT.getSignature().equals(argumentSignatures[i])) { extraArgument |= Advice.ThisJoinPointStaticPart; } else if (AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.getSignature().equals(argumentSignatures[i])) { extraArgument |= Advice.ThisEnclosingJoinPointStaticPart; } } return extraArgument; } /** * Returns the runtime (RV/RIV) annotation of type annotationType or null if no such annotation * * @param rvs * @param annotationType * @return annotation */ private static AnnotationGen getAnnotation(RuntimeAnnotations rvs, UnresolvedType annotationType) { final String annotationTypeName = annotationType.getName(); for (Iterator iterator = rvs.getAnnotations().iterator(); iterator.hasNext();) { AnnotationGen rv = (AnnotationGen) iterator.next(); if (annotationTypeName.equals(rv.getTypeName())) { return rv; } } return null; } /** * Returns the value of a given element of an annotation or null if not found Caution: Does not handles default value. * * @param annotation * @param elementName * @return annotation NVP */ private static ElementNameValuePairGen getAnnotationElement(AnnotationGen annotation, String elementName) { for (Iterator iterator1 = annotation.getValues().iterator(); iterator1.hasNext();) { ElementNameValuePairGen element = (ElementNameValuePairGen) iterator1.next(); if (elementName.equals(element.getNameString())) { return element; } } return null; } /** * Return the argNames set for an annotation or null if it is not specified. */ private static String getArgNamesValue(AnnotationGen anno) { for (Iterator iterator1 = anno.getValues().iterator(); iterator1.hasNext();) { ElementNameValuePairGen element = (ElementNameValuePairGen) iterator1.next(); if (ARGNAMES.equals(element.getNameString())) { return element.getValue().stringifyValue(); } } return null; } private static String lastbit(String fqname) { int i = fqname.lastIndexOf("."); if (i == -1) return fqname; else return fqname.substring(i + 1); } /** * Extract the method argument names. First we try the debug info attached to the method (the LocalVariableTable) - if we cannot * find that we look to use the argNames value that may have been supplied on the associated annotation. If that fails we just * don't know and return an empty string. * * @param method * @param argNamesFromAnnotation * @param methodStruct * @return method argument names */ private static String[] getMethodArgumentNames(Method method, String argNamesFromAnnotation, AjAttributeMethodStruct methodStruct) { if (method.getArgumentTypes().length == 0) { return EMPTY_STRINGS; } final int startAtStackIndex = method.isStatic() ? 0 : 1; final List arguments = new ArrayList(); LocalVariableTable lt = method.getLocalVariableTable(); if (lt != null) { for (int j = 0; j < lt.getLocalVariableTable().length; j++) { LocalVariable localVariable = lt.getLocalVariableTable()[j]; if (localVariable.getStartPC() == 0) { if (localVariable.getIndex() >= startAtStackIndex) { arguments.add(new MethodArgument(localVariable.getName(), localVariable.getIndex())); } } } } else { // No debug info, do we have an annotation value we can rely on? if (argNamesFromAnnotation != null) { StringTokenizer st = new StringTokenizer(argNamesFromAnnotation, " ,"); List args = new ArrayList(); while (st.hasMoreTokens()) { args.add(st.nextToken()); } if (args.size() != method.getArgumentTypes().length) { StringBuffer shortString = new StringBuffer().append(lastbit(method.getReturnType().toString())).append(" ") .append(method.getName()); if (method.getArgumentTypes().length > 0) { shortString.append("("); for (int i = 0; i < method.getArgumentTypes().length; i++) { shortString.append(lastbit(method.getArgumentTypes()[i].toString())); if ((i + 1) < method.getArgumentTypes().length) shortString.append(","); } shortString.append(")"); } reportError("argNames annotation value does not specify the right number of argument names for the method '" + shortString.toString() + "'", methodStruct); return EMPTY_STRINGS; } return (String[]) args.toArray(new String[] {}); } } if (arguments.size() != method.getArgumentTypes().length) { return EMPTY_STRINGS; } // sort by index Collections.sort(arguments, new Comparator() { public int compare(Object o, Object o1) { MethodArgument mo = (MethodArgument) o; MethodArgument mo1 = (MethodArgument) o1; if (mo.indexOnStack == mo1.indexOnStack) { return 0; } else if (mo.indexOnStack > mo1.indexOnStack) { return 1; } else { return -1; } } }); String[] argumentNames = new String[arguments.size()]; int i = 0; for (Iterator iterator = arguments.iterator(); iterator.hasNext(); i++) { MethodArgument methodArgument = (MethodArgument) iterator.next(); argumentNames[i] = methodArgument.name; } return argumentNames; } /** * A method argument, used for sorting by indexOnStack (ie order in signature) * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ private static class MethodArgument { String name; int indexOnStack; public MethodArgument(String name, int indexOnStack) { this.name = name; this.indexOnStack = indexOnStack; } } /** * LazyResolvedPointcutDefinition lazyly resolve the pointcut so that we have time to register all pointcut referenced before * pointcut resolution happens * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public static class LazyResolvedPointcutDefinition extends ResolvedPointcutDefinition { private final Pointcut m_pointcutUnresolved; private final IScope m_binding; private Pointcut m_lazyPointcut = null; public LazyResolvedPointcutDefinition(UnresolvedType declaringType, int modifiers, String name, UnresolvedType[] parameterTypes, UnresolvedType returnType, Pointcut pointcut, IScope binding) { super(declaringType, modifiers, name, parameterTypes, returnType, null); m_pointcutUnresolved = pointcut; m_binding = binding; } public Pointcut getPointcut() { if (m_lazyPointcut == null) { m_lazyPointcut = m_pointcutUnresolved.resolve(m_binding); m_lazyPointcut.copyLocationFrom(m_pointcutUnresolved); } return m_lazyPointcut; } } /** * Helper to test empty strings * * @param s * @return true if empty or null */ private static boolean isNullOrEmpty(String s) { return (s == null || s.length() <= 0); } /** * Set the pointcut bindings for which to ignore unbound issues, so that we can implicitly bind xxxJoinPoint for @AJ advices * * @param pointcut * @param bindings */ private static void setIgnoreUnboundBindingNames(Pointcut pointcut, FormalBinding[] bindings) { // register ImplicitBindings as to be ignored since unbound // TODO is it likely to fail in a bad way if f.e. this(jp) etc ? List ignores = new ArrayList(); for (int i = 0; i < bindings.length; i++) { FormalBinding formalBinding = bindings[i]; if (formalBinding instanceof FormalBinding.ImplicitFormalBinding) { ignores.add(formalBinding.getName()); } } pointcut.m_ignoreUnboundBindingForNames = (String[]) ignores.toArray(new String[ignores.size()]); } /** * A check exception when we cannot read debug info (needed for formal binding) */ private static class UnreadableDebugInfoException extends Exception { } /** * Report an error * * @param message * @param location */ private static void reportError(String message, AjAttributeStruct location) { if (!location.handler.isIgnoring(IMessage.ERROR)) { location.handler.handleMessage(new Message(message, location.enclosingType.getSourceLocation(), true)); } } /** * Report a warning * * @param message * @param location */ private static void reportWarning(String message, AjAttributeStruct location) { if (!location.handler.isIgnoring(IMessage.WARNING)) { location.handler.handleMessage(new Message(message, location.enclosingType.getSourceLocation(), false)); } } /** * Parse the given pointcut, return null on failure and issue an error * * @param pointcutString * @param struct * @param allowIf * @return pointcut, unresolved */ private static Pointcut parsePointcut(String pointcutString, AjAttributeStruct struct, boolean allowIf) { try { PatternParser parser = new PatternParser(pointcutString, struct.context); Pointcut pointcut = parser.parsePointcut(); parser.checkEof(); pointcut.check(null, struct.enclosingType.getWorld()); if (!allowIf && pointcutString.indexOf("if()") >= 0 && hasIf(pointcut)) { reportError("if() pointcut is not allowed at this pointcut location '" + pointcutString + "'", struct); return null; } pointcut.setLocation(struct.context, -1, -1);// FIXME -1,-1 is not good enough return pointcut; } catch (ParserException e) { reportError("Invalid pointcut '" + pointcutString + "': " + e.toString() + (e.getLocation() == null ? "" : " at position " + e.getLocation().getStart()), struct); return null; } } private static boolean hasIf(Pointcut pointcut) { IfFinder visitor = new IfFinder(); pointcut.accept(visitor, null); return visitor.hasIf; } /** * Parse the given type pattern, return null on failure and issue an error * * @param patternString * @param location * @return type pattern */ private static TypePattern parseTypePattern(String patternString, AjAttributeStruct location) { try { TypePattern typePattern = new PatternParser(patternString).parseTypePattern(); typePattern.setLocation(location.context, -1, -1);// FIXME -1,-1 is not good enough return typePattern; } catch (ParserException e) { reportError("Invalid type pattern'" + patternString + "' : " + e.getLocation(), location); return null; } } static class ThrownFormalNotDeclaredInAdviceSignatureException extends Exception { private final String formalName; public ThrownFormalNotDeclaredInAdviceSignatureException(String formalName) { this.formalName = formalName; } public String getFormalName() { return formalName; } } static class ReturningFormalNotDeclaredInAdviceSignatureException extends Exception { private final String formalName; public ReturningFormalNotDeclaredInAdviceSignatureException(String formalName) { this.formalName = formalName; } public String getFormalName() { return formalName; } } }
185,447
Bug 185447 [plan] [ataspectj] Abstract @Aspect causing problems
Trying to use an abstract @Aspect from a library jar file is causing problems. In the (soon to be) attached zip of eclipse projects: * logging-library: defines two abstract trivial logging aspects, one in code-style and one in @AspectJ style. * sample-system: uses the code-style abstract aspect successfully * sample-system2: uses the @AspectJ style abstract aspect and won't compile in Eclipse Exception: java.lang.NullPointerException at org.aspectj.weaver.bcel.AtAjAttributes$LazyResolvedPointcutDefinition.getPointcut(AtAjAttributes.java:1632) at org.aspectj.weaver.ShadowMunger.addChildNodes(ShadowMunger.java:258) at org.aspectj.weaver.ShadowMunger.createHierarchy(ShadowMunger.java:247) at org.aspectj.weaver.AsmRelationshipProvider.adviceMunger(AsmRelationshipProvider.java:180) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:717) a ... int;)Ljava/lang/String; ARETURN end public Object run(Object[])
resolved fixed
120b47f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-12-01T21:00:43Z"
"2007-05-03T22:06:40Z"
weaver/src/org/aspectj/weaver/model/AsmRelationshipProvider.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.model; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.IRelationship; import org.aspectj.asm.IRelationshipMap; import org.aspectj.asm.internal.ProgramElement; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.Checker; import org.aspectj.weaver.Lint; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.patterns.DeclareErrorOrWarning; public class AsmRelationshipProvider { protected static AsmRelationshipProvider INSTANCE = new AsmRelationshipProvider(); public static final String ADVISES = "advises"; public static final String ADVISED_BY = "advised by"; public static final String DECLARES_ON = "declares on"; public static final String DECLAREDY_BY = "declared by"; public static final String SOFTENS = "softens"; public static final String SOFTENED_BY = "softened by"; public static final String MATCHED_BY = "matched by"; public static final String MATCHES_DECLARE = "matches declare"; public static final String INTER_TYPE_DECLARES = "declared on"; public static final String INTER_TYPE_DECLARED_BY = "aspect declarations"; public static final String ANNOTATES = "annotates"; public static final String ANNOTATED_BY = "annotated by"; public static void checkerMunger(AsmManager asm, Shadow shadow, Checker checker) { if (asm == null) // !AsmManager.isCreatingModel()) return; if (shadow.getSourceLocation() == null || checker.getSourceLocation() == null) return; if (World.createInjarHierarchy) { createHierarchy(asm, checker); } // Ensure a node for the target exists IProgramElement targetNode = getNode(asm, shadow); if (targetNode == null) return; String targetHandle = asm.getHandleProvider().createHandleIdentifier(targetNode); if (targetHandle == null) return; IProgramElement sourceNode = asm.getHierarchy().findElementForSourceLine(checker.getSourceLocation()); String sourceHandle = asm.getHandleProvider().createHandleIdentifier(sourceNode); if (sourceHandle == null) return; IRelationshipMap mapper = asm.getRelationshipMap(); IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE, MATCHED_BY, false, true); foreward.addTarget(targetHandle); IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE, MATCHES_DECLARE, false, true); if (back != null && back.getTargets() != null) { back.addTarget(sourceHandle); } if (sourceNode.getSourceLocation() != null) { asm.addAspectInEffectThisBuild(sourceNode.getSourceLocation().getSourceFile()); } } // For ITDs public void addRelationship(AsmManager asm, ResolvedType onType, ResolvedTypeMunger munger, ResolvedType originatingAspect) { if (asm == null)// !AsmManager.isCreatingModel()) return; if (originatingAspect.getSourceLocation() != null) { String sourceHandle = ""; IProgramElement sourceNode = null; if (munger.getSourceLocation() != null && munger.getSourceLocation().getOffset() != -1) { sourceNode = asm.getHierarchy().findElementForSourceLine(munger.getSourceLocation()); sourceHandle = asm.getHandleProvider().createHandleIdentifier(sourceNode); } else { sourceNode = asm.getHierarchy().findElementForSourceLine(originatingAspect.getSourceLocation()); sourceHandle = asm.getHandleProvider().createHandleIdentifier(sourceNode); } if (sourceHandle == null) return; IProgramElement targetNode = asm.getHierarchy().findElementForSourceLine(onType.getSourceLocation()); String targetHandle = asm.getHandleProvider().createHandleIdentifier(targetNode); if (targetHandle == null) return; IRelationshipMap mapper = asm.getRelationshipMap(); IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARES, false, true); foreward.addTarget(targetHandle); IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARED_BY, false, true); back.addTarget(sourceHandle); asm.addAspectInEffectThisBuild(sourceNode.getSourceLocation().getSourceFile()); } } // public void addDeclareParentsRelationship(ISourceLocation decp, // ResolvedType targetType, List newParents) { // if (!AsmManager.isCreatingModel()) // return; // // IProgramElement sourceNode = // AsmManager.getDefault().getHierarchy().findElementForSourceLine(decp); // String sourceHandle = // AsmManager.getDefault().getHandleProvider().createHandleIdentifier // (sourceNode); // if (sourceHandle == null) // return; // // IProgramElement targetNode = AsmManager.getDefault().getHierarchy() // .findElementForSourceLine(targetType.getSourceLocation()); // String targetHandle = // AsmManager.getDefault().getHandleProvider().createHandleIdentifier // (targetNode); // if (targetHandle == null) // return; // // IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap(); // IRelationship foreward = mapper.get(sourceHandle, // IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARES, false, true); // foreward.addTarget(targetHandle); // // IRelationship back = mapper.get(targetHandle, // IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARED_BY, false, // true); // back.addTarget(sourceHandle); // } /** * Adds a declare annotation relationship, sometimes entities don't have source locs (methods/fields) so use other variants of * this method if that is the case as they will look the entities up in the structure model. */ public void addDeclareAnnotationRelationship(AsmManager asm, ISourceLocation declareAnnotationLocation, ISourceLocation annotatedLocation) { if (asm == null) // !AsmManager.isCreatingModel()) return; IProgramElement sourceNode = asm.getHierarchy().findElementForSourceLine(declareAnnotationLocation); String sourceHandle = asm.getHandleProvider().createHandleIdentifier(sourceNode); if (sourceHandle == null) return; IProgramElement targetNode = asm.getHierarchy().findElementForSourceLine(annotatedLocation); String targetHandle = asm.getHandleProvider().createHandleIdentifier(targetNode); if (targetHandle == null) return; IRelationshipMap mapper = asm.getRelationshipMap(); IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATES, false, true); foreward.addTarget(targetHandle); IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATED_BY, false, true); back.addTarget(sourceHandle); if (sourceNode.getSourceLocation() != null) { asm.addAspectInEffectThisBuild(sourceNode.getSourceLocation().getSourceFile()); } } /** * Creates the hierarchy for binary aspects */ public static void createHierarchy(AsmManager asm, ShadowMunger munger) { if (!munger.isBinary()) return; IProgramElement sourceFileNode = asm.getHierarchy().findElementForSourceLine(munger.getSourceLocation()); // the call to findElementForSourceLine(ISourceLocation) returns a file // node // if it can't find a node in the hierarchy for the given // sourcelocation. // Therefore, if this is returned, we know we can't find one and have to // continue to fault in the model. if (!sourceFileNode.getKind().equals(IProgramElement.Kind.FILE_JAVA)) { return; } ResolvedType aspect = munger.getDeclaringType(); // create the class file node IProgramElement classFileNode = new ProgramElement(asm, sourceFileNode.getName(), IProgramElement.Kind.FILE, munger .getBinarySourceLocation(aspect.getSourceLocation()), 0, null, null); // create package ipe if one exists.... IProgramElement root = asm.getHierarchy().getRoot(); IProgramElement binaries = asm.getHierarchy().findElementForLabel(root, IProgramElement.Kind.SOURCE_FOLDER, "binaries"); if (binaries == null) { binaries = new ProgramElement(asm, "binaries", IProgramElement.Kind.SOURCE_FOLDER, new ArrayList()); root.addChild(binaries); } // if (aspect.getPackageName() != null) { String packagename = aspect.getPackageName() == null ? "" : aspect.getPackageName(); // check that there doesn't already exist a node with this name IProgramElement pkgNode = asm.getHierarchy().findElementForLabel(binaries, IProgramElement.Kind.PACKAGE, packagename); // note packages themselves have no source location if (pkgNode == null) { pkgNode = new ProgramElement(asm, packagename, IProgramElement.Kind.PACKAGE, new ArrayList()); binaries.addChild(pkgNode); pkgNode.addChild(classFileNode); } else { // need to add it first otherwise the handle for classFileNode // may not be generated correctly if it uses information from // it's parent node pkgNode.addChild(classFileNode); for (Iterator iter = pkgNode.getChildren().iterator(); iter.hasNext();) { IProgramElement element = (IProgramElement) iter.next(); if (!element.equals(classFileNode) && element.getHandleIdentifier().equals(classFileNode.getHandleIdentifier())) { // already added the classfile so have already // added the structure for this aspect pkgNode.removeChild(classFileNode); return; } } } // } else { // // need to add it first otherwise the handle for classFileNode // // may not be generated correctly if it uses information from // // it's parent node // root.addChild(classFileNode); // for (Iterator iter = root.getChildren().iterator(); iter.hasNext();) { // IProgramElement element = (IProgramElement) iter.next(); // if (!element.equals(classFileNode) && element.getHandleIdentifier().equals(classFileNode.getHandleIdentifier())) { // // already added the sourcefile so have already // // added the structure for this aspect // root.removeChild(classFileNode); // return; // } // } // } // add and create empty import declaration ipe classFileNode.addChild(new ProgramElement(asm, "import declarations", IProgramElement.Kind.IMPORT_REFERENCE, null, 0, null, null)); // add and create aspect ipe IProgramElement aspectNode = new ProgramElement(asm, aspect.getSimpleName(), IProgramElement.Kind.ASPECT, munger .getBinarySourceLocation(aspect.getSourceLocation()), aspect.getModifiers(), null, null); classFileNode.addChild(aspectNode); addChildNodes(asm, munger, aspectNode, aspect.getDeclaredPointcuts()); addChildNodes(asm, munger, aspectNode, aspect.getDeclaredAdvice()); addChildNodes(asm, munger, aspectNode, aspect.getDeclares()); } private static void addChildNodes(AsmManager asm, ShadowMunger munger, IProgramElement parent, ResolvedMember[] children) { for (int i = 0; i < children.length; i++) { ResolvedMember pcd = children[i]; if (pcd instanceof ResolvedPointcutDefinition) { ResolvedPointcutDefinition rpcd = (ResolvedPointcutDefinition) pcd; ISourceLocation sLoc = rpcd.getPointcut().getSourceLocation(); if (sLoc == null) { sLoc = rpcd.getSourceLocation(); } parent.addChild(new ProgramElement(asm, pcd.getName(), IProgramElement.Kind.POINTCUT, munger .getBinarySourceLocation(sLoc), pcd.getModifiers(), null, Collections.EMPTY_LIST)); } } } private static void addChildNodes(AsmManager asm, ShadowMunger munger, IProgramElement parent, Collection children) { int deCtr = 1; int dwCtr = 1; for (Iterator iter = children.iterator(); iter.hasNext();) { Object element = iter.next(); if (element instanceof DeclareErrorOrWarning) { DeclareErrorOrWarning decl = (DeclareErrorOrWarning) element; int counter = 0; if (decl.isError()) { counter = deCtr++; } else { counter = dwCtr++; } parent.addChild(createDeclareErrorOrWarningChild(asm, munger, decl, counter)); } else if (element instanceof Advice) { Advice advice = (Advice) element; parent.addChild(createAdviceChild(asm, advice)); } } } private static IProgramElement createDeclareErrorOrWarningChild(AsmManager asm, ShadowMunger munger, DeclareErrorOrWarning decl, int count) { IProgramElement deowNode = new ProgramElement(asm, decl.getName(), decl.isError() ? IProgramElement.Kind.DECLARE_ERROR : IProgramElement.Kind.DECLARE_WARNING, munger.getBinarySourceLocation(decl.getSourceLocation()), decl .getDeclaringType().getModifiers(), null, null); deowNode.setDetails("\"" + AsmRelationshipUtils.genDeclareMessage(decl.getMessage()) + "\""); if (count != -1) { deowNode.setBytecodeName(decl.getName() + "_" + count); } return deowNode; } private static IProgramElement createAdviceChild(AsmManager asm, Advice advice) { IProgramElement adviceNode = new ProgramElement(asm, advice.getKind().getName(), IProgramElement.Kind.ADVICE, advice .getBinarySourceLocation(advice.getSourceLocation()), advice.getSignature().getModifiers(), null, Collections.EMPTY_LIST); adviceNode.setDetails(AsmRelationshipUtils.genPointcutDetails(advice.getPointcut())); adviceNode.setBytecodeName(advice.getSignature().getName()); // String nn = advice.getSignature().getName(); // if (counter != 1) { // adviceNode.setBytecodeName(advice.getKind().getName() + "$" // + counter + "$"); // } return adviceNode; } public static String getHandle(Advice advice, AsmManager asm) { if (null == advice.handle) { ISourceLocation sl = advice.getSourceLocation(); if (sl != null) { IProgramElement ipe = asm.getHierarchy().findElementForSourceLine(sl); advice.handle = asm.getHandleProvider().createHandleIdentifier(ipe); } } return advice.handle; } public static void adviceMunger(AsmManager asm, Shadow shadow, ShadowMunger munger) { if (asm == null) // !AsmManager.isCreatingModel()) return; if (munger instanceof Advice) { Advice advice = (Advice) munger; if (advice.getKind().isPerEntry() || advice.getKind().isCflow()) { // TODO: might want to show these in the future return; } if (World.createInjarHierarchy) { createHierarchy(asm, advice); } IRelationshipMap mapper = asm.getRelationshipMap(); IProgramElement targetNode = getNode(asm, shadow); if (targetNode == null) return; boolean runtimeTest = advice.hasDynamicTests(); // Work out extra info to inform interested UIs ! IProgramElement.ExtraInformation ai = new IProgramElement.ExtraInformation(); String adviceHandle = getHandle(advice, asm); if (adviceHandle == null) return; // What kind of advice is it? // TODO: Prob a better way to do this but I just want to // get it into CVS !!! AdviceKind ak = ((Advice) munger).getKind(); ai.setExtraAdviceInformation(ak.getName()); IProgramElement adviceElement = asm.getHierarchy().findElementForHandle(adviceHandle); if (adviceElement != null) { adviceElement.setExtraInfo(ai); } String targetHandle = targetNode.getHandleIdentifier(); if (advice.getKind().equals(AdviceKind.Softener)) { IRelationship foreward = mapper.get(adviceHandle, IRelationship.Kind.DECLARE_SOFT, SOFTENS, runtimeTest, true); if (foreward != null) foreward.addTarget(targetHandle);// foreward.getTargets().add // (targetHandle); IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE, SOFTENED_BY, runtimeTest, true); if (back != null) back.addTarget(adviceHandle);// back.getTargets().add( // adviceHandle); } else { IRelationship foreward = mapper.get(adviceHandle, IRelationship.Kind.ADVICE, ADVISES, runtimeTest, true); if (foreward != null) foreward.addTarget(targetHandle);// foreward.getTargets().add // (targetHandle); IRelationship back = mapper.get(targetHandle, IRelationship.Kind.ADVICE, ADVISED_BY, runtimeTest, true); if (back != null) back.addTarget(adviceHandle);// back.getTargets().add( // adviceHandle); } if (adviceElement.getSourceLocation() != null) { asm.addAspectInEffectThisBuild(adviceElement.getSourceLocation().getSourceFile()); } } } protected static IProgramElement getNode(AsmManager model, Shadow shadow) { Member enclosingMember = shadow.getEnclosingCodeSignature(); IProgramElement enclosingNode = lookupMember(model.getHierarchy(), enclosingMember); if (enclosingNode == null) { Lint.Kind err = shadow.getIWorld().getLint().shadowNotInStructure; if (err.isEnabled()) { err.signal(shadow.toString(), shadow.getSourceLocation()); } return null; } Member shadowSig = shadow.getSignature(); // pr235204 if (shadow.getKind() == Shadow.MethodCall || !shadowSig.equals(enclosingMember)) { IProgramElement bodyNode = findOrCreateCodeNode(model, enclosingNode, shadowSig, shadow); return bodyNode; } else { return enclosingNode; } } private static boolean sourceLinesMatch(ISourceLocation loc1, ISourceLocation loc2) { if (loc1.getLine() != loc2.getLine()) return false; return true; } /** * Finds or creates a code IProgramElement for the given shadow. * * The byteCodeName of the created node is set to 'shadowSig.getName() + "!" + counter', eg "println!3". The counter is the * occurence count of children within the enclosingNode which have the same name. So, for example, if a method contains two * System.out.println statements, the first one will have byteCodeName 'println!1' and the second will have byteCodeName * 'println!2'. This is to ensure the two nodes have unique handles when the handles do not depend on sourcelocations. * * Currently the shadows are examined in the sequence they appear in the source file. This means that the counters are * consistent over incremental builds. All aspects are compiled up front and any new aspect created will force a full build. * Moreover, if the body of the enclosingShadow is changed, then the model for this is rebuilt from scratch. */ private static IProgramElement findOrCreateCodeNode(AsmManager asm, IProgramElement enclosingNode, Member shadowSig, Shadow shadow) { for (Iterator it = enclosingNode.getChildren().iterator(); it.hasNext();) { IProgramElement node = (IProgramElement) it.next(); int excl = node.getBytecodeName().lastIndexOf('!'); if (((excl != -1 && shadowSig.getName().equals(node.getBytecodeName().substring(0, excl))) || shadowSig.getName() .equals(node.getBytecodeName())) && shadowSig.getSignature().equals(node.getBytecodeSignature()) && sourceLinesMatch(node.getSourceLocation(), shadow.getSourceLocation())) { return node; } } ISourceLocation sl = shadow.getSourceLocation(); // XXX why not use shadow file? new SourceLocation(sl.getSourceFile(), // sl.getLine()), SourceLocation peLoc = new SourceLocation(enclosingNode.getSourceLocation().getSourceFile(), sl.getLine()); peLoc.setOffset(sl.getOffset()); IProgramElement peNode = new ProgramElement(asm, shadow.toString(), IProgramElement.Kind.CODE, peLoc, 0, null, null); // check to see if the enclosing shadow already has children with the // same name. If so we want to add a counter to the byteCodeName // otherwise // we wont get unique handles int numberOfChildrenWithThisName = 0; for (Iterator it = enclosingNode.getChildren().iterator(); it.hasNext();) { IProgramElement child = (IProgramElement) it.next(); if (child.getName().equals(shadow.toString())) { numberOfChildrenWithThisName++; } } peNode.setBytecodeName(shadowSig.getName() + "!" + String.valueOf(numberOfChildrenWithThisName + 1)); peNode.setBytecodeSignature(shadowSig.getSignature()); enclosingNode.addChild(peNode); return peNode; } protected static IProgramElement lookupMember(IHierarchy model, Member member) { UnresolvedType declaringType = member.getDeclaringType(); IProgramElement classNode = model.findElementForType(declaringType.getPackageName(), declaringType.getClassName()); return findMemberInClass(classNode, member); } protected static IProgramElement findMemberInClass(IProgramElement classNode, Member member) { if (classNode == null) return null; // XXX remove this check for (Iterator it = classNode.getChildren().iterator(); it.hasNext();) { IProgramElement node = (IProgramElement) it.next(); if (member.getName().equals(node.getBytecodeName()) && member.getSignature().equals(node.getBytecodeSignature())) { return node; } } // if we can't find the member, we'll just put it in the class return classNode; } // private static IProgramElement.Kind genShadowKind(Shadow shadow) { // IProgramElement.Kind shadowKind; // if (shadow.getKind() == Shadow.MethodCall // || shadow.getKind() == Shadow.ConstructorCall // || shadow.getKind() == Shadow.FieldGet // || shadow.getKind() == Shadow.FieldSet // || shadow.getKind() == Shadow.ExceptionHandler) { // return IProgramElement.Kind.CODE; // // } else if (shadow.getKind() == Shadow.MethodExecution) { // return IProgramElement.Kind.METHOD; // // } else if (shadow.getKind() == Shadow.ConstructorExecution) { // return IProgramElement.Kind.CONSTRUCTOR; // // } else if (shadow.getKind() == Shadow.PreInitialization // || shadow.getKind() == Shadow.Initialization) { // return IProgramElement.Kind.CLASS; // // } else if (shadow.getKind() == Shadow.AdviceExecution) { // return IProgramElement.Kind.ADVICE; // // } else { // return IProgramElement.Kind.ERROR; // } // } public static AsmRelationshipProvider getDefault() { return INSTANCE; } /** * Add a relationship to the known set for a declare @method/@constructor construct. Locating the method is a messy (for messy * read 'fragile') bit of code that could break at any moment but it's working for my simple testcase. Currently just fails * silently if any of the lookup code doesn't find anything... * * @param hierarchy */ public void addDeclareAnnotationMethodRelationship(ISourceLocation sourceLocation, String typename, ResolvedMember method, AsmManager structureModel) { if (structureModel == null) // !AsmManager.isCreatingModel()) return; String pkg = null; String type = typename; int packageSeparator = typename.lastIndexOf("."); if (packageSeparator != -1) { pkg = typename.substring(0, packageSeparator); type = typename.substring(packageSeparator + 1); } IHierarchy hierarchy = structureModel.getHierarchy(); IProgramElement typeElem = hierarchy.findElementForType(pkg, type); if (typeElem == null) return; StringBuffer parmString = new StringBuffer("("); UnresolvedType[] args = method.getParameterTypes(); // Type[] args = method.getArgumentTypes(); for (int i = 0; i < args.length; i++) { String s = args[i].getName();// Utility.signatureToString(args[i]. // getName()getSignature(), false); parmString.append(s); if ((i + 1) < args.length) parmString.append(","); } parmString.append(")"); IProgramElement methodElem = null; if (method.getName().startsWith("<init>")) { // its a ctor methodElem = hierarchy.findElementForSignature(typeElem, IProgramElement.Kind.CONSTRUCTOR, type + parmString); if (methodElem == null && args.length == 0) methodElem = typeElem; // assume default ctor } else { // its a method methodElem = hierarchy.findElementForSignature(typeElem, IProgramElement.Kind.METHOD, method.getName() + parmString); } if (methodElem == null) return; try { String targetHandle = methodElem.getHandleIdentifier(); if (targetHandle == null) return; IProgramElement sourceNode = hierarchy.findElementForSourceLine(sourceLocation); String sourceHandle = structureModel.getHandleProvider().createHandleIdentifier(sourceNode); if (sourceHandle == null) return; IRelationshipMap mapper = structureModel.getRelationshipMap(); IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATES, false, true); foreward.addTarget(targetHandle); IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATED_BY, false, true); back.addTarget(sourceHandle); } catch (Throwable t) { // I'm worried about that code above, this will // make sure we don't explode if it plays up t.printStackTrace(); // I know I know .. but I don't want to lose // it! } } /** * Add a relationship to the known set for a declare @field construct. Locating the field is trickier than it might seem since * we have no line number info for it, we have to dig through the structure model under the fields' type in order to locate it. * Currently just fails silently if any of the lookup code doesn't find anything... */ public void addDeclareAnnotationFieldRelationship(AsmManager asm, ISourceLocation sourceLocation, String typename, ResolvedMember field) { if (asm == null) // !AsmManager.isCreatingModel()) return; String pkg = null; String type = typename; int packageSeparator = typename.lastIndexOf("."); if (packageSeparator != -1) { pkg = typename.substring(0, packageSeparator); type = typename.substring(packageSeparator + 1); } IHierarchy hierarchy = asm.getHierarchy(); IProgramElement typeElem = hierarchy.findElementForType(pkg, type); if (typeElem == null) return; IProgramElement fieldElem = hierarchy.findElementForSignature(typeElem, IProgramElement.Kind.FIELD, field.getName()); if (fieldElem == null) return; String targetHandle = fieldElem.getHandleIdentifier(); if (targetHandle == null) return; IProgramElement sourceNode = hierarchy.findElementForSourceLine(sourceLocation); String sourceHandle = asm.getHandleProvider().createHandleIdentifier(sourceNode); if (sourceHandle == null) return; IRelationshipMap mapper = asm.getRelationshipMap(); IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATES, false, true); foreward.addTarget(targetHandle); IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATED_BY, false, true); back.addTarget(sourceHandle); } }
251,326
Bug 251326 Anonymous inner classes declare inside an ITD method will cause IllegalAccessError
If i declare an aspect in pkgB, having an ITD method for a class in pkgA using an inner anonymous class, is created in the pkgA package, package protected, but then instantiated from pkgB causeing the error. Test case is attached.
resolved fixed
f1a83b5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-12-09T19:21:17Z"
"2008-10-19T21:00:00Z"
tests/bugs163/pr251326/pkgA/Listener.java
251,326
Bug 251326 Anonymous inner classes declare inside an ITD method will cause IllegalAccessError
If i declare an aspect in pkgB, having an ITD method for a class in pkgA using an inner anonymous class, is created in the pkgA package, package protected, but then instantiated from pkgB causeing the error. Test case is attached.
resolved fixed
f1a83b5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-12-09T19:21:17Z"
"2008-10-19T21:00:00Z"
tests/bugs163/pr251326/pkgA/Target.java
251,326
Bug 251326 Anonymous inner classes declare inside an ITD method will cause IllegalAccessError
If i declare an aspect in pkgB, having an ITD method for a class in pkgA using an inner anonymous class, is created in the pkgA package, package protected, but then instantiated from pkgB causeing the error. Test case is attached.
resolved fixed
f1a83b5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-12-09T19:21:17Z"
"2008-10-19T21:00:00Z"
tests/src/org/aspectj/systemtest/ajc163/Ajc163Tests.java
/******************************************************************************* * Copyright (c) 2008 Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc163; import java.io.File; import java.util.Iterator; import java.util.List; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.LocalVariable; import org.aspectj.apache.bcel.classfile.LocalVariableTable; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.testing.Utils; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc163Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testAtTargetPlus_pr255856() { runTest("attarget with plus"); } public void testNonNullAtArgs_pr257833() { runTest("param annos and at args"); } // public void testAtAspectJDecp_pr164016() { // runTest("ataspectj decp"); // } public void testIncorrectArgOrdering_pr219419() { runTest("incorrect arg ordering anno style"); } public void testIncorrectArgOrdering_pr219419_2() { runTest("incorrect arg ordering anno style - 2"); } public void testIncorrectArgOrdering_pr219419_3() { runTest("incorrect arg ordering anno style - 3"); } // similar to 3 but parameters other way round public void testIncorrectArgOrdering_pr219419_4() { runTest("incorrect arg ordering anno style - 4"); } // similar to 3 but also JoinPoint passed into advice public void testIncorrectArgOrdering_pr219419_5() { runTest("incorrect arg ordering anno style - 5"); } public void testDecpAnnoStyle_pr257754() { runTest("decp anno style"); } public void testDecpAnnoStyle_pr257754_2() { runTest("decp anno style - 2"); } public void testPoorAtAjIfMessage_pr256458() { runTest("poor ataj if message - 1"); } public void testPoorAtAjIfMessage_pr256458_2() { runTest("poor ataj if message - 2"); } /* * public void testInheritedAnnotations_pr128664() { runTest("inherited annotations"); } * * public void testInheritedAnnotations_pr128664_2() { runTest("inherited annotations - 2"); } */ public void testGetMethodNull_pr154427() { runTest("getMethod returning null"); } public void testItdOnAnonInner_pr171042() { runTest("itd on anonymous inner"); } public void testMixedStyles_pr213751() { runTest("mixed styles"); } public void testHandles_pr249216c24() { runTest("handles - escaped square brackets"); IHierarchy top = AsmManager.lastActiveStructureModel.getHierarchy(); IProgramElement ipe = null; ipe = findElementAtLine(top.getRoot(), 4);// public java.util.List<String> Ship.i(List<String>[][] u) assertEquals("<{Handles.java}Handles)Ship.i)\\[\\[Qjava.util.List\\<QString;>;", ipe.getHandleIdentifier()); ipe = findElementAtLine(top.getRoot(), 7);// public java.util.List<String> Ship.i(Set<String>[][] u) assertEquals("<{Handles.java}Handles)Ship.i)\\[\\[Qjava.util.Set\\<QString;>;", ipe.getHandleIdentifier()); // public java.util.Set<String> i(java.util.Set<String>[][] u) ipe = findElementAtLine(top.getRoot(), 10); assertEquals("<{Handles.java}Handles~i~\\[\\[Qjava.util.Set\\<QString;>;", ipe.getHandleIdentifier()); ipe = findElementAtLine(top.getRoot(), 13);// public java.util.Set<String> i(java.util.Set<String>[][] u,int i) { assertEquals("<{Handles.java}Handles~i~\\[\\[Qjava.util.Set\\<QString;>;~I", ipe.getHandleIdentifier()); ipe = findElementAtLine(top.getRoot(), 16);// public java.util.Set<String> i(java.util.Set<String>[][] u,int i) { assertEquals("<{Handles.java}Handles~i2~\\[\\[Qjava.util.Set\\<+QCollection\\<QString;>;>;", ipe.getHandleIdentifier()); ipe = findElementAtLine(top.getRoot(), 19);// public java.util.Set<String> i3(java.util.Set<? extends // Collection<String[]>>[][] u) assertEquals("<{Handles.java}Handles~i3~\\[\\[Qjava.util.Set\\<+QCollection\\<\\[QString;>;>;", ipe.getHandleIdentifier()); ipe = findElementAtLine(top.getRoot(), 22); assertEquals("<{Handles.java}Handles~i4~Qjava.util.Set\\<+QCollection\\<QString;>;>;", ipe.getHandleIdentifier()); ipe = findElementAtLine(top.getRoot(), 25); assertEquals("<{Handles.java}Handles~i5~Qjava.util.Set\\<*>;", ipe.getHandleIdentifier()); } public void testFQType_pr256937() { runTest("fully qualified return type"); IHierarchy top = AsmManager.lastActiveStructureModel.getHierarchy(); IProgramElement itd = findElementAtLine(top.getRoot(), 10); String type = itd.getCorrespondingType(true); assertEquals("java.util.List<java.lang.String>", type); itd = findElementAtLine(top.getRoot(), 16); type = itd.getCorrespondingType(true); assertEquals("java.util.List<java.lang.String>", type); } private IProgramElement findElementAtLine(IProgramElement whereToLook, int line) { if (whereToLook == null) { return null; } if (whereToLook.getSourceLocation() != null && whereToLook.getSourceLocation().getLine() == line) { return whereToLook; } List kids = whereToLook.getChildren(); for (Iterator iterator = kids.iterator(); iterator.hasNext();) { IProgramElement object = (IProgramElement) iterator.next(); if (object.getSourceLocation() != null && object.getSourceLocation().getLine() == line) { return object; } IProgramElement gotSomething = findElementAtLine(object, line); if (gotSomething != null) { return gotSomething; } } return null; } public void testParameterAnnotationsOnITDs_pr256669() { // regular itd runTest("parameter annotations on ITDs"); } public void testParameterAnnotationsOnITDs_pr256669_2() { // static itd runTest("parameter annotations on ITDs - 2"); } public void testParameterAnnotationsOnITDs_pr256669_3() { // multiple parameters runTest("parameter annotations on ITDs - 3"); } public void testParameterAnnotationsOnITDs_pr256669_4() { // itd on interface runTest("parameter annotations on ITDs - 4"); } public void testOrderingIssue_1() { runTest("ordering issue"); } public void testOrderingIssue_2() { runTest("ordering issue - 2"); } // public void testGenericPointcuts_5() { // runTest("generic pointcuts - 5"); // } public void testGenericPointcuts_1() { runTest("generic pointcuts - 1"); } public void testGenericPointcuts_2() { runTest("generic pointcuts - 2"); } public void testGenericPointcuts_3() { runTest("generic pointcuts - 3"); } public void testGenericPointcuts_4() { runTest("generic pointcuts - 4"); } // public void testBrokenLVT_pr194314_1() throws Exception { // runTest("broken lvt - 1"); // JavaClass jc = Utils.getClassFrom(ajc.getSandboxDirectory().getAbsolutePath(), "Service"); // Method[] ms = jc.getMethods(); // Method m = null; // for (int i = 0; i < ms.length; i++) { // if (ms[i].getName().equals("method_aroundBody1$advice")) { // m = ms[i]; // } // } // if (m.getLocalVariableTable() == null) { // fail("Local variable table should not be null"); // } // System.out.println(m.getLocalVariableTable()); // LocalVariable[] lvt = m.getLocalVariableTable().getLocalVariableTable(); // assertEquals(8, lvt.length); // } // // public void testBrokenLVT_pr194314_2() throws Exception { // runTest("broken lvt - 2"); // JavaClass jc = Utils.getClassFrom(ajc.getSandboxDirectory().getAbsolutePath(), "Service"); // Method[] ms = jc.getMethods(); // Method m = null; // for (int i = 0; i < ms.length; i++) { // if (ms[i].getName().equals("method_aroundBody1$advice")) { // m = ms[i]; // } // } // if (m.getLocalVariableTable() == null) { // fail("Local variable table should not be null"); // } // System.out.println(m.getLocalVariableTable()); // LocalVariable[] lvt = m.getLocalVariableTable().getLocalVariableTable(); // assertEquals(8, lvt.length); // // assertEquals(2, m.getLocalVariableTable().getLocalVariableTable().length); // // // Before I've started any work on this: // // LocalVariable(start_pc = 0, length = 68, index = 0:ServiceInterceptorCodeStyle this) // // LocalVariable(start_pc = 0, length = 68, index = 1:org.aspectj.runtime.internal.AroundClosure ajc_aroundClosure) // // LocalVariable(start_pc = 0, length = 68, index = 2:org.aspectj.lang.JoinPoint thisJoinPoint) // // LocalVariable(start_pc = 9, length = 59, index = 3:Object[] args) // // LocalVariable(start_pc = 21, length = 47, index = 4:long id) // // // Method signature: // // private static final void method_aroundBody1$advice(Service, long, org.aspectj.lang.JoinPoint, // // ServiceInterceptorCodeStyle, org.aspectj.runtime.internal.AroundClosure, org.aspectj.lang.JoinPoint); // // // // Service, JoinPoint, ServiceInterceptorCodeStyle, AroundClosure, JoinPoint // // // args should be in slot 7 and the long in position 8 // // } public void testDontAddMethodBodiesToInterface_pr163005() { runTest("do not add method bodies to an interface"); } public void testDontAddMethodBodiesToInterface_pr163005_2() { runTest("do not add method bodies to an interface - 2"); } public void testDontAddMethodBodiesToInterface_pr163005_3() { runTest("do not add method bodies to an interface - 3"); } public void testMissingLocalVariableTableEntriesOnAroundAdvice_pr173978() throws Exception { runTest("missing local variable table on around advice"); JavaClass jc = Utils.getClassFrom(ajc.getSandboxDirectory().getAbsolutePath(), "Test"); Method[] ms = jc.getMethods(); Method m = null; for (int i = 0; i < ms.length; i++) { if (ms[i].getName().equals("sayHello")) { m = ms[i]; } } if (m.getLocalVariableTable() == null) { fail("Local variable table should not be null"); } assertEquals(2, m.getLocalVariableTable().getLocalVariableTable().length); // LocalVariableTable: // Start Length Slot Name Signature // 0 12 0 this LTest; // 0 12 1 message Ljava/lang/String; LocalVariable lv = m.getLocalVariableTable().getLocalVariable(0); assertNotNull(lv); assertEquals("this", lv.getName()); assertEquals(0, lv.getStartPC(), 0); assertEquals(12, lv.getLength(), 12); assertEquals("LTest;", lv.getSignature()); lv = m.getLocalVariableTable().getLocalVariable(1); assertNotNull(lv); assertEquals("message", lv.getName()); assertEquals(0, lv.getStartPC(), 0); assertEquals(12, lv.getLength(), 12); assertEquals("Ljava/lang/String;", lv.getSignature()); // print(m.getLocalVariableTable()); } public void testTerminateAfterCompilation_pr249710() { runTest("terminateAfterCompilation"); } public void testItdCCE_pr250091() { runTest("itd cce"); } public void testBreakingRecovery_pr226163() { runTest("breaking recovery"); } public void testGenericMethodConversions_pr250632() { runTest("type conversion in generic itd"); } public void testGenericMethodBridging_pr250493() { runTest("bridge methods for generic itds"); } public void testGenericFieldBridging_pr252285() { runTest("bridge methods for generic itd fields"); } public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc163Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc163/ajc163.xml"); } // --- private void print(LocalVariableTable localVariableTable) { LocalVariable[] lvs = localVariableTable.getLocalVariableTable(); for (int i = 0; i < lvs.length; i++) { LocalVariable localVariable = lvs[i]; System.out.println(localVariable); } } }
259,528
Bug 259528 [incremental] [build] Class with ITD declared on it causes too many full builds
When there is a structural change to a class that has an ITD on it there is a full build. This should be an incremental build, but the compiler always drops to a full build.
resolved fixed
2b43e63
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-12-24T00:29:21Z"
"2008-12-22T21:06:40Z"
tests/multiIncremental/pr259528/base/src/b/IsAdvised.java
259,528
Bug 259528 [incremental] [build] Class with ITD declared on it causes too many full builds
When there is a structural change to a class that has an ITD on it there is a full build. This should be an incremental build, but the compiler always drops to a full build.
resolved fixed
2b43e63
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-12-24T00:29:21Z"
"2008-12-22T21:06:40Z"
tests/multiIncremental/pr259528/inc1/src/b/IsAdvised.java
260,751
Bug 260751 java.lang.StringIndexOutOfBoundsException
ava.lang.StringIndexOutOfBoundsException at java.lang.String.substring(String.java:1938) at org.aspectj.ajdt.ajc.ConfigParser.stripWhitespaceAndComments(ConfigParser.java:103) at org.aspectj.ajdt.ajc.ConfigParser.parseConfigFileHelper(ConfigParser.java:69) at org.aspectj.ajdt.ajc.ConfigParser.parseImportedConfigFile(ConfigParser.java:224) at org.aspectj.ajdt.ajc.ConfigParser.parseOneArg(ConfigParser.java:213) at org.aspectj.ajdt.ajc.ConfigP ... 82) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)
resolved fixed
d9bd46d
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-01-12T21:35:16Z"
"2009-01-12T17:06:40Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/ConfigParser.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.ajc; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileReader; import java.io.IOException; import java.util.LinkedList; import java.util.List; public class ConfigParser { Location location; protected File relativeDirectory = null; protected List files = new LinkedList(); private boolean fileParsed = false; protected static String CONFIG_MSG = "build config error: "; public List getFiles() { return files; } public void parseCommandLine(String[] argsArray) throws ParseException { location = new CommandLineLocation(); LinkedList args = new LinkedList(); for (int i = 0; i < argsArray.length; i++) { args.add(new Arg(argsArray[i], location)); } parseArgs(args); } public void parseConfigFile(File configFile) throws ParseException { if (fileParsed == true) { throw new ParseException(CONFIG_MSG + "The file has already been parsed.", null); } else { parseConfigFileHelper(configFile); } } /** * @throws ParseException if the config file has already been prased. */ private void parseConfigFileHelper(File configFile) { if (!configFile.exists()) { showError("file does not exist: " + configFile.getPath()); return; } LinkedList args = new LinkedList(); int lineNum = 0; try { BufferedReader stream = new BufferedReader(new FileReader(configFile)); String line = null; while ((line = stream.readLine()) != null) { lineNum += 1; line = stripWhitespaceAndComments(line); if (line.length() == 0) continue; args.add(new Arg(line, new CPSourceLocation(configFile, lineNum))); } stream.close(); } catch (IOException e) { location = new CPSourceLocation(configFile, lineNum); showError("error reading config file: " + e.toString()); } File oldRelativeDirectory = relativeDirectory; // for nested arg files; relativeDirectory = configFile.getParentFile(); parseArgs(args); relativeDirectory = oldRelativeDirectory; fileParsed = true; } File getCurrentDir() { return location.getDirectory(); } String stripSingleLineComment(String s, String commentString) { int commentStart = s.indexOf(commentString); if (commentStart == -1) return s; else return s.substring(0, commentStart); } String stripWhitespaceAndComments(String s) { s = stripSingleLineComment(s, "//"); s = stripSingleLineComment(s, "#"); s = s.trim(); if (s.startsWith("\"") && s.endsWith("\"")) { s = s.substring(1, s.length() - 1); } return s; } /** * ??? We would like to call a showNonFatalError method here to show all errors in config files before aborting the compilation */ protected void addFile(File sourceFile) { if (!sourceFile.isFile()) { showError("source file does not exist: " + sourceFile.getPath()); } files.add(sourceFile); } void addFileOrPattern(File sourceFile) { if (sourceFile.getName().charAt(0) == '*') { if (sourceFile.getName().equals("*.java")) { addFiles(sourceFile.getParentFile(), new FileFilter() { public boolean accept(File f) { return f != null && f.getName().endsWith(".java"); } }); } else if (sourceFile.getName().equals("*.aj")) { addFiles(sourceFile.getParentFile(), new FileFilter() { public boolean accept(File f) { return f != null && f.getName().endsWith(".aj"); } }); } else { addFile(sourceFile); } } else { addFile(sourceFile); } } void addFiles(File dir, FileFilter filter) { if (dir == null) dir = new File(System.getProperty("user.dir")); if (!dir.isDirectory()) { showError("can't find " + dir.getPath()); } else { File[] files = dir.listFiles(filter); if (files.length == 0) { showWarning("no matching files found in: " + dir); } for (int i = 0; i < files.length; i++) { addFile(files[i]); } } } protected void parseOption(String arg, LinkedList args) { showWarning("unrecognized option: " + arg); } protected void showWarning(String message) { if (location != null) { message += " at " + location.toString(); } System.err.println(CONFIG_MSG + message); } protected void showError(String message) { throw new ParseException(CONFIG_MSG + message, location); } void parseArgs(LinkedList args) { while (args.size() > 0) parseOneArg(args); } protected Arg removeArg(LinkedList args) { if (args.size() == 0) { showError("value missing"); return null; } else { return (Arg) args.removeFirst(); } } protected String removeStringArg(LinkedList args) { Arg arg = removeArg(args); if (arg == null) return null; return arg.getValue(); } boolean isSourceFileName(String s) { if (s.endsWith(".java")) return true; if (s.endsWith(".aj")) return true; // if (s.endsWith(".ajava")) { // showWarning(".ajava is deprecated, replace with .aj or .java: " + s); // return true; // } return false; } void parseOneArg(LinkedList args) { Arg arg = removeArg(args); String v = arg.getValue(); location = arg.getLocation(); if (v.startsWith("@")) { parseImportedConfigFile(v.substring(1)); } else if (v.equals("-argfile")) { parseConfigFileHelper(makeFile(removeArg(args).getValue())); } else if (isSourceFileName(v)) { addFileOrPattern(makeFile(v)); } else { parseOption(arg.getValue(), args); } } protected void parseImportedConfigFile(String relativeFilePath) { parseConfigFileHelper(makeFile(relativeFilePath)); } public File makeFile(String name) { if (relativeDirectory != null) { return makeFile(relativeDirectory, name); } else { return makeFile(getCurrentDir(), name); } } private File makeFile(File dir, String name) { name = name.replace('/', File.separatorChar); File ret = new File(name); boolean isAbsolute = ret.isAbsolute() || (ret.exists() && ret.getPath().startsWith(File.separator)); if (!isAbsolute && (dir != null)) { ret = new File(dir, name); } try { ret = ret.getCanonicalFile(); } catch (IOException ioEx) { // proceed without canonicalization // so nothing to do here } return ret; } protected static class Arg { private Location location; private String value; public Arg(String value, Location location) { this.value = value; this.location = location; } public void setValue(String value) { this.value = value; } public void setLocation(Location location) { this.location = location; } public String getValue() { return value; } public Location getLocation() { return location; } } static abstract class Location { public abstract File getFile(); public abstract File getDirectory(); public abstract int getLine(); public abstract String toString(); } static class CPSourceLocation extends Location { private int line; private File file; public CPSourceLocation(File file, int line) { this.line = line; this.file = file; } public File getFile() { return file; } public File getDirectory() { return file.getParentFile(); } public int getLine() { return line; } public String toString() { return file.getPath() + ":" + line; } } static class CommandLineLocation extends Location { public File getFile() { return new File(System.getProperty("user.dir")); } public File getDirectory() { return new File(System.getProperty("user.dir")); } public int getLine() { return -1; } public String toString() { return "command-line"; } } public static class ParseException extends RuntimeException { private Location location; public ParseException(String message, Location location) { super(message); this.location = location; } public int getLine() { if (location == null) return -1; return location.getLine(); } public File getFile() { if (location == null) return null; return location.getFile(); } } }
261,808
Bug 261808 iajc-Ant-Task fails "type already defined"
null
resolved fixed
1da1f7c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-01-31T04:33:22Z"
"2009-01-21T12:13:20Z"
taskdefs/src/org/aspectj/tools/ant/taskdefs/AjcTask.java
/* ******************************************************************* * Copyright (c) 2001-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC) * 2003-2004 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Xerox/PARC initial implementation * Wes Isberg 2003-2004 changes * ******************************************************************/ package org.aspectj.tools.ant.taskdefs; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Location; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Copy; import org.apache.tools.ant.taskdefs.Delete; import org.apache.tools.ant.taskdefs.Execute; import org.apache.tools.ant.taskdefs.Expand; import org.apache.tools.ant.taskdefs.Javac; import org.apache.tools.ant.taskdefs.LogStreamHandler; import org.apache.tools.ant.taskdefs.MatchingTask; import org.apache.tools.ant.taskdefs.Mkdir; import org.apache.tools.ant.taskdefs.PumpStreamHandler; import org.apache.tools.ant.taskdefs.Zip; import org.apache.tools.ant.taskdefs.compilers.DefaultCompilerAdapter; import org.apache.tools.ant.types.Commandline; import org.apache.tools.ant.types.CommandlineJava; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.PatternSet; import org.apache.tools.ant.types.Reference; import org.apache.tools.ant.types.ZipFileSet; import org.apache.tools.ant.util.TaskLogger; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IMessageHolder; import org.aspectj.bridge.MessageHandler; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.tools.ajc.Main; import org.aspectj.util.FileUtil; import org.aspectj.util.LangUtil; /** * This runs the AspectJ 1.1 compiler, * supporting all the command-line options. * In 1.1.1, ajc copies resources from input jars, * but you can copy resources from the source directories * using sourceRootCopyFilter. * When not forking, things will be copied as needed * for each iterative compile, * but when forking things are only copied at the * completion of a successful compile. * <p> * See the development environment guide for * usage documentation. * * @since AspectJ 1.1, Ant 1.5 */ public class AjcTask extends MatchingTask { /* * This task mainly converts ant specification for ajc, * verbosely ignoring improper input. * It also has some special features for non-obvious clients: * (1) Javac compiler adapter supported in * <code>setupAjc(AjcTask, Javac, File)</code> * and * <code>readArguments(String[])</code>; * (2) testing is supported by * (a) permitting the same specification to be re-run * with added flags (settings once made cannot be * removed); and * (b) permitting recycling the task with * <code>reset()</code> (untested). * * The parts that do more than convert ant specs are * (a) code for forking; * (b) code for copying resources. * * If you maintain/upgrade this task, keep in mind: * (1) changes to the semantics of ajc (new options, new * values permitted, etc.) will have to be reflected here. * (2) the clients: * the iajc ant script, Javac compiler adapter, * maven clients of iajc, and testing code. */ // XXX move static methods after static initializer /** * This method extracts javac arguments to ajc, * and add arguments to make ajc behave more like javac * in copying resources. * <p> * Pass ajc-specific options using compilerarg sub-element: * <pre> * &lt;javac srcdir="src"> * &lt;compilerarg compiler="..." line="-argfile src/args.lst"/> * &lt;javac> * </pre> * Some javac arguments are not supported in this component (yet): * <pre> * String memoryInitialSize; * boolean includeAntRuntime = true; * boolean includeJavaRuntime = false; * </pre> * Other javac arguments are not supported in ajc 1.1: * <pre> * boolean optimize; * String forkedExecutable; * FacadeTaskHelper facade; * boolean depend; * String debugLevel; * Path compileSourcepath; * </pre> * @param javac the Javac command to implement (not null) * @param ajc the AjcTask to adapt (not null) * @param destDir the File class destination directory (may be null) * @return null if no error, or String error otherwise */ public String setupAjc(Javac javac) { if (null == javac) { return "null javac"; } AjcTask ajc = this; // no null checks b/c AjcTask handles null input gracefully ajc.setProject(javac.getProject()); ajc.setLocation(javac.getLocation()); ajc.setTaskName("javac-iajc"); ajc.setDebug(javac.getDebug()); ajc.setDeprecation(javac.getDeprecation()); ajc.setFailonerror(javac.getFailonerror()); final boolean fork = javac.isForkedJavac(); ajc.setFork(fork); if (fork) { ajc.setMaxmem(javac.getMemoryMaximumSize()); } ajc.setNowarn(javac.getNowarn()); ajc.setListFileArgs(javac.getListfiles()); ajc.setVerbose(javac.getVerbose()); ajc.setTarget(javac.getTarget()); ajc.setSource(javac.getSource()); ajc.setEncoding(javac.getEncoding()); File javacDestDir = javac.getDestdir(); if (null != javacDestDir) { ajc.setDestdir(javacDestDir); // filter requires dest dir // mimic Javac task's behavior in copying resources, ajc.setSourceRootCopyFilter("**/CVS/*,**/*.java,**/*.aj"); } ajc.setBootclasspath(javac.getBootclasspath()); ajc.setExtdirs(javac.getExtdirs()); ajc.setClasspath(javac.getClasspath()); // ignore srcDir -- all files picked up in recalculated file list // ajc.setSrcDir(javac.getSrcdir()); ajc.addFiles(javac.getFileList()); // arguments can override the filter, add to paths, override options ajc.readArguments(javac.getCurrentCompilerArgs()); return null; } /** * Find aspectjtools.jar on the task or system classpath. * Accept <code>aspectj{-}tools{...}.jar</code> * mainly to support build systems using maven-style * re-naming * (e.g., <code>aspectj-tools-1.1.0.jar</code>. * Note that we search the task classpath first, * though an entry on the system classpath would be loaded first, * because it seems more correct as the more specific one. * @return readable File for aspectjtools.jar, or null if not found. */ public static File findAspectjtoolsJar() { File result = null; ClassLoader loader = AjcTask.class.getClassLoader(); if (loader instanceof AntClassLoader) { AntClassLoader taskLoader = (AntClassLoader) loader; String cp = taskLoader.getClasspath(); String[] cps = LangUtil.splitClasspath(cp); for (int i = 0; (i < cps.length) && (null == result); i++) { result = isAspectjtoolsjar(cps[i]); } } if (null == result) { final Path classpath = Path.systemClasspath; final String[] paths = classpath.list(); for (int i = 0; (i < paths.length) && (null == result); i++) { result = isAspectjtoolsjar(paths[i]); } } return (null == result? null : result.getAbsoluteFile()); } /** @return File if readable jar with aspectj tools name, or null */ private static File isAspectjtoolsjar(String path) { if (null == path) { return null; } final String prefix = "aspectj"; final String infix = "tools"; final String altInfix = "-tools"; final String suffix = ".jar"; final int prefixLength = 7; // prefix.length(); final int minLength = 16; // prefixLength + infix.length() + suffix.length(); if (!path.endsWith(suffix)) { return null; } int loc = path.lastIndexOf(prefix); if ((-1 != loc) && ((loc + minLength) <= path.length())) { String rest = path.substring(loc+prefixLength); if (-1 != rest.indexOf(File.pathSeparator)) { return null; } if (rest.startsWith(infix) || rest.startsWith(altInfix)) { File result = new File(path); if (result.canRead() && result.isFile()) { return result; } } } return null; } /** * Maximum length (in chars) of command line * before converting to an argfile when forking */ private static final int MAX_COMMANDLINE = 4096; private static final File DEFAULT_DESTDIR = new File(".") { public String toString() { return "(no destination dir specified)"; } }; /** do not throw BuildException on fail/abort message with usage */ private static final String USAGE_SUBSTRING = "AspectJ-specific options"; /** valid -X[...] options other than -Xlint variants */ private static final List VALID_XOPTIONS; /** valid warning (-warn:[...]) variants */ private static final List VALID_WARNINGS; /** valid debugging (-g:[...]) variants */ private static final List VALID_DEBUG; /** * -Xlint variants (error, warning, ignore) * @see org.aspectj.weaver.Lint */ private static final List VALID_XLINT; public static final String COMMAND_EDITOR_NAME = AjcTask.class.getName() + ".COMMAND_EDITOR"; static final String[] TARGET_INPUTS = new String [] { "1.1", "1.2", "1.3", "1.4", "1.5", "1.6" }; static final String[] SOURCE_INPUTS = new String [] { "1.3", "1.4", "1.5", "1.6" }; static final String[] COMPLIANCE_INPUTS = new String [] { "-1.3", "-1.4", "-1.5", "-1.6" }; private static final ICommandEditor COMMAND_EDITOR; static { // many now deprecated: reweavable* String[] xs = new String[] { "serializableAspects", "incrementalFile", "lazyTjp", "reweavable", "reweavable:compress", "notReweavable", "noInline", "terminateAfterCompilation","hasMember", "ajruntimetarget:1.2", "ajruntimetarget:1.5", "addSerialVersionUID" //, "targetNearSource", "OcodeSize", }; VALID_XOPTIONS = Collections.unmodifiableList(Arrays.asList(xs)); xs = new String[] { "constructorName", "packageDefaultMethod", "deprecation", "maskedCatchBlocks", "unusedLocals", "unusedArguments", "unusedImports", "syntheticAccess", "assertIdentifier", "allDeprecation","allJavadoc","charConcat","conditionAssign", "emptyBlock", "fieldHiding", "finally", "indirectStatic", "intfNonInherited", "javadoc", "localHiding", "nls", "noEffectAssign", "pkgDefaultMethod", "semicolon", "unqualifiedField", "unusedPrivate", "unusedThrown", "uselessTypeCheck", "specialParamHiding", "staticReceiver", "syntheticAccess", "none" }; VALID_WARNINGS = Collections.unmodifiableList(Arrays.asList(xs)); xs = new String[] {"none", "lines", "vars", "source" }; VALID_DEBUG = Collections.unmodifiableList(Arrays.asList(xs)); xs = new String[] { "error", "warning", "ignore"}; VALID_XLINT = Collections.unmodifiableList(Arrays.asList(xs)); ICommandEditor editor = null; try { String editorClassName = System.getProperty(COMMAND_EDITOR_NAME); if (null != editorClassName) { ClassLoader cl = AjcTask.class.getClassLoader(); Class editorClass = cl.loadClass(editorClassName); editor = (ICommandEditor) editorClass.newInstance(); } } catch (Throwable t) { System.err.println("Warning: unable to load command editor"); t.printStackTrace(System.err); } COMMAND_EDITOR = editor; } // ---------------------------- state and Ant interface thereto private boolean verbose; private boolean listFileArgs; private boolean failonerror; private boolean fork; private String maxMem; private TaskLogger logger; // ------- single entries dumped into cmd protected GuardedCommand cmd; // ------- lists resolved in addListArgs() at execute() time private Path srcdir; private Path injars; private Path inpath; private Path classpath; private Path bootclasspath; private Path forkclasspath; private Path extdirs; private Path aspectpath; private Path argfiles; private List ignored; private Path sourceRoots; private File xweaveDir; private String xdoneSignal; // ----- added by adapter - integrate better? private List /* File */ adapterFiles; private String[] adapterArguments; private IMessageHolder messageHolder; private ICommandEditor commandEditor; // -------- resource-copying /** true if copying injar non-.class files to the output jar */ private boolean copyInjars; private boolean copyInpath; /** non-null if copying all source root files but the filtered ones */ private String sourceRootCopyFilter; /** non-null if copying all inpath dir files but the filtered ones */ private String inpathDirCopyFilter; /** directory sink for classes */ private File destDir; /** zip file sink for classes */ private File outjar; /** track whether we've supplied any temp outjar */ private boolean outjarFixedup; /** * When possibly copying resources to the output jar, * pass ajc a fake output jar to copy from, * so we don't change the modification time of the output jar * when copying injars/inpath into the actual outjar. */ private File tmpOutjar; private boolean executing; /** non-null only while executing in same vm */ private Main main; /** true only when executing in other vm */ private boolean executingInOtherVM; /** true if -incremental */ private boolean inIncrementalMode; /** true if -XincrementalFile (i.e, setTagFile)*/ private boolean inIncrementalFileMode; /** log command in non-verbose mode */ private boolean logCommand; /** used when forking */ private CommandlineJava javaCmd = new CommandlineJava(); // also note MatchingTask grabs source files... public AjcTask() { reset(); } /** to use this same Task more than once (testing) */ public void reset() { // XXX possible to reset MatchingTask? // need declare for "all fields initialized in ..." adapterArguments = null; adapterFiles = new ArrayList(); argfiles = null; executing = false; aspectpath = null; bootclasspath = null; classpath = null; cmd = new GuardedCommand(); copyInjars = false; copyInpath = false; destDir = DEFAULT_DESTDIR; executing = false; executingInOtherVM = false; extdirs = null; failonerror = true; // non-standard default forkclasspath = null; inIncrementalMode = false; inIncrementalFileMode = false; ignored = new ArrayList(); injars = null; inpath = null; listFileArgs = false; maxMem = null; messageHolder = null; outjar = null; sourceRootCopyFilter = null; inpathDirCopyFilter = null; sourceRoots = null; srcdir = null; tmpOutjar = null; verbose = false; xweaveDir = null; xdoneSignal = null; logCommand = false; javaCmd = new CommandlineJava(); } protected void ignore(String ignored) { this.ignored.add(ignored + " at " + getLocation()); } //---------------------- option values // used by entries with internal commas protected String validCommaList(String list, List valid, String label) { return validCommaList(list, valid, label, valid.size()); } protected String validCommaList(String list, List valid, String label, int max) { StringBuffer result = new StringBuffer(); StringTokenizer st = new StringTokenizer(list, ","); int num = 0; while (st.hasMoreTokens()) { String token = st.nextToken().trim(); num++; if (num > max) { ignore("too many entries for -" + label + ": " + token); break; } if (!valid.contains(token)) { ignore("bad commaList entry for -" + label + ": " + token); } else { if (0 < result.length()) { result.append(","); } result.append(token); } } return (0 == result.length() ? null : result.toString()); } public void setIncremental(boolean incremental) { cmd.addFlag("-incremental", incremental); inIncrementalMode = incremental; } public void setLogCommand(boolean logCommand) { this.logCommand = logCommand; } public void setHelp(boolean help) { cmd.addFlag("-help", help); } public void setVersion(boolean version) { cmd.addFlag("-version", version); } public void setXTerminateAfterCompilation(boolean b) { cmd.addFlag("-XterminateAfterCompilation", b); } public void setXReweavable(boolean reweavable) { cmd.addFlag("-Xreweavable",reweavable); } public void setXJoinpoints(String optionalJoinpoints) { cmd.addFlag("-Xjoinpoints:"+optionalJoinpoints,true); } public void setCheckRuntimeVersion(boolean b) { cmd.addFlag("-checkRuntimeVersion:"+b,true); } public void setXNoWeave(boolean b) { if (logger!=null) logger.warning("the noweave option is no longer required and is being ignored"); } public void setNoWeave(boolean b) { if (logger!=null) logger.warning("the noweave option is no longer required and is being ignored"); } public void setXNotReweavable(boolean notReweavable) { cmd.addFlag("-XnotReweavable",notReweavable); } public void setXaddSerialVersionUID(boolean addUID) { cmd.addFlag("-XaddSerialVersionUID",addUID); } public void setXNoInline(boolean noInline) { cmd.addFlag("-XnoInline",noInline); } public void setShowWeaveInfo(boolean showweaveinfo) { cmd.addFlag("-showWeaveInfo",showweaveinfo); } public void setNowarn(boolean nowarn) { cmd.addFlag("-nowarn", nowarn); } public void setDeprecation(boolean deprecation) { cmd.addFlag("-deprecation", deprecation); } public void setWarn(String warnings) { warnings = validCommaList(warnings, VALID_WARNINGS, "warn"); cmd.addFlag("-warn:" + warnings, (null != warnings)); } public void setDebug(boolean debug) { cmd.addFlag("-g", debug); } public void setDebugLevel(String level) { level = validCommaList(level, VALID_DEBUG, "g"); cmd.addFlag("-g:" + level, (null != level)); } public void setEmacssym(boolean emacssym) { cmd.addFlag("-emacssym", emacssym); } public void setCrossrefs(boolean on) { cmd.addFlag("-crossrefs", on); } /** * -Xlint - set default level of -Xlint messages to warning * (same as </code>-Xlint:warning</code>) */ public void setXlintwarnings(boolean xlintwarnings) { cmd.addFlag("-Xlint", xlintwarnings); } /** -Xlint:{error|warning|info} - set default level for -Xlint messages * @param xlint the String with one of error, warning, ignored */ public void setXlint(String xlint) { xlint = validCommaList(xlint, VALID_XLINT, "Xlint", 1); cmd.addFlag("-Xlint:" + xlint, (null != xlint)); } /** * -Xlintfile {lint.properties} - enable or disable specific forms * of -Xlint messages based on a lint properties file * (default is * <code>org/aspectj/weaver/XLintDefault.properties</code>) * @param xlintFile the File with lint properties */ public void setXlintfile(File xlintFile) { cmd.addFlagged("-Xlintfile", xlintFile.getAbsolutePath()); } public void setPreserveAllLocals(boolean preserveAllLocals) { cmd.addFlag("-preserveAllLocals", preserveAllLocals); } public void setNoImportError(boolean noImportError) { cmd.addFlag("-warn:-unusedImport", noImportError); } public void setEncoding(String encoding) { cmd.addFlagged("-encoding", encoding); } public void setLog(File file) { cmd.addFlagged("-log", file.getAbsolutePath()); } public void setProceedOnError(boolean proceedOnError) { cmd.addFlag("-proceedOnError", proceedOnError); } public void setVerbose(boolean verbose) { cmd.addFlag("-verbose", verbose); this.verbose = verbose; } public void setListFileArgs(boolean listFileArgs) { this.listFileArgs = listFileArgs; } public void setReferenceInfo(boolean referenceInfo) { cmd.addFlag("-referenceInfo", referenceInfo); } public void setTime(boolean time) { cmd.addFlag("-time", time); } public void setNoExit(boolean noExit) { cmd.addFlag("-noExit", noExit); } public void setFailonerror(boolean failonerror) { this.failonerror = failonerror; } /** * @return true if fork was set */ public boolean isForked() { return fork; } public void setFork(boolean fork) { this.fork = fork; } public void setMaxmem(String maxMem) { this.maxMem = maxMem; } /** support for nested &lt;jvmarg&gt; elements */ public Commandline.Argument createJvmarg() { return this.javaCmd.createVmArgument(); } // ---------------- public void setTagFile(File file) { inIncrementalMode = true; cmd.addFlagged(Main.CommandController.TAG_FILE_OPTION, file.getAbsolutePath()); inIncrementalFileMode = true; } public void setOutjar(File file) { if (DEFAULT_DESTDIR != destDir) { String e = "specifying both output jar (" + file + ") and destination dir (" + destDir + ")"; throw new BuildException(e); } outjar = file; outjarFixedup = false; tmpOutjar = null; } public void setOutxml(boolean outxml) { cmd.addFlag("-outxml",outxml); } public void setOutxmlfile(String name) { cmd.addFlagged("-outxmlfile", name); } public void setDestdir(File dir) { if (null != outjar) { String e = "specifying both output jar (" + outjar + ") and destination dir (" + dir + ")"; throw new BuildException(e); } cmd.addFlagged("-d", dir.getAbsolutePath()); destDir = dir; } /** * @param input a String in TARGET_INPUTS */ public void setTarget(String input) { String ignore = cmd.addOption("-target", TARGET_INPUTS, input); if (null != ignore) { ignore(ignore); } } /** * Language compliance level. * If not set explicitly, eclipse default holds. * @param input a String in COMPLIANCE_INPUTS */ public void setCompliance(String input) { String ignore = cmd.addOption(null, COMPLIANCE_INPUTS, input); if (null != ignore) { ignore(ignore); } } /** * Source compliance level. * If not set explicitly, eclipse default holds. * @param input a String in SOURCE_INPUTS */ public void setSource(String input) { String ignore = cmd.addOption("-source", SOURCE_INPUTS, input); if (null != ignore) { ignore(ignore); } } /** * Flag to copy all non-.class contents of injars * to outjar after compile completes. * Requires both injars and outjar. * @param doCopy */ public void setCopyInjars(boolean doCopy){ ignore("copyInJars"); log("copyInjars not required since 1.1.1.\n", Project.MSG_WARN); //this.copyInjars = doCopy; } /** * Option to copy all files from * all source root directories * except those specified here. * If this is specified and sourceroots are specified, * then this will copy all files except * those specified in the filter pattern. * Requires sourceroots. * * @param filter a String acceptable as an excludes * filter for an Ant Zip fileset. */ public void setSourceRootCopyFilter(String filter){ this.sourceRootCopyFilter = filter; } /** * Option to copy all files from * all inpath directories * except the files specified here. * If this is specified and inpath directories are specified, * then this will copy all files except * those specified in the filter pattern. * Requires inpath. * If the input does not contain "**\/*.class", then * this prepends it, to avoid overwriting woven classes * with unwoven input. * @param filter a String acceptable as an excludes * filter for an Ant Zip fileset. */ public void setInpathDirCopyFilter(String filter){ if (null != filter) { if (-1 == filter.indexOf("**/*.class")) { filter = "**/*.class," + filter; } } this.inpathDirCopyFilter = filter; } public void setX(String input) { // ajc-only eajc-also docDone StringTokenizer tokens = new StringTokenizer(input, ",", false); while (tokens.hasMoreTokens()) { String token = tokens.nextToken().trim(); if (1 < token.length()) { // new special case: allow -Xset:anything if (VALID_XOPTIONS.contains(token) || token.indexOf("set:")==0 || token.indexOf("joinpoints:")==0) { cmd.addFlag("-X" + token, true); } else { ignore("-X" + token); } } } } public void setXDoneSignal(String doneSignal) { this.xdoneSignal = doneSignal; } /** direct API for testing */ public void setMessageHolder(IMessageHolder holder) { this.messageHolder = holder; } /** * Setup custom message handling. * @param className the String fully-qualified-name of a class * reachable from this object's class loader, * implementing IMessageHolder, and * having a public no-argument constructor. * @throws BuildException if unable to create instance of className */ public void setMessageHolderClass(String className) { try { Class mclass = Class.forName(className); IMessageHolder holder = (IMessageHolder) mclass.newInstance(); setMessageHolder(holder); } catch (Throwable t) { String m = "unable to instantiate message holder: " + className; throw new BuildException(m, t); } } /** direct API for testing */ public void setCommandEditor(ICommandEditor editor) { this.commandEditor = editor; } /** * Setup command-line filter. * To do this staticly, define the environment variable * <code>org.aspectj.tools.ant.taskdefs.AjcTask.COMMAND_EDITOR</code> * with the <code>className</code> parameter. * @param className the String fully-qualified-name of a class * reachable from this object's class loader, * implementing ICommandEditor, and * having a public no-argument constructor. * @throws BuildException if unable to create instance of className */ public void setCommandEditorClass(String className) { // skip Ant interface? try { Class mclass = Class.forName(className); setCommandEditor((ICommandEditor) mclass.newInstance()); } catch (Throwable t) { String m = "unable to instantiate command editor: " + className; throw new BuildException(m, t); } } //---------------------- Path lists /** * Add path elements to source path and return result. * Elements are added even if they do not exist. * @param source the Path to add to - may be null * @param toAdd the Path to add - may be null * @return the (never-null) Path that results */ protected Path incPath(Path source, Path toAdd) { if (null == source) { source = new Path(project); } if (null != toAdd) { source.append(toAdd); } return source; } public void setSourcerootsref(Reference ref) { createSourceRoots().setRefid(ref); } public void setSourceRoots(Path roots) { sourceRoots = incPath(sourceRoots, roots); } public Path createSourceRoots() { if (sourceRoots == null) { sourceRoots = new Path(project); } return sourceRoots.createPath(); } public void setXWeaveDir(File file) { if ((null != file) && file.isDirectory() && file.canRead()) { xweaveDir = file; } } public void setInjarsref(Reference ref) { createInjars().setRefid(ref); } public void setInpathref(Reference ref) { createInpath().setRefid(ref); } public void setInjars(Path path) { injars = incPath(injars, path); } public void setInpath(Path path) { inpath = incPath(inpath,path); } public Path createInjars() { if (injars == null) { injars = new Path(project); } return injars.createPath(); } public Path createInpath() { if (inpath == null) { inpath = new Path(project); } return inpath.createPath(); } public void setClasspath(Path path) { classpath = incPath(classpath, path); } public void setClasspathref(Reference classpathref) { createClasspath().setRefid(classpathref); } public Path createClasspath() { if (classpath == null) { classpath = new Path(project); } return classpath.createPath(); } public void setBootclasspath(Path path) { bootclasspath = incPath(bootclasspath, path); } public void setBootclasspathref(Reference bootclasspathref) { createBootclasspath().setRefid(bootclasspathref); } public Path createBootclasspath() { if (bootclasspath == null) { bootclasspath = new Path(project); } return bootclasspath.createPath(); } public void setForkclasspath(Path path) { forkclasspath = incPath(forkclasspath, path); } public void setForkclasspathref(Reference forkclasspathref) { createForkclasspath().setRefid(forkclasspathref); } public Path createForkclasspath() { if (forkclasspath == null) { forkclasspath = new Path(project); } return forkclasspath.createPath(); } public void setExtdirs(Path path) { extdirs = incPath(extdirs, path); } public void setExtdirsref(Reference ref) { createExtdirs().setRefid(ref); } public Path createExtdirs() { if (extdirs == null) { extdirs = new Path(project); } return extdirs.createPath(); } public void setAspectpathref(Reference ref) { createAspectpath().setRefid(ref); } public void setAspectpath(Path path) { aspectpath = incPath(aspectpath, path); } public Path createAspectpath() { if (aspectpath == null) { aspectpath = new Path(project); } return aspectpath.createPath(); } public void setSrcDir(Path path) { srcdir = incPath(srcdir, path); } public Path createSrc() { return createSrcdir(); } public Path createSrcdir() { if (srcdir == null) { srcdir = new Path(project); } return srcdir.createPath(); } /** @return true if in incremental mode (command-line or file) */ public boolean isInIncrementalMode() { return inIncrementalMode; } /** @return true if in incremental file mode */ public boolean isInIncrementalFileMode() { return inIncrementalFileMode; } public void setArgfilesref(Reference ref) { createArgfiles().setRefid(ref); } public void setArgfiles(Path path) { // ajc-only eajc-also docDone argfiles = incPath(argfiles, path); } public Path createArgfiles() { if (argfiles == null) { argfiles = new Path(project); } return argfiles.createPath(); } // ------------------------------ run /** * Compile using ajc per settings. * @exception BuildException if the compilation has problems * or if there were compiler errors and failonerror is true. */ public void execute() throws BuildException { this.logger = new TaskLogger(this); if (executing) { throw new IllegalStateException("already executing"); } else { executing = true; } setupOptions(); verifyOptions(); try { String[] args = makeCommand(); if (logCommand) { log("ajc " + Arrays.asList(args)); } else { logVerbose("ajc " + Arrays.asList(args)); } if (!fork) { executeInSameVM(args); } else { // when forking, Adapter handles failonerror executeInOtherVM(args); } } catch (BuildException e) { throw e; } catch (Throwable x) { this.logger.error(Main.renderExceptionForUser(x)); throw new BuildException("IGNORE -- See " + LangUtil.unqualifiedClassName(x) + " rendered to ant logger"); } finally { executing = false; if (null != tmpOutjar) { tmpOutjar.delete(); } } } /** * Halt processing. * This tells main in the same vm to quit. * It fails when running in forked mode. * @return true if not in forked mode * and main has quit or been told to quit */ public boolean quit() { if (executingInOtherVM) { return false; } Main me = main; if (null != me) { me.quit(); } return true; } // package-private for testing String[] makeCommand() { ArrayList result = new ArrayList(); if (0 < ignored.size()) { for (Iterator iter = ignored.iterator(); iter.hasNext();) { logVerbose("ignored: " + iter.next()); } } // when copying resources, use temp jar for class output // then copy temp jar contents and resources to output jar if ((null != outjar) && !outjarFixedup) { if (copyInjars || copyInpath || (null != sourceRootCopyFilter) || (null != inpathDirCopyFilter)) { String path = outjar.getAbsolutePath(); int len = FileUtil.zipSuffixLength(path); path = path.substring(0, path.length()-len) + ".tmp.jar"; tmpOutjar = new File(path); } if (null == tmpOutjar) { cmd.addFlagged("-outjar", outjar.getAbsolutePath()); } else { cmd.addFlagged("-outjar", tmpOutjar.getAbsolutePath()); } outjarFixedup = true; } result.addAll(cmd.extractArguments()); addListArgs(result); String[] command = (String[]) result.toArray(new String[0]); if (null != commandEditor) { command = commandEditor.editCommand(command); } else if (null != COMMAND_EDITOR) { command = COMMAND_EDITOR.editCommand(command); } return command; } /** * Create any pseudo-options required to implement * some of the macro options * @throws BuildException if options conflict */ protected void setupOptions() { if (null != xweaveDir) { if (DEFAULT_DESTDIR != destDir) { throw new BuildException("weaveDir forces destdir"); } if (null != outjar) { throw new BuildException("weaveDir forces outjar"); } if (null != injars) { throw new BuildException("weaveDir incompatible with injars now"); } if (null != inpath) { throw new BuildException("weaveDir incompatible with inpath now"); } File injar = zipDirectory(xweaveDir); setInjars(new Path(getProject(), injar.getAbsolutePath())); setDestdir(xweaveDir); } } protected File zipDirectory(File dir) { File tempDir = new File("."); try { tempDir = File.createTempFile("AjcTest", ".tmp"); tempDir.mkdirs(); tempDir.deleteOnExit(); // XXX remove zip explicitly.. } catch (IOException e) { // ignore } // File result = new File(tempDir, String filename = "AjcTask-" + System.currentTimeMillis() + ".zip"; File result = new File(filename); Zip zip = new Zip(); zip.setProject(getProject()); zip.setDestFile(result); zip.setTaskName(getTaskName() + " - zip"); FileSet fileset = new FileSet(); fileset.setDir(dir); zip.addFileset(fileset); zip.execute(); Delete delete = new Delete(); delete.setProject(getProject()); delete.setTaskName(getTaskName() + " - delete"); delete.setDir(dir); delete.execute(); Mkdir mkdir = new Mkdir(); mkdir.setProject(getProject()); mkdir.setTaskName(getTaskName() + " - mkdir"); mkdir.setDir(dir); mkdir.execute(); return result; } /** * @throw BuildException if options conflict */ protected void verifyOptions() { StringBuffer sb = new StringBuffer(); if (fork && isInIncrementalMode() && !isInIncrementalFileMode()) { sb.append("can fork incremental only using tag file.\n"); } if (((null != inpathDirCopyFilter) || (null != sourceRootCopyFilter)) && (null == outjar) && (DEFAULT_DESTDIR == destDir)) { final String REQ = " requires dest dir or output jar.\n"; if (null == inpathDirCopyFilter) { sb.append("sourceRootCopyFilter"); } else if (null == sourceRootCopyFilter) { sb.append("inpathDirCopyFilter"); } else { sb.append("sourceRootCopyFilter and inpathDirCopyFilter"); } sb.append(REQ); } if (0 < sb.length()) { throw new BuildException(sb.toString()); } } /** * Run the compile in the same VM by * loading the compiler (Main), * setting up any message holders, * doing the compile, * and converting abort/failure and error messages * to BuildException, as appropriate. * @throws BuildException if abort or failure messages * or if errors and failonerror. * */ protected void executeInSameVM(String[] args) { if (null != maxMem) { log("maxMem ignored unless forked: " + maxMem, Project.MSG_WARN); } IMessageHolder holder = messageHolder; int numPreviousErrors; if (null == holder) { MessageHandler mhandler = new MessageHandler(true); final IMessageHandler delegate; delegate = new AntMessageHandler(this.logger,this.verbose, false); mhandler.setInterceptor(delegate); holder = mhandler; numPreviousErrors = 0; } else { numPreviousErrors = holder.numMessages(IMessage.ERROR, true); } { Main newmain = new Main(); newmain.setHolder(holder); newmain.setCompletionRunner(new Runnable() { public void run() { doCompletionTasks(); } }); if (null != main) { MessageUtil.fail(holder, "still running prior main"); return; } main = newmain; } main.runMain(args, false); if (failonerror) { int errs = holder.numMessages(IMessage.ERROR, false); errs -= numPreviousErrors; if (0 < errs) { String m = errs + " errors"; MessageUtil.print(System.err, holder, "", MessageUtil.MESSAGE_ALL, MessageUtil.PICK_ERROR, true); throw new BuildException(m); } } // Throw BuildException if there are any fail or abort // messages. // The BuildException message text has a list of class names // for the exceptions found in the messages, or the // number of fail/abort messages found if there were // no exceptions for any of the fail/abort messages. // The interceptor message handler should have already // printed the messages, including any stack traces. // HACK: this ignores the Usage message { IMessage[] fails = holder.getMessages(IMessage.FAIL, true); if (!LangUtil.isEmpty(fails)) { StringBuffer sb = new StringBuffer(); String prefix = "fail due to "; int numThrown = 0; for (int i = 0; i < fails.length; i++) { String message = fails[i].getMessage(); if (LangUtil.isEmpty(message)) { message = "<no message>"; } else if (-1 != message.indexOf(USAGE_SUBSTRING)) { continue; } Throwable t = fails[i].getThrown(); if (null != t) { numThrown++; sb.append(prefix); sb.append(LangUtil.unqualifiedClassName(t.getClass())); String thrownMessage = t.getMessage(); if (!LangUtil.isEmpty(thrownMessage)) { sb.append(" \"" + thrownMessage + "\""); } } sb.append("\"" + message + "\""); prefix = ", "; } if (0 < sb.length()) { sb.append(" (" + numThrown + " exceptions)"); throw new BuildException(sb.toString()); } } } } /** * Execute in a separate VM. * Differences from normal same-VM execution: * <ul> * <li>ignores any message holder {class} set</li> * <li>No resource-copying between interative runs</li> * <li>failonerror fails when process interface fails * to return negative values</li> * </ul> * @param args String[] of the complete compiler command to execute * * @see DefaultCompilerAdapter#executeExternalCompile(String[], int) * @throws BuildException if ajc aborts (negative value) * or if failonerror and there were compile errors. */ protected void executeInOtherVM(String[] args) { javaCmd.setClassname(org.aspectj.tools.ajc.Main.class.getName()); final Path vmClasspath = javaCmd.createClasspath(getProject()); { File aspectjtools = null; int vmClasspathSize = vmClasspath.size(); if ((null != forkclasspath) && (0 != forkclasspath.size())) { vmClasspath.addExisting(forkclasspath); } else { aspectjtools = findAspectjtoolsJar(); if (null != aspectjtools) { vmClasspath.createPathElement().setLocation(aspectjtools); } } int newVmClasspathSize = vmClasspath.size(); if (vmClasspathSize == newVmClasspathSize) { String m = "unable to find aspectjtools to fork - "; if (null != aspectjtools) { m += "tried " + aspectjtools.toString(); } else if (null != forkclasspath) { m += "tried " + forkclasspath.toString(); } else { m += "define forkclasspath or put aspectjtools on classpath"; } throw new BuildException(m); } } if (null != maxMem) { javaCmd.setMaxmemory(maxMem); } File tempFile = null; int numArgs = args.length; args = GuardedCommand.limitTo(args, MAX_COMMANDLINE, getLocation()); if (args.length != numArgs) { tempFile = new File(args[1]); } try { boolean setMessageHolderOnForking = (this.messageHolder != null); String[] javaArgs = javaCmd.getCommandline(); String[] both = new String[javaArgs.length + args.length + (setMessageHolderOnForking ? 2 : 0)]; System.arraycopy(javaArgs,0,both,0,javaArgs.length); System.arraycopy(args,0,both,javaArgs.length,args.length); if (setMessageHolderOnForking) { both[both.length - 2] = "-messageHolder"; both[both.length - 1] = this.messageHolder.getClass().getName(); } // try to use javaw instead on windows if (both[0].endsWith("java.exe")) { String path = both[0]; path = path.substring(0, path.length()-4); path = path + "w.exe"; File javaw = new File(path); if (javaw.canRead() && javaw.isFile()) { both[0] = path; } } logVerbose("forking " + Arrays.asList(both)); int result = execInOtherVM(both); if (0 > result) { throw new BuildException("failure[" + result + "] running ajc"); } else if (failonerror && (0 < result)) { throw new BuildException("compile errors: " + result); } // when forking, do completion only at end and when successful doCompletionTasks(); } finally { if (null != tempFile) { tempFile.delete(); } } } /** * Execute in another process using the same JDK * and the base directory of the project. XXX correct? * @param args * @return */ protected int execInOtherVM(String[] args) { try { Project project = getProject(); PumpStreamHandler handler = new LogStreamHandler(this, verbose ? Project.MSG_VERBOSE : Project.MSG_INFO, Project.MSG_WARN); // replace above two lines with what follows as an aid to debugging when running the unit tests.... // LogStreamHandler handler = new LogStreamHandler(this, // Project.MSG_INFO, Project.MSG_WARN) { // // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // /* (non-Javadoc) // * @see org.apache.tools.ant.taskdefs.PumpStreamHandler#createProcessOutputPump(java.io.InputStream, java.io.OutputStream) // */ // protected void createProcessErrorPump(InputStream is, // OutputStream os) { // super.createProcessErrorPump(is, baos); // } // // /* (non-Javadoc) // * @see org.apache.tools.ant.taskdefs.LogStreamHandler#stop() // */ // public void stop() { // byte[] written = baos.toByteArray(); // System.err.print(new String(written)); // super.stop(); // } // }; Execute exe = new Execute(handler); exe.setAntRun(project); exe.setWorkingDirectory(project.getBaseDir()); exe.setCommandline(args); try { if (executingInOtherVM) { String s = "already running in other vm?"; throw new BuildException(s, location); } executingInOtherVM = true; exe.execute(); } finally { executingInOtherVM = false; } return exe.getExitValue(); } catch (IOException e) { String m = "Error executing command " + Arrays.asList(args); throw new BuildException(m, e, location); } } // ------------------------------ setup and reporting /** @return null if path null or empty, String rendition otherwise */ protected static void addFlaggedPath(String flag, Path path, List list) { if (!LangUtil.isEmpty(flag) && ((null != path) && (0 < path.size()))) { list.add(flag); list.add(path.toString()); } } /** * Add to list any path or plural arguments. */ protected void addListArgs(List list) throws BuildException { addFlaggedPath("-classpath", classpath, list); addFlaggedPath("-bootclasspath", bootclasspath, list); addFlaggedPath("-extdirs", extdirs, list); addFlaggedPath("-aspectpath", aspectpath, list); addFlaggedPath("-injars", injars, list); addFlaggedPath("-inpath", inpath, list); addFlaggedPath("-sourceroots", sourceRoots, list); if (argfiles != null) { String[] files = argfiles.list(); for (int i = 0; i < files.length; i++) { File argfile = project.resolveFile(files[i]); if (check(argfile, files[i], false, location)) { list.add("-argfile"); list.add(argfile.getAbsolutePath()); } } } if (srcdir != null) { // todo: ignore any srcdir if any argfiles and no explicit includes String[] dirs = srcdir.list(); for (int i = 0; i < dirs.length; i++) { File dir = project.resolveFile(dirs[i]); check(dir, dirs[i], true, location); // relies on compiler to prune non-source files String[] files = getDirectoryScanner(dir).getIncludedFiles(); for (int j = 0; j < files.length; j++) { File file = new File(dir, files[j]); if (FileUtil.hasSourceSuffix(file)) { list.add(file.getAbsolutePath()); } } } } if (0 < adapterFiles.size()) { for (Iterator iter = adapterFiles.iterator(); iter.hasNext();) { File file = (File) iter.next(); if (file.canRead() && FileUtil.hasSourceSuffix(file)) { list.add(file.getAbsolutePath()); } else { this.logger.warning("skipping file: " + file); } } } } /** * Throw BuildException unless file is valid. * @param file the File to check * @param name the symbolic name to print on error * @param isDir if true, verify file is a directory * @param loc the Location used to create sensible BuildException * @return * @throws BuildException unless file valid */ protected final boolean check(File file, String name, boolean isDir, Location loc) { loc = loc != null ? loc : location; if (file == null) { throw new BuildException(name + " is null!", loc); } if (!file.exists()) { throw new BuildException(file + " doesn't exist!", loc); } if (isDir ^ file.isDirectory()) { String e = file + " should" + (isDir ? "" : "n't") + " be a directory!"; throw new BuildException(e, loc); } return true; } /** * Called when compile or incremental compile is completing, * this completes the output jar or directory * by copying resources if requested. * Note: this is a callback run synchronously by the compiler. * That means exceptions thrown here are caught by Main.run(..) * and passed to the message handler. */ protected void doCompletionTasks() { if (!executing) { throw new IllegalStateException("should be executing"); } if (null != outjar) { completeOutjar(); } else { completeDestdir(); } if (null != xdoneSignal) { MessageUtil.info(messageHolder, xdoneSignal); } } /** * Complete the destination directory * by copying resources from the source root directories * (if the filter is specified) * and non-.class files from the input jars * (if XCopyInjars is enabled). */ private void completeDestdir() { if (!copyInjars && (null == sourceRootCopyFilter) && (null == inpathDirCopyFilter)) { return; } else if ((destDir == DEFAULT_DESTDIR) || !destDir.canWrite()) { String s = "unable to copy resources to destDir: " + destDir; throw new BuildException(s); } final Project project = getProject(); if (copyInjars) { // XXXX remove as unused since 1.1.1 if (null != inpath) { log("copyInjars does not support inpath.\n", Project.MSG_WARN); } String taskName = getTaskName() + " - unzip"; String[] paths = injars.list(); if (!LangUtil.isEmpty(paths)) { PatternSet patternSet = new PatternSet(); patternSet.setProject(project); patternSet.setIncludes("**/*"); patternSet.setExcludes("**/*.class"); for (int i = 0; i < paths.length; i++) { Expand unzip = new Expand(); unzip.setProject(project); unzip.setTaskName(taskName); unzip.setDest(destDir); unzip.setSrc(new File(paths[i])); unzip.addPatternset(patternSet); unzip.execute(); } } } if ((null != sourceRootCopyFilter) && (null != sourceRoots)) { String[] paths = sourceRoots.list(); if (!LangUtil.isEmpty(paths)) { Copy copy = new Copy(); copy.setProject(project); copy.setTodir(destDir); for (int i = 0; i < paths.length; i++) { FileSet fileSet = new FileSet(); fileSet.setDir(new File(paths[i])); fileSet.setIncludes("**/*"); fileSet.setExcludes(sourceRootCopyFilter); copy.addFileset(fileSet); } copy.execute(); } } if ((null != inpathDirCopyFilter) && (null != inpath)) { String[] paths = inpath.list(); if (!LangUtil.isEmpty(paths)) { Copy copy = new Copy(); copy.setProject(project); copy.setTodir(destDir); boolean gotDir = false; for (int i = 0; i < paths.length; i++) { File inpathDir = new File(paths[i]); if (inpathDir.isDirectory() && inpathDir.canRead()) { if (!gotDir) { gotDir = true; } FileSet fileSet = new FileSet(); fileSet.setDir(inpathDir); fileSet.setIncludes("**/*"); fileSet.setExcludes(inpathDirCopyFilter); copy.addFileset(fileSet); } } if (gotDir) { copy.execute(); } } } } /** * Complete the output jar * by copying resources from the source root directories * if the filter is specified. * and non-.class files from the input jars if enabled. */ private void completeOutjar() { if (((null == tmpOutjar) || !tmpOutjar.canRead()) || (!copyInjars && (null == sourceRootCopyFilter) && (null == inpathDirCopyFilter))) { return; } Zip zip = new Zip(); Project project = getProject(); zip.setProject(project); zip.setTaskName(getTaskName() + " - zip"); zip.setDestFile(outjar); ZipFileSet zipfileset = new ZipFileSet(); zipfileset.setProject(project); zipfileset.setSrc(tmpOutjar); zipfileset.setIncludes("**/*.class"); zip.addZipfileset(zipfileset); if (copyInjars) { String[] paths = injars.list(); if (!LangUtil.isEmpty(paths)) { for (int i = 0; i < paths.length; i++) { File jarFile = new File(paths[i]); zipfileset = new ZipFileSet(); zipfileset.setProject(project); zipfileset.setSrc(jarFile); zipfileset.setIncludes("**/*"); zipfileset.setExcludes("**/*.class"); zip.addZipfileset(zipfileset); } } } if ((null != sourceRootCopyFilter) && (null != sourceRoots)) { String[] paths = sourceRoots.list(); if (!LangUtil.isEmpty(paths)) { for (int i = 0; i < paths.length; i++) { File srcRoot = new File(paths[i]); FileSet fileset = new FileSet(); fileset.setProject(project); fileset.setDir(srcRoot); fileset.setIncludes("**/*"); fileset.setExcludes(sourceRootCopyFilter); zip.addFileset(fileset); } } } if ((null != inpathDirCopyFilter) && (null != inpath)) { String[] paths = inpath.list(); if (!LangUtil.isEmpty(paths)) { for (int i = 0; i < paths.length; i++) { File inpathDir = new File(paths[i]); if (inpathDir.isDirectory() && inpathDir.canRead()) { FileSet fileset = new FileSet(); fileset.setProject(project); fileset.setDir(inpathDir); fileset.setIncludes("**/*"); fileset.setExcludes(inpathDirCopyFilter); zip.addFileset(fileset); } } } } zip.execute(); } // -------------------------- compiler adapter interface extras /** * Add specified source files. */ void addFiles(File[] paths) { for (int i = 0; i < paths.length; i++) { addFile(paths[i]); } } /** * Add specified source file. */ void addFile(File path) { if (null != path) { adapterFiles.add(path); } } /** * Read arguments in as if from a command line, * mainly to support compiler adapter compilerarg subelement. * * @param args the String[] of arguments to read */ public void readArguments(String[] args) { // XXX slow, stupid, unmaintainable if ((null == args) || (0 == args.length)) { return; } /** String[] wrapper with increment, error reporting */ class Args { final String[] args; int index = 0; Args(String[] args) { this.args = args; // not null or empty } boolean hasNext() { return index < args.length; } String next() { String err = null; if (!hasNext()) { err = "need arg for flag " + args[args.length-1]; } else { String s = args[index++]; if (null == s) { err = "null value"; } else { s = s.trim(); if (0 == s.trim().length()) { err = "no value"; } else { return s; } } } err += " at [" + index + "] of " + Arrays.asList(args); throw new BuildException(err); } } // class Args Args in = new Args(args); String flag; while (in.hasNext()) { flag = in.next(); if ("-1.3".equals(flag)) { setCompliance(flag); } else if ("-1.4".equals(flag)) { setCompliance(flag); } else if ("-1.5".equals(flag)) { setCompliance("1.5"); } else if ("-argfile".equals(flag)) { setArgfiles(new Path(project, in.next())); } else if ("-aspectpath".equals(flag)) { setAspectpath(new Path(project, in.next())); } else if ("-classpath".equals(flag)) { setClasspath(new Path(project, in.next())); } else if ("-extdirs".equals(flag)) { setExtdirs(new Path(project, in.next())); } else if ("-Xcopyinjars".equals(flag)) { setCopyInjars(true); // ignored - will be flagged by setter } else if ("-g".equals(flag)) { setDebug(true); } else if (flag.startsWith("-g:")) { setDebugLevel(flag.substring(2)); } else if ("-deprecation".equals(flag)) { setDeprecation(true); } else if ("-d".equals(flag)) { setDestdir(new File(in.next())); } else if ("-crossrefs".equals(flag)) { setCrossrefs(true); } else if ("-emacssym".equals(flag)) { setEmacssym(true); } else if ("-encoding".equals(flag)) { setEncoding(in.next()); } else if ("-Xfailonerror".equals(flag)) { setFailonerror(true); } else if ("-fork".equals(flag)) { setFork(true); } else if ("-forkclasspath".equals(flag)) { setForkclasspath(new Path(project, in.next())); } else if ("-help".equals(flag)) { setHelp(true); } else if ("-incremental".equals(flag)) { setIncremental(true); } else if ("-injars".equals(flag)) { setInjars(new Path(project, in.next())); } else if ("-inpath".equals(flag)) { setInpath(new Path(project,in.next())); } else if ("-Xlistfileargs".equals(flag)) { setListFileArgs(true); } else if ("-Xmaxmem".equals(flag)) { setMaxmem(in.next()); } else if ("-Xmessageholderclass".equals(flag)) { setMessageHolderClass(in.next()); } else if ("-noexit".equals(flag)) { setNoExit(true); } else if ("-noimport".equals(flag)) { setNoExit(true); } else if ("-noExit".equals(flag)) { setNoExit(true); } else if ("-noImportError".equals(flag)) { setNoImportError(true); } else if ("-noWarn".equals(flag)) { setNowarn(true); } else if ("-noexit".equals(flag)) { setNoExit(true); } else if ("-outjar".equals(flag)) { setOutjar(new File(in.next())); } else if ("-outxml".equals(flag)) { setOutxml(true); } else if ("-outxmlfile".equals(flag)) { setOutxmlfile(in.next()); } else if ("-preserveAllLocals".equals(flag)) { setPreserveAllLocals(true); } else if ("-proceedOnError".equals(flag)) { setProceedOnError(true); } else if ("-referenceInfo".equals(flag)) { setReferenceInfo(true); } else if ("-source".equals(flag)) { setSource(in.next()); } else if ("-Xsourcerootcopyfilter".equals(flag)) { setSourceRootCopyFilter(in.next()); } else if ("-sourceroots".equals(flag)) { setSourceRoots(new Path(project, in.next())); } else if ("-Xsrcdir".equals(flag)) { setSrcDir(new Path(project, in.next())); } else if ("-Xtagfile".equals(flag)) { setTagFile(new File(in.next())); } else if ("-target".equals(flag)) { setTarget(in.next()); } else if ("-time".equals(flag)) { setTime(true); } else if ("-time".equals(flag)) { setTime(true); } else if ("-verbose".equals(flag)) { setVerbose(true); } else if ("-showWeaveInfo".equals(flag)) { setShowWeaveInfo(true); } else if ("-version".equals(flag)) { setVersion(true); } else if ("-warn".equals(flag)) { setWarn(in.next()); } else if (flag.startsWith("-warn:")) { setWarn(flag.substring(6)); } else if ("-Xlint".equals(flag)) { setXlintwarnings(true); } else if (flag.startsWith("-Xlint:")) { setXlint(flag.substring(7)); } else if ("-Xlintfile".equals(flag)) { setXlintfile(new File(in.next())); } else if ("-XterminateAfterCompilation".equals(flag)) { setXTerminateAfterCompilation(true); } else if ("-Xreweavable".equals(flag)) { setXReweavable(true); } else if ("-XnotReweavable".equals(flag)) { setXNotReweavable(true); } else if (flag.startsWith("@")) { File file = new File(flag.substring(1)); if (file.canRead()) { setArgfiles(new Path(project, file.getPath())); } else { ignore(flag); } } else { File file = new File(flag); if (file.isFile() && file.canRead() && FileUtil.hasSourceSuffix(file)) { addFile(file); } else { ignore(flag); } } } } protected void logVerbose(String text) { if (this.verbose) { this.logger.info(text); } else { this.logger.verbose(text); } } /** * Commandline wrapper that * only permits addition of non-empty values * and converts to argfile form if necessary. */ public static class GuardedCommand { Commandline command; //int size; static boolean isEmpty(String s) { return ((null == s) || (0 == s.trim().length())); } GuardedCommand() { command = new Commandline(); } void addFlag(String flag, boolean doAdd) { if (doAdd && !isEmpty(flag)) { command.createArgument().setValue(flag); //size += 1 + flag.length(); } } /** @return null if added or ignoreString otherwise */ String addOption(String prefix, String[] validOptions, String input) { if (isEmpty(input)) { return null; } for (int i = 0; i < validOptions.length; i++) { if (input.equals(validOptions[i])) { if (isEmpty(prefix)) { addFlag(input, true); } else { addFlagged(prefix, input); } return null; } } return (null == prefix ? input : prefix + " " + input); } void addFlagged(String flag, String argument) { if (!isEmpty(flag) && !isEmpty(argument)) { command.addArguments(new String[] {flag, argument}); //size += 1 + flag.length() + argument.length(); } } // private void addFile(File file) { // if (null != file) { // String path = file.getAbsolutePath(); // addFlag(path, true); // } // } List extractArguments() { ArrayList result = new ArrayList(); String[] cmds = command.getArguments(); if (!LangUtil.isEmpty(cmds)) { result.addAll(Arrays.asList(cmds)); } return result; } /** * Adjust args for size if necessary by creating * an argument file, which should be deleted by the client * after the compiler run has completed. * @param max the int maximum length of the command line (in char) * @return the temp File for the arguments (if generated), * for deletion when done. * @throws IllegalArgumentException if max is negative */ static String[] limitTo(String[] args, int max, Location location) { if (max < 0) { throw new IllegalArgumentException("negative max: " + max); } // sigh - have to count anyway for now int size = 0; for (int i = 0; (i < args.length) && (size < max); i++) { size += 1 + (null == args[i] ? 0 : args[i].length()); } if (size <= max) { return args; } File tmpFile = null; PrintWriter out = null; // adapted from DefaultCompilerAdapter.executeExternalCompile try { String userDirName = System.getProperty("user.dir"); File userDir = new File(userDirName); tmpFile = File.createTempFile("argfile", "", userDir); out = new PrintWriter(new FileWriter(tmpFile)); for (int i = 0; i < args.length; i++) { out.println(args[i]); } out.flush(); return new String[] {"-argfile", tmpFile.getAbsolutePath()}; } catch (IOException e) { throw new BuildException("Error creating temporary file", e, location); } finally { if (out != null) { try {out.close();} catch (Throwable t) {} } } } } private static class AntMessageHandler implements IMessageHandler { private TaskLogger logger; private final boolean taskLevelVerbose; private final boolean handledMessage; public AntMessageHandler(TaskLogger logger, boolean taskVerbose, boolean handledMessage) { this.logger = logger; this.taskLevelVerbose = taskVerbose; this.handledMessage = handledMessage; } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#handleMessage(org.aspectj.bridge.IMessage) */ public boolean handleMessage(IMessage message) throws AbortException { Kind messageKind = message.getKind(); String messageText = message.toString(); if (messageKind == IMessage.ABORT) { this.logger.error(messageText); } else if (messageKind == IMessage.DEBUG) { this.logger.debug(messageText); } else if (messageKind == IMessage.ERROR) { this.logger.error(messageText); } else if (messageKind == IMessage.FAIL){ this.logger.error(messageText); } else if (messageKind == IMessage.INFO) { if (this.taskLevelVerbose) { this.logger.info(messageText); } else { this.logger.verbose(messageText); } } else if (messageKind == IMessage.WARNING) { this.logger.warning(messageText); } else if (messageKind == IMessage.WEAVEINFO) { this.logger.info(messageText); } else if (messageKind == IMessage.TASKTAG) { // ignore } else { throw new BuildException("Unknown message kind from AspectJ compiler: " + messageKind.toString()); } return handledMessage; } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#isIgnoring(org.aspectj.bridge.IMessage.Kind) */ public boolean isIgnoring(Kind kind) { return false; } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#dontIgnore(org.aspectj.bridge.IMessage.Kind) */ public void dontIgnore(Kind kind) { } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#ignore(org.aspectj.bridge.IMessage.Kind) */ public void ignore(Kind kind) { } } }
263,837
Bug 263837 Error during Delete AJ Markers
Error sent through the AJDT mailing list. I believe this is an LTW weaving error, so not raising it against AJDT.
resolved fixed
1b54b4b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-02-06T00:15:57Z"
"2009-02-05T18:53:20Z"
weaver/src/org/aspectj/weaver/bcel/BcelClassWeaver.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.ConstantPool; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen; import org.aspectj.apache.bcel.generic.FieldGen; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionBranch; import org.aspectj.apache.bcel.generic.InstructionCP; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionLV; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InstructionSelect; import org.aspectj.apache.bcel.generic.InstructionTargeter; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.LineNumberTag; import org.aspectj.apache.bcel.generic.LocalVariableTag; import org.aspectj.apache.bcel.generic.MULTIANEWARRAY; import org.aspectj.apache.bcel.generic.MethodGen; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.RET; import org.aspectj.apache.bcel.generic.Tag; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.asm.AsmManager; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.util.PartialOrder; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.IClassWeaver; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.MissingResolvedTypeWithKnownSignature; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.model.AsmRelationshipProvider; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.ExactTypePattern; import org.aspectj.weaver.tools.Trace; import org.aspectj.weaver.tools.TraceFactory; class BcelClassWeaver implements IClassWeaver { private static Trace trace = TraceFactory.getTraceFactory().getTrace(BcelClassWeaver.class); /** * This is called from {@link BcelWeaver} to perform the per-class weaving process. */ public static boolean weave(BcelWorld world, LazyClassGen clazz, List shadowMungers, List typeMungers, List lateTypeMungers) { boolean b = new BcelClassWeaver(world, clazz, shadowMungers, typeMungers, lateTypeMungers).weave(); // System.out.println(clazz.getClassName() + ", " + // clazz.getType().getWeaverState()); // clazz.print(); return b; } // -------------------------------------------- private final LazyClassGen clazz; private final List shadowMungers; private final List typeMungers; private final List lateTypeMungers; private final BcelObjectType ty; // alias of clazz.getType() private final BcelWorld world; // alias of ty.getWorld() private final ConstantPool cpg; // alias of clazz.getConstantPoolGen() private final InstructionFactory fact; // alias of clazz.getFactory(); private final List addedLazyMethodGens = new ArrayList(); private final Set addedDispatchTargets = new HashSet(); // Static setting across BcelClassWeavers private static boolean inReweavableMode = false; private List addedSuperInitializersAsList = null; // List<IfaceInitList> private final Map addedSuperInitializers = new HashMap(); // Interface -> // IfaceInitList private final List addedThisInitializers = new ArrayList(); // List<NewFieldMunger> private final List addedClassInitializers = new ArrayList(); // List<NewFieldMunger // > private final Map mapToAnnotations = new HashMap(); // private BcelShadow clinitShadow = null; /** * This holds the initialization and pre-initialization shadows for this class that were actually matched by mungers (if no * match, then we don't even create the shadows really). */ private final List initializationShadows = new ArrayList(1); private BcelClassWeaver(BcelWorld world, LazyClassGen clazz, List shadowMungers, List typeMungers, List lateTypeMungers) { super(); // assert world == clazz.getType().getWorld() this.world = world; this.clazz = clazz; this.shadowMungers = shadowMungers; this.typeMungers = typeMungers; this.lateTypeMungers = lateTypeMungers; this.ty = clazz.getBcelObjectType(); this.cpg = clazz.getConstantPool(); this.fact = clazz.getFactory(); fastMatchShadowMungers(shadowMungers); initializeSuperInitializerMap(ty.getResolvedTypeX()); if (!checkedXsetForLowLevelContextCapturing) { Properties p = world.getExtraConfiguration(); if (p != null) { String s = p.getProperty(World.xsetCAPTURE_ALL_CONTEXT, "false"); captureLowLevelContext = s.equalsIgnoreCase("true"); if (captureLowLevelContext) world.getMessageHandler().handleMessage( MessageUtil.info("[" + World.xsetCAPTURE_ALL_CONTEXT + "=true] Enabling collection of low level context for debug/crash messages")); } checkedXsetForLowLevelContextCapturing = true; } } private List[] perKindShadowMungers; private boolean canMatchBodyShadows = false; // private boolean canMatchInitialization = false; private void fastMatchShadowMungers(List shadowMungers) { // beware the annoying property that SHADOW_KINDS[i].getKey == (i+1) ! perKindShadowMungers = new List[Shadow.MAX_SHADOW_KIND + 1]; for (int i = 0; i < perKindShadowMungers.length; i++) { perKindShadowMungers[i] = new ArrayList(0); } for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); int couldMatchKinds = munger.getPointcut().couldMatchKinds(); for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { Shadow.Kind kind = Shadow.SHADOW_KINDS[i]; if (kind.isSet(couldMatchKinds)) perKindShadowMungers[kind.getKey()].add(munger); } // Set couldMatchKinds = munger.getPointcut().couldMatchKinds(); // for (Iterator kindIterator = couldMatchKinds.iterator(); // kindIterator.hasNext();) { // Shadow.Kind aKind = (Shadow.Kind) kindIterator.next(); // perKindShadowMungers[aKind.getKey()].add(munger); // } } // if (!perKindShadowMungers[Shadow.Initialization.getKey()].isEmpty()) // canMatchInitialization = true; for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { Shadow.Kind kind = Shadow.SHADOW_KINDS[i]; if (!kind.isEnclosingKind() && !perKindShadowMungers[i + 1].isEmpty()) { canMatchBodyShadows = true; } if (perKindShadowMungers[i + 1].isEmpty()) { perKindShadowMungers[i + 1] = null; } } } private boolean canMatch(Shadow.Kind kind) { return perKindShadowMungers[kind.getKey()] != null; } // private void fastMatchShadowMungers(List shadowMungers, ArrayList // mungers, Kind kind) { // FastMatchInfo info = new FastMatchInfo(clazz.getType(), kind); // for (Iterator i = shadowMungers.iterator(); i.hasNext();) { // ShadowMunger munger = (ShadowMunger) i.next(); // FuzzyBoolean fb = munger.getPointcut().fastMatch(info); // WeaverMetrics.recordFastMatchResult(fb);// Could pass: // munger.getPointcut().toString() // if (fb.maybeTrue()) mungers.add(munger); // } // } private void initializeSuperInitializerMap(ResolvedType child) { ResolvedType[] superInterfaces = child.getDeclaredInterfaces(); for (int i = 0, len = superInterfaces.length; i < len; i++) { if (ty.getResolvedTypeX().isTopmostImplementor(superInterfaces[i])) { if (addSuperInitializer(superInterfaces[i])) { initializeSuperInitializerMap(superInterfaces[i]); } } } } private boolean addSuperInitializer(ResolvedType onType) { if (onType.isRawType() || onType.isParameterizedType()) onType = onType.getGenericType(); IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType); if (l != null) return false; l = new IfaceInitList(onType); addedSuperInitializers.put(onType, l); return true; } public void addInitializer(ConcreteTypeMunger cm) { NewFieldTypeMunger m = (NewFieldTypeMunger) cm.getMunger(); ResolvedType onType = m.getSignature().getDeclaringType().resolve(world); if (onType.isRawType()) onType = onType.getGenericType(); if (m.getSignature().isStatic()) { addedClassInitializers.add(cm); } else { if (onType == ty.getResolvedTypeX()) { addedThisInitializers.add(cm); } else { IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType); l.list.add(cm); } } } private static class IfaceInitList implements PartialOrder.PartialComparable { final ResolvedType onType; List list = new ArrayList(); IfaceInitList(ResolvedType onType) { this.onType = onType; } public int compareTo(Object other) { IfaceInitList o = (IfaceInitList) other; if (onType.isAssignableFrom(o.onType)) return +1; else if (o.onType.isAssignableFrom(onType)) return -1; else return 0; } public int fallbackCompareTo(Object other) { return 0; } } // XXX this is being called, but the result doesn't seem to be being used public boolean addDispatchTarget(ResolvedMember m) { return addedDispatchTargets.add(m); } public void addLazyMethodGen(LazyMethodGen gen) { addedLazyMethodGens.add(gen); } public void addOrReplaceLazyMethodGen(LazyMethodGen mg) { if (alreadyDefined(clazz, mg)) return; for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext();) { LazyMethodGen existing = (LazyMethodGen) i.next(); if (signaturesMatch(mg, existing)) { if (existing.definingType == null) { // this means existing was introduced on the class itself return; } else if (mg.definingType.isAssignableFrom(existing.definingType)) { // existing is mg's subtype and dominates mg return; } else if (existing.definingType.isAssignableFrom(mg.definingType)) { // mg is existing's subtype and dominates existing i.remove(); addedLazyMethodGens.add(mg); return; } else { throw new BCException("conflict between: " + mg + " and " + existing); } } } addedLazyMethodGens.add(mg); } private boolean alreadyDefined(LazyClassGen clazz, LazyMethodGen mg) { for (Iterator i = clazz.getMethodGens().iterator(); i.hasNext();) { LazyMethodGen existing = (LazyMethodGen) i.next(); if (signaturesMatch(mg, existing)) { if (!mg.isAbstract() && existing.isAbstract()) { i.remove(); return false; } return true; } } return false; } private boolean signaturesMatch(LazyMethodGen mg, LazyMethodGen existing) { return mg.getName().equals(existing.getName()) && mg.getSignature().equals(existing.getSignature()); } protected static LazyMethodGen makeBridgeMethod(LazyClassGen gen, ResolvedMember member) { // remove abstract modifier int mods = member.getModifiers(); if (Modifier.isAbstract(mods)) mods = mods - Modifier.ABSTRACT; LazyMethodGen ret = new LazyMethodGen(mods, BcelWorld.makeBcelType(member.getReturnType()), member.getName(), BcelWorld .makeBcelTypes(member.getParameterTypes()), UnresolvedType.getNames(member.getExceptions()), gen); // 43972 : Static crosscutting makes interfaces unusable for javac // ret.makeSynthetic(); return ret; } /** * Create a single bridge method called 'theBridgeMethod' that bridges to 'whatToBridgeTo' */ private static void createBridgeMethod(BcelWorld world, LazyMethodGen whatToBridgeToMethodGen, LazyClassGen clazz, ResolvedMember theBridgeMethod) { InstructionList body; InstructionFactory fact; int pos = 0; ResolvedMember whatToBridgeTo = whatToBridgeToMethodGen.getMemberView(); if (whatToBridgeTo == null) { whatToBridgeTo = new ResolvedMemberImpl(Member.METHOD, whatToBridgeToMethodGen.getEnclosingClass().getType(), whatToBridgeToMethodGen.getAccessFlags(), whatToBridgeToMethodGen.getName(), whatToBridgeToMethodGen .getSignature()); } // The bridge method in this type will have the same signature as the one in the supertype LazyMethodGen bridgeMethod = makeBridgeMethod(clazz, theBridgeMethod); int newflags = bridgeMethod.getAccessFlags() | 0x00000040;// BRIDGE = 0x00000040 if ((newflags & 0x00000100) != 0) { newflags = newflags - 0x100;// NATIVE = 0x00000100 - need to clear it } bridgeMethod.setAccessFlags(newflags); Type returnType = BcelWorld.makeBcelType(theBridgeMethod.getReturnType()); Type[] paramTypes = BcelWorld.makeBcelTypes(theBridgeMethod.getParameterTypes()); Type[] newParamTypes = whatToBridgeToMethodGen.getArgumentTypes(); body = bridgeMethod.getBody(); fact = clazz.getFactory(); if (!whatToBridgeToMethodGen.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); if (!newParamTypes[i].equals(paramTypes[i])) { if (world.forDEBUG_bridgingCode) System.err.println("Bridging: Cast " + newParamTypes[i] + " from " + paramTypes[i]); body.append(fact.createCast(paramTypes[i], newParamTypes[i])); } pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, world, whatToBridgeTo)); body.append(InstructionFactory.createReturn(returnType)); clazz.addMethodGen(bridgeMethod); } // ---- public boolean weave() { if (clazz.isWoven() && !clazz.isReweavable()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ALREADY_WOVEN, clazz.getType().getName()), ty .getSourceLocation(), null); return false; } Set aspectsAffectingType = null; if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType = new HashSet(); boolean isChanged = false; // we want to "touch" all aspects if (clazz.getType().isAspect()) isChanged = true; // start by munging all typeMungers for (Iterator i = typeMungers.iterator(); i.hasNext();) { Object o = i.next(); if (!(o instanceof BcelTypeMunger)) { // ???System.err.println("surprising: " + o); continue; } BcelTypeMunger munger = (BcelTypeMunger) o; boolean typeMungerAffectedType = munger.munge(this); if (typeMungerAffectedType) { isChanged = true; if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.add(munger.getAspectType().getName()); } } // Weave special half type/half shadow mungers... isChanged = weaveDeclareAtMethodCtor(clazz) || isChanged; isChanged = weaveDeclareAtField(clazz) || isChanged; // XXX do major sort of stuff // sort according to: Major: type hierarchy // within each list: dominates // don't forget to sort addedThisInitialiers according to dominates addedSuperInitializersAsList = new ArrayList(addedSuperInitializers.values()); addedSuperInitializersAsList = PartialOrder.sort(addedSuperInitializersAsList); if (addedSuperInitializersAsList == null) { throw new BCException("circularity in inter-types"); } // this will create a static initializer if there isn't one // this is in just as bad taste as NOPs LazyMethodGen staticInit = clazz.getStaticInitializer(); staticInit.getBody().insert(genInitInstructions(addedClassInitializers, true)); // now go through each method, and match against each method. This // sets up each method's {@link LazyMethodGen#matchedShadows} field, // and it also possibly adds to {@link #initializationShadows}. List methodGens = new ArrayList(clazz.getMethodGens()); for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen) i.next(); if (!mg.hasBody()) continue; if (world.isJoinpointSynchronizationEnabled() && world.areSynchronizationPointcutsInUse() && mg.getMethod().isSynchronized()) { transformSynchronizedMethod(mg); } boolean shadowMungerMatched = match(mg); if (shadowMungerMatched) { // For matching mungers, add their declaring aspects to the list // that affected this type if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.addAll(findAspectsForMungers(mg)); isChanged = true; } } // now we weave all but the initialization shadows for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen) i.next(); if (!mg.hasBody()) continue; implement(mg); } // if we matched any initialization shadows, we inline and weave if (!initializationShadows.isEmpty()) { // Repeat next step until nothing left to inline...cant go on // infinetly as compiler will have detected and reported // "Recursive constructor invocation" while (inlineSelfConstructors(methodGens)) ; positionAndImplement(initializationShadows); } // now proceed with late type mungers if (lateTypeMungers != null) { for (Iterator i = lateTypeMungers.iterator(); i.hasNext();) { BcelTypeMunger munger = (BcelTypeMunger) i.next(); if (munger.matches(clazz.getType())) { boolean typeMungerAffectedType = munger.munge(this); if (typeMungerAffectedType) { isChanged = true; if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.add(munger.getAspectType().getName()); } } } } // FIXME AV - see #75442, for now this is not enough to fix the bug, // comment that out until we really fix it // // flush to save some memory // PerObjectInterfaceTypeMunger.unregisterFromAsAdvisedBy(clazz.getType() // ); // finally, if we changed, we add in the introduced methods. if (isChanged) { clazz.getOrCreateWeaverStateInfo(inReweavableMode); weaveInAddedMethods(); // FIXME asc are these potentially affected // by declare annotation? } if (inReweavableMode) { WeaverStateInfo wsi = clazz.getOrCreateWeaverStateInfo(true); wsi.addAspectsAffectingType(aspectsAffectingType); wsi.setUnwovenClassFileData(ty.getJavaClass().getBytes()); wsi.setReweavable(true); } else { clazz.getOrCreateWeaverStateInfo(false).setReweavable(false); } // tidyup, reduce ongoing memory usage of BcelMethods that hang around for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen) i.next(); BcelMethod bM = mg.getMemberView(); if (bM != null) bM.wipeJoinpointSignatures(); } return isChanged; } // **************************** start of bridge method creation code // ***************** // FIXME asc tidy this lot up !! // FIXME asc refactor into ResolvedType or even ResolvedMember? /** * Check if a particular method is overriding another - refactored into this helper so it can be used from multiple places. */ private static ResolvedMember isOverriding(ResolvedType typeToCheck, ResolvedMember methodThatMightBeGettingOverridden, String mname, String mrettype, int mmods, boolean inSamePackage, UnresolvedType[] methodParamsArray) { // Check if we can be an override... if (methodThatMightBeGettingOverridden.isStatic()) return null; // we can't be overriding a static method if (methodThatMightBeGettingOverridden.isPrivate()) return null; // we can't be overriding a private method if (!methodThatMightBeGettingOverridden.getName().equals(mname)) return null; // names dont match (this will also skip <init> and // <clinit> too) if (methodThatMightBeGettingOverridden.getParameterTypes().length != methodParamsArray.length) return null; // check same number of parameters if (!isVisibilityOverride(mmods, methodThatMightBeGettingOverridden, inSamePackage)) return null; if (typeToCheck.getWorld().forDEBUG_bridgingCode) System.err.println(" Bridging:seriously considering this might be getting overridden '" + methodThatMightBeGettingOverridden + "'"); // Look at erasures of parameters (List<String> erased is List) boolean sameParams = true; for (int p = 0; p < methodThatMightBeGettingOverridden.getParameterTypes().length; p++) { if (!methodThatMightBeGettingOverridden.getParameterTypes()[p].getErasureSignature().equals( methodParamsArray[p].getErasureSignature())) sameParams = false; } // If the 'typeToCheck' represents a parameterized type then the method // will be the parameterized form of the // generic method in the generic type. So if the method was 'void // m(List<T> lt, T t)' and the parameterized type here // is I<String> then the method we are looking at will be 'void // m(List<String> lt, String t)' which when erased // is 'void m(List lt,String t)' - so if the parameters *do* match then // there is a generic method we are // overriding if (sameParams) { // check for covariance if (typeToCheck.isParameterizedType()) { return methodThatMightBeGettingOverridden.getBackingGenericMember(); } else if (!methodThatMightBeGettingOverridden.getReturnType().getErasureSignature().equals(mrettype)) { // addressing the wierd situation from bug 147801 // just check whether these things are in the right relationship // for covariance... ResolvedType superReturn = typeToCheck.getWorld().resolve( UnresolvedType.forSignature(methodThatMightBeGettingOverridden.getReturnType().getErasureSignature())); ResolvedType subReturn = typeToCheck.getWorld().resolve(UnresolvedType.forSignature(mrettype)); if (superReturn.isAssignableFrom(subReturn)) return methodThatMightBeGettingOverridden; } } return null; } /** * Looks at the visibility modifiers between two methods, and knows whether they are from classes in the same package, and * decides whether one overrides the other. * * @return true if there is an overrides rather than a 'hides' relationship */ static boolean isVisibilityOverride(int methodMods, ResolvedMember inheritedMethod, boolean inSamePackage) { if (inheritedMethod.isStatic()) return false; if (methodMods == inheritedMethod.getModifiers()) return true; if (inheritedMethod.isPrivate()) return false; boolean isPackageVisible = !inheritedMethod.isPrivate() && !inheritedMethod.isProtected() && !inheritedMethod.isPublic(); if (isPackageVisible && !inSamePackage) return false; return true; } /** * This method recurses up a specified type looking for a method that overrides the one passed in. * * @return the method being overridden or null if none is found */ public static ResolvedMember checkForOverride(ResolvedType typeToCheck, String mname, String mparams, String mrettype, int mmods, String mpkg, UnresolvedType[] methodParamsArray) { if (typeToCheck == null) return null; if (typeToCheck instanceof MissingResolvedTypeWithKnownSignature) return null; // we just can't tell ! if (typeToCheck.getWorld().forDEBUG_bridgingCode) System.err.println(" Bridging:checking for override of " + mname + " in " + typeToCheck); String packageName = typeToCheck.getPackageName(); if (packageName == null) packageName = ""; boolean inSamePackage = packageName.equals(mpkg); // used when looking // at visibility // rules ResolvedMember[] methods = typeToCheck.getDeclaredMethods(); for (int ii = 0; ii < methods.length; ii++) { ResolvedMember methodThatMightBeGettingOverridden = methods[ii]; // the // method // we // are // going // to // check ResolvedMember isOverriding = isOverriding(typeToCheck, methodThatMightBeGettingOverridden, mname, mrettype, mmods, inSamePackage, methodParamsArray); if (isOverriding != null) return isOverriding; } List l = typeToCheck.getInterTypeMungers(); for (Iterator iterator = l.iterator(); iterator.hasNext();) { Object o = iterator.next(); // FIXME asc if its not a BcelTypeMunger then its an // EclipseTypeMunger ... do I need to worry about that? if (o instanceof BcelTypeMunger) { BcelTypeMunger element = (BcelTypeMunger) o; if (element.getMunger() instanceof NewMethodTypeMunger) { if (typeToCheck.getWorld().forDEBUG_bridgingCode) System.err.println("Possible ITD candidate " + element); ResolvedMember aMethod = element.getSignature(); ResolvedMember isOverriding = isOverriding(typeToCheck, aMethod, mname, mrettype, mmods, inSamePackage, methodParamsArray); if (isOverriding != null) return isOverriding; } } } if (typeToCheck.equals(UnresolvedType.OBJECT)) return null; ResolvedType superclass = typeToCheck.getSuperclass(); ResolvedMember overriddenMethod = checkForOverride(superclass, mname, mparams, mrettype, mmods, mpkg, methodParamsArray); if (overriddenMethod != null) return overriddenMethod; ResolvedType[] interfaces = typeToCheck.getDeclaredInterfaces(); for (int i = 0; i < interfaces.length; i++) { ResolvedType anInterface = interfaces[i]; overriddenMethod = checkForOverride(anInterface, mname, mparams, mrettype, mmods, mpkg, methodParamsArray); if (overriddenMethod != null) return overriddenMethod; } return null; } /** * We need to determine if any methods in this type require bridge methods - this method should only be called if necessary to * do this calculation, i.e. we are on a 1.5 VM (where covariance/generics exist) and the type hierarchy for the specified class * has changed (via decp/itd). * * See pr108101 */ public static boolean calculateAnyRequiredBridgeMethods(BcelWorld world, LazyClassGen clazz) { world.ensureAdvancedConfigurationProcessed(); if (!world.isInJava5Mode()) return false; // just double check... the caller should have already // verified this if (clazz.isInterface()) return false; // dont bother if we're an interface boolean didSomething = false; // set if we build any bridge methods // So what methods do we have right now in this class? List /* LazyMethodGen */methods = clazz.getMethodGens(); // Keep a set of all methods from this type - it'll help us to check if // bridge methods // have already been created, we don't want to do it twice! Set methodsSet = new HashSet(); for (int i = 0; i < methods.size(); i++) { LazyMethodGen aMethod = (LazyMethodGen) methods.get(i); methodsSet.add(aMethod.getName() + aMethod.getSignature()); // e.g. // "foo(Ljava/lang/String;)V" } // Now go through all the methods in this type for (int i = 0; i < methods.size(); i++) { // This is the local method that we *might* have to bridge to LazyMethodGen bridgeToCandidate = (LazyMethodGen) methods.get(i); if (bridgeToCandidate.isBridgeMethod()) continue; // Doh! String name = bridgeToCandidate.getName(); String psig = bridgeToCandidate.getParameterSignature(); String rsig = bridgeToCandidate.getReturnType().getSignature(); // if (bridgeToCandidate.isAbstract()) continue; if (bridgeToCandidate.isStatic()) continue; // ignore static methods if (name.endsWith("init>")) continue; // Skip constructors and static initializers if (world.forDEBUG_bridgingCode) System.err.println("Bridging: Determining if we have to bridge to " + clazz.getName() + "." + name + "" + bridgeToCandidate.getSignature()); // Let's take a look at the superclass ResolvedType theSuperclass = clazz.getSuperClass(); if (world.forDEBUG_bridgingCode) { System.err.println("Bridging: Checking supertype " + theSuperclass); } String pkgName = clazz.getPackageName(); UnresolvedType[] bm = BcelWorld.fromBcel(bridgeToCandidate.getArgumentTypes()); ResolvedMember overriddenMethod = checkForOverride(theSuperclass, name, psig, rsig, bridgeToCandidate.getAccessFlags(), pkgName, bm); if (overriddenMethod != null) { String key = new StringBuffer().append(overriddenMethod.getName()).append(overriddenMethod.getSignatureErased()) .toString(); // pr237419 boolean alreadyHaveABridgeMethod = methodsSet.contains(key); if (!alreadyHaveABridgeMethod) { if (world.forDEBUG_bridgingCode) { System.err.println("Bridging:bridging to '" + overriddenMethod + "'"); } createBridgeMethod(world, bridgeToCandidate, clazz, overriddenMethod); methodsSet.add(key); didSomething = true; continue; // look at the next method } } // Check superinterfaces String[] interfaces = clazz.getInterfaceNames(); for (int j = 0; j < interfaces.length; j++) { if (world.forDEBUG_bridgingCode) System.err.println("Bridging:checking superinterface " + interfaces[j]); ResolvedType interfaceType = world.resolve(interfaces[j]); overriddenMethod = checkForOverride(interfaceType, name, psig, rsig, bridgeToCandidate.getAccessFlags(), clazz .getPackageName(), bm); if (overriddenMethod != null) { String key = new StringBuffer().append(overriddenMethod.getName()) .append(overriddenMethod.getSignatureErased()).toString(); // pr // 237419 boolean alreadyHaveABridgeMethod = methodsSet.contains(key); if (!alreadyHaveABridgeMethod) { createBridgeMethod(world, bridgeToCandidate, clazz, overriddenMethod); methodsSet.add(key); didSomething = true; if (world.forDEBUG_bridgingCode) System.err.println("Bridging:bridging to " + overriddenMethod); continue; // look at the next method } } } } return didSomething; } // **************************** end of bridge method creation code // ***************** /** * Weave any declare @method/@ctor statements into the members of the supplied class */ private boolean weaveDeclareAtMethodCtor(LazyClassGen clazz) { List reportedProblems = new ArrayList(); List allDecams = world.getDeclareAnnotationOnMethods(); if (allDecams.isEmpty()) return false; // nothing to do boolean isChanged = false; // deal with ITDs List itdMethodsCtors = getITDSubset(clazz, ResolvedTypeMunger.Method); itdMethodsCtors.addAll(getITDSubset(clazz, ResolvedTypeMunger.Constructor)); if (!itdMethodsCtors.isEmpty()) { // Can't use the subset called 'decaMs' as it won't be right for // ITDs... isChanged = weaveAtMethodOnITDSRepeatedly(allDecams, itdMethodsCtors, reportedProblems); } // deal with all the other methods... List members = clazz.getMethodGens(); List decaMs = getMatchingSubset(allDecams, clazz.getType()); if (decaMs.isEmpty()) return false; // nothing to do if (!members.isEmpty()) { Set unusedDecams = new HashSet(); unusedDecams.addAll(decaMs); for (int memberCounter = 0; memberCounter < members.size(); memberCounter++) { LazyMethodGen mg = (LazyMethodGen) members.get(memberCounter); if (!mg.getName().startsWith(NameMangler.PREFIX)) { // Single first pass List worthRetrying = new ArrayList(); boolean modificationOccured = false; List /* AnnotationGen */annotationsToAdd = null; for (Iterator iter = decaMs.iterator(); iter.hasNext();) { DeclareAnnotation decaM = (DeclareAnnotation) iter.next(); if (decaM.matches(mg.getMemberView(), world)) { if (doesAlreadyHaveAnnotation(mg.getMemberView(), decaM, reportedProblems)) { // remove the declare @method since don't want // an error when // the annotation is already there unusedDecams.remove(decaM); continue; // skip this one... } if (annotationsToAdd == null) annotationsToAdd = new ArrayList(); AnnotationGen a = ((BcelAnnotation) decaM.getAnnotationX()).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, clazz.getConstantPool(), true); annotationsToAdd.add(ag); mg.addAnnotation(decaM.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationMethodRelationship(decaM.getSourceLocation(), clazz.getName(), mg.getMemberView(), world.getModelAsAsmManager());// getMethod()); reportMethodCtorWeavingMessage(clazz, mg.getMemberView(), decaM, mg.getDeclarationLineNumber()); isChanged = true; modificationOccured = true; // remove the declare @method since have matched // against it unusedDecams.remove(decaM); } else { if (!decaM.isStarredAnnotationPattern()) worthRetrying.add(decaM); // an annotation is // specified that // might be put on // by a subsequent // decaf } } // Multiple secondary passes while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; // lets have another go List forRemoval = new ArrayList(); for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaM = (DeclareAnnotation) iter.next(); if (decaM.matches(mg.getMemberView(), world)) { if (doesAlreadyHaveAnnotation(mg.getMemberView(), decaM, reportedProblems)) { // remove the declare @method since don't // want an error when // the annotation is already there unusedDecams.remove(decaM); continue; // skip this one... } if (annotationsToAdd == null) annotationsToAdd = new ArrayList(); AnnotationGen a = ((BcelAnnotation) decaM.getAnnotationX()).getBcelAnnotation(); // CUSTARD superfluous? // AnnotationGen ag = new // AnnotationGen(a,clazz.getConstantPool // (),true); annotationsToAdd.add(a); mg.addAnnotation(decaM.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationMethodRelationship( decaM.getSourceLocation(), clazz.getName(), mg.getMemberView(), world.getModelAsAsmManager());// getMethod()); isChanged = true; modificationOccured = true; forRemoval.add(decaM); // remove the declare @method since have matched // against it unusedDecams.remove(decaM); } } worthRetrying.removeAll(forRemoval); } if (annotationsToAdd != null) { Method oldMethod = mg.getMethod(); MethodGen myGen = new MethodGen(oldMethod, clazz.getClassName(), clazz.getConstantPool(), false);// dont // use // tags, // they // won't // get // repaired // like // for // woven // methods // . for (Iterator iter = annotationsToAdd.iterator(); iter.hasNext();) { AnnotationGen a = (AnnotationGen) iter.next(); myGen.addAnnotation(a); } Method newMethod = myGen.getMethod(); members.set(memberCounter, new LazyMethodGen(newMethod, clazz)); } } } checkUnusedDeclareAtTypes(unusedDecams, false); } return isChanged; } // TAG: WeavingMessage private void reportMethodCtorWeavingMessage(LazyClassGen clazz, ResolvedMember member, DeclareAnnotation decaM, int memberLineNumber) { if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { StringBuffer parmString = new StringBuffer("("); UnresolvedType[] paramTypes = member.getParameterTypes(); for (int i = 0; i < paramTypes.length; i++) { UnresolvedType type = paramTypes[i]; String s = org.aspectj.apache.bcel.classfile.Utility.signatureToString(type.getSignature()); if (s.lastIndexOf('.') != -1) s = s.substring(s.lastIndexOf('.') + 1); parmString.append(s); if ((i + 1) < paramTypes.length) parmString.append(","); } parmString.append(")"); String methodName = member.getName(); StringBuffer sig = new StringBuffer(); sig.append(org.aspectj.apache.bcel.classfile.Utility.accessToString(member.getModifiers())); sig.append(" "); sig.append(member.getReturnType().toString()); sig.append(" "); sig.append(member.getDeclaringType().toString()); sig.append("."); sig.append(methodName.equals("<init>") ? "new" : methodName); sig.append(parmString); StringBuffer loc = new StringBuffer(); if (clazz.getFileName() == null) { loc.append("no debug info available"); } else { loc.append(clazz.getFileName()); if (memberLineNumber != -1) { loc.append(":" + memberLineNumber); } } getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES, new String[] { sig.toString(), loc.toString(), decaM.getAnnotationString(), methodName.startsWith("<init>") ? "constructor" : "method", decaM.getAspect().toString(), Utility.beautifyLocation(decaM.getSourceLocation()) })); } } /** * Looks through a list of declare annotation statements and only returns those that could possibly match on a field/method/ctor * in type. */ private List getMatchingSubset(List declareAnnotations, ResolvedType type) { List subset = new ArrayList(); for (Iterator iter = declareAnnotations.iterator(); iter.hasNext();) { DeclareAnnotation da = (DeclareAnnotation) iter.next(); if (da.couldEverMatch(type)) { subset.add(da); } } return subset; } /** * Get a subset of all the type mungers defined on this aspect */ private List getITDSubset(LazyClassGen clazz, ResolvedTypeMunger.Kind wantedKind) { List subset = new ArrayList(); Collection c = clazz.getBcelObjectType().getTypeMungers(); for (Iterator iter = c.iterator(); iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next(); if (typeMunger.getMunger().getKind() == wantedKind) subset.add(typeMunger); } return subset; } public LazyMethodGen locateAnnotationHolderForFieldMunger(LazyClassGen clazz, BcelTypeMunger fieldMunger) { NewFieldTypeMunger nftm = (NewFieldTypeMunger) fieldMunger.getMunger(); ResolvedMember lookingFor = AjcMemberMaker.interFieldInitializer(nftm.getSignature(), clazz.getType()); List meths = clazz.getMethodGens(); for (Iterator iter = meths.iterator(); iter.hasNext();) { LazyMethodGen element = (LazyMethodGen) iter.next(); if (element.getName().equals(lookingFor.getName())) return element; } return null; } // FIXME asc refactor this to neaten it up public LazyMethodGen locateAnnotationHolderForMethodCtorMunger(LazyClassGen clazz, BcelTypeMunger methodCtorMunger) { ResolvedTypeMunger rtMunger = methodCtorMunger.getMunger(); ResolvedMember lookingFor = null; if (rtMunger instanceof NewMethodTypeMunger) { NewMethodTypeMunger nftm = (NewMethodTypeMunger) rtMunger; lookingFor = AjcMemberMaker.interMethodDispatcher(nftm.getSignature(), methodCtorMunger.getAspectType()); } else if (rtMunger instanceof NewConstructorTypeMunger) { NewConstructorTypeMunger nftm = (NewConstructorTypeMunger) rtMunger; lookingFor = AjcMemberMaker.postIntroducedConstructor(methodCtorMunger.getAspectType(), nftm.getSignature() .getDeclaringType(), nftm.getSignature().getParameterTypes()); } else { throw new BCException("Not sure what this is: " + methodCtorMunger); } List meths = clazz.getMethodGens(); String name = lookingFor.getName(); String paramSignature = lookingFor.getParameterSignature(); for (Iterator iter = meths.iterator(); iter.hasNext();) { LazyMethodGen element = (LazyMethodGen) iter.next(); if (element.getName().equals(name) && element.getParameterSignature().equals(paramSignature)) { return element; } } return null; } /** * Applies some set of declare @field constructs (List<DeclareAnnotation>) to some bunch of ITDfields (List<BcelTypeMunger>. It * will iterate over the fields repeatedly until everything has been applied. * */ private boolean weaveAtFieldRepeatedly(List decaFs, List itdFields, List reportedErrors) { boolean isChanged = false; for (Iterator iter = itdFields.iterator(); iter.hasNext();) { BcelTypeMunger fieldMunger = (BcelTypeMunger) iter.next(); ResolvedMember itdIsActually = fieldMunger.getSignature(); List worthRetrying = new ArrayList(); boolean modificationOccured = false; for (Iterator iter2 = decaFs.iterator(); iter2.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter2.next(); if (decaF.matches(itdIsActually, world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, fieldMunger); if (doesAlreadyHaveAnnotation(annotationHolder, itdIsActually, decaF, reportedErrors)) continue; // skip this one... annotationHolder.addAnnotation(decaF.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(world.getModelAsAsmManager(), decaF.getSourceLocation(), itdIsActually.getSourceLocation()); isChanged = true; modificationOccured = true; } else { if (!decaF.isStarredAnnotationPattern()) worthRetrying.add(decaF); // an annotation is specified // that might be put on by a // subsequent decaf } } while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; List forRemoval = new ArrayList(); for (Iterator iter2 = worthRetrying.iterator(); iter2.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter2.next(); if (decaF.matches(itdIsActually, world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, fieldMunger); if (doesAlreadyHaveAnnotation(annotationHolder, itdIsActually, decaF, reportedErrors)) continue; // skip this one... annotationHolder.addAnnotation(decaF.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(world.getModelAsAsmManager(), decaF.getSourceLocation(), itdIsActually.getSourceLocation()); isChanged = true; modificationOccured = true; forRemoval.add(decaF); } worthRetrying.removeAll(forRemoval); } } } return isChanged; } /** * Applies some set of declare @method/@ctor constructs (List<DeclareAnnotation>) to some bunch of ITDmembers * (List<BcelTypeMunger>. It will iterate over the fields repeatedly until everything has been applied. */ private boolean weaveAtMethodOnITDSRepeatedly(List decaMCs, List itdsForMethodAndConstructor, List reportedErrors) { boolean isChanged = false; AsmManager asmManager = world.getModelAsAsmManager(); for (Iterator iter = itdsForMethodAndConstructor.iterator(); iter.hasNext();) { BcelTypeMunger methodctorMunger = (BcelTypeMunger) iter.next(); ResolvedMember unMangledInterMethod = methodctorMunger.getSignature(); List worthRetrying = new ArrayList(); boolean modificationOccured = false; for (Iterator iter2 = decaMCs.iterator(); iter2.hasNext();) { DeclareAnnotation decaMC = (DeclareAnnotation) iter2.next(); if (decaMC.matches(unMangledInterMethod, world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForMethodCtorMunger(clazz, methodctorMunger); if (annotationHolder == null || doesAlreadyHaveAnnotation(annotationHolder, unMangledInterMethod, decaMC, reportedErrors)) { continue; // skip this one... } annotationHolder.addAnnotation(decaMC.getAnnotationX()); isChanged = true; AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(asmManager, decaMC.getSourceLocation(), unMangledInterMethod.getSourceLocation()); reportMethodCtorWeavingMessage(clazz, unMangledInterMethod, decaMC, -1); modificationOccured = true; } else { // If an annotation is specified, it might be added by one of the other declare annotation statements if (!decaMC.isStarredAnnotationPattern()) { worthRetrying.add(decaMC); } } } while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; List forRemoval = new ArrayList(); for (Iterator iter2 = worthRetrying.iterator(); iter2.hasNext();) { DeclareAnnotation decaMC = (DeclareAnnotation) iter2.next(); if (decaMC.matches(unMangledInterMethod, world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, methodctorMunger); if (doesAlreadyHaveAnnotation(annotationHolder, unMangledInterMethod, decaMC, reportedErrors)) continue; // skip this one... annotationHolder.addAnnotation(decaMC.getAnnotationX()); unMangledInterMethod.addAnnotation(decaMC.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(asmManager, decaMC.getSourceLocation(), unMangledInterMethod.getSourceLocation()); isChanged = true; modificationOccured = true; forRemoval.add(decaMC); } worthRetrying.removeAll(forRemoval); } } } return isChanged; } private boolean dontAddTwice(DeclareAnnotation decaF, AnnotationAJ[] dontAddMeTwice) { for (int i = 0; i < dontAddMeTwice.length; i++) { AnnotationAJ ann = dontAddMeTwice[i]; if (ann != null && decaF.getAnnotationX().getTypeName().equals(ann.getTypeName())) { // dontAddMeTwice[i] = null; // incase it really has been added // twice! return true; } } return false; } /** * Weave any declare @field statements into the fields of the supplied class * * Interesting case relating to public ITDd fields. The annotations are really stored against the interfieldinit method in the * aspect, but the public field is placed in the target type and then is processed in the 2nd pass over fields that occurs. I * think it would be more expensive to avoid putting the annotation on that inserted public field than just to have it put there * as well as on the interfieldinit method. */ private boolean weaveDeclareAtField(LazyClassGen clazz) { // BUGWARNING not getting enough warnings out on declare @field ? // There is a potential problem here with warnings not coming out - this // will occur if they are created on the second iteration round this // loop. // We currently deactivate error reporting for the second time round. // A possible solution is to record what annotations were added by what // decafs and check that to see if an error needs to be reported - this // would be expensive so lets skip it for now List reportedProblems = new ArrayList(); List allDecafs = world.getDeclareAnnotationOnFields(); if (allDecafs.isEmpty()) return false; // nothing to do boolean isChanged = false; List itdFields = getITDSubset(clazz, ResolvedTypeMunger.Field); if (itdFields != null) { isChanged = weaveAtFieldRepeatedly(allDecafs, itdFields, reportedProblems); } List decaFs = getMatchingSubset(allDecafs, clazz.getType()); if (decaFs.isEmpty()) return false; // nothing more to do List fields = clazz.getFieldGens(); if (fields != null) { Set unusedDecafs = new HashSet(); unusedDecafs.addAll(decaFs); for (int fieldCounter = 0; fieldCounter < fields.size(); fieldCounter++) { BcelField aBcelField = (BcelField) fields.get(fieldCounter);// new // BcelField(clazz.getBcelObjectType(),fields[fieldCounter // ]); if (!aBcelField.getName().startsWith(NameMangler.PREFIX)) { // Single first pass List worthRetrying = new ArrayList(); boolean modificationOccured = false; AnnotationAJ[] dontAddMeTwice = aBcelField.getAnnotations(); // go through all the declare @field statements for (Iterator iter = decaFs.iterator(); iter.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter.next(); if (decaF.matches(aBcelField, world)) { if (!dontAddTwice(decaF, dontAddMeTwice)) { if (doesAlreadyHaveAnnotation(aBcelField, decaF, reportedProblems)) { // remove the declare @field since don't // want an error when // the annotation is already there unusedDecafs.remove(decaF); continue; } if (decaF.getAnnotationX().isRuntimeVisible()) { // isAnnotationWithRuntimeRetention // ( // clazz // . // getJavaClass(world))){ // if(decaF.getAnnotationTypeX(). // isAnnotationWithRuntimeRetention(world)){ // it should be runtime visible, so put it // on the Field // Annotation a = // decaF.getAnnotationX().getBcelAnnotation // (); // AnnotationGen ag = new // AnnotationGen(a,clazz // .getConstantPoolGen(),true); // FieldGen myGen = new // FieldGen(fields[fieldCounter // ],clazz.getConstantPoolGen()); // myGen.addAnnotation(ag); // Field newField = myGen.getField(); aBcelField.addAnnotation(decaF.getAnnotationX()); // clazz.replaceField(fields[fieldCounter], // newField); // fields[fieldCounter]=newField; } else { aBcelField.addAnnotation(decaF.getAnnotationX()); } } AsmRelationshipProvider.getDefault().addDeclareAnnotationFieldRelationship( world.getModelAsAsmManager(), decaF.getSourceLocation(), clazz.getName(), aBcelField);// .getFieldAsIs()); reportFieldAnnotationWeavingMessage(clazz, fields, fieldCounter, decaF); isChanged = true; modificationOccured = true; // remove the declare @field since have matched // against it unusedDecafs.remove(decaF); } else { if (!decaF.isStarredAnnotationPattern()) worthRetrying.add(decaF); // an annotation is // specified that // might be put on // by a subsequent // decaf } } // Multiple secondary passes while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; // lets have another go List forRemoval = new ArrayList(); for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter.next(); if (decaF.matches(aBcelField, world)) { // below code is for recursive things if (doesAlreadyHaveAnnotation(aBcelField, decaF, reportedProblems)) { // remove the declare @field since don't // want an error when // the annotation is already there unusedDecafs.remove(decaF); continue; // skip this one... } aBcelField.addAnnotation(decaF.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationFieldRelationship( world.getModelAsAsmManager(), decaF.getSourceLocation(), clazz.getName(), aBcelField);// .getFieldAsIs()); isChanged = true; modificationOccured = true; forRemoval.add(decaF); // remove the declare @field since have matched // against it unusedDecafs.remove(decaF); } } worthRetrying.removeAll(forRemoval); } } } checkUnusedDeclareAtTypes(unusedDecafs, true); } return isChanged; } // bug 99191 - put out an error message if the type doesn't exist /** * Report an error if the reason a "declare @method/ctor/field" was not used was because the member specified does not exist. * This method is passed some set of declare statements that didn't match and a flag indicating whether the set contains declare @field * or declare @method/ctor entries. */ private void checkUnusedDeclareAtTypes(Set unusedDecaTs, boolean isDeclareAtField) { for (Iterator iter = unusedDecaTs.iterator(); iter.hasNext();) { DeclareAnnotation declA = (DeclareAnnotation) iter.next(); // Error if an exact type pattern was specified if ((declA.isExactPattern() || (declA.getSignaturePattern().getDeclaringType() instanceof ExactTypePattern)) && (!declA.getSignaturePattern().getName().isAny() || (declA.getKind() == DeclareAnnotation.AT_CONSTRUCTOR))) { // Quickly check if an ITD supplies the 'missing' member boolean itdMatch = false; List lst = clazz.getType().getInterTypeMungers(); for (Iterator iterator = lst.iterator(); iterator.hasNext() && !itdMatch;) { ConcreteTypeMunger element = (ConcreteTypeMunger) iterator.next(); if (element.getMunger() instanceof NewFieldTypeMunger) { NewFieldTypeMunger nftm = (NewFieldTypeMunger) element.getMunger(); itdMatch = declA.getSignaturePattern().matches(nftm.getSignature(), world, false); } else if (element.getMunger() instanceof NewMethodTypeMunger) { NewMethodTypeMunger nmtm = (NewMethodTypeMunger) element.getMunger(); itdMatch = declA.getSignaturePattern().matches(nmtm.getSignature(), world, false); } else if (element.getMunger() instanceof NewConstructorTypeMunger) { NewConstructorTypeMunger nctm = (NewConstructorTypeMunger) element.getMunger(); itdMatch = declA.getSignaturePattern().matches(nctm.getSignature(), world, false); } } if (!itdMatch) { IMessage message = null; if (isDeclareAtField) { message = new Message("The field '" + declA.getSignaturePattern().toString() + "' does not exist", declA .getSourceLocation(), true); } else { message = new Message("The method '" + declA.getSignaturePattern().toString() + "' does not exist", declA .getSourceLocation(), true); } world.getMessageHandler().handleMessage(message); } } } } // TAG: WeavingMessage private void reportFieldAnnotationWeavingMessage(LazyClassGen clazz, List fields, int fieldCounter, DeclareAnnotation decaF) { if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { BcelField theField = (BcelField) fields.get(fieldCounter); world.getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES, new String[] { theField.getFieldAsIs().toString() + "' of type '" + clazz.getName(), clazz.getFileName(), decaF.getAnnotationString(), "field", decaF.getAspect().toString(), Utility.beautifyLocation(decaF.getSourceLocation()) })); } } /** * Check if a resolved member (field/method/ctor) already has an annotation, if it does then put out a warning and return true */ private boolean doesAlreadyHaveAnnotation(ResolvedMember rm, DeclareAnnotation deca, List reportedProblems) { if (rm.hasAnnotation(deca.getAnnotationTypeX())) { if (world.getLint().elementAlreadyAnnotated.isEnabled()) { Integer uniqueID = new Integer(rm.hashCode() * deca.hashCode()); if (!reportedProblems.contains(uniqueID)) { reportedProblems.add(uniqueID); world.getLint().elementAlreadyAnnotated.signal(new String[] { rm.toString(), deca.getAnnotationTypeX().toString() }, rm.getSourceLocation(), new ISourceLocation[] { deca .getSourceLocation() }); } } return true; } return false; } private boolean doesAlreadyHaveAnnotation(LazyMethodGen rm, ResolvedMember itdfieldsig, DeclareAnnotation deca, List reportedProblems) { if (rm != null && rm.hasAnnotation(deca.getAnnotationTypeX())) { if (world.getLint().elementAlreadyAnnotated.isEnabled()) { Integer uniqueID = new Integer(rm.hashCode() * deca.hashCode()); if (!reportedProblems.contains(uniqueID)) { reportedProblems.add(uniqueID); reportedProblems.add(new Integer(itdfieldsig.hashCode() * deca.hashCode())); world.getLint().elementAlreadyAnnotated.signal(new String[] { itdfieldsig.toString(), deca.getAnnotationTypeX().toString() }, rm.getSourceLocation(), new ISourceLocation[] { deca .getSourceLocation() }); } } return true; } return false; } private Set findAspectsForMungers(LazyMethodGen mg) { Set aspectsAffectingType = new HashSet(); for (Iterator iter = mg.matchedShadows.iterator(); iter.hasNext();) { BcelShadow aShadow = (BcelShadow) iter.next(); // Mungers in effect on that shadow for (Iterator iter2 = aShadow.getMungers().iterator(); iter2.hasNext();) { ShadowMunger aMunger = (ShadowMunger) iter2.next(); if (aMunger instanceof BcelAdvice) { BcelAdvice bAdvice = (BcelAdvice) aMunger; if (bAdvice.getConcreteAspect() != null) { aspectsAffectingType.add(bAdvice.getConcreteAspect().getName()); } } else { // It is a 'Checker' - we don't need to remember aspects // that only contributed Checkers... } } } return aspectsAffectingType; } private boolean inlineSelfConstructors(List methodGens) { boolean inlinedSomething = false; for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen) i.next(); if (!mg.getName().equals("<init>")) continue; InstructionHandle ih = findSuperOrThisCall(mg); if (ih != null && isThisCall(ih)) { LazyMethodGen donor = getCalledMethod(ih); inlineMethod(donor, mg, ih); inlinedSomething = true; } } return inlinedSomething; } private void positionAndImplement(List initializationShadows) { for (Iterator i = initializationShadows.iterator(); i.hasNext();) { BcelShadow s = (BcelShadow) i.next(); positionInitializationShadow(s); // s.getEnclosingMethod().print(); s.implement(); } } private void positionInitializationShadow(BcelShadow s) { LazyMethodGen mg = s.getEnclosingMethod(); InstructionHandle call = findSuperOrThisCall(mg); InstructionList body = mg.getBody(); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); if (s.getKind() == Shadow.PreInitialization) { // XXX assert first instruction is an ALOAD_0. // a pre shadow goes from AFTER the first instruction (which we // believe to // be an ALOAD_0) to just before the call to super r.associateWithTargets(Range.genStart(body, body.getStart().getNext()), Range.genEnd(body, call.getPrev())); } else { // assert s.getKind() == Shadow.Initialization r.associateWithTargets(Range.genStart(body, call.getNext()), Range.genEnd(body)); } } private boolean isThisCall(InstructionHandle ih) { InvokeInstruction inst = (InvokeInstruction) ih.getInstruction(); return inst.getClassName(cpg).equals(clazz.getName()); } /** * inline a particular call in bytecode. * * @param donor the method we want to inline * @param recipient the method containing the call we want to inline * @param call the instructionHandle in recipient's body holding the call we want to inline. */ public static void inlineMethod(LazyMethodGen donor, LazyMethodGen recipient, InstructionHandle call) { // assert recipient.contains(call) /* * Implementation notes: * * We allocate two slots for every tempvar so we don't screw up longs and doubles which may share space. This could be * conservatively avoided (no reference to a long/double instruction, don't do it) or packed later. Right now we don't * bother to pack. * * Allocate a new var for each formal param of the inlined. Fill with stack contents. Then copy the inlined instructions in * with the appropriate remap table. Any framelocs used by locals in inlined are reallocated to top of frame, */ final InstructionFactory fact = recipient.getEnclosingClass().getFactory(); IntMap frameEnv = new IntMap(); // this also sets up the initial environment InstructionList argumentStores = genArgumentStores(donor, recipient, frameEnv, fact); InstructionList inlineInstructions = genInlineInstructions(donor, recipient, frameEnv, fact, false); inlineInstructions.insert(argumentStores); recipient.getBody().append(call, inlineInstructions); Utility.deleteInstruction(call, recipient); } // public BcelVar genTempVar(UnresolvedType typeX) { // return new BcelVar(typeX.resolve(world), // genTempVarIndex(typeX.getSize())); // } // // private int genTempVarIndex(int size) { // return enclosingMethod.allocateLocal(size); // } /** * Input method is a synchronized method, we remove the bit flag for synchronized and then insert a try..finally block * * Some jumping through firey hoops required - depending on the input code level (1.5 or not) we may or may not be able to use * the LDC instruction that takes a class literal (doesnt on <1.5). * * FIXME asc Before promoting -Xjoinpoints:synchronization to be a standard option, this needs a bunch of tidying up - there is * some duplication that can be removed. */ public static void transformSynchronizedMethod(LazyMethodGen synchronizedMethod) { if (trace.isTraceEnabled()) trace.enter("transformSynchronizedMethod", synchronizedMethod); // System.err.println("DEBUG: Transforming synchronized method: "+ // synchronizedMethod.getName()); final InstructionFactory fact = synchronizedMethod.getEnclosingClass().getFactory(); InstructionList body = synchronizedMethod.getBody(); InstructionList prepend = new InstructionList(); Type enclosingClassType = BcelWorld.makeBcelType(synchronizedMethod.getEnclosingClass().getType()); // STATIC METHOD TRANSFORMATION if (synchronizedMethod.isStatic()) { // What to do here depends on the level of the class file! // LDC can handle class literals in Java5 and above *sigh* if (synchronizedMethod.getEnclosingClass().isAtLeastJava5()) { // MONITORENTER logic: // 0: ldc #2; //class C // 2: dup // 3: astore_0 // 4: monitorenter int slotForLockObject = synchronizedMethod.allocateLocal(enclosingClassType); prepend.append(fact.createConstant(enclosingClassType)); prepend.append(InstructionFactory.createDup(1)); prepend.append(InstructionFactory.createStore(enclosingClassType, slotForLockObject)); prepend.append(InstructionFactory.MONITORENTER); // MONITOREXIT logic: // We basically need to wrap the code from the method in a // finally block that // will ensure monitorexit is called. Content on the finally // block seems to // be always: // // E1: ALOAD_1 // MONITOREXIT // ATHROW // // so lets build that: InstructionList finallyBlock = new InstructionList(); finallyBlock.append(InstructionFactory.createLoad(Type.getType(java.lang.Class.class), slotForLockObject)); finallyBlock.append(InstructionConstants.MONITOREXIT); finallyBlock.append(InstructionConstants.ATHROW); // finally -> E1 // | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line // 21) // | LDC "hello" // | INVOKEVIRTUAL java.io.PrintStream.println // (Ljava/lang/String;)V // | ALOAD_1 (line 20) // | MONITOREXIT // finally -> E1 // GOTO L0 // finally -> E1 // | E1: ALOAD_1 // | MONITOREXIT // finally -> E1 // ATHROW // L0: RETURN (line 23) // search for 'returns' and make them jump to the // aload_<n>,monitorexit InstructionHandle walker = body.getStart(); List rets = new ArrayList(); while (walker != null) { if (walker.getInstruction().isReturnInstruction()) { rets.add(walker); } walker = walker.getNext(); } if (!rets.isEmpty()) { // need to ensure targeters for 'return' now instead target // the load instruction // (so we never jump over the monitorexit logic) for (Iterator iter = rets.iterator(); iter.hasNext();) { InstructionHandle element = (InstructionHandle) iter.next(); InstructionList monitorExitBlock = new InstructionList(); monitorExitBlock.append(InstructionFactory.createLoad(enclosingClassType, slotForLockObject)); monitorExitBlock.append(InstructionConstants.MONITOREXIT); // monitorExitBlock.append(Utility.copyInstruction(element // .getInstruction())); // element.setInstruction(InstructionFactory.createLoad( // classType,slotForThis)); InstructionHandle monitorExitBlockStart = body.insert(element, monitorExitBlock); // now move the targeters from the RET to the start of // the monitorexit block InstructionTargeter[] targeters = element.getTargetersArray(); if (targeters != null) { for (int i = 0; i < targeters.length; i++) { InstructionTargeter targeter = targeters[i]; // what kinds are there? if (targeter instanceof LocalVariableTag) { // ignore } else if (targeter instanceof LineNumberTag) { // ignore // } else if (targeter instanceof // InstructionBranch && // ((InstructionBranch)targeter).isGoto()) { // // move it... // targeter.updateTarget(element, // monitorExitBlockStart); } else if (targeter instanceof InstructionBranch) { // move it targeter.updateTarget(element, monitorExitBlockStart); } else { throw new BCException("Unexpected targeter encountered during transform: " + targeter); } } } } } // now the magic, putting the finally block around the code InstructionHandle finallyStart = finallyBlock.getStart(); InstructionHandle tryPosition = body.getStart(); InstructionHandle catchPosition = body.getEnd(); body.insert(body.getStart(), prepend); // now we can put the // monitorenter stuff on synchronizedMethod.getBody().append(finallyBlock); synchronizedMethod.addExceptionHandler(tryPosition, catchPosition, finallyStart, null/* ==finally */, false); synchronizedMethod.addExceptionHandler(finallyStart, finallyStart.getNext(), finallyStart, null, false); } else { // TRANSFORMING STATIC METHOD ON PRE JAVA5 // Hideous nightmare, class literal references prior to Java5 // YIKES! this is just the code for MONITORENTER ! // 0: getstatic #59; //Field class$1:Ljava/lang/Class; // 3: dup // 4: ifnonnull 32 // 7: pop // try // 8: ldc #61; //String java.lang.String // 10: invokestatic #44; //Method // java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class; // 13: dup // catch // 14: putstatic #59; //Field class$1:Ljava/lang/Class; // 17: goto 32 // 20: new #46; //class java/lang/NoClassDefFoundError // 23: dup_x1 // 24: swap // 25: invokevirtual #52; //Method // java/lang/Throwable.getMessage:()Ljava/lang/String; // 28: invokespecial #54; //Method // java/lang/NoClassDefFoundError."<init>":(Ljava/lang/String;)V // 31: athrow // 32: dup <-- partTwo (branch target) // 33: astore_0 // 34: monitorenter // // plus exceptiontable entry! // 8 13 20 Class java/lang/ClassNotFoundException Type classType = BcelWorld.makeBcelType(synchronizedMethod.getEnclosingClass().getType()); Type clazzType = Type.getType(Class.class); InstructionList parttwo = new InstructionList(); parttwo.append(InstructionFactory.createDup(1)); int slotForThis = synchronizedMethod.allocateLocal(classType); parttwo.append(InstructionFactory.createStore(clazzType, slotForThis)); // ? should be the real type ? String or // something? parttwo.append(InstructionFactory.MONITORENTER); String fieldname = synchronizedMethod.getEnclosingClass().allocateField("class$"); FieldGen f = new FieldGen(Modifier.STATIC | Modifier.PRIVATE, Type.getType(Class.class), fieldname, synchronizedMethod.getEnclosingClass().getConstantPool()); synchronizedMethod.getEnclosingClass().addField(f, null); // 10: invokestatic #44; //Method // java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class; // 13: dup // 14: putstatic #59; //Field class$1:Ljava/lang/Class; // 17: goto 32 // 20: new #46; //class java/lang/NoClassDefFoundError // 23: dup_x1 // 24: swap // 25: invokevirtual #52; //Method // java/lang/Throwable.getMessage:()Ljava/lang/String; // 28: invokespecial #54; //Method // java/lang/NoClassDefFoundError."<init>":(Ljava/lang/String;)V // 31: athrow String name = synchronizedMethod.getEnclosingClass().getName(); prepend.append(fact.createGetStatic(name, fieldname, Type.getType(Class.class))); prepend.append(InstructionFactory.createDup(1)); prepend.append(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, parttwo.getStart())); prepend.append(InstructionFactory.POP); prepend.append(fact.createConstant(name)); InstructionHandle tryInstruction = prepend.getEnd(); prepend.append(fact.createInvoke("java.lang.Class", "forName", clazzType, new Type[] { Type.getType(String.class) }, Constants.INVOKESTATIC)); InstructionHandle catchInstruction = prepend.getEnd(); prepend.append(InstructionFactory.createDup(1)); prepend.append(fact.createPutStatic(synchronizedMethod.getEnclosingClass().getType().getName(), fieldname, Type .getType(Class.class))); prepend.append(InstructionFactory.createBranchInstruction(Constants.GOTO, parttwo.getStart())); // start of catch block InstructionList catchBlockForLiteralLoadingFail = new InstructionList(); catchBlockForLiteralLoadingFail.append(fact.createNew((ObjectType) Type.getType(NoClassDefFoundError.class))); catchBlockForLiteralLoadingFail.append(InstructionFactory.createDup_1(1)); catchBlockForLiteralLoadingFail.append(InstructionFactory.SWAP); catchBlockForLiteralLoadingFail.append(fact.createInvoke("java.lang.Throwable", "getMessage", Type .getType(String.class), new Type[] {}, Constants.INVOKEVIRTUAL)); catchBlockForLiteralLoadingFail.append(fact.createInvoke("java.lang.NoClassDefFoundError", "<init>", Type.VOID, new Type[] { Type.getType(String.class) }, Constants.INVOKESPECIAL)); catchBlockForLiteralLoadingFail.append(InstructionFactory.ATHROW); InstructionHandle catchBlockStart = catchBlockForLiteralLoadingFail.getStart(); prepend.append(catchBlockForLiteralLoadingFail); prepend.append(parttwo); // MONITORENTER // pseudocode: load up 'this' (var0), dup it, store it in a new // local var (for use with monitorexit) and call // monitorenter: // ALOAD_0, DUP, ASTORE_<n>, MONITORENTER // prepend.append(InstructionFactory.createLoad(classType,0)); // prepend.append(InstructionFactory.createDup(1)); // int slotForThis = // synchronizedMethod.allocateLocal(classType); // prepend.append(InstructionFactory.createStore(classType, // slotForThis)); // prepend.append(InstructionFactory.MONITORENTER); // MONITOREXIT // here be dragons // We basically need to wrap the code from the method in a // finally block that // will ensure monitorexit is called. Content on the finally // block seems to // be always: // // E1: ALOAD_1 // MONITOREXIT // ATHROW // // so lets build that: InstructionList finallyBlock = new InstructionList(); finallyBlock.append(InstructionFactory.createLoad(Type.getType(java.lang.Class.class), slotForThis)); finallyBlock.append(InstructionConstants.MONITOREXIT); finallyBlock.append(InstructionConstants.ATHROW); // finally -> E1 // | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line // 21) // | LDC "hello" // | INVOKEVIRTUAL java.io.PrintStream.println // (Ljava/lang/String;)V // | ALOAD_1 (line 20) // | MONITOREXIT // finally -> E1 // GOTO L0 // finally -> E1 // | E1: ALOAD_1 // | MONITOREXIT // finally -> E1 // ATHROW // L0: RETURN (line 23) // frameEnv.put(donorFramePos, thisSlot); // search for 'returns' and make them to the // aload_<n>,monitorexit InstructionHandle walker = body.getStart(); List rets = new ArrayList(); while (walker != null) { // !walker.equals(body.getEnd())) { if (walker.getInstruction().isReturnInstruction()) { rets.add(walker); } walker = walker.getNext(); } if (rets.size() > 0) { // need to ensure targeters for 'return' now instead target // the load instruction // (so we never jump over the monitorexit logic) for (Iterator iter = rets.iterator(); iter.hasNext();) { InstructionHandle element = (InstructionHandle) iter.next(); // System.err.println("Adding monitor exit block at "+ // element); InstructionList monitorExitBlock = new InstructionList(); monitorExitBlock.append(InstructionFactory.createLoad(classType, slotForThis)); monitorExitBlock.append(InstructionConstants.MONITOREXIT); // monitorExitBlock.append(Utility.copyInstruction(element // .getInstruction())); // element.setInstruction(InstructionFactory.createLoad( // classType,slotForThis)); InstructionHandle monitorExitBlockStart = body.insert(element, monitorExitBlock); // now move the targeters from the RET to the start of // the monitorexit block InstructionTargeter[] targeters = element.getTargetersArray(); if (targeters != null) { for (int i = 0; i < targeters.length; i++) { InstructionTargeter targeter = targeters[i]; // what kinds are there? if (targeter instanceof LocalVariableTag) { // ignore } else if (targeter instanceof LineNumberTag) { // ignore // } else if (targeter instanceof GOTO || // targeter instanceof GOTO_W) { // // move it... // targeter.updateTarget(element, // monitorExitBlockStart); } else if (targeter instanceof InstructionBranch) { // move it targeter.updateTarget(element, monitorExitBlockStart); } else { throw new BCException("Unexpected targeter encountered during transform: " + targeter); } } } } } // body = // rewriteWithMonitorExitCalls(body,fact,true,slotForThis, // classType); // synchronizedMethod.setBody(body); // now the magic, putting the finally block around the code InstructionHandle finallyStart = finallyBlock.getStart(); InstructionHandle tryPosition = body.getStart(); InstructionHandle catchPosition = body.getEnd(); body.insert(body.getStart(), prepend); // now we can put the // monitorenter stuff on synchronizedMethod.getBody().append(finallyBlock); synchronizedMethod.addExceptionHandler(tryPosition, catchPosition, finallyStart, null/* ==finally */, false); synchronizedMethod.addExceptionHandler(tryInstruction, catchInstruction, catchBlockStart, (ObjectType) Type .getType(ClassNotFoundException.class), true); synchronizedMethod.addExceptionHandler(finallyStart, finallyStart.getNext(), finallyStart, null, false); } } else { // TRANSFORMING NON STATIC METHOD Type classType = BcelWorld.makeBcelType(synchronizedMethod.getEnclosingClass().getType()); // MONITORENTER // pseudocode: load up 'this' (var0), dup it, store it in a new // local var (for use with monitorexit) and call // monitorenter: // ALOAD_0, DUP, ASTORE_<n>, MONITORENTER prepend.append(InstructionFactory.createLoad(classType, 0)); prepend.append(InstructionFactory.createDup(1)); int slotForThis = synchronizedMethod.allocateLocal(classType); prepend.append(InstructionFactory.createStore(classType, slotForThis)); prepend.append(InstructionFactory.MONITORENTER); // body.insert(body.getStart(),prepend); // MONITOREXIT // We basically need to wrap the code from the method in a finally // block that // will ensure monitorexit is called. Content on the finally block // seems to // be always: // // E1: ALOAD_1 // MONITOREXIT // ATHROW // // so lets build that: InstructionList finallyBlock = new InstructionList(); finallyBlock.append(InstructionFactory.createLoad(classType, slotForThis)); finallyBlock.append(InstructionConstants.MONITOREXIT); finallyBlock.append(InstructionConstants.ATHROW); // finally -> E1 // | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 21) // | LDC "hello" // | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V // | ALOAD_1 (line 20) // | MONITOREXIT // finally -> E1 // GOTO L0 // finally -> E1 // | E1: ALOAD_1 // | MONITOREXIT // finally -> E1 // ATHROW // L0: RETURN (line 23) // frameEnv.put(donorFramePos, thisSlot); // search for 'returns' and make them to the aload_<n>,monitorexit InstructionHandle walker = body.getStart(); List rets = new ArrayList(); while (walker != null) { // !walker.equals(body.getEnd())) { if (walker.getInstruction().isReturnInstruction()) { rets.add(walker); } walker = walker.getNext(); } if (!rets.isEmpty()) { // need to ensure targeters for 'return' now instead target the // load instruction // (so we never jump over the monitorexit logic) for (Iterator iter = rets.iterator(); iter.hasNext();) { InstructionHandle element = (InstructionHandle) iter.next(); // System.err.println("Adding monitor exit block at "+element // ); InstructionList monitorExitBlock = new InstructionList(); monitorExitBlock.append(InstructionFactory.createLoad(classType, slotForThis)); monitorExitBlock.append(InstructionConstants.MONITOREXIT); // monitorExitBlock.append(Utility.copyInstruction(element. // getInstruction())); // element.setInstruction(InstructionFactory.createLoad( // classType,slotForThis)); InstructionHandle monitorExitBlockStart = body.insert(element, monitorExitBlock); // now move the targeters from the RET to the start of the // monitorexit block InstructionTargeter[] targeters = element.getTargetersArray(); if (targeters != null) { for (int i = 0; i < targeters.length; i++) { InstructionTargeter targeter = targeters[i]; // what kinds are there? if (targeter instanceof LocalVariableTag) { // ignore } else if (targeter instanceof LineNumberTag) { // ignore // } else if (targeter instanceof GOTO || // targeter instanceof GOTO_W) { // // move it... // targeter.updateTarget(element, // monitorExitBlockStart); } else if (targeter instanceof InstructionBranch) { // move it targeter.updateTarget(element, monitorExitBlockStart); } else { throw new BCException("Unexpected targeter encountered during transform: " + targeter); } } } } } // now the magic, putting the finally block around the code InstructionHandle finallyStart = finallyBlock.getStart(); InstructionHandle tryPosition = body.getStart(); InstructionHandle catchPosition = body.getEnd(); body.insert(body.getStart(), prepend); // now we can put the // monitorenter stuff on synchronizedMethod.getBody().append(finallyBlock); synchronizedMethod.addExceptionHandler(tryPosition, catchPosition, finallyStart, null/* ==finally */, false); synchronizedMethod.addExceptionHandler(finallyStart, finallyStart.getNext(), finallyStart, null, false); // also the exception handling for the finally block jumps to itself // max locals will already have been modified in the allocateLocal() // call // synchronized bit is removed on LazyMethodGen.pack() } // gonna have to go through and change all aload_0s to load the var from // a variable, // going to add a new variable for the this var if (trace.isTraceEnabled()) trace.exit("transformSynchronizedMethod"); } /** * generate the instructions to be inlined. * * @param donor the method from which we will copy (and adjust frame and jumps) instructions. * @param recipient the method the instructions will go into. Used to get the frame size so we can allocate new frame locations * for locals in donor. * @param frameEnv an environment to map from donor frame to recipient frame, initially populated with argument locations. * @param fact an instruction factory for recipient */ static InstructionList genInlineInstructions(LazyMethodGen donor, LazyMethodGen recipient, IntMap frameEnv, InstructionFactory fact, boolean keepReturns) { InstructionList footer = new InstructionList(); InstructionHandle end = footer.append(InstructionConstants.NOP); InstructionList ret = new InstructionList(); InstructionList sourceList = donor.getBody(); Map srcToDest = new HashMap(); ConstantPool donorCpg = donor.getEnclosingClass().getConstantPool(); ConstantPool recipientCpg = recipient.getEnclosingClass().getConstantPool(); boolean isAcrossClass = donorCpg != recipientCpg; // first pass: copy the instructions directly, populate the srcToDest // map, // fix frame instructions for (InstructionHandle src = sourceList.getStart(); src != null; src = src.getNext()) { Instruction fresh = Utility.copyInstruction(src.getInstruction()); InstructionHandle dest; // OPTIMIZE optimize this stuff? if (fresh.isConstantPoolInstruction()) { // need to reset index to go to new constant pool. This is // totally // a computation leak... we're testing this LOTS of times. Sigh. if (isAcrossClass) { InstructionCP cpi = (InstructionCP) fresh; cpi.setIndex(recipientCpg.addConstant(donorCpg.getConstant(cpi.getIndex()), donorCpg)); } } if (src.getInstruction() == Range.RANGEINSTRUCTION) { dest = ret.append(Range.RANGEINSTRUCTION); } else if (fresh.isReturnInstruction()) { if (keepReturns) { dest = ret.append(fresh); } else { dest = ret.append(InstructionFactory.createBranchInstruction(Constants.GOTO, end)); } } else if (fresh instanceof InstructionBranch) { dest = ret.append((InstructionBranch) fresh); } else if (fresh.isLocalVariableInstruction() || fresh instanceof RET) { // IndexedInstruction indexed = (IndexedInstruction) fresh; int oldIndex = fresh.getIndex(); int freshIndex; if (!frameEnv.hasKey(oldIndex)) { freshIndex = recipient.allocateLocal(2); frameEnv.put(oldIndex, freshIndex); } else { freshIndex = frameEnv.get(oldIndex); } if (fresh instanceof RET) { fresh.setIndex(freshIndex); } else { fresh = ((InstructionLV) fresh).setIndexAndCopyIfNecessary(freshIndex); } dest = ret.append(fresh); } else { dest = ret.append(fresh); } srcToDest.put(src, dest); } // second pass: retarget branch instructions, copy ranges and tags Map tagMap = new HashMap(); Map shadowMap = new HashMap(); for (InstructionHandle dest = ret.getStart(), src = sourceList.getStart(); dest != null; dest = dest.getNext(), src = src .getNext()) { Instruction inst = dest.getInstruction(); // retarget branches if (inst instanceof InstructionBranch) { InstructionBranch branch = (InstructionBranch) inst; InstructionHandle oldTarget = branch.getTarget(); InstructionHandle newTarget = (InstructionHandle) srcToDest.get(oldTarget); if (newTarget == null) { // assert this is a GOTO // this was a return instruction we previously replaced } else { branch.setTarget(newTarget); if (branch instanceof InstructionSelect) { InstructionSelect select = (InstructionSelect) branch; InstructionHandle[] oldTargets = select.getTargets(); for (int k = oldTargets.length - 1; k >= 0; k--) { select.setTarget(k, (InstructionHandle) srcToDest.get(oldTargets[k])); } } } } // copy over tags and range attributes Iterator tIter = src.getTargeters().iterator(); while (tIter.hasNext()) { InstructionTargeter old = (InstructionTargeter) tIter.next(); if (old instanceof Tag) { Tag oldTag = (Tag) old; Tag fresh = (Tag) tagMap.get(oldTag); if (fresh == null) { fresh = oldTag.copy(); if (old instanceof LocalVariableTag) { // LocalVariable LocalVariableTag lvTag = (LocalVariableTag) old; LocalVariableTag lvTagFresh = (LocalVariableTag) fresh; if (lvTag.getSlot() == 0) { fresh = new LocalVariableTag(lvTag.getRealType().getSignature(), "ajc$aspectInstance", frameEnv .get(lvTag.getSlot()), 0); } else { // // Do not move it - when copying the code from the aspect to the affected target, 'this' is // // going to change from aspect to affected type. So just fix the type // System.out.println("For local variable tag at instruction " + src + " changing slot from " // + lvTag.getSlot() + " > " + frameEnv.get(lvTag.getSlot())); lvTagFresh.updateSlot(frameEnv.get(lvTag.getSlot())); } } tagMap.put(oldTag, fresh); } dest.addTargeter(fresh); } else if (old instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) old; if (er.getStart() == src) { ExceptionRange freshEr = new ExceptionRange(recipient.getBody(), er.getCatchType(), er.getPriority()); freshEr.associateWithTargets(dest, (InstructionHandle) srcToDest.get(er.getEnd()), (InstructionHandle) srcToDest.get(er.getHandler())); } } else if (old instanceof ShadowRange) { ShadowRange oldRange = (ShadowRange) old; if (oldRange.getStart() == src) { BcelShadow oldShadow = oldRange.getShadow(); BcelShadow freshEnclosing = oldShadow.getEnclosingShadow() == null ? null : (BcelShadow) shadowMap .get(oldShadow.getEnclosingShadow()); BcelShadow freshShadow = oldShadow.copyInto(recipient, freshEnclosing); ShadowRange freshRange = new ShadowRange(recipient.getBody()); freshRange.associateWithShadow(freshShadow); freshRange.associateWithTargets(dest, (InstructionHandle) srcToDest.get(oldRange.getEnd())); shadowMap.put(oldRange, freshRange); // recipient.matchedShadows.add(freshShadow); // XXX should go through the NEW copied shadow and // update // the thisVar, targetVar, and argsVar // ??? Might want to also go through at this time and // add // "extra" vars to the shadow. } } } } if (!keepReturns) ret.append(footer); return ret; } // static InstructionList rewriteWithMonitorExitCalls(InstructionList // sourceList,InstructionFactory fact,boolean keepReturns,int // monitorVarSlot,Type monitorVarType) // { // InstructionList footer = new InstructionList(); // InstructionHandle end = footer.append(InstructionConstants.NOP); // // InstructionList newList = new InstructionList(); // // Map srcToDest = new HashMap(); // // // first pass: copy the instructions directly, populate the srcToDest // map, // // fix frame instructions // for (InstructionHandle src = sourceList.getStart(); src != null; src = // src.getNext()) { // Instruction fresh = Utility.copyInstruction(src.getInstruction()); // InstructionHandle dest; // if (src.getInstruction() == Range.RANGEINSTRUCTION) { // dest = newList.append(Range.RANGEINSTRUCTION); // } else if (fresh.isReturnInstruction()) { // if (keepReturns) { // newList.append(InstructionFactory.createLoad(monitorVarType,monitorVarSlot // )); // newList.append(InstructionConstants.MONITOREXIT); // dest = newList.append(fresh); // } else { // dest = // newList.append(InstructionFactory.createBranchInstruction(Constants.GOTO, // end)); // } // } else if (fresh instanceof InstructionBranch) { // dest = newList.append((InstructionBranch) fresh); // } else if ( // fresh.isLocalVariableInstruction() || fresh instanceof RET) { // //IndexedInstruction indexed = (IndexedInstruction) fresh; // int oldIndex = fresh.getIndex(); // int freshIndex; // // if (!frameEnv.hasKey(oldIndex)) { // // freshIndex = recipient.allocateLocal(2); // // frameEnv.put(oldIndex, freshIndex); // // } else { // freshIndex = oldIndex;//frameEnv.get(oldIndex); // // } // if (fresh instanceof RET) { // fresh.setIndex(freshIndex); // } else { // fresh = ((InstructionLV)fresh).setIndexAndCopyIfNecessary(freshIndex); // } // dest = newList.append(fresh); // } else { // dest = newList.append(fresh); // } // srcToDest.put(src, dest); // } // // // second pass: retarget branch instructions, copy ranges and tags // Map tagMap = new HashMap(); // for (InstructionHandle dest = newList.getStart(), src = // sourceList.getStart(); // dest != null; // dest = dest.getNext(), src = src.getNext()) { // Instruction inst = dest.getInstruction(); // // // retarget branches // if (inst instanceof InstructionBranch) { // InstructionBranch branch = (InstructionBranch) inst; // InstructionHandle oldTarget = branch.getTarget(); // InstructionHandle newTarget = // (InstructionHandle) srcToDest.get(oldTarget); // if (newTarget == null) { // // assert this is a GOTO // // this was a return instruction we previously replaced // } else { // branch.setTarget(newTarget); // if (branch instanceof InstructionSelect) { // InstructionSelect select = (InstructionSelect) branch; // InstructionHandle[] oldTargets = select.getTargets(); // for (int k = oldTargets.length - 1; k >= 0; k--) { // select.setTarget( // k, // (InstructionHandle) srcToDest.get(oldTargets[k])); // } // } // } // } // // //copy over tags and range attributes // Iterator tIter = src.getTargeters().iterator(); // // while (tIter.hasNext()) { // InstructionTargeter old = (InstructionTargeter)tIter.next(); // if (old instanceof Tag) { // Tag oldTag = (Tag) old; // Tag fresh = (Tag) tagMap.get(oldTag); // if (fresh == null) { // fresh = oldTag.copy(); // tagMap.put(oldTag, fresh); // } // dest.addTargeter(fresh); // } else if (old instanceof ExceptionRange) { // ExceptionRange er = (ExceptionRange) old; // if (er.getStart() == src) { // ExceptionRange freshEr = // new ExceptionRange(newList/*recipient.getBody()*/,er.getCatchType(),er. // getPriority()); // freshEr.associateWithTargets( // dest, // (InstructionHandle)srcToDest.get(er.getEnd()), // (InstructionHandle)srcToDest.get(er.getHandler())); // } // } // /*else if (old instanceof ShadowRange) { // ShadowRange oldRange = (ShadowRange) old; // if (oldRange.getStart() == src) { // BcelShadow oldShadow = oldRange.getShadow(); // BcelShadow freshEnclosing = // oldShadow.getEnclosingShadow() == null // ? null // : (BcelShadow) shadowMap.get(oldShadow.getEnclosingShadow()); // BcelShadow freshShadow = // oldShadow.copyInto(recipient, freshEnclosing); // ShadowRange freshRange = new ShadowRange(recipient.getBody()); // freshRange.associateWithShadow(freshShadow); // freshRange.associateWithTargets( // dest, // (InstructionHandle) srcToDest.get(oldRange.getEnd())); // shadowMap.put(oldRange, freshRange); // //recipient.matchedShadows.add(freshShadow); // // XXX should go through the NEW copied shadow and update // // the thisVar, targetVar, and argsVar // // ??? Might want to also go through at this time and add // // "extra" vars to the shadow. // } // }*/ // } // } // if (!keepReturns) newList.append(footer); // return newList; // } /** * generate the argument stores in preparation for inlining. * * @param donor the method we will inline from. Used to get the signature. * @param recipient the method we will inline into. Used to get the frame size so we can allocate fresh locations. * @param frameEnv an empty environment we populate with a map from donor frame to recipient frame. * @param fact an instruction factory for recipient */ private static InstructionList genArgumentStores(LazyMethodGen donor, LazyMethodGen recipient, IntMap frameEnv, InstructionFactory fact) { InstructionList ret = new InstructionList(); int donorFramePos = 0; // writing ret back to front because we're popping. if (!donor.isStatic()) { int targetSlot = recipient.allocateLocal(Type.OBJECT); ret.insert(InstructionFactory.createStore(Type.OBJECT, targetSlot)); frameEnv.put(donorFramePos, targetSlot); donorFramePos += 1; } Type[] argTypes = donor.getArgumentTypes(); for (int i = 0, len = argTypes.length; i < len; i++) { Type argType = argTypes[i]; int argSlot = recipient.allocateLocal(argType); ret.insert(InstructionFactory.createStore(argType, argSlot)); frameEnv.put(donorFramePos, argSlot); donorFramePos += argType.getSize(); } return ret; } /** * get a called method: Assumes the called method is in this class, and the reference to it is exact (a la INVOKESPECIAL). * * @param ih The InvokeInstruction instructionHandle pointing to the called method. */ private LazyMethodGen getCalledMethod(InstructionHandle ih) { InvokeInstruction inst = (InvokeInstruction) ih.getInstruction(); String methodName = inst.getName(cpg); String signature = inst.getSignature(cpg); return clazz.getLazyMethodGen(methodName, signature); } private void weaveInAddedMethods() { Collections.sort(addedLazyMethodGens, new Comparator() { public int compare(Object a, Object b) { LazyMethodGen aa = (LazyMethodGen) a; LazyMethodGen bb = (LazyMethodGen) b; int i = aa.getName().compareTo(bb.getName()); if (i != 0) return i; return aa.getSignature().compareTo(bb.getSignature()); } }); for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext();) { clazz.addMethodGen((LazyMethodGen) i.next()); } } // void addPerSingletonField(Member field) { // ObjectType aspectType = (ObjectType) // BcelWorld.makeBcelType(field.getReturnType()); // String aspectName = field.getReturnType().getName(); // // LazyMethodGen clinit = clazz.getStaticInitializer(); // InstructionList setup = new InstructionList(); // InstructionFactory fact = clazz.getFactory(); // // setup.append(fact.createNew(aspectType)); // setup.append(InstructionFactory.createDup(1)); // setup.append(fact.createInvoke(aspectName, "<init>", Type.VOID, new // Type[0], Constants.INVOKESPECIAL)); // setup.append(fact.createFieldAccess(aspectName, field.getName(), // aspectType, Constants.PUTSTATIC)); // clinit.getBody().insert(setup); // } /** * Returns null if this is not a Java constructor, and then we won't weave into it at all */ private InstructionHandle findSuperOrThisCall(LazyMethodGen mg) { int depth = 1; InstructionHandle start = mg.getBody().getStart(); while (true) { if (start == null) return null; Instruction inst = start.getInstruction(); if (inst.opcode == Constants.INVOKESPECIAL && ((InvokeInstruction) inst).getName(cpg).equals("<init>")) { depth--; if (depth == 0) return start; } else if (inst.opcode == Constants.NEW) { depth++; } start = start.getNext(); } } // ---- private boolean match(LazyMethodGen mg) { BcelShadow enclosingShadow; List shadowAccumulator = new ArrayList(); boolean startsAngly = mg.getName().charAt(0) == '<'; // we want to match ajsynthetic constructors... if (startsAngly && mg.getName().equals("<init>")) { return matchInit(mg, shadowAccumulator); } else if (!shouldWeaveBody(mg)) { // .isAjSynthetic()) { return false; } else { if (startsAngly && mg.getName().equals("<clinit>")) { // clinitShadow = enclosingShadow = BcelShadow.makeStaticInitialization(world, mg); // System.err.println(enclosingShadow); } else if (mg.isAdviceMethod()) { enclosingShadow = BcelShadow.makeAdviceExecution(world, mg); } else { AjAttribute.EffectiveSignatureAttribute effective = mg.getEffectiveSignature(); if (effective == null) { enclosingShadow = BcelShadow.makeMethodExecution(world, mg, !canMatchBodyShadows); } else if (effective.isWeaveBody()) { ResolvedMember rm = effective.getEffectiveSignature(); // Annotations for things with effective signatures are // never stored in the effective // signature itself - we have to hunt for them. Storing them // in the effective signature // would mean keeping two sets up to date (no way!!) fixParameterNamesForResolvedMember(rm, mg.getMemberView()); fixAnnotationsForResolvedMember(rm, mg.getMemberView()); enclosingShadow = BcelShadow.makeShadowForMethod(world, mg, effective.getShadowKind(), rm); } else { return false; } } if (canMatchBodyShadows) { for (InstructionHandle h = mg.getBody().getStart(); h != null; h = h.getNext()) { match(mg, h, enclosingShadow, shadowAccumulator); } } // FIXME asc change from string match if we can, rather brittle. // this check actually prevents field-exec jps if (canMatch(enclosingShadow.getKind()) && !(mg.getName().charAt(0) == 'a' && mg.getName().startsWith("ajc$interFieldInit"))) { if (match(enclosingShadow, shadowAccumulator)) { enclosingShadow.init(); } } mg.matchedShadows = shadowAccumulator; return !shadowAccumulator.isEmpty(); } } private boolean matchInit(LazyMethodGen mg, List shadowAccumulator) { BcelShadow enclosingShadow; // XXX the enclosing join point is wrong for things before ignoreMe. InstructionHandle superOrThisCall = findSuperOrThisCall(mg); // we don't walk bodies of things where it's a wrong constructor thingie if (superOrThisCall == null) return false; enclosingShadow = BcelShadow.makeConstructorExecution(world, mg, superOrThisCall); if (mg.getEffectiveSignature() != null) { enclosingShadow.setMatchingSignature(mg.getEffectiveSignature().getEffectiveSignature()); } // walk the body boolean beforeSuperOrThisCall = true; if (shouldWeaveBody(mg)) { if (canMatchBodyShadows) { for (InstructionHandle h = mg.getBody().getStart(); h != null; h = h.getNext()) { if (h == superOrThisCall) { beforeSuperOrThisCall = false; continue; } match(mg, h, beforeSuperOrThisCall ? null : enclosingShadow, shadowAccumulator); } } if (canMatch(Shadow.ConstructorExecution)) match(enclosingShadow, shadowAccumulator); } // XXX we don't do pre-inits of interfaces // now add interface inits if (!isThisCall(superOrThisCall)) { InstructionHandle curr = enclosingShadow.getRange().getStart(); for (Iterator i = addedSuperInitializersAsList.iterator(); i.hasNext();) { IfaceInitList l = (IfaceInitList) i.next(); Member ifaceInitSig = AjcMemberMaker.interfaceConstructor(l.onType); BcelShadow initShadow = BcelShadow.makeIfaceInitialization(world, mg, ifaceInitSig); // insert code in place InstructionList inits = genInitInstructions(l.list, false); if (match(initShadow, shadowAccumulator) || !inits.isEmpty()) { initShadow.initIfaceInitializer(curr); initShadow.getRange().insert(inits, Range.OutsideBefore); } } // now we add our initialization code InstructionList inits = genInitInstructions(addedThisInitializers, false); enclosingShadow.getRange().insert(inits, Range.OutsideBefore); } // actually, you only need to inline the self constructors that are // in a particular group (partition the constructors into groups where // members // call or are called only by those in the group). Then only inline // constructors // in groups where at least one initialization jp matched. Future work. boolean addedInitialization = match(BcelShadow.makeUnfinishedInitialization(world, mg), initializationShadows); addedInitialization |= match(BcelShadow.makeUnfinishedPreinitialization(world, mg), initializationShadows); mg.matchedShadows = shadowAccumulator; return addedInitialization || !shadowAccumulator.isEmpty(); } private boolean shouldWeaveBody(LazyMethodGen mg) { if (mg.isBridgeMethod()) return false; if (mg.isAjSynthetic()) return mg.getName().equals("<clinit>"); AjAttribute.EffectiveSignatureAttribute a = mg.getEffectiveSignature(); if (a != null) return a.isWeaveBody(); return true; } /** * first sorts the mungers, then gens the initializers in the right order */ private InstructionList genInitInstructions(List list, boolean isStatic) { list = PartialOrder.sort(list); if (list == null) { throw new BCException("circularity in inter-types"); } InstructionList ret = new InstructionList(); for (Iterator i = list.iterator(); i.hasNext();) { ConcreteTypeMunger cmunger = (ConcreteTypeMunger) i.next(); NewFieldTypeMunger munger = (NewFieldTypeMunger) cmunger.getMunger(); ResolvedMember initMethod = munger.getInitMethod(cmunger.getAspectType()); if (!isStatic) ret.append(InstructionConstants.ALOAD_0); ret.append(Utility.createInvoke(fact, world, initMethod)); } return ret; } private void match(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { Instruction i = ih.getInstruction(); // Exception handlers (pr230817) if (canMatch(Shadow.ExceptionHandler) && !Range.isRangeHandle(ih)) { InstructionTargeter[] targeters = ih.getTargetersArray(); if (targeters != null) { for (int j = 0; j < targeters.length; j++) { InstructionTargeter t = targeters[j]; if (t instanceof ExceptionRange) { // assert t.getHandler() == ih ExceptionRange er = (ExceptionRange) t; if (er.getCatchType() == null) continue; if (isInitFailureHandler(ih)) return; if (!ih.getInstruction().isStoreInstruction() && ih.getInstruction().getOpcode() != Constants.NOP) { // If using cobertura, the catch block stats with // INVOKESTATIC rather than ASTORE, in order that // the // ranges // for the methodcall and exceptionhandler shadows // that occur at this same // line, we need to modify the instruction list to // split them - adding a // NOP before the invokestatic that gets all the // targeters // that were aimed at the INVOKESTATIC mg.getBody().insert(ih, InstructionConstants.NOP); InstructionHandle newNOP = ih.getPrev(); // what about a try..catch that starts at the start // of the exception handler? need to only include // certain targeters really. er.updateTarget(ih, newNOP, mg.getBody()); for (int ii = 0; ii < targeters.length; ii++) { newNOP.addTargeter(targeters[ii]); } ih.removeAllTargeters(); match(BcelShadow.makeExceptionHandler(world, er, mg, newNOP, enclosingShadow), shadowAccumulator); } else { match(BcelShadow.makeExceptionHandler(world, er, mg, ih, enclosingShadow), shadowAccumulator); } } } } } if ((i instanceof FieldInstruction) && (canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet))) { FieldInstruction fi = (FieldInstruction) i; if (fi.opcode == Constants.PUTFIELD || fi.opcode == Constants.PUTSTATIC) { // check for sets of constant fields. We first check the // previous // instruction. If the previous instruction is a LD_WHATEVER // (push // constant on the stack) then we must resolve the field to // determine // if it's final. If it is final, then we don't generate a // shadow. InstructionHandle prevHandle = ih.getPrev(); Instruction prevI = prevHandle.getInstruction(); if (Utility.isConstantPushInstruction(prevI)) { Member field = BcelWorld.makeFieldJoinPointSignature(clazz, (FieldInstruction) i); ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. } else if (Modifier.isFinal(resolvedField.getModifiers())) { // it's final, so it's the set of a final constant, so // it's // not a join point according to 1.0.6 and 1.1. } else { if (canMatch(Shadow.FieldSet)) matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else { if (canMatch(Shadow.FieldSet)) matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else { if (canMatch(Shadow.FieldGet)) matchGetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else if (i instanceof InvokeInstruction) { InvokeInstruction ii = (InvokeInstruction) i; if (ii.getMethodName(clazz.getConstantPool()).equals("<init>")) { if (canMatch(Shadow.ConstructorCall)) match(BcelShadow.makeConstructorCall(world, mg, ih, enclosingShadow), shadowAccumulator); } else if (ii.opcode == Constants.INVOKESPECIAL) { String onTypeName = ii.getClassName(cpg); if (onTypeName.equals(mg.getEnclosingClass().getName())) { // we are private matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator); } else { // we are a super call, and this is not a join point in // AspectJ-1.{0,1} } } else { matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator); } } else if (world.isJoinpointArrayConstructionEnabled() && i.isArrayCreationInstruction()) { if (canMatch(Shadow.ConstructorCall)) { boolean debug = false; if (debug) System.err.println("Found new array instruction: " + i); if (i.opcode == Constants.ANEWARRAY) { // ANEWARRAY arrayInstruction = (ANEWARRAY)i; ObjectType arrayType = i.getLoadClassType(clazz.getConstantPool()); if (debug) System.err.println("Array type is " + arrayType); BcelShadow ctorCallShadow = BcelShadow.makeArrayConstructorCall(world, mg, ih, enclosingShadow); match(ctorCallShadow, shadowAccumulator); } else if (i.opcode == Constants.NEWARRAY) { // NEWARRAY arrayInstruction = (NEWARRAY)i; Type arrayType = i.getType(); if (debug) System.err.println("Array type is " + arrayType); BcelShadow ctorCallShadow = BcelShadow.makeArrayConstructorCall(world, mg, ih, enclosingShadow); match(ctorCallShadow, shadowAccumulator); } else if (i instanceof MULTIANEWARRAY) { MULTIANEWARRAY arrayInstruction = (MULTIANEWARRAY) i; ObjectType arrayType = arrayInstruction.getLoadClassType(clazz.getConstantPool()); if (debug) System.err.println("Array type is " + arrayType); BcelShadow ctorCallShadow = BcelShadow.makeArrayConstructorCall(world, mg, ih, enclosingShadow); match(ctorCallShadow, shadowAccumulator); } } // see pr77166 if you are thinking about implementing this // } else if (i instanceof AALOAD ) { // AALOAD arrayLoad = (AALOAD)i; // Type arrayType = arrayLoad.getType(clazz.getConstantPoolGen()); // BcelShadow arrayLoadShadow = // BcelShadow.makeArrayLoadCall(world,mg,ih,enclosingShadow); // match(arrayLoadShadow,shadowAccumulator); // } else if (i instanceof AASTORE) { // // ... magic required } else if (world.isJoinpointSynchronizationEnabled() && ((i.getOpcode() == Constants.MONITORENTER) || (i.getOpcode() == Constants.MONITOREXIT))) { // if (canMatch(Shadow.Monitoring)) { if (i.getOpcode() == Constants.MONITORENTER) { BcelShadow monitorEntryShadow = BcelShadow.makeMonitorEnter(world, mg, ih, enclosingShadow); match(monitorEntryShadow, shadowAccumulator); } else { BcelShadow monitorExitShadow = BcelShadow.makeMonitorExit(world, mg, ih, enclosingShadow); match(monitorExitShadow, shadowAccumulator); } // } } } private boolean isInitFailureHandler(InstructionHandle ih) { // Skip the astore_0 and aload_0 at the start of the handler and // then check if the instruction following these is // 'putstatic ajc$initFailureCause'. If it is then we are // in the handler we created in AspectClinit.generatePostSyntheticCode() InstructionHandle twoInstructionsAway = ih.getNext().getNext(); if (twoInstructionsAway.getInstruction().opcode == Constants.PUTSTATIC) { String name = ((FieldInstruction) twoInstructionsAway.getInstruction()).getFieldName(cpg); if (name.equals(NameMangler.INITFAILURECAUSE_FIELD_NAME)) return true; } return false; } private void matchSetInstruction(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { FieldInstruction fi = (FieldInstruction) ih.getInstruction(); Member field = BcelWorld.makeFieldJoinPointSignature(clazz, fi); // synthetic fields are never join points if (field.getName().startsWith(NameMangler.PREFIX)) return; ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. return; } else if (Modifier.isFinal(resolvedField.getModifiers()) && Utility.isConstantPushInstruction(ih.getPrev().getInstruction())) { // it's the set of a final constant, so it's // not a join point according to 1.0.6 and 1.1. return; } else if (resolvedField.isSynthetic()) { // sets of synthetics aren't join points in 1.1 return; } else { // Fix for bug 172107 (similar the "get" fix for bug 109728) BcelShadow bs = BcelShadow.makeFieldSet(world, resolvedField, mg, ih, enclosingShadow); String cname = fi.getClassName(cpg); if (!resolvedField.getDeclaringType().getName().equals(cname)) { bs.setActualTargetType(cname); } match(bs, shadowAccumulator); } } private void matchGetInstruction(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { FieldInstruction fi = (FieldInstruction) ih.getInstruction(); Member field = BcelWorld.makeFieldJoinPointSignature(clazz, fi); // synthetic fields are never join points if (field.getName().startsWith(NameMangler.PREFIX)) return; ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. return; } else if (resolvedField.isSynthetic()) { // sets of synthetics aren't join points in 1.1 return; } else { BcelShadow bs = BcelShadow.makeFieldGet(world, resolvedField, mg, ih, enclosingShadow); String cname = fi.getClassName(cpg); if (!resolvedField.getDeclaringType().getName().equals(cname)) { bs.setActualTargetType(cname); } match(bs, shadowAccumulator); } } /** * For some named resolved type, this method looks for a member with a particular name - it should only be used when you truly * believe there is only one member with that name in the type as it returns the first one it finds. */ private ResolvedMember findResolvedMemberNamed(ResolvedType type, String methodName) { ResolvedMember[] allMethods = type.getDeclaredMethods(); for (int i = 0; i < allMethods.length; i++) { ResolvedMember member = allMethods[i]; if (member.getName().equals(methodName)) return member; } return null; } /** * For a given resolvedmember, this will discover the real annotations for it. <b>Should only be used when the resolvedmember is * the contents of an effective signature attribute, as thats the only time when the annotations aren't stored directly in the * resolvedMember</b> * * @param rm the sig we want it to pretend to be 'int A.m()' or somesuch ITD like thing * @param declaredSig the real sig 'blah.ajc$xxx' */ private void fixParameterNamesForResolvedMember(ResolvedMember rm, ResolvedMember declaredSig) { UnresolvedType memberHostType = declaredSig.getDeclaringType(); String methodName = declaredSig.getName(); String[] pnames = null; if (rm.getKind() == Member.METHOD && !rm.isAbstract()) { if (methodName.startsWith("ajc$inlineAccessMethod") || methodName.startsWith("ajc$superDispatch")) { ResolvedMember resolvedDooberry = world.resolve(declaredSig); pnames = resolvedDooberry.getParameterNames(); } else { ResolvedMember realthing = AjcMemberMaker.interMethodDispatcher(rm.resolve(world), memberHostType).resolve(world); ResolvedMember theRealMember = findResolvedMemberNamed(memberHostType.resolve(world), realthing.getName()); if (theRealMember != null) { pnames = theRealMember.getParameterNames(); // static ITDs don't need any parameter shifting if (pnames.length > 0 && pnames[0].equals("ajc$this_")) { String[] pnames2 = new String[pnames.length - 1]; System.arraycopy(pnames, 1, pnames2, 0, pnames2.length); pnames = pnames2; } } } // i think ctors are missing from here... copy code from below... } rm.setParameterNames(pnames); } /** * For a given resolvedmember, this will discover the real annotations for it. <b>Should only be used when the resolvedmember is * the contents of an effective signature attribute, as thats the only time when the annotations aren't stored directly in the * resolvedMember</b> * * @param rm the sig we want it to pretend to be 'int A.m()' or somesuch ITD like thing * @param declaredSig the real sig 'blah.ajc$xxx' */ private void fixAnnotationsForResolvedMember(ResolvedMember rm, ResolvedMember declaredSig) { try { UnresolvedType memberHostType = declaredSig.getDeclaringType(); ResolvedType[] annotations = (ResolvedType[]) mapToAnnotations.get(rm); String methodName = declaredSig.getName(); // FIXME asc shouldnt really rely on string names ! if (annotations == null) { if (rm.getKind() == Member.FIELD) { if (methodName.startsWith("ajc$inlineAccessField")) { ResolvedMember resolvedDooberry = world.resolve(rm); annotations = resolvedDooberry.getAnnotationTypes(); } else { ResolvedMember realthing = AjcMemberMaker.interFieldInitializer(rm, memberHostType); ResolvedMember resolvedDooberry = world.resolve(realthing); annotations = resolvedDooberry.getAnnotationTypes(); } } else if (rm.getKind() == Member.METHOD && !rm.isAbstract()) { if (methodName.startsWith("ajc$inlineAccessMethod") || methodName.startsWith("ajc$superDispatch")) { ResolvedMember resolvedDooberry = world.resolve(declaredSig); annotations = resolvedDooberry.getAnnotationTypes(); } else { ResolvedMember realthing = AjcMemberMaker.interMethodDispatcher(rm.resolve(world), memberHostType).resolve( world); // ResolvedMember resolvedDooberry = // world.resolve(realthing); ResolvedMember theRealMember = findResolvedMemberNamed(memberHostType.resolve(world), realthing.getName()); // AMC temp guard for M4 if (theRealMember == null) { throw new UnsupportedOperationException( "Known limitation in M4 - can't find ITD members when type variable is used as an argument and has upper bound specified"); } annotations = theRealMember.getAnnotationTypes(); } } else if (rm.getKind() == Member.CONSTRUCTOR) { ResolvedMember realThing = AjcMemberMaker.postIntroducedConstructor(memberHostType.resolve(world), rm .getDeclaringType(), rm.getParameterTypes()); ResolvedMember resolvedDooberry = world.resolve(realThing); // AMC temp guard for M4 if (resolvedDooberry == null) { throw new UnsupportedOperationException( "Known limitation in M4 - can't find ITD members when type variable is used as an argument and has upper bound specified"); } annotations = resolvedDooberry.getAnnotationTypes(); } if (annotations == null) annotations = new ResolvedType[0]; mapToAnnotations.put(rm, annotations); } rm.setAnnotationTypes(annotations); } catch (UnsupportedOperationException ex) { throw ex; } catch (Throwable t) { // FIXME asc remove this catch after more testing has confirmed the // above stuff is OK throw new BCException("Unexpectedly went bang when searching for annotations on " + rm, t); } } private void matchInvokeInstruction(LazyMethodGen mg, InstructionHandle ih, InvokeInstruction invoke, BcelShadow enclosingShadow, List shadowAccumulator) { String methodName = invoke.getName(cpg); if (methodName.startsWith(NameMangler.PREFIX)) { Member jpSig = world.makeJoinPointSignatureForMethodInvocation(clazz, invoke); ResolvedMember declaredSig = jpSig.resolve(world); // System.err.println(method + ", declaredSig: " +declaredSig); if (declaredSig == null) return; if (declaredSig.getKind() == Member.FIELD) { Shadow.Kind kind; if (jpSig.getReturnType().equals(ResolvedType.VOID)) { kind = Shadow.FieldSet; } else { kind = Shadow.FieldGet; } if (canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet)) match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow, kind, declaredSig), shadowAccumulator); } else { AjAttribute.EffectiveSignatureAttribute effectiveSig = declaredSig.getEffectiveSignature(); if (effectiveSig == null) return; // System.err.println("call to inter-type member: " + // effectiveSig); if (effectiveSig.isWeaveBody()) return; ResolvedMember rm = effectiveSig.getEffectiveSignature(); fixParameterNamesForResolvedMember(rm, declaredSig); fixAnnotationsForResolvedMember(rm, declaredSig); // abracadabra if (canMatch(effectiveSig.getShadowKind())) match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow, effectiveSig.getShadowKind(), rm), shadowAccumulator); } } else { if (canMatch(Shadow.MethodCall)) match(BcelShadow.makeMethodCall(world, mg, ih, enclosingShadow), shadowAccumulator); } } // static ... so all worlds will share the config for the first one // created... private static boolean checkedXsetForLowLevelContextCapturing = false; private static boolean captureLowLevelContext = false; private boolean match(BcelShadow shadow, List shadowAccumulator) { // System.err.println("match: " + shadow); if (captureLowLevelContext) { // duplicate blocks - one with context // capture, one without, seems faster // than multiple // 'ifs()' ContextToken shadowMatchToken = CompilationAndWeavingContext.enteringPhase( CompilationAndWeavingContext.MATCHING_SHADOW, shadow); boolean isMatched = false; for (Iterator i = shadowMungers.iterator(); i.hasNext();) { ShadowMunger munger = (ShadowMunger) i.next(); ContextToken mungerMatchToken = CompilationAndWeavingContext.enteringPhase( CompilationAndWeavingContext.MATCHING_POINTCUT, munger.getPointcut()); if (munger.match(shadow, world)) { shadow.addMunger(munger); isMatched = true; if (shadow.getKind() == Shadow.StaticInitialization) { clazz.warnOnAddedStaticInitializer(shadow, munger.getSourceLocation()); } } CompilationAndWeavingContext.leavingPhase(mungerMatchToken); } if (isMatched) shadowAccumulator.add(shadow); CompilationAndWeavingContext.leavingPhase(shadowMatchToken); return isMatched; } else { boolean isMatched = false; int max = shadowMungers.size(); for (int i = 0; i < max; i++) { ShadowMunger munger = (ShadowMunger) shadowMungers.get(i); if (munger.match(shadow, world)) { shadow.addMunger(munger); isMatched = true; if (shadow.getKind() == Shadow.StaticInitialization) { clazz.warnOnAddedStaticInitializer(shadow, munger.getSourceLocation()); } } } if (isMatched) { shadowAccumulator.add(shadow); } return isMatched; } } // ---- private void implement(LazyMethodGen mg) { List shadows = mg.matchedShadows; if (shadows == null) return; // We depend on a partial order such that inner shadows are earlier on // the list // than outer shadows. That's fine. This order is preserved if: // A preceeds B iff B.getStart() is LATER THAN A.getStart(). for (Iterator i = shadows.iterator(); i.hasNext();) { BcelShadow shadow = (BcelShadow) i.next(); ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.IMPLEMENTING_ON_SHADOW, shadow); shadow.implement(); CompilationAndWeavingContext.leavingPhase(tok); } // int ii = mg.getMaxLocals(); mg.matchedShadows = null; } // ---- public LazyClassGen getLazyClassGen() { return clazz; } public List getShadowMungers() { return shadowMungers; } public BcelWorld getWorld() { return world; } // Called by the BcelWeaver to let us know all BcelClassWeavers need to // collect reweavable info public static void setReweavableMode(boolean mode) { inReweavableMode = mode; } public static boolean getReweavableMode() { return inReweavableMode; } public String toString() { return "BcelClassWeaver instance for : " + clazz; } }
263,837
Bug 263837 Error during Delete AJ Markers
Error sent through the AJDT mailing list. I believe this is an LTW weaving error, so not raising it against AJDT.
resolved fixed
1b54b4b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-02-06T00:15:57Z"
"2009-02-05T18:53:20Z"
weaver/src/org/aspectj/weaver/bcel/BcelTypeMunger.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur @AspectJ ITDs * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.ConstantPool; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen; import org.aspectj.apache.bcel.generic.FieldGen; import org.aspectj.apache.bcel.generic.InstructionBranch; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.Member; import org.aspectj.weaver.MethodDelegateTypeMunger; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.PerObjectInterfaceTypeMunger; import org.aspectj.weaver.PrivilegedAccessMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.model.AsmRelationshipProvider; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.Pointcut; //XXX addLazyMethodGen is probably bad everywhere public class BcelTypeMunger extends ConcreteTypeMunger { public BcelTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType) { super(munger, aspectType); } public String toString() { return "(BcelTypeMunger " + getMunger() + ")"; } public boolean shouldOverwrite() { return false; } public boolean munge(BcelClassWeaver weaver) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MUNGING_WITH, this); boolean changed = false; boolean worthReporting = true; if (munger.getKind() == ResolvedTypeMunger.Field) { changed = mungeNewField(weaver, (NewFieldTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.Method) { changed = mungeNewMethod(weaver, (NewMethodTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.MethodDelegate2) { changed = mungeMethodDelegate(weaver, (MethodDelegateTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.FieldHost) { changed = mungeFieldHost(weaver, (MethodDelegateTypeMunger.FieldHostTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.PerObjectInterface) { changed = mungePerObjectInterface(weaver, (PerObjectInterfaceTypeMunger) munger); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.PerTypeWithinInterface) { // PTWIMPL Transform the target type (add the aspect instance field) changed = mungePerTypeWithinTransformer(weaver); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.PrivilegedAccess) { changed = mungePrivilegedAccess(weaver, (PrivilegedAccessMunger) munger); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.Constructor) { changed = mungeNewConstructor(weaver, (NewConstructorTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.Parent) { changed = mungeNewParent(weaver, (NewParentTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.AnnotationOnType) { changed = mungeNewAnnotationOnType(weaver, (AnnotationOnTypeMunger) munger); worthReporting = false; } else { throw new RuntimeException("unimplemented"); } if (changed && munger.changesPublicSignature()) { WeaverStateInfo info = weaver.getLazyClassGen().getOrCreateWeaverStateInfo(BcelClassWeaver.getReweavableMode()); info.addConcreteMunger(this); } if (changed && worthReporting) { AsmRelationshipProvider.getDefault().addRelationship(((BcelWorld) getWorld()).getModelAsAsmManager(), weaver.getLazyClassGen().getType(), munger, getAspectType()); } // TAG: WeavingMessage if (changed && worthReporting && munger != null && !weaver.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { String tName = weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getName(); if (tName.indexOf("no debug info available") != -1) tName = "no debug info available"; else tName = getShortname(weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getPath()); String fName = getShortname(getAspectType().getSourceLocation().getSourceFile().getPath()); if (munger.getKind().equals(ResolvedTypeMunger.Parent)) { // This message could come out of AjLookupEnvironment.addParent // if doing parents // munging at compile time only... NewParentTypeMunger parentTM = (NewParentTypeMunger) munger; if (parentTM.getNewParent().isInterface()) { weaver.getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS, new String[] { weaver.getLazyClassGen().getType().getName(), tName, parentTM.getNewParent().getName(), fName }, weaver.getLazyClassGen().getClassName(), getAspectType().getName())); } else { weaver.getWorld().getMessageHandler().handleMessage( WeaveMessage .constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS, new String[] { weaver.getLazyClassGen().getType().getName(), tName, parentTM.getNewParent().getName(), fName })); // TAG: WeavingMessage DECLARE PARENTS: EXTENDS // reportDeclareParentsMessage(WeaveMessage. // WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent); } } else if (munger.getKind().equals(ResolvedTypeMunger.FieldHost)) { // hidden } else { ResolvedMember declaredSig = munger.getSignature(); // if (declaredSig==null) declaredSig= munger.getSignature(); weaver.getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ITD, new String[] { weaver.getLazyClassGen().getType().getName(), tName, munger.getKind().toString().toLowerCase(), getAspectType().getName(), fName + ":'" + declaredSig + "'" }, weaver.getLazyClassGen() .getClassName(), getAspectType().getName())); } } CompilationAndWeavingContext.leavingPhase(tok); return changed; } private String getShortname(String path) { int takefrom = path.lastIndexOf('/'); if (takefrom == -1) { takefrom = path.lastIndexOf('\\'); } return path.substring(takefrom + 1); } private boolean mungeNewAnnotationOnType(BcelClassWeaver weaver, AnnotationOnTypeMunger munger) { // FIXME asc this has already been done up front, need to do it here // too? weaver.getLazyClassGen().addAnnotation(((BcelAnnotation) munger.getNewAnnotation()).getBcelAnnotation()); return true; } /** * For a long time, AspectJ did not allow binary weaving of declare parents. This restriction is now lifted but could do with * more testing! */ private boolean mungeNewParent(BcelClassWeaver weaver, NewParentTypeMunger munger) { LazyClassGen newParentTarget = weaver.getLazyClassGen(); ResolvedType newParent = munger.getNewParent(); boolean cont = true; // Set to false when we error, so we don't actually // *do* the munge cont = enforceDecpRule1_abstractMethodsImplemented(weaver, munger.getSourceLocation(), newParentTarget, newParent); cont = enforceDecpRule2_cantExtendFinalClass(weaver, munger.getSourceLocation(), newParentTarget, newParent) && cont; List methods = newParent.getMethodsWithoutIterator(false, true); for (Iterator iter = methods.iterator(); iter.hasNext();) { ResolvedMember superMethod = (ResolvedMember) iter.next(); if (!superMethod.getName().equals("<init>")) { LazyMethodGen subMethod = findMatchingMethod(newParentTarget, superMethod); if (subMethod != null && !subMethod.isBridgeMethod()) { // FIXME // asc // is // this // safe // for // all // bridge // methods // ? if (!(subMethod.isSynthetic() && superMethod.isSynthetic())) { if (!(subMethod.isStatic() && subMethod.getName().startsWith("access$"))) { // ignore generated // accessors cont = enforceDecpRule3_visibilityChanges(weaver, newParent, superMethod, subMethod) && cont; cont = enforceDecpRule4_compatibleReturnTypes(weaver, superMethod, subMethod) && cont; cont = enforceDecpRule5_cantChangeFromStaticToNonstatic(weaver, munger.getSourceLocation(), superMethod, subMethod) && cont; } } } } } if (!cont) return false; // A rule was violated and an error message already // reported if (newParent.isClass()) { // Changing the supertype if (!attemptToModifySuperCalls(weaver, newParentTarget, newParent)) return false; newParentTarget.setSuperClass(newParent); } else { // Adding a new interface newParentTarget.addInterface(newParent, getSourceLocation()); } return true; } /** * Rule 1: For the declare parents to be allowed, the target type must override and implement inherited abstract methods (if the * type is not declared abstract) */ private boolean enforceDecpRule1_abstractMethodsImplemented(BcelClassWeaver weaver, ISourceLocation mungerLoc, LazyClassGen newParentTarget, ResolvedType newParent) { boolean ruleCheckingSucceeded = true; if (!(newParentTarget.isAbstract() || newParentTarget.isInterface())) { // Ignore // abstract // classes // or // interfaces List methods = newParent.getMethodsWithoutIterator(false, true); for (Iterator i = methods.iterator(); i.hasNext();) { ResolvedMember o = (ResolvedMember) i.next(); if (o.isAbstract() && !o.getName().startsWith("ajc$interField")) { // Ignore // abstract // methods // of // ajc$interField // prefixed // methods ResolvedMember discoveredImpl = null; List newParentTargetMethods = newParentTarget.getType().getMethodsWithoutIterator(false, true); for (Iterator ii = newParentTargetMethods.iterator(); ii.hasNext() && discoveredImpl == null;) { ResolvedMember gen2 = (ResolvedMember) ii.next(); if (gen2.getName().equals(o.getName()) && gen2.getParameterSignature().equals(o.getParameterSignature()) && !gen2.isAbstract()) { discoveredImpl = gen2; // Found a valid // implementation ! } } if (discoveredImpl == null) { // didnt find a valid implementation, lets check the // ITDs on this type to see if they satisfy it boolean satisfiedByITD = false; for (Iterator ii = newParentTarget.getType().getInterTypeMungersIncludingSupers().iterator(); ii.hasNext();) { ConcreteTypeMunger m = (ConcreteTypeMunger) ii.next(); if (m.getMunger() != null && m.getMunger().getKind() == ResolvedTypeMunger.Method) { ResolvedMember sig = m.getSignature(); if (!Modifier.isAbstract(sig.getModifiers())) { // If the ITD shares a type variable with // some target type, we need to tailor it // for that // type if (m.isTargetTypeParameterized()) { ResolvedType genericOnType = getWorld().resolve(sig.getDeclaringType()).getGenericType(); m = m.parameterizedFor(newParent.discoverActualOccurrenceOfTypeInHierarchy(genericOnType)); sig = m.getSignature(); // possible sig // change when // type // parameters // filled in } if (ResolvedType.matches(AjcMemberMaker.interMethod(sig, m.getAspectType(), sig .getDeclaringType().resolve(weaver.getWorld()).isInterface()), o)) { satisfiedByITD = true; } } } else if (m.getMunger() != null && m.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate2) { satisfiedByITD = true;// AV - that should be // enough, no need to // check more } } if (!satisfiedByITD) { error(weaver, "The type " + newParentTarget.getName() + " must implement the inherited abstract method " + o.getDeclaringType() + "." + o.getName() + o.getParameterSignature(), newParentTarget.getType().getSourceLocation(), new ISourceLocation[] { o.getSourceLocation(), mungerLoc }); ruleCheckingSucceeded = false; } } } } } return ruleCheckingSucceeded; } /** * Rule 2. Can't extend final types */ private boolean enforceDecpRule2_cantExtendFinalClass(BcelClassWeaver weaver, ISourceLocation mungerLoc, LazyClassGen newParentTarget, ResolvedType newParent) { if (newParent.isFinal()) { error(weaver, "Cannot make type " + newParentTarget.getName() + " extend final class " + newParent.getName(), newParentTarget.getType().getSourceLocation(), new ISourceLocation[] { mungerLoc }); return false; } return true; } /** * Rule 3. Can't narrow visibility of methods when overriding */ private boolean enforceDecpRule3_visibilityChanges(BcelClassWeaver weaver, ResolvedType newParent, ResolvedMember superMethod, LazyMethodGen subMethod) { boolean cont = true; if (superMethod.isPublic()) { if (subMethod.isProtected() || subMethod.isDefault() || subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage( MessageUtil.error("Cannot reduce the visibility of the inherited method '" + superMethod + "' from " + newParent.getName(), superMethod.getSourceLocation())); cont = false; } } else if (superMethod.isProtected()) { if (subMethod.isDefault() || subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage( MessageUtil.error("Cannot reduce the visibility of the inherited method '" + superMethod + "' from " + newParent.getName(), superMethod.getSourceLocation())); cont = false; } } else if (superMethod.isDefault()) { if (subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage( MessageUtil.error("Cannot reduce the visibility of the inherited method '" + superMethod + "' from " + newParent.getName(), superMethod.getSourceLocation())); cont = false; } } return cont; } /** * Rule 4. Can't have incompatible return types */ private boolean enforceDecpRule4_compatibleReturnTypes(BcelClassWeaver weaver, ResolvedMember superMethod, LazyMethodGen subMethod) { boolean cont = true; String superReturnTypeSig = superMethod.getGenericReturnType().getSignature(); // eg. Pjava/util/Collection<LFoo;> String subReturnTypeSig = subMethod.getGenericReturnTypeSignature(); superReturnTypeSig = superReturnTypeSig.replace('.', '/'); subReturnTypeSig = subReturnTypeSig.replace('.', '/'); if (!superReturnTypeSig.equals(subReturnTypeSig)) { // Check for covariance ResolvedType subType = weaver.getWorld().resolve(subMethod.getReturnType()); ResolvedType superType = weaver.getWorld().resolve(superMethod.getReturnType()); if (!superType.isAssignableFrom(subType)) { weaver.getWorld().getMessageHandler().handleMessage( MessageUtil.error("The return type is incompatible with " + superMethod.getDeclaringType() + "." + superMethod.getName() + superMethod.getParameterSignature(), subMethod.getSourceLocation())); // this just might be a better error message... // "The return type '"+subReturnTypeSig+ // "' is incompatible with the overridden method " // +superMethod.getDeclaringType()+"."+ // superMethod.getName()+superMethod.getParameterSignature()+ // " which returns '"+superReturnTypeSig+"'", cont = false; } } return cont; } /** * Rule5. Method overrides can't change the staticality (word?) - you can't override and make an instance method static or * override and make a static method an instance method. */ private boolean enforceDecpRule5_cantChangeFromStaticToNonstatic(BcelClassWeaver weaver, ISourceLocation mungerLoc, ResolvedMember superMethod, LazyMethodGen subMethod) { if (superMethod.isStatic() && !subMethod.isStatic()) { error(weaver, "This instance method " + subMethod.getName() + subMethod.getParameterSignature() + " cannot override the static method from " + superMethod.getDeclaringType().getName(), subMethod .getSourceLocation(), new ISourceLocation[] { mungerLoc }); return false; } else if (!superMethod.isStatic() && subMethod.isStatic()) { error(weaver, "The static method " + subMethod.getName() + subMethod.getParameterSignature() + " cannot hide the instance method from " + superMethod.getDeclaringType().getName(), subMethod .getSourceLocation(), new ISourceLocation[] { mungerLoc }); return false; } return true; } public void error(BcelClassWeaver weaver, String text, ISourceLocation primaryLoc, ISourceLocation[] extraLocs) { IMessage msg = new Message(text, primaryLoc, true, extraLocs); weaver.getWorld().getMessageHandler().handleMessage(msg); } /** * Search the specified type for a particular method - do not use the return value in the comparison as it is not considered for * overriding. */ private LazyMethodGen findMatchingMethod(LazyClassGen newParentTarget, ResolvedMember m) { LazyMethodGen found = null; List methodGens = newParentTarget.getMethodGens(); for (Iterator i = methodGens.iterator(); i.hasNext() && found == null;) { LazyMethodGen gen = (LazyMethodGen) i.next(); if (gen.getName().equals(m.getName()) && gen.getParameterSignature().equals(m.getParameterSignature())) { found = gen; } } return found; } /** * The main part of implementing declare parents extends. Modify super ctor calls to target the new type. */ public boolean attemptToModifySuperCalls(BcelClassWeaver weaver, LazyClassGen newParentTarget, ResolvedType newParent) { String currentParent = newParentTarget.getSuperClass().getName();// getName(); if (newParent.getGenericType() != null) newParent = newParent.getGenericType(); // target new super calls at // the generic type if its // raw or parameterized List mgs = newParentTarget.getMethodGens(); // Look for ctors to modify for (Iterator iter = mgs.iterator(); iter.hasNext();) { LazyMethodGen aMethod = (LazyMethodGen) iter.next(); if (aMethod.getName().equals("<init>")) { InstructionList insList = aMethod.getBody(); InstructionHandle handle = insList.getStart(); while (handle != null) { if (handle.getInstruction().opcode == Constants.INVOKESPECIAL) { ConstantPool cpg = newParentTarget.getConstantPool(); InvokeInstruction invokeSpecial = (InvokeInstruction) handle.getInstruction(); if (invokeSpecial.getClassName(cpg).equals(currentParent) && invokeSpecial.getMethodName(cpg).equals("<init>")) { // System.err.println( // "Transforming super call '<init>" // +sp.getSignature(cpg)+"'"); // 1. Check there is a ctor in the new parent with // the same signature ResolvedMember newCtor = getConstructorWithSignature(newParent, invokeSpecial.getSignature(cpg)); if (newCtor == null) { // 2. Check ITDCs to see if the necessary ctor // is provided that way boolean satisfiedByITDC = false; for (Iterator ii = newParentTarget.getType().getInterTypeMungersIncludingSupers().iterator(); ii .hasNext() && !satisfiedByITDC;) { ConcreteTypeMunger m = (ConcreteTypeMunger) ii.next(); if (m.getMunger() instanceof NewConstructorTypeMunger) { if (m.getSignature().getSignature().equals(invokeSpecial.getSignature(cpg))) { satisfiedByITDC = true; } } } if (!satisfiedByITDC) { String csig = createReadableCtorSig(newParent, cpg, invokeSpecial); weaver.getWorld().getMessageHandler().handleMessage( MessageUtil.error("Unable to modify hierarchy for " + newParentTarget.getClassName() + " - the constructor " + csig + " is missing", this.getSourceLocation())); return false; } } int idx = cpg.addMethodref(newParent.getName(), invokeSpecial.getMethodName(cpg), invokeSpecial .getSignature(cpg)); invokeSpecial.setIndex(idx); } } handle = handle.getNext(); } } } return true; } /** * Creates a nice signature for the ctor, something like "(int,Integer,String)" */ private String createReadableCtorSig(ResolvedType newParent, ConstantPool cpg, InvokeInstruction invokeSpecial) { StringBuffer sb = new StringBuffer(); Type[] ctorArgs = invokeSpecial.getArgumentTypes(cpg); sb.append(newParent.getClassName()); sb.append("("); for (int i = 0; i < ctorArgs.length; i++) { String argtype = ctorArgs[i].toString(); if (argtype.lastIndexOf(".") != -1) sb.append(argtype.substring(argtype.lastIndexOf(".") + 1)); else sb.append(argtype); if (i + 1 < ctorArgs.length) sb.append(","); } sb.append(")"); return sb.toString(); } private ResolvedMember getConstructorWithSignature(ResolvedType tx, String signature) { ResolvedMember[] mems = tx.getDeclaredJavaMethods(); for (int i = 0; i < mems.length; i++) { ResolvedMember rm = mems[i]; if (rm.getName().equals("<init>")) { if (rm.getSignature().equals(signature)) return rm; } } return null; } private boolean mungePrivilegedAccess(BcelClassWeaver weaver, PrivilegedAccessMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); ResolvedMember member = munger.getMember(); ResolvedType onType = weaver.getWorld().resolve(member.getDeclaringType(), munger.getSourceLocation()); if (onType.isRawType()) onType = onType.getGenericType(); // System.out.println("munging: " + gen + " with " + member); if (onType.equals(gen.getType())) { if (member.getKind() == Member.FIELD) { // System.out.println("matched: " + gen); addFieldGetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldGet(aspectType, member)); addFieldSetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldSet(aspectType, member)); return true; } else if (member.getKind() == Member.METHOD) { addMethodDispatch(gen, member, AjcMemberMaker.privilegedAccessMethodForMethod(aspectType, member)); return true; } else if (member.getKind() == Member.CONSTRUCTOR) { for (Iterator i = gen.getMethodGens().iterator(); i.hasNext();) { LazyMethodGen m = (LazyMethodGen) i.next(); if (m.getMemberView() != null && m.getMemberView().getKind() == Member.CONSTRUCTOR) { // m.getMemberView().equals(member)) { m.forcePublic(); // return true; } } return true; // throw new BCException("no match for " + member + " in " + // gen); } else if (member.getKind() == Member.STATIC_INITIALIZATION) { gen.forcePublic(); return true; } else { throw new RuntimeException("unimplemented"); } } return false; } private void addFieldGetter(LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); if (field.isStatic()) { il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()), Constants.GETSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()), Constants.GETFIELD)); } il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(field.getType()))); mg.getBody().insert(il); gen.addMethodGen(mg, getSignature().getSourceLocation()); } private void addFieldSetter(LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); Type fieldType = BcelWorld.makeBcelType(field.getType()); if (field.isStatic()) { il.append(InstructionFactory.createLoad(fieldType, 0)); il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), fieldType, Constants.PUTSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(InstructionFactory.createLoad(fieldType, 1)); il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), fieldType, Constants.PUTFIELD)); } il.append(InstructionFactory.createReturn(Type.VOID)); mg.getBody().insert(il); gen.addMethodGen(mg, getSignature().getSourceLocation()); } private void addMethodDispatch(LazyClassGen gen, ResolvedMember method, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); // Type fieldType = BcelWorld.makeBcelType(field.getType()); Type[] paramTypes = BcelWorld.makeBcelTypes(method.getParameterTypes()); int pos = 0; if (!method.isStatic()) { il.append(InstructionConstants.ALOAD_0); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; il.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } il.append(Utility.createInvoke(fact, (BcelWorld) aspectType.getWorld(), method)); il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(method.getReturnType()))); mg.getBody().insert(il); gen.addMethodGen(mg); } protected LazyMethodGen makeMethodGen(LazyClassGen gen, ResolvedMember member) { LazyMethodGen ret = new LazyMethodGen(member.getModifiers(), BcelWorld.makeBcelType(member.getReturnType()), member .getName(), BcelWorld.makeBcelTypes(member.getParameterTypes()), UnresolvedType.getNames(member.getExceptions()), gen); // 43972 : Static crosscutting makes interfaces unusable for javac // ret.makeSynthetic(); return ret; } protected FieldGen makeFieldGen(LazyClassGen gen, ResolvedMember member) { return new FieldGen(member.getModifiers(), BcelWorld.makeBcelType(member.getReturnType()), member.getName(), gen .getConstantPool()); } private boolean mungePerObjectInterface(BcelClassWeaver weaver, PerObjectInterfaceTypeMunger munger) { // System.err.println("Munging perobject ["+munger+"] onto "+weaver. // getLazyClassGen().getClassName()); LazyClassGen gen = weaver.getLazyClassGen(); if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) { FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perObjectField(gen.getType(), aspectType)); gen.addField(fg, getSourceLocation()); Type fieldType = BcelWorld.makeBcelType(aspectType); LazyMethodGen mg = new LazyMethodGen(Modifier.PUBLIC, fieldType, NameMangler.perObjectInterfaceGet(aspectType), new Type[0], new String[0], gen); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD)); il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); LazyMethodGen mg1 = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, NameMangler.perObjectInterfaceSet(aspectType), new Type[] { fieldType, }, new String[0], gen); InstructionList il1 = new InstructionList(); il1.append(InstructionConstants.ALOAD_0); il1.append(InstructionFactory.createLoad(fieldType, 1)); il1.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD)); il1.append(InstructionFactory.createReturn(Type.VOID)); mg1.getBody().insert(il1); gen.addMethodGen(mg1); gen.addInterface(munger.getInterfaceType().resolve(weaver.getWorld()), getSourceLocation()); return true; } else { return false; } } // PTWIMPL Add field to hold aspect instance and an accessor private boolean mungePerTypeWithinTransformer(BcelClassWeaver weaver) { LazyClassGen gen = weaver.getLazyClassGen(); // if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) { // Add (to the target type) the field that will hold the aspect instance // e.g ajc$com_blah_SecurityAspect$ptwAspectInstance FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perTypeWithinField(gen.getType(), aspectType)); gen.addField(fg, getSourceLocation()); // Add an accessor for this new field, the // ajc$<aspectname>$localAspectOf() method // e.g. // "public com_blah_SecurityAspect ajc$com_blah_SecurityAspect$localAspectOf()" Type fieldType = BcelWorld.makeBcelType(aspectType); LazyMethodGen mg = new LazyMethodGen(Modifier.PUBLIC | Modifier.STATIC, fieldType, NameMangler .perTypeWithinLocalAspectOf(aspectType), new Type[0], new String[0], gen); InstructionList il = new InstructionList(); // PTWIMPL ?? Should check if it is null and throw // NoAspectBoundException InstructionFactory fact = gen.getFactory(); il.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.GETSTATIC)); il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); return true; // } else { // return false; // } } // ??? Why do we have this method? I thought by now we would know if it // matched or not private boolean couldMatch(BcelObjectType bcelObjectType, Pointcut pointcut) { return !bcelObjectType.isInterface(); } private boolean mungeNewMethod(BcelClassWeaver weaver, NewMethodTypeMunger munger) { World w = weaver.getWorld(); // Resolving it will sort out the tvars ResolvedMember unMangledInterMethod = munger.getSignature().resolve(w); // do matching on the unMangled one, but actually add them to the // mangled method ResolvedMember interMethodBody = munger.getDeclaredInterMethodBody(aspectType, w); ResolvedMember interMethodDispatcher = munger.getDeclaredInterMethodDispatcher(aspectType, w); ResolvedMember memberHoldingAnyAnnotations = interMethodDispatcher; ResolvedType onType = weaver.getWorld().resolve(unMangledInterMethod.getDeclaringType(), munger.getSourceLocation()); LazyClassGen gen = weaver.getLazyClassGen(); boolean mungingInterface = gen.isInterface(); if (onType.isRawType()) onType = onType.getGenericType(); boolean onInterface = onType.isInterface(); // Simple checks, can't ITD on annotations or enums if (onType.isAnnotation()) { signalError(WeaverMessages.ITDM_ON_ANNOTATION_NOT_ALLOWED, weaver, onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDM_ON_ENUM_NOT_ALLOWED, weaver, onType); return false; } if (onInterface && gen.getLazyMethodGen(unMangledInterMethod.getName(), unMangledInterMethod.getSignature(), true) != null) { // this is ok, we could be providing the default implementation of a // method // that the target has already declared return false; } // If we are processing the intended ITD target type (might be an // interface) if (onType.equals(gen.getType())) { ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, onInterface); LazyMethodGen newMethod = makeMethodGen(gen, mangledInterMethod); if (mungingInterface) { // we want the modifiers of the ITD to be used for all // *implementors* of the // interface, but the method itself we add to the interface must // be public abstract newMethod.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT); } // pr98901 // For copying the annotations across, we have to discover the real // member in the aspect which is holding them. if (weaver.getWorld().isInJava5Mode()) { AnnotationAJ annotationsOnRealMember[] = null; ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) toLookOn = aspectType.getGenericType(); ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn, memberHoldingAnyAnnotations, false); if (realMember == null) throw new BCException("Couldn't find ITD holder member '" + memberHoldingAnyAnnotations + "' on aspect " + aspectType); annotationsOnRealMember = realMember.getAnnotations(); if (annotationsOnRealMember != null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationAJ annotationX = annotationsOnRealMember[i]; AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); newMethod.addAnnotation(new BcelAnnotation(ag, weaver.getWorld())); } } AnnotationAJ[][] pAnnos = realMember.getParameterAnnotations(); int offset = newMethod.isStatic() ? 0 : 1; if (pAnnos != null && pAnnos.length != 0) { int param = 0; for (int i = offset; i < pAnnos.length; i++) { AnnotationAJ[] annosOnParam = pAnnos[i]; if (annosOnParam != null && annosOnParam.length > 0) { for (int j = 0; j < annosOnParam.length; j++) { newMethod.addParameterAnnotation(param, annosOnParam[j]); } } param++; } } // the below loop fixes the very special (and very stupid) // case where an aspect declares an annotation // on an ITD it declared on itself. List allDecams = weaver.getWorld().getDeclareAnnotationOnMethods(); for (Iterator i = allDecams.iterator(); i.hasNext();) { DeclareAnnotation decaMC = (DeclareAnnotation) i.next(); if (decaMC.matches(unMangledInterMethod, weaver.getWorld()) && newMethod.getEnclosingClass().getType() == aspectType) { newMethod.addAnnotation(decaMC.getAnnotationX()); } } } // If it doesn't target an interface and there is a body (i.e. it // isnt abstract) if (!onInterface && !Modifier.isAbstract(mangledInterMethod.getModifiers())) { InstructionList body = newMethod.getBody(); InstructionFactory fact = gen.getFactory(); int pos = 0; if (!unMangledInterMethod.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes()); for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), interMethodBody)); body.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(mangledInterMethod.getReturnType()))); if (weaver.getWorld().isInJava5Mode()) { // Don't need bridge // methods if not in // 1.5 mode. createAnyBridgeMethodsForCovariance(weaver, munger, unMangledInterMethod, onType, gen, paramTypes); } } else { // ??? this is okay // if (!(mg.getBody() == null)) throw new // RuntimeException("bas"); } if (weaver.getWorld().isInJava5Mode()) { String basicSignature = mangledInterMethod.getSignature(); String genericSignature = ((ResolvedMemberImpl) mangledInterMethod).getSignatureForAttribute(); if (!basicSignature.equals(genericSignature)) { // Add a signature attribute to it newMethod.addAttribute(createSignatureAttribute(gen.getConstantPool(), genericSignature)); } } // XXX make sure to check that we set exceptions properly on this // guy. weaver.addLazyMethodGen(newMethod); weaver.getLazyClassGen().warnOnAddedMethod(newMethod.getMethod(), getSignature().getSourceLocation()); addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled()); return true; } else if (onInterface && !Modifier.isAbstract(unMangledInterMethod.getModifiers())) { // This means the 'gen' should be the top most implementor // - if it is *not* then something went wrong after we worked // out that it was the top most implementor (see pr49657) if (!gen.getType().isTopmostImplementor(onType)) { ResolvedType rtx = gen.getType().getTopmostImplementor(onType); if (!rtx.isExposedToWeaver()) { ISourceLocation sLoc = munger.getSourceLocation(); weaver.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_NON_EXPOSED_IMPLEMENTOR, rtx, getAspectType().getName()), (sLoc == null ? getAspectType().getSourceLocation() : sLoc))); } else { // XXX what does this state mean? // We have incorrectly identified what is the top most // implementor and its not because // a type wasn't exposed to the weaver } return false; } else { ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, false); LazyMethodGen mg = makeMethodGen(gen, mangledInterMethod); // From 98901#29 - need to copy annotations across if (weaver.getWorld().isInJava5Mode()) { AnnotationAJ annotationsOnRealMember[] = null; ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) toLookOn = aspectType.getGenericType(); ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn, memberHoldingAnyAnnotations, false); if (realMember == null) throw new BCException("Couldn't find ITD holder member '" + memberHoldingAnyAnnotations + "' on aspect " + aspectType); annotationsOnRealMember = realMember.getAnnotations(); if (annotationsOnRealMember != null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationAJ annotationX = annotationsOnRealMember[i]; AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); mg.addAnnotation(new BcelAnnotation(ag, weaver.getWorld())); } } AnnotationAJ[][] pAnnos = realMember.getParameterAnnotations(); int offset = mg.isStatic() ? 0 : 1; if (pAnnos != null && pAnnos.length != 0) { int param = 0; for (int i = offset; i < pAnnos.length; i++) { AnnotationAJ[] annosOnParam = pAnnos[i]; if (annosOnParam != null && annosOnParam.length > 0) { for (int j = 0; j < annosOnParam.length; j++) { mg.addParameterAnnotation(param, annosOnParam[j]); } } param++; } } } if (mungingInterface) { // we want the modifiers of the ITD to be used for all // *implementors* of the // interface, but the method itself we add to the interface // must be public abstract mg.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT); } Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(mangledInterMethod.getReturnType()); InstructionList body = mg.getBody(); InstructionFactory fact = gen.getFactory(); int pos = 0; if (!mangledInterMethod.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), interMethodBody)); Type t = BcelWorld.makeBcelType(interMethodBody.getReturnType()); if (!t.equals(returnType)) { body.append(fact.createCast(t, returnType)); } body.append(InstructionFactory.createReturn(returnType)); mg.definingType = onType; if (weaver.getWorld().isInJava5Mode()) { String basicSignature = mangledInterMethod.getSignature(); String genericSignature = ((ResolvedMemberImpl) mangledInterMethod).getSignatureForAttribute(); if (!basicSignature.equals(genericSignature)) { // Add a signature attribute to it mg.addAttribute(createSignatureAttribute(gen.getConstantPool(), genericSignature)); } } weaver.addOrReplaceLazyMethodGen(mg); addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled()); // Work out if we need a bridge method for the new method added // to the topmostimplementor. if (munger.getDeclaredSignature() != null) { // Check if the // munger being // processed is // a // parameterized // form of some // original // munger. boolean needsbridging = false; ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null, munger.getSignature().getDeclaringType().resolve(getWorld()), false, munger.getTypeVariableAliases()); if (!toBridgeTo.getReturnType().getErasureSignature().equals( munger.getSignature().getReturnType().getErasureSignature())) needsbridging = true; UnresolvedType[] originalParams = toBridgeTo.getParameterTypes(); UnresolvedType[] newParams = munger.getSignature().getParameterTypes(); for (int ii = 0; ii < originalParams.length; ii++) { if (!originalParams[ii].getErasureSignature().equals(newParams[ii].getErasureSignature())) needsbridging = true; } if (needsbridging) { ResolvedMember bridgerMethod = AjcMemberMaker.bridgerToInterMethod(unMangledInterMethod, gen.getType()); ResolvedMember bridgingSetter = AjcMemberMaker.interMethodBridger(toBridgeTo, aspectType, false); // pr250493 // FIXME asc ----------------8<---------------- extract // method LazyMethodGen bridgeMethod = makeMethodGen(gen, bridgingSetter); paramTypes = BcelWorld.makeBcelTypes(bridgingSetter.getParameterTypes()); Type[] bridgingToParms = BcelWorld.makeBcelTypes(unMangledInterMethod.getParameterTypes()); returnType = BcelWorld.makeBcelType(bridgingSetter.getReturnType()); body = bridgeMethod.getBody(); fact = gen.getFactory(); pos = 0; if (!bridgingSetter.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals( unMangledInterMethod.getParameterTypes()[i].getErasureSignature())) { // System.err.println("Putting in cast from "+ // paramType+" to "+bridgingToParms[i]); body.append(fact.createCast(paramType, bridgingToParms[i])); } pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), bridgerMethod)); body.append(InstructionFactory.createReturn(returnType)); gen.addMethodGen(bridgeMethod); // mg.definingType = onType; // FIXME asc (see above) // ---------------------8<--------------- extract method } } return true; } } else { return false; } } /** * Helper method to create a signature attribute based on a string signature: e.g. "Ljava/lang/Object;LI<Ljava/lang/Double;>;" */ private Signature createSignatureAttribute(ConstantPool cp, String signature) { int nameIndex = cp.addUtf8("Signature"); int sigIndex = cp.addUtf8(signature); return new Signature(nameIndex, 2, sigIndex, cp); } /** * Create any bridge method required because of covariant returns being used. This method is used in the case where an ITD is * applied to some type and it may be in an override relationship with a method from the supertype - but due to covariance there * is a mismatch in return values. Example of when required: Super defines: Object m(String s) Sub defines: String m(String s) * then we need a bridge method in Sub called 'Object m(String s)' that forwards to 'String m(String s)' */ private void createAnyBridgeMethodsForCovariance(BcelClassWeaver weaver, NewMethodTypeMunger munger, ResolvedMember unMangledInterMethod, ResolvedType onType, LazyClassGen gen, Type[] paramTypes) { // PERFORMANCE BOTTLENECK? Might need investigating, method analysis // between types in a hierarchy just seems expensive... // COVARIANCE BRIDGING // Algorithm: Step1. Check in this type - has someone already created // the bridge method? // Step2. Look above us - do we 'override' a method and yet differ in // return type (i.e. covariance) // Step3. Create a forwarding bridge method // ResolvedType superclass = onType.getSuperclass(); boolean quitRightNow = false; String localMethodName = unMangledInterMethod.getName(); String localParameterSig = unMangledInterMethod.getParameterSignature(); String localReturnTypeESig = unMangledInterMethod.getReturnType().getErasureSignature(); // Step1 boolean alreadyDone = false; // Compiler might have done it ResolvedMember[] localMethods = onType.getDeclaredMethods(); for (int i = 0; i < localMethods.length; i++) { ResolvedMember member = localMethods[i]; if (member.getName().equals(localMethodName)) { // Check the params if (member.getParameterSignature().equals(localParameterSig)) alreadyDone = true; } } // Step2 if (!alreadyDone) { // Use the iterator form of 'getMethods()' so we do as little work // as necessary for (Iterator iter = onType.getSuperclass().getMethods(); iter.hasNext() && !quitRightNow;) { ResolvedMember aMethod = (ResolvedMember) iter.next(); if (aMethod.getName().equals(localMethodName) && aMethod.getParameterSignature().equals(localParameterSig)) { // check the return types, if they are different we need a // bridging method. if (!aMethod.getReturnType().getErasureSignature().equals(localReturnTypeESig) && !Modifier.isPrivate(aMethod.getModifiers())) { // Step3 createBridgeMethod(weaver.getWorld(), munger, unMangledInterMethod, gen, paramTypes, aMethod); quitRightNow = true; } } } } } /** * Create a bridge method for a particular munger. * * @param world * @param munger * @param unMangledInterMethod the method to bridge 'to' that we have already created in the 'subtype' * @param clazz the class in which to put the bridge method * @param paramTypes Parameter types for the bridge method, passed in as an optimization since the caller is likely to have * already created them. * @param theBridgeMethod */ private void createBridgeMethod(BcelWorld world, NewMethodTypeMunger munger, ResolvedMember unMangledInterMethod, LazyClassGen clazz, Type[] paramTypes, ResolvedMember theBridgeMethod) { InstructionList body; InstructionFactory fact; int pos = 0; LazyMethodGen bridgeMethod = makeMethodGen(clazz, theBridgeMethod); // The // bridge // method // in // this // type // will // have // the // same // signature // as // the // one // in // the // supertype bridgeMethod.setAccessFlags(bridgeMethod.getAccessFlags() | 0x00000040 /* * BRIDGE = 0x00000040 */); // UnresolvedType[] newParams = // munger.getSignature().getParameterTypes(); Type returnType = BcelWorld.makeBcelType(theBridgeMethod.getReturnType()); body = bridgeMethod.getBody(); fact = clazz.getFactory(); if (!unMangledInterMethod.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); // if (!bridgingSetter.getParameterTypes()[i].getErasureSignature(). // equals // (unMangledInterMethod.getParameterTypes()[i].getErasureSignature // ())) { // System.err.println("Putting in cast from "+paramType+" to "+ // bridgingToParms[i]); // body.append(fact.createCast(paramType,bridgingToParms[i])); // } pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, world, unMangledInterMethod)); body.append(InstructionFactory.createReturn(returnType)); clazz.addMethodGen(bridgeMethod); } // Unlike toString() on a member, this does not include the declaring type private String stringifyMember(ResolvedMember member) { StringBuffer buf = new StringBuffer(); buf.append(member.getReturnType().getName()); buf.append(' '); buf.append(member.getName()); if (member.getKind() != Member.FIELD) { buf.append("("); UnresolvedType[] params = member.getParameterTypes(); if (params.length != 0) { buf.append(params[0]); for (int i = 1, len = params.length; i < len; i++) { buf.append(", "); buf.append(params[i].getName()); } } buf.append(")"); } return buf.toString(); } private boolean mungeMethodDelegate(BcelClassWeaver weaver, MethodDelegateTypeMunger munger) { ResolvedMember introduced = munger.getSignature(); LazyClassGen gen = weaver.getLazyClassGen(); ResolvedType fromType = weaver.getWorld().resolve(introduced.getDeclaringType(), munger.getSourceLocation()); if (fromType.isRawType()) fromType = fromType.getGenericType(); if (gen.getType().isAnnotation() || gen.getType().isEnum()) { // don't signal error as it could be a consequence of a wild type // pattern return false; } boolean shouldApply = munger.matches(weaver.getLazyClassGen().getType(), aspectType); if (shouldApply) { // If no implementation class was specified, the intention was that // the types matching the pattern // already implemented the interface, let's check that now! if (munger.getImplClassName() == null) { boolean isOK = false; List/* LazyMethodGen */existingMethods = gen.getMethodGens(); for (Iterator i = existingMethods.iterator(); i.hasNext() && !isOK;) { LazyMethodGen m = (LazyMethodGen) i.next(); if (m.getName().equals(introduced.getName()) && m.getParameterSignature().equals(introduced.getParameterSignature()) && m.getReturnType().equals(introduced.getReturnType())) { isOK = true; } } if (!isOK) { // the class does not implement this method, they needed to // supply a default impl class IMessage msg = new Message("@DeclareParents: No defaultImpl was specified but the type '" + gen.getName() + "' does not implement the method '" + stringifyMember(introduced) + "' defined on the interface '" + introduced.getDeclaringType() + "'", weaver.getLazyClassGen().getType().getSourceLocation(), true, new ISourceLocation[] { munger.getSourceLocation() }); weaver.getWorld().getMessageHandler().handleMessage(msg); return false; } return true; } LazyMethodGen mg = new LazyMethodGen(introduced.getModifiers() - Modifier.ABSTRACT, BcelWorld.makeBcelType(introduced .getReturnType()), introduced.getName(), BcelWorld.makeBcelTypes(introduced.getParameterTypes()), BcelWorld .makeBcelTypesAsClassNames(introduced.getExceptions()), gen); // annotation copy from annotation on ITD interface if (weaver.getWorld().isInJava5Mode()) { AnnotationAJ annotationsOnRealMember[] = null; ResolvedType toLookOn = weaver.getWorld().lookupOrCreateName(introduced.getDeclaringType()); if (fromType.isRawType()) toLookOn = fromType.getGenericType(); // lookup the method ResolvedMember[] ms = toLookOn.getDeclaredJavaMethods(); for (int i = 0; i < ms.length; i++) { ResolvedMember m = ms[i]; if (introduced.getName().equals(m.getName()) && introduced.getSignature().equals(m.getSignature())) { annotationsOnRealMember = m.getAnnotations(); } } if (annotationsOnRealMember != null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationAJ annotationX = annotationsOnRealMember[i]; AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); mg.addAnnotation(new BcelAnnotation(ag, weaver.getWorld())); } } } InstructionList body = new InstructionList(); InstructionFactory fact = gen.getFactory(); // getfield body.append(InstructionConstants.ALOAD_0); body.append(Utility.createGet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); InstructionBranch ifNonNull = InstructionFactory.createBranchInstruction(Constants.IFNONNULL, null); body.append(ifNonNull); // Create and store a new instance body.append(InstructionConstants.ALOAD_0); body.append(fact.createNew(munger.getImplClassName())); body.append(InstructionConstants.DUP); body.append(fact.createInvoke(munger.getImplClassName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL)); body.append(Utility.createSet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); // if not null use the instance we've got InstructionHandle ifNonNullElse = body.append(InstructionConstants.ALOAD_0); ifNonNull.setTarget(ifNonNullElse); body.append(Utility.createGet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); // args int pos = 0; if (!introduced.isStatic()) { // skip 'this' (?? can this really // happen) // body.append(InstructionFactory.createThis()); pos++; } Type[] paramTypes = BcelWorld.makeBcelTypes(introduced.getParameterTypes()); for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, Constants.INVOKEINTERFACE, introduced)); body.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(introduced.getReturnType()))); mg.getBody().append(body); weaver.addLazyMethodGen(mg); weaver.getLazyClassGen().warnOnAddedMethod(mg.getMethod(), getSignature().getSourceLocation()); return true; } return false; } private boolean mungeFieldHost(BcelClassWeaver weaver, MethodDelegateTypeMunger.FieldHostTypeMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); if (gen.getType().isAnnotation() || gen.getType().isEnum()) { // don't signal error as it could be a consequence of a wild type // pattern return false; } // boolean shouldApply = munger.matches(weaver.getLazyClassGen().getType(), aspectType); // why // do // this? ResolvedMember host = AjcMemberMaker.itdAtDeclareParentsField(weaver.getLazyClassGen().getType(), munger.getSignature() .getType(), aspectType); weaver.getLazyClassGen().addField(makeFieldGen(weaver.getLazyClassGen(), host), null); return true; } private ResolvedMember getRealMemberForITDFromAspect(ResolvedType aspectType, ResolvedMember lookingFor, boolean isCtorRelated) { World world = aspectType.getWorld(); boolean debug = false; if (debug) { System.err.println("Searching for a member on type: " + aspectType); System.err.println("Member we are looking for: " + lookingFor); } ResolvedMember aspectMethods[] = aspectType.getDeclaredMethods(); UnresolvedType[] lookingForParams = lookingFor.getParameterTypes(); ResolvedMember realMember = null; for (int i = 0; realMember == null && i < aspectMethods.length; i++) { ResolvedMember member = aspectMethods[i]; if (member.getName().equals(lookingFor.getName())) { UnresolvedType[] memberParams = member.getGenericParameterTypes(); if (memberParams.length == lookingForParams.length) { if (debug) System.err.println("Reviewing potential candidates: " + member); boolean matchOK = true; // If not related to a ctor ITD then the name is enough to // confirm we have the // right one. If it is ctor related we need to check the // params all match, although // only the erasure. if (isCtorRelated) { for (int j = 0; j < memberParams.length && matchOK; j++) { ResolvedType pMember = memberParams[j].resolve(world); ResolvedType pLookingFor = lookingForParams[j].resolve(world); if (pMember.isTypeVariableReference()) pMember = ((TypeVariableReference) pMember).getTypeVariable().getFirstBound().resolve(world); if (pMember.isParameterizedType() || pMember.isGenericType()) pMember = pMember.getRawType().resolve(aspectType.getWorld()); if (pLookingFor.isTypeVariableReference()) pLookingFor = ((TypeVariableReference) pLookingFor).getTypeVariable().getFirstBound() .resolve(world); if (pLookingFor.isParameterizedType() || pLookingFor.isGenericType()) pLookingFor = pLookingFor.getRawType().resolve(world); if (debug) System.err.println("Comparing parameter " + j + " member=" + pMember + " lookingFor=" + pLookingFor); if (!pMember.equals(pLookingFor)) { matchOK = false; } } } if (matchOK) realMember = member; } } } if (debug && realMember == null) System.err.println("Didn't find a match"); return realMember; } private void addNeededSuperCallMethods(BcelClassWeaver weaver, ResolvedType onType, Set neededSuperCalls) { LazyClassGen gen = weaver.getLazyClassGen(); for (Iterator iter = neededSuperCalls.iterator(); iter.hasNext();) { ResolvedMember superMethod = (ResolvedMember) iter.next(); if (weaver.addDispatchTarget(superMethod)) { // System.err.println("super type: " + // superMethod.getDeclaringType() + ", " + gen.getType()); boolean isSuper = !superMethod.getDeclaringType().equals(gen.getType()); String dispatchName; if (isSuper) dispatchName = NameMangler.superDispatchMethod(onType, superMethod.getName()); else dispatchName = NameMangler.protectedDispatchMethod(onType, superMethod.getName()); superMethod = superMethod.resolve(weaver.getWorld()); LazyMethodGen dispatcher = makeDispatcher(gen, dispatchName, superMethod, weaver.getWorld(), isSuper); weaver.addLazyMethodGen(dispatcher); } } } private void signalError(String msgid, BcelClassWeaver weaver, UnresolvedType onType) { IMessage msg = MessageUtil.error(WeaverMessages.format(msgid, onType.getName()), getSourceLocation()); weaver.getWorld().getMessageHandler().handleMessage(msg); } private boolean mungeNewConstructor(BcelClassWeaver weaver, NewConstructorTypeMunger newConstructorTypeMunger) { final LazyClassGen currentClass = weaver.getLazyClassGen(); final InstructionFactory fact = currentClass.getFactory(); ResolvedMember newConstructorMember = newConstructorTypeMunger.getSyntheticConstructor(); ResolvedType onType = newConstructorMember.getDeclaringType().resolve(weaver.getWorld()); if (onType.isRawType()) onType = onType.getGenericType(); if (onType.isAnnotation()) { signalError(WeaverMessages.ITDC_ON_ANNOTATION_NOT_ALLOWED, weaver, onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDC_ON_ENUM_NOT_ALLOWED, weaver, onType); return false; } if (!onType.equals(currentClass.getType())) return false; ResolvedMember explicitConstructor = newConstructorTypeMunger.getExplicitConstructor(); // int declaredParameterCount = // newConstructorTypeMunger.getDeclaredParameterCount(); LazyMethodGen mg = makeMethodGen(currentClass, newConstructorMember); mg.setEffectiveSignature(newConstructorTypeMunger.getSignature(), Shadow.ConstructorExecution, true); // pr98901 // For copying the annotations across, we have to discover the real // member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()) { ResolvedMember interMethodDispatcher = AjcMemberMaker.postIntroducedConstructor(aspectType, onType, newConstructorTypeMunger.getSignature().getParameterTypes()); AnnotationAJ annotationsOnRealMember[] = null; ResolvedMember realMember = getRealMemberForITDFromAspect(aspectType, interMethodDispatcher, true); if (realMember == null) throw new BCException("Couldn't find ITD holder member '" + interMethodDispatcher + "' on aspect " + aspectType); annotationsOnRealMember = realMember.getAnnotations(); if (annotationsOnRealMember != null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationAJ annotationX = annotationsOnRealMember[i]; AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); mg.addAnnotation(new BcelAnnotation(ag, weaver.getWorld())); } } // the below loop fixes the very special (and very stupid) // case where an aspect declares an annotation // on an ITD it declared on itself. List allDecams = weaver.getWorld().getDeclareAnnotationOnMethods(); for (Iterator i = allDecams.iterator(); i.hasNext();) { DeclareAnnotation decaMC = (DeclareAnnotation) i.next(); if (decaMC.matches(explicitConstructor, weaver.getWorld()) && mg.getEnclosingClass().getType() == aspectType) { mg.addAnnotation(decaMC.getAnnotationX()); } } } currentClass.addMethodGen(mg); // weaver.addLazyMethodGen(freshConstructor); InstructionList body = mg.getBody(); // add to body: push arts for call to pre, from actual args starting at // 1 (skipping this), going to // declared argcount + 1 UnresolvedType[] declaredParams = newConstructorTypeMunger.getSignature().getParameterTypes(); Type[] paramTypes = mg.getArgumentTypes(); int frameIndex = 1; for (int i = 0, len = declaredParams.length; i < len; i++) { body.append(InstructionFactory.createLoad(paramTypes[i], frameIndex)); frameIndex += paramTypes[i].getSize(); } // do call to pre Member preMethod = AjcMemberMaker.preIntroducedConstructor(aspectType, onType, declaredParams); body.append(Utility.createInvoke(fact, null, preMethod)); // create a local, and store return pre stuff into it. int arraySlot = mg.allocateLocal(1); body.append(InstructionFactory.createStore(Type.OBJECT, arraySlot)); // put this on the stack body.append(InstructionConstants.ALOAD_0); // unpack pre args onto stack UnresolvedType[] superParamTypes = explicitConstructor.getParameterTypes(); for (int i = 0, len = superParamTypes.length; i < len; i++) { body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot)); body.append(Utility.createConstant(fact, i)); body.append(InstructionFactory.createArrayLoad(Type.OBJECT)); body.append(Utility.createConversion(fact, Type.OBJECT, BcelWorld.makeBcelType(superParamTypes[i]))); } // call super/this body.append(Utility.createInvoke(fact, null, explicitConstructor)); // put this back on the stack body.append(InstructionConstants.ALOAD_0); // unpack params onto stack Member postMethod = AjcMemberMaker.postIntroducedConstructor(aspectType, onType, declaredParams); UnresolvedType[] postParamTypes = postMethod.getParameterTypes(); for (int i = 1, len = postParamTypes.length; i < len; i++) { body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot)); body.append(Utility.createConstant(fact, superParamTypes.length + i - 1)); body.append(InstructionFactory.createArrayLoad(Type.OBJECT)); body.append(Utility.createConversion(fact, Type.OBJECT, BcelWorld.makeBcelType(postParamTypes[i]))); } // call post body.append(Utility.createInvoke(fact, null, postMethod)); // don't forget to return!! body.append(InstructionConstants.RETURN); return true; } private static LazyMethodGen makeDispatcher(LazyClassGen onGen, String dispatchName, ResolvedMember superMethod, BcelWorld world, boolean isSuper) { Type[] paramTypes = BcelWorld.makeBcelTypes(superMethod.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(superMethod.getReturnType()); int modifiers = Modifier.PUBLIC; if (onGen.isInterface()) modifiers |= Modifier.ABSTRACT; LazyMethodGen mg = new LazyMethodGen(modifiers, returnType, dispatchName, paramTypes, UnresolvedType.getNames(superMethod .getExceptions()), onGen); InstructionList body = mg.getBody(); if (onGen.isInterface()) return mg; // assert (!superMethod.isStatic()) InstructionFactory fact = onGen.getFactory(); int pos = 0; body.append(InstructionFactory.createThis()); pos++; for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } if (isSuper) { body.append(Utility.createSuperInvoke(fact, world, superMethod)); } else { body.append(Utility.createInvoke(fact, world, superMethod)); } body.append(InstructionFactory.createReturn(returnType)); return mg; } private boolean mungeNewField(BcelClassWeaver weaver, NewFieldTypeMunger munger) { /* ResolvedMember initMethod = */munger.getInitMethod(aspectType); LazyClassGen gen = weaver.getLazyClassGen(); ResolvedMember field = munger.getSignature(); ResolvedType onType = weaver.getWorld().resolve(field.getDeclaringType(), munger.getSourceLocation()); if (onType.isRawType()) onType = onType.getGenericType(); boolean onInterface = onType.isInterface(); if (onType.isAnnotation()) { signalError(WeaverMessages.ITDF_ON_ANNOTATION_NOT_ALLOWED, weaver, onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDF_ON_ENUM_NOT_ALLOWED, weaver, onType); return false; } ResolvedMember interMethodBody = munger.getInitMethod(aspectType); AnnotationAJ annotationsOnRealMember[] = null; // pr98901 // For copying the annotations across, we have to discover the real // member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()) { // the below line just gets the method with the same name in // aspectType.getDeclaredMethods(); ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) toLookOn = aspectType.getGenericType(); ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn, interMethodBody, false); if (realMember == null) throw new BCException("Couldn't find ITD init member '" + interMethodBody + "' on aspect " + aspectType); annotationsOnRealMember = realMember.getAnnotations(); } if (onType.equals(gen.getType())) { if (onInterface) { ResolvedMember itdfieldGetter = AjcMemberMaker.interFieldInterfaceGetter(field, onType, aspectType); LazyMethodGen mg = makeMethodGen(gen, itdfieldGetter); gen.addMethodGen(mg); LazyMethodGen mg1 = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceSetter(field, onType, aspectType)); gen.addMethodGen(mg1); } else { weaver.addInitializer(this); FieldGen fg = makeFieldGen(gen, AjcMemberMaker.interFieldClassField(field, aspectType)); if (annotationsOnRealMember != null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationAJ annotationX = annotationsOnRealMember[i]; AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); fg.addAnnotation(ag); } } if (weaver.getWorld().isInJava5Mode()) { String basicSignature = field.getSignature(); String genericSignature = field.getReturnType().resolve(weaver.getWorld()).getSignatureForAttribute(); // String genericSignature = // ((ResolvedMemberImpl)field).getSignatureForAttribute(); if (!basicSignature.equals(genericSignature)) { // Add a signature attribute to it fg.addAttribute(createSignatureAttribute(gen.getConstantPool(), genericSignature)); } } gen.addField(fg, getSourceLocation()); } return true; } else if (onInterface && gen.getType().isTopmostImplementor(onType)) { // wew know that we can't be static since we don't allow statics on // interfaces if (field.isStatic()) throw new RuntimeException("unimplemented"); weaver.addInitializer(this); // System.err.println("impl body on " + gen.getType() + " for " + // munger); Type fieldType = BcelWorld.makeBcelType(field.getType()); FieldGen fg = makeFieldGen(gen, AjcMemberMaker.interFieldInterfaceField(field, onType, aspectType)); if (annotationsOnRealMember != null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationAJ annotationX = annotationsOnRealMember[i]; AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); fg.addAnnotation(ag); } } gen.addField(fg, getSourceLocation()); // this uses a shadow munger to add init method to constructors // weaver.getShadowMungers().add(makeInitCallShadowMunger(initMethod) // ); ResolvedMember itdfieldGetter = AjcMemberMaker.interFieldInterfaceGetter(field, gen.getType()/* onType */, aspectType); LazyMethodGen mg = makeMethodGen(gen, itdfieldGetter); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); if (field.isStatic()) { il.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.GETSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD)); } il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); // Check if we need bridge methods for the field getter and setter if (munger.getDeclaredSignature() != null) { // is this munger a // parameterized // form of some // original munger? ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null, munger.getSignature().getDeclaringType().resolve(getWorld()), false, munger.getTypeVariableAliases()); boolean needsbridging = false; if (!toBridgeTo.getReturnType().getErasureSignature().equals( munger.getSignature().getReturnType().getErasureSignature())) needsbridging = true; if (needsbridging) { ResolvedMember bridgingGetter = AjcMemberMaker.interFieldInterfaceGetter(toBridgeTo, gen.getType(), aspectType); createBridgeMethodForITDF(weaver, gen, itdfieldGetter, bridgingGetter); } } ResolvedMember itdfieldSetter = AjcMemberMaker.interFieldInterfaceSetter(field, gen.getType(), aspectType); LazyMethodGen mg1 = makeMethodGen(gen, itdfieldSetter); InstructionList il1 = new InstructionList(); if (field.isStatic()) { il1.append(InstructionFactory.createLoad(fieldType, 0)); il1.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.PUTSTATIC)); } else { il1.append(InstructionConstants.ALOAD_0); il1.append(InstructionFactory.createLoad(fieldType, 1)); il1.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD)); } il1.append(InstructionFactory.createReturn(Type.VOID)); mg1.getBody().insert(il1); gen.addMethodGen(mg1); if (munger.getDeclaredSignature() != null) { ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null, munger.getSignature().getDeclaringType().resolve(getWorld()), false, munger.getTypeVariableAliases()); boolean needsbridging = false; if (!toBridgeTo.getReturnType().getErasureSignature().equals( munger.getSignature().getReturnType().getErasureSignature())) { needsbridging = true; } if (needsbridging) { ResolvedMember bridgingSetter = AjcMemberMaker.interFieldInterfaceSetter(toBridgeTo, gen.getType(), aspectType); createBridgeMethodForITDF(weaver, gen, itdfieldSetter, bridgingSetter); } } return true; } else { return false; } } // FIXME asc combine with other createBridge.. method in this class, avoid // the duplication... private void createBridgeMethodForITDF(BcelClassWeaver weaver, LazyClassGen gen, ResolvedMember itdfieldSetter, ResolvedMember bridgingSetter) { InstructionFactory fact; LazyMethodGen bridgeMethod = makeMethodGen(gen, bridgingSetter); bridgeMethod.setAccessFlags(bridgeMethod.getAccessFlags() | 0x00000040); // BRIDGE = 0x00000040 Type[] paramTypes = BcelWorld.makeBcelTypes(bridgingSetter.getParameterTypes()); Type[] bridgingToParms = BcelWorld.makeBcelTypes(itdfieldSetter.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(bridgingSetter.getReturnType()); InstructionList body = bridgeMethod.getBody(); fact = gen.getFactory(); int pos = 0; if (!bridgingSetter.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals( itdfieldSetter.getParameterTypes()[i].getErasureSignature())) { body.append(fact.createCast(paramType, bridgingToParms[i])); } pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), itdfieldSetter)); body.append(InstructionFactory.createReturn(returnType)); gen.addMethodGen(bridgeMethod); } public ConcreteTypeMunger parameterizedFor(ResolvedType target) { return new BcelTypeMunger(munger.parameterizedFor(target), aspectType); } public ConcreteTypeMunger parameterizeWith(Map m, World w) { return new BcelTypeMunger(munger.parameterizeWith(m, w), aspectType); } /** * Returns a list of type variable aliases used in this munger. For example, if the ITD is 'int I<A,B>.m(List<A> las,List<B> * lbs) {}' then this returns a list containing the strings "A" and "B". */ public List /* String */getTypeVariableAliases() { return munger.getTypeVariableAliases(); } public boolean equals(Object other) { if (!(other instanceof BcelTypeMunger)) return false; BcelTypeMunger o = (BcelTypeMunger) other; return ((o.getMunger() == null) ? (getMunger() == null) : o.getMunger().equals(getMunger())) && ((o.getAspectType() == null) ? (getAspectType() == null) : o.getAspectType().equals(getAspectType())); // && (AsmManager.getDefault().getHandleProvider().dependsOnLocation() ? ((o.getSourceLocation() == null) ? // (getSourceLocation() == null) // : o.getSourceLocation().equals(getSourceLocation())) // : true); // pr134471 - remove when handles are improved // to be independent of location } private volatile int hashCode = 0; public int hashCode() { if (hashCode == 0) { int result = 17; result = 37 * result + ((getMunger() == null) ? 0 : getMunger().hashCode()); result = 37 * result + ((getAspectType() == null) ? 0 : getAspectType().hashCode()); hashCode = result; } return hashCode; } }
263,837
Bug 263837 Error during Delete AJ Markers
Error sent through the AJDT mailing list. I believe this is an LTW weaving error, so not raising it against AJDT.
resolved fixed
1b54b4b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-02-06T00:15:57Z"
"2009-02-05T18:53:20Z"
weaver/src/org/aspectj/weaver/bcel/BcelWeaver.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.jar.Attributes.Name; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.SourceLocation; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.util.FileUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.CrosscuttingMembersSet; import org.aspectj.weaver.CustomMungerFactory; import org.aspectj.weaver.IClassFileProvider; import org.aspectj.weaver.IUnwovenClassFile; import org.aspectj.weaver.IWeaveRequestor; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.model.AsmRelationshipProvider; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.BindingPattern; import org.aspectj.weaver.patterns.BindingTypePattern; import org.aspectj.weaver.patterns.ConcreteCflowPointcut; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.FastMatchInfo; import org.aspectj.weaver.patterns.IfPointcut; import org.aspectj.weaver.patterns.KindedPointcut; import org.aspectj.weaver.patterns.NameBindingPointcut; import org.aspectj.weaver.patterns.NotPointcut; import org.aspectj.weaver.patterns.OrPointcut; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.PointcutRewriter; import org.aspectj.weaver.patterns.WithinPointcut; import org.aspectj.weaver.tools.Trace; import org.aspectj.weaver.tools.TraceFactory; public class BcelWeaver { public static final String CLOSURE_CLASS_PREFIX = "$Ajc"; public static final String SYNTHETIC_CLASS_POSTFIX = "$ajc"; private final BcelWorld world; private final CrosscuttingMembersSet xcutSet; private boolean inReweavableMode = false; private static Trace trace = TraceFactory.getTraceFactory().getTrace(BcelWeaver.class); public BcelWeaver(BcelWorld world) { super(); if (trace.isTraceEnabled()) trace.enter("<init>", this, world); this.world = world; this.xcutSet = world.getCrosscuttingMembersSet(); if (trace.isTraceEnabled()) trace.exit("<init>"); } // ---- fields // private Map sourceJavaClasses = new HashMap(); /* String -> // UnwovenClassFile */ private List addedClasses = new ArrayList(); /* List<UnwovenClassFile> */ private List deletedTypenames = new ArrayList(); /* List<String> */ // private Map resources = new HashMap(); /* String -> UnwovenClassFile */ private Manifest manifest = null; private boolean needToReweaveWorld = false; private boolean isBatchWeave = true; private List shadowMungerList = null; // setup by prepareForWeave private List typeMungerList = null; // setup by prepareForWeave private List lateTypeMungerList = null; // setup by prepareForWeave private List declareParentsList = null; // setup by prepareForWeave private ZipOutputStream zipOutputStream; private CustomMungerFactory customMungerFactory; // ---- // only called for testing public void setShadowMungers(List l) { shadowMungerList = l; } /** * Add the given aspect to the weaver. The type is resolved to support DOT for static inner classes as well as DOLLAR * * @param aspectName * @return aspect */ public ResolvedType addLibraryAspect(String aspectName) { if (trace.isTraceEnabled()) trace.enter("addLibraryAspect", this, aspectName); // 1 - resolve as is UnresolvedType unresolvedT = UnresolvedType.forName(aspectName); unresolvedT.setNeedsModifiableDelegate(true); ResolvedType type = world.resolve(unresolvedT, true); if (type.isMissing()) { // fallback on inner class lookup mechanism String fixedName = aspectName; int hasDot = fixedName.lastIndexOf('.'); while (hasDot > 0) { // System.out.println("BcelWeaver.addLibraryAspect " + // fixedName); char[] fixedNameChars = fixedName.toCharArray(); fixedNameChars[hasDot] = '$'; fixedName = new String(fixedNameChars); hasDot = fixedName.lastIndexOf('.'); UnresolvedType ut = UnresolvedType.forName(fixedName); ut.setNeedsModifiableDelegate(true); type = world.resolve(ut, true); if (!type.isMissing()) { break; } } } // System.out.println("type: " + type + " for " + aspectName); if (type.isAspect()) { // Bug 119657 ensure we use the unwoven aspect WeaverStateInfo wsi = type.getWeaverState(); if (wsi != null && wsi.isReweavable()) { BcelObjectType classType = getClassType(type.getName()); JavaClass wovenJavaClass = classType.getJavaClass(); JavaClass unwovenJavaClass = Utility.makeJavaClass(wovenJavaClass.getFileName(), wsi .getUnwovenClassFileData(wovenJavaClass.getBytes())); world.storeClass(unwovenJavaClass); classType.setJavaClass(unwovenJavaClass); // classType.setJavaClass(Utility.makeJavaClass(classType. // getJavaClass().getFileName(), // wsi.getUnwovenClassFileData(classType.getJavaClass().getBytes( // )))); } // TODO AV - happens to reach that a lot of time: for each type // flagged reweavable X for each aspect in the weaverstate // => mainly for nothing for LTW - pbly for something in incremental // build... xcutSet.addOrReplaceAspect(type); if (trace.isTraceEnabled()) trace.exit("addLibraryAspect", type); if (type.getSuperclass().isAspect()) { // If the supertype includes ITDs and the user has not included // that aspect in the aop.xml, they will // not get picked up, which can give unusual behaviour! See bug // 223094 // This change causes us to pick up the super aspect regardless // of what was said in the aop.xml - giving // predictable behaviour. If the user also supplied it, there // will be no problem other than the second // addition overriding the first addLibraryAspect(type.getSuperclass().getName()); } return type; } else { // FIXME AV - better warning upon no such aspect from aop.xml RuntimeException ex = new RuntimeException("Cannot register non aspect: " + type.getName() + " , " + aspectName); if (trace.isTraceEnabled()) trace.exit("addLibraryAspect", ex); throw ex; } } /** * * @param inFile File path to class directory or zip/jar class archive * @throws IOException */ public void addLibraryJarFile(File inFile) throws IOException { List addedAspects = null; if (inFile.isDirectory()) { addedAspects = addAspectsFromDirectory(inFile); } else { addedAspects = addAspectsFromJarFile(inFile); } for (Iterator i = addedAspects.iterator(); i.hasNext();) { ResolvedType aspectX = (ResolvedType) i.next(); xcutSet.addOrReplaceAspect(aspectX); } } private List addAspectsFromJarFile(File inFile) throws FileNotFoundException, IOException { ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); // ??? buffered List addedAspects = new ArrayList(); try { while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; } // FIXME ASC performance? of this alternative soln. ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName()); JavaClass jc = parser.parse(); inStream.closeEntry(); ResolvedType type = world.addSourceObjectType(jc).getResolvedTypeX(); type.setBinaryPath(inFile.getAbsolutePath()); if (type.isAspect()) { addedAspects.add(type); } } } finally { inStream.close(); } return addedAspects; } private List addAspectsFromDirectory(File dir) throws FileNotFoundException, IOException { List addedAspects = new ArrayList(); File[] classFiles = FileUtil.listFiles(dir, new FileFilter() { public boolean accept(File pathname) { return pathname.getName().endsWith(".class"); } }); for (int i = 0; i < classFiles.length; i++) { FileInputStream fis = new FileInputStream(classFiles[i]); byte[] bytes = FileUtil.readAsByteArray(fis); addIfAspect(bytes, classFiles[i].getAbsolutePath(), addedAspects, dir); fis.close(); } return addedAspects; } private void addIfAspect(byte[] bytes, String name, List toList, File dir) throws IOException { ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes), name); JavaClass jc = parser.parse(); ResolvedType type = world.addSourceObjectType(jc).getResolvedTypeX(); String typeName = type.getName().replace('.', File.separatorChar); int end = name.lastIndexOf(typeName + ".class"); String binaryPath = null; // if end is -1 then something wierd happened, the class file is not in // the correct place, something like // bin/A.class when the declaration for A specifies it is in a package. if (end == -1) { binaryPath = dir.getAbsolutePath(); } else { binaryPath = name.substring(0, end - 1); } type.setBinaryPath(binaryPath); if (type.isAspect()) { toList.add(type); } } // // The ANT copy task should be used to copy resources across. // private final static boolean // CopyResourcesFromInpathDirectoriesToOutput=false; /** * Add any .class files in the directory to the outdir. Anything other than .class files in the directory (or its * subdirectories) are considered resources and are also copied. * */ public List addDirectoryContents(File inFile, File outDir) throws IOException { List addedClassFiles = new ArrayList(); // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(inFile, new FileFilter() { public boolean accept(File f) { boolean accept = !f.isDirectory(); return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { addedClassFiles.add(addClassFile(files[i], inFile, outDir)); } return addedClassFiles; } /** * Adds all class files in the jar */ public List addJarFile(File inFile, File outDir, boolean canBeDirectory) { // System.err.println("? addJarFile(" + inFile + ", " + outDir + ")"); List addedClassFiles = new ArrayList(); needToReweaveWorld = true; JarFile inJar = null; try { // Is this a directory we are looking at? if (inFile.isDirectory() && canBeDirectory) { addedClassFiles.addAll(addDirectoryContents(inFile, outDir)); } else { inJar = new JarFile(inFile); try { addManifest(inJar.getManifest()); Enumeration entries = inJar.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); InputStream inStream = inJar.getInputStream(entry); byte[] bytes = FileUtil.readAsByteArray(inStream); String filename = entry.getName(); // System.out.println("? addJarFile() filename='" + filename // + "'"); UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes); if (filename.endsWith(".class")) { this.addClassFile(classFile); addedClassFiles.add(classFile); } // else if (!entry.isDirectory()) { // // /* bug-44190 Copy meta-data */ // addResource(filename,classFile); // } inStream.close(); } } finally { inJar.close(); } inJar.close(); } } catch (FileNotFoundException ex) { IMessage message = new Message("Could not find input jar file " + inFile.getPath() + ", ignoring", new SourceLocation( inFile, 0), false); world.getMessageHandler().handleMessage(message); } catch (IOException ex) { IMessage message = new Message("Could not read input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile, 0), true); world.getMessageHandler().handleMessage(message); } finally { if (inJar != null) { try { inJar.close(); } catch (IOException ex) { IMessage message = new Message("Could not close input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile, 0), true); world.getMessageHandler().handleMessage(message); } } } return addedClassFiles; } // public void addResource(String name, File inPath, File outDir) throws // IOException { // // /* Eliminate CVS files. Relative paths use "/" */ // if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && // !name.endsWith("/CVS")) { // // System.err.println("? addResource('" + name + "')"); // // BufferedInputStream inStream = new BufferedInputStream(new // FileInputStream(inPath)); // // byte[] bytes = new byte[(int)inPath.length()]; // // inStream.read(bytes); // // inStream.close(); // byte[] bytes = FileUtil.readAsByteArray(inPath); // UnwovenClassFile resourceFile = new UnwovenClassFile(new File(outDir, // name).getAbsolutePath(), bytes); // addResource(name,resourceFile); // } // } public boolean needToReweaveWorld() { return needToReweaveWorld; } /** * Should be addOrReplace */ public void addClassFile(UnwovenClassFile classFile) { addedClasses.add(classFile); // if (null != sourceJavaClasses.put(classFile.getClassName(), // classFile)) { // // throw new RuntimeException(classFile.getClassName()); // } world.addSourceObjectType(classFile.getJavaClass()); } public UnwovenClassFile addClassFile(File classFile, File inPathDir, File outDir) throws IOException { FileInputStream fis = new FileInputStream(classFile); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); // ASSERT: // files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = classFile.getAbsolutePath().substring(inPathDir.getAbsolutePath().length() + 1); UnwovenClassFile ucf = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes); if (filename.endsWith(".class")) { // System.err.println( // "BCELWeaver: processing class from input directory "+classFile); this.addClassFile(ucf); } fis.close(); return ucf; } public void deleteClassFile(String typename) { deletedTypenames.add(typename); // sourceJavaClasses.remove(typename); world.deleteSourceObjectType(UnresolvedType.forName(typename)); } // public void addResource (String name, UnwovenClassFile resourceFile) { // /* bug-44190 Change error to warning and copy first resource */ // if (!resources.containsKey(name)) { // resources.put(name, resourceFile); // } // else { // world.showMessage(IMessage.WARNING, "duplicate resource: '" + name + "'", // null, null); // } // } // ---- weave preparation public void setIsBatchWeave(boolean b) { isBatchWeave = b; } public void prepareForWeave() { if (trace.isTraceEnabled()) trace.enter("prepareForWeave", this); needToReweaveWorld = xcutSet.hasChangedSinceLastReset(); // update mungers for (Iterator i = addedClasses.iterator(); i.hasNext();) { UnwovenClassFile jc = (UnwovenClassFile) i.next(); String name = jc.getClassName(); ResolvedType type = world.resolve(name); // System.err.println("added: " + type + " aspect? " + // type.isAspect()); if (type.isAspect()) { needToReweaveWorld |= xcutSet.addOrReplaceAspect(type); } } for (Iterator i = deletedTypenames.iterator(); i.hasNext();) { String name = (String) i.next(); if (xcutSet.deleteAspect(UnresolvedType.forName(name))) needToReweaveWorld = true; } shadowMungerList = xcutSet.getShadowMungers(); // world.debug("shadow mungers=" + shadowMungerList); rewritePointcuts(shadowMungerList); // Sometimes an error occurs during rewriting pointcuts (for example, if // ambiguous bindings // are detected) - we ought to fail the prepare when this happens // because continuing with // inconsistent pointcuts could lead to problems typeMungerList = xcutSet.getTypeMungers(); lateTypeMungerList = xcutSet.getLateTypeMungers(); declareParentsList = xcutSet.getDeclareParents(); addCustomMungers(); // The ordering here used to be based on a string compare on toString() // for the two mungers - // that breaks for the @AJ style where advice names aren't // programmatically generated. So we // have changed the sorting to be based on source location in the file - // this is reliable, in // the case of source locations missing, we assume they are 'sorted' - // i.e. the order in // which they were added to the collection is correct, this enables the // @AJ stuff to work properly. // When @AJ processing starts filling in source locations for mungers, // this code may need // a bit of alteration... Collections.sort(shadowMungerList, new Comparator() { public int compare(Object o1, Object o2) { ShadowMunger sm1 = (ShadowMunger) o1; ShadowMunger sm2 = (ShadowMunger) o2; if (sm1.getSourceLocation() == null) return (sm2.getSourceLocation() == null ? 0 : 1); if (sm2.getSourceLocation() == null) return -1; return (sm2.getSourceLocation().getOffset() - sm1.getSourceLocation().getOffset()); } }); if (inReweavableMode) world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.REWEAVABLE_MODE), null, null); if (trace.isTraceEnabled()) trace.exit("prepareForWeave"); } private void addCustomMungers() { if (customMungerFactory != null) { for (Iterator i = addedClasses.iterator(); i.hasNext();) { UnwovenClassFile jc = (UnwovenClassFile) i.next(); String name = jc.getClassName(); ResolvedType type = world.resolve(name); if (type.isAspect()) { Collection/* ShadowMunger */shadowMungers = customMungerFactory.createCustomShadowMungers(type); if (shadowMungers != null) { shadowMungerList.addAll(shadowMungers); } Collection/* ConcreteTypeMunger */typeMungers = customMungerFactory.createCustomTypeMungers(type); if (typeMungers != null) typeMungerList.addAll(typeMungers); } } } } public void setCustomMungerFactory(CustomMungerFactory factory) { customMungerFactory = factory; } /* * Rewrite all of the pointcuts in the world into their most efficient form for subsequent matching. Also ensure that if * pc1.equals(pc2) then pc1 == pc2 (for non-binding pcds) by making references all point to the same instance. Since pointcuts * remember their match decision on the last shadow, this makes matching faster when many pointcuts share common elements, or * even when one single pointcut has one common element (which can be a side-effect of DNF rewriting). */ private void rewritePointcuts(List/* ShadowMunger */shadowMungers) { PointcutRewriter rewriter = new PointcutRewriter(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); Pointcut newP = rewriter.rewrite(p); // validateBindings now whilst we still have around the pointcut // that resembles what the user actually wrote in their program // text. if (munger instanceof Advice) { Advice advice = (Advice) munger; if (advice.getSignature() != null) { final int numFormals; final String names[]; // If the advice is being concretized in a @AJ aspect *and* // the advice was declared in // an @AJ aspect (it could have been inherited from a code // style aspect) then // evaluate the alternative set of formals. pr125699 if (advice.getConcreteAspect().isAnnotationStyleAspect() && advice.getDeclaringAspect() != null && advice.getDeclaringAspect().resolve(world).isAnnotationStyleAspect()) { numFormals = advice.getBaseParameterCount(); int numArgs = advice.getSignature().getParameterTypes().length; if (numFormals > 0) { names = advice.getSignature().getParameterNames(world); validateBindings(newP, p, numArgs, names); } } else { numFormals = advice.getBaseParameterCount(); if (numFormals > 0) { names = advice.getBaseParameterNames(world); validateBindings(newP, p, numFormals, names); } } } } munger.setPointcut(newP); } // now that we have optimized individual pointcuts, optimize // across the set of pointcuts.... // Use a map from key based on pc equality, to value based on // pc identity. Map/* <Pointcut,Pointcut> */pcMap = new HashMap(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); munger.setPointcut(shareEntriesFromMap(p, pcMap)); } } private Pointcut shareEntriesFromMap(Pointcut p, Map pcMap) { // some things cant be shared... if (p instanceof NameBindingPointcut) return p; if (p instanceof IfPointcut) return p; if (p instanceof ConcreteCflowPointcut) return p; if (p instanceof AndPointcut) { AndPointcut apc = (AndPointcut) p; Pointcut left = shareEntriesFromMap(apc.getLeft(), pcMap); Pointcut right = shareEntriesFromMap(apc.getRight(), pcMap); return new AndPointcut(left, right); } else if (p instanceof OrPointcut) { OrPointcut opc = (OrPointcut) p; Pointcut left = shareEntriesFromMap(opc.getLeft(), pcMap); Pointcut right = shareEntriesFromMap(opc.getRight(), pcMap); return new OrPointcut(left, right); } else if (p instanceof NotPointcut) { NotPointcut npc = (NotPointcut) p; Pointcut not = shareEntriesFromMap(npc.getNegatedPointcut(), pcMap); return new NotPointcut(not); } else { // primitive pcd if (pcMap.containsKey(p)) { // based on equality return (Pointcut) pcMap.get(p); // same instance (identity) } else { pcMap.put(p, p); return p; } } } // userPointcut is the pointcut that the user wrote in the program text. // dnfPointcut is the same pointcut rewritten in DNF // numFormals is the number of formal parameters in the pointcut // if numFormals > 0 then every branch of a disjunction must bind each // formal once and only once. // in addition, the left and right branches of a disjunction must hold on // join point kinds in // common. private void validateBindings(Pointcut dnfPointcut, Pointcut userPointcut, int numFormals, String[] names) { if (numFormals == 0) return; // nothing to check if (dnfPointcut.couldMatchKinds() == Shadow.NO_SHADOW_KINDS_BITS) return; // cant have problems if you dont match! if (dnfPointcut instanceof OrPointcut) { OrPointcut orBasedDNFPointcut = (OrPointcut) dnfPointcut; Pointcut[] leftBindings = new Pointcut[numFormals]; Pointcut[] rightBindings = new Pointcut[numFormals]; validateOrBranch(orBasedDNFPointcut, userPointcut, numFormals, names, leftBindings, rightBindings); } else { Pointcut[] bindings = new Pointcut[numFormals]; validateSingleBranch(dnfPointcut, userPointcut, numFormals, names, bindings); } } private void validateOrBranch(OrPointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] leftBindings, Pointcut[] rightBindings) { Pointcut left = pc.getLeft(); Pointcut right = pc.getRight(); if (left instanceof OrPointcut) { Pointcut[] newRightBindings = new Pointcut[numFormals]; validateOrBranch((OrPointcut) left, userPointcut, numFormals, names, leftBindings, newRightBindings); } else { if (left.couldMatchKinds() != Shadow.NO_SHADOW_KINDS_BITS) validateSingleBranch(left, userPointcut, numFormals, names, leftBindings); } if (right instanceof OrPointcut) { Pointcut[] newLeftBindings = new Pointcut[numFormals]; validateOrBranch((OrPointcut) right, userPointcut, numFormals, names, newLeftBindings, rightBindings); } else { if (right.couldMatchKinds() != Shadow.NO_SHADOW_KINDS_BITS) validateSingleBranch(right, userPointcut, numFormals, names, rightBindings); } int kindsInCommon = left.couldMatchKinds() & right.couldMatchKinds(); if (kindsInCommon != Shadow.NO_SHADOW_KINDS_BITS && couldEverMatchSameJoinPoints(left, right)) { // we know that every branch binds every formal, so there is no // ambiguity // if each branch binds it in exactly the same way... List ambiguousNames = new ArrayList(); for (int i = 0; i < numFormals; i++) { if (leftBindings[i] == null) { if (rightBindings[i] != null) { ambiguousNames.add(names[i]); } } else if (!leftBindings[i].equals(rightBindings[i])) { ambiguousNames.add(names[i]); } } if (!ambiguousNames.isEmpty()) raiseAmbiguityInDisjunctionError(userPointcut, ambiguousNames); } } // pc is a pointcut that does not contain any disjunctions // check that every formal is bound (negation doesn't count). // we know that numFormals > 0 or else we would not be called private void validateSingleBranch(Pointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] bindings) { boolean[] foundFormals = new boolean[numFormals]; for (int i = 0; i < foundFormals.length; i++) { foundFormals[i] = false; } validateSingleBranchRecursion(pc, userPointcut, foundFormals, names, bindings); for (int i = 0; i < foundFormals.length; i++) { if (!foundFormals[i]) { boolean ignore = false; // ATAJ soften the unbound error for implicit bindings like // JoinPoint in @AJ style for (int j = 0; j < userPointcut.m_ignoreUnboundBindingForNames.length; j++) { if (names[i] != null && names[i].equals(userPointcut.m_ignoreUnboundBindingForNames[j])) { ignore = true; break; } } if (!ignore) { raiseUnboundFormalError(names[i], userPointcut); } } } } // each formal must appear exactly once private void validateSingleBranchRecursion(Pointcut pc, Pointcut userPointcut, boolean[] foundFormals, String[] names, Pointcut[] bindings) { if (pc instanceof NotPointcut) { // nots can only appear at leaves in DNF NotPointcut not = (NotPointcut) pc; if (not.getNegatedPointcut() instanceof NameBindingPointcut) { NameBindingPointcut nnbp = (NameBindingPointcut) not.getNegatedPointcut(); if (!nnbp.getBindingAnnotationTypePatterns().isEmpty() && !nnbp.getBindingTypePatterns().isEmpty()) raiseNegationBindingError(userPointcut); } } else if (pc instanceof AndPointcut) { AndPointcut and = (AndPointcut) pc; validateSingleBranchRecursion(and.getLeft(), userPointcut, foundFormals, names, bindings); validateSingleBranchRecursion(and.getRight(), userPointcut, foundFormals, names, bindings); } else if (pc instanceof NameBindingPointcut) { List/* BindingTypePattern */btps = ((NameBindingPointcut) pc).getBindingTypePatterns(); for (Iterator iter = btps.iterator(); iter.hasNext();) { BindingTypePattern btp = (BindingTypePattern) iter.next(); int index = btp.getFormalIndex(); bindings[index] = pc; if (foundFormals[index]) { raiseAmbiguousBindingError(names[index], userPointcut); } else { foundFormals[index] = true; } } List/* BindingPattern */baps = ((NameBindingPointcut) pc).getBindingAnnotationTypePatterns(); for (Iterator iter = baps.iterator(); iter.hasNext();) { BindingPattern bap = (BindingPattern) iter.next(); int index = bap.getFormalIndex(); bindings[index] = pc; if (foundFormals[index]) { raiseAmbiguousBindingError(names[index], userPointcut); } else { foundFormals[index] = true; } } } else if (pc instanceof ConcreteCflowPointcut) { ConcreteCflowPointcut cfp = (ConcreteCflowPointcut) pc; int[] slots = cfp.getUsedFormalSlots(); for (int i = 0; i < slots.length; i++) { bindings[slots[i]] = cfp; if (foundFormals[slots[i]]) { raiseAmbiguousBindingError(names[slots[i]], userPointcut); } else { foundFormals[slots[i]] = true; } } } } // By returning false from this method, we are allowing binding of the same // variable on either side of an or. // Be conservative :- have to consider overriding, varargs, autoboxing, // the effects of itds (on within for example), interfaces, the fact that // join points can have multiple signatures and so on. private boolean couldEverMatchSameJoinPoints(Pointcut left, Pointcut right) { if (left instanceof OrPointcut) { OrPointcut leftOrPointcut = (OrPointcut) left; if (couldEverMatchSameJoinPoints(leftOrPointcut.getLeft(), right)) return true; if (couldEverMatchSameJoinPoints(leftOrPointcut.getRight(), right)) return true; return false; } if (right instanceof OrPointcut) { OrPointcut rightOrPointcut = (OrPointcut) right; if (couldEverMatchSameJoinPoints(left, rightOrPointcut.getLeft())) return true; if (couldEverMatchSameJoinPoints(left, rightOrPointcut.getRight())) return true; return false; } // look for withins WithinPointcut leftWithin = (WithinPointcut) findFirstPointcutIn(left, WithinPointcut.class); WithinPointcut rightWithin = (WithinPointcut) findFirstPointcutIn(right, WithinPointcut.class); if ((leftWithin != null) && (rightWithin != null)) { if (!leftWithin.couldEverMatchSameJoinPointsAs(rightWithin)) return false; } // look for kinded KindedPointcut leftKind = (KindedPointcut) findFirstPointcutIn(left, KindedPointcut.class); KindedPointcut rightKind = (KindedPointcut) findFirstPointcutIn(right, KindedPointcut.class); if ((leftKind != null) && (rightKind != null)) { if (!leftKind.couldEverMatchSameJoinPointsAs(rightKind)) return false; } return true; } private Pointcut findFirstPointcutIn(Pointcut toSearch, Class toLookFor) { if (toSearch instanceof NotPointcut) return null; if (toLookFor.isInstance(toSearch)) return toSearch; if (toSearch instanceof AndPointcut) { AndPointcut apc = (AndPointcut) toSearch; Pointcut left = findFirstPointcutIn(apc.getLeft(), toLookFor); if (left != null) return left; return findFirstPointcutIn(apc.getRight(), toLookFor); } return null; } /** * @param userPointcut */ private void raiseNegationBindingError(Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.NEGATION_DOESNT_ALLOW_BINDING), userPointcut .getSourceContext().makeSourceLocation(userPointcut), null); } /** * @param name * @param userPointcut */ private void raiseAmbiguousBindingError(String name, Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING, name), userPointcut .getSourceContext().makeSourceLocation(userPointcut), null); } /** * @param userPointcut */ private void raiseAmbiguityInDisjunctionError(Pointcut userPointcut, List names) { StringBuffer formalNames = new StringBuffer(names.get(0).toString()); for (int i = 1; i < names.size(); i++) { formalNames.append(", "); formalNames.append(names.get(i)); } world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING_IN_OR, formalNames), userPointcut .getSourceContext().makeSourceLocation(userPointcut), null); } /** * @param name * @param userPointcut */ private void raiseUnboundFormalError(String name, Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.UNBOUND_FORMAL, name), userPointcut .getSourceLocation(), null); } // public void dumpUnwoven(File file) throws IOException { // BufferedOutputStream os = FileUtil.makeOutputStream(file); // this.zipOutputStream = new ZipOutputStream(os); // dumpUnwoven(); // /* BUG 40943*/ // dumpResourcesToOutJar(); // zipOutputStream.close(); //this flushes and closes the acutal file // } // // // public void dumpUnwoven() throws IOException { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // public void dumpResourcesToOutPath() throws IOException { // // System.err.println("? dumpResourcesToOutPath() resources=" + // resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // UnwovenClassFile res = (UnwovenClassFile)resources.get(i.next()); // dumpUnchanged(res); // } // //resources = new HashMap(); // } // /* BUG #40943 */ // public void dumpResourcesToOutJar() throws IOException { // // System.err.println("? dumpResourcesToOutJar() resources=" + // resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // String name = (String)i.next(); // UnwovenClassFile res = (UnwovenClassFile)resources.get(name); // writeZipEntry(name,res.getBytes()); // } // resources = new HashMap(); // } // // // halfway house for when the jar is managed outside of the weaver, but // the resources // // to be copied are known in the weaver. // public void dumpResourcesToOutJar(ZipOutputStream zos) throws IOException // { // this.zipOutputStream = zos; // dumpResourcesToOutJar(); // } public void addManifest(Manifest newManifest) { // System.out.println("? addManifest() newManifest=" + newManifest); if (manifest == null) { manifest = newManifest; } } private static final String WEAVER_MANIFEST_VERSION = "1.0"; private static final Attributes.Name CREATED_BY = new Name("Created-By"); private static final String WEAVER_CREATED_BY = "AspectJ Compiler"; public Manifest getManifest(boolean shouldCreate) { if (manifest == null && shouldCreate) { manifest = new Manifest(); Attributes attributes = manifest.getMainAttributes(); attributes.put(Name.MANIFEST_VERSION, WEAVER_MANIFEST_VERSION); attributes.put(CREATED_BY, WEAVER_CREATED_BY); } return manifest; } // ---- weaving // Used by some test cases only... public Collection weave(File file) throws IOException { OutputStream os = FileUtil.makeOutputStream(file); this.zipOutputStream = new ZipOutputStream(os); prepareForWeave(); Collection c = weave(new IClassFileProvider() { public boolean isApplyAtAspectJMungersOnly() { return false; } public Iterator getClassFileIterator() { return addedClasses.iterator(); } public IWeaveRequestor getRequestor() { return new IWeaveRequestor() { public void acceptResult(IUnwovenClassFile result) { try { writeZipEntry(result.getFilename(), result.getBytes()); } catch (IOException ex) { } } public void processingReweavableState() { } public void addingTypeMungers() { } public void weavingAspects() { } public void weavingClasses() { } public void weaveCompleted() { } }; } }); // /* BUG 40943*/ // dumpResourcesToOutJar(); zipOutputStream.close(); // this flushes and closes the acutal file return c; } // public Collection weave() throws IOException { // prepareForWeave(); // Collection filesToWeave; // // if (needToReweaveWorld) { // filesToWeave = sourceJavaClasses.values(); // } else { // filesToWeave = addedClasses; // } // // Collection wovenClassNames = new ArrayList(); // world.showMessage(IMessage.INFO, "might need to weave " + filesToWeave + // "(world=" + needToReweaveWorld + ")", null, null); // // // //System.err.println("typeMungers: " + typeMungerList); // // prepareToProcessReweavableState(); // // clear all state from files we'll be reweaving // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = getClassType(className); // processReweavableStateIfPresent(className, classType); // } // // // // //XXX this isn't quite the right place for this... // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // addTypeMungers(className); // } // // // first weave into aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = // BcelWorld.getBcelObjectType(world.resolve(className)); // if (classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // // then weave into non-aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = // BcelWorld.getBcelObjectType(world.resolve(className)); // if (! classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // if (zipOutputStream != null && !needToReweaveWorld) { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // filesToDump.removeAll(filesToWeave); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // // addedClasses = new ArrayList(); // deletedTypenames = new ArrayList(); // // return wovenClassNames; // } // variation of "weave" that sources class files from an external source. public Collection weave(IClassFileProvider input) throws IOException { if (trace.isTraceEnabled()) trace.enter("weave", this, input); ContextToken weaveToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING, ""); Collection wovenClassNames = new ArrayList(); IWeaveRequestor requestor = input.getRequestor(); for (Iterator i = input.getClassFileIterator(); i.hasNext();) { UnwovenClassFile classFile = (UnwovenClassFile) i.next(); if (world.getModel() != null /* AsmManager.isCreatingModel() */&& !isBatchWeave) { // remove all relationships where this file being woven is the // target of the relationship world.getModelAsAsmManager().removeRelationshipsTargettingThisType(classFile.getClassName()); } } // Go through the types and ensure any 'damaged' during compile time are // repaired prior to weaving for (Iterator i = input.getClassFileIterator(); i.hasNext();) { UnwovenClassFile classFile = (UnwovenClassFile) i.next(); String className = classFile.getClassName(); ResolvedType theType = world.resolve(className); if (theType != null) { theType.ensureConsistent(); } } // special case for AtAspectJMungerOnly - see #113587 if (input.isApplyAtAspectJMungersOnly()) { ContextToken atAspectJMungersOnly = CompilationAndWeavingContext.enteringPhase( CompilationAndWeavingContext.PROCESSING_ATASPECTJTYPE_MUNGERS_ONLY, ""); requestor.weavingAspects(); // ContextToken aspectToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, ""); for (Iterator i = input.getClassFileIterator(); i.hasNext();) { UnwovenClassFile classFile = (UnwovenClassFile) i.next(); String className = classFile.getClassName(); ResolvedType theType = world.resolve(className); if (theType.isAnnotationStyleAspect()) { BcelObjectType classType = BcelWorld.getBcelObjectType(theType); if (classType == null) { throw new BCException("Can't find bcel delegate for " + className + " type=" + theType.getClass()); } LazyClassGen clazz = classType.getLazyClassGen(); BcelPerClauseAspectAdder selfMunger = new BcelPerClauseAspectAdder(theType, theType.getPerClause().getKind()); selfMunger.forceMunge(clazz, true); classType.finishedWith(); UnwovenClassFile[] newClasses = getClassFilesFor(clazz); for (int news = 0; news < newClasses.length; news++) { requestor.acceptResult(newClasses[news]); } wovenClassNames.add(classFile.getClassName()); } } requestor.weaveCompleted(); CompilationAndWeavingContext.leavingPhase(atAspectJMungersOnly); return wovenClassNames; } requestor.processingReweavableState(); ContextToken reweaveToken = CompilationAndWeavingContext.enteringPhase( CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE, ""); prepareToProcessReweavableState(); // clear all state from files we'll be reweaving for (Iterator i = input.getClassFileIterator(); i.hasNext();) { UnwovenClassFile classFile = (UnwovenClassFile) i.next(); String className = classFile.getClassName(); BcelObjectType classType = getClassType(className); // null return from getClassType() means the delegate is an eclipse // source type - so // there *cant* be any reweavable state... (he bravely claimed...) if (classType != null) { ContextToken tok = CompilationAndWeavingContext.enteringPhase( CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE, className); processReweavableStateIfPresent(className, classType); CompilationAndWeavingContext.leavingPhase(tok); } } CompilationAndWeavingContext.leavingPhase(reweaveToken); ContextToken typeMungingToken = CompilationAndWeavingContext.enteringPhase( CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS, ""); requestor.addingTypeMungers(); // We process type mungers in two groups, first mungers that change the // type // hierarchy, then 'normal' ITD type mungers. // Process the types in a predictable order (rather than the order // encountered). // For class A, the order is superclasses of A then superinterfaces of A // (and this mechanism is applied recursively) List typesToProcess = new ArrayList(); for (Iterator iter = input.getClassFileIterator(); iter.hasNext();) { UnwovenClassFile clf = (UnwovenClassFile) iter.next(); typesToProcess.add(clf.getClassName()); } while (typesToProcess.size() > 0) { weaveParentsFor(typesToProcess, (String) typesToProcess.get(0)); } for (Iterator i = input.getClassFileIterator(); i.hasNext();) { UnwovenClassFile classFile = (UnwovenClassFile) i.next(); String className = classFile.getClassName(); addNormalTypeMungers(className); } CompilationAndWeavingContext.leavingPhase(typeMungingToken); requestor.weavingAspects(); ContextToken aspectToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, ""); // first weave into aspects for (Iterator i = input.getClassFileIterator(); i.hasNext();) { UnwovenClassFile classFile = (UnwovenClassFile) i.next(); String className = classFile.getClassName(); ResolvedType theType = world.resolve(className); if (theType.isAspect()) { BcelObjectType classType = BcelWorld.getBcelObjectType(theType); if (classType == null) { // Sometimes.. if the Bcel Delegate couldn't be found then a // problem occurred at compile time - on // a previous compiler run. In this case I assert the // delegate will still be an EclipseSourceType // and we can ignore the problem here (the original compile // error will be reported again from // the eclipse source type) - pr113531 ReferenceTypeDelegate theDelegate = ((ReferenceType) theType).getDelegate(); if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) continue; throw new BCException("Can't find bcel delegate for " + className + " type=" + theType.getClass()); } weaveAndNotify(classFile, classType, requestor); wovenClassNames.add(className); } } CompilationAndWeavingContext.leavingPhase(aspectToken); requestor.weavingClasses(); ContextToken classToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_CLASSES, ""); // then weave into non-aspects for (Iterator i = input.getClassFileIterator(); i.hasNext();) { UnwovenClassFile classFile = (UnwovenClassFile) i.next(); String className = classFile.getClassName(); ResolvedType theType = world.resolve(className); if (!theType.isAspect()) { BcelObjectType classType = BcelWorld.getBcelObjectType(theType); if (classType == null) { // bug 119882 - see above comment for bug 113531 ReferenceTypeDelegate theDelegate = ((ReferenceType) theType).getDelegate(); // TODO urgh - put a method on the interface to check this, // string compare is hideous if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) continue; throw new BCException("Can't find bcel delegate for " + className + " type=" + theType.getClass()); } weaveAndNotify(classFile, classType, requestor); wovenClassNames.add(className); } } CompilationAndWeavingContext.leavingPhase(classToken); addedClasses = new ArrayList(); deletedTypenames = new ArrayList(); requestor.weaveCompleted(); CompilationAndWeavingContext.leavingPhase(weaveToken); if (trace.isTraceEnabled()) trace.exit("weave", wovenClassNames); return wovenClassNames; } public void allWeavingComplete() { warnOnUnmatchedAdvice(); } /** * In 1.5 mode and with XLint:adviceDidNotMatch enabled, put out messages for any mungers that did not match anything. */ private void warnOnUnmatchedAdvice() { class AdviceLocation { private final int lineNo; private final UnresolvedType inAspect; public AdviceLocation(BcelAdvice advice) { this.lineNo = advice.getSourceLocation().getLine(); this.inAspect = advice.getDeclaringAspect(); } public boolean equals(Object obj) { if (!(obj instanceof AdviceLocation)) return false; AdviceLocation other = (AdviceLocation) obj; if (this.lineNo != other.lineNo) return false; if (!this.inAspect.equals(other.inAspect)) return false; return true; } public int hashCode() { return 37 + 17 * lineNo + 17 * inAspect.hashCode(); } } // FIXME asc Should be factored out into Xlint code and done // automatically for all xlint messages, ideally. // if a piece of advice hasn't matched anywhere and we are in -1.5 mode, // put out a warning if (world.isInJava5Mode() && world.getLint().adviceDidNotMatch.isEnabled()) { List l = world.getCrosscuttingMembersSet().getShadowMungers(); Set alreadyWarnedLocations = new HashSet(); for (Iterator iter = l.iterator(); iter.hasNext();) { ShadowMunger element = (ShadowMunger) iter.next(); // This will stop us incorrectly reporting deow checkers: if (element instanceof BcelAdvice) { BcelAdvice ba = (BcelAdvice) element; if (ba.getKind() == AdviceKind.CflowEntry || ba.getKind() == AdviceKind.CflowBelowEntry) { continue; } if (!ba.hasMatchedSomething()) { // Because we implement some features of AJ itself by // creating our own kind of mungers, you sometimes // find that ba.getSignature() is not a BcelMethod - for // example it might be a cflow entry munger. if (ba.getSignature() != null) { // check we haven't already warned on this advice and line // (cflow creates multiple mungers for the same advice) AdviceLocation loc = new AdviceLocation(ba); if (alreadyWarnedLocations.contains(loc)) { continue; } else { alreadyWarnedLocations.add(loc); } if (!(ba.getSignature() instanceof BcelMethod) || !Utility.isSuppressing(ba.getSignature(), "adviceDidNotMatch")) { world.getLint().adviceDidNotMatch.signal(ba.getDeclaringAspect().toString(), new SourceLocation( element.getSourceLocation().getSourceFile(), element.getSourceLocation().getLine())); } } } } } } } /** * 'typeToWeave' is one from the 'typesForWeaving' list. This routine ensures we process supertypes (classes/interfaces) of * 'typeToWeave' that are in the 'typesForWeaving' list before 'typeToWeave' itself. 'typesToWeave' is then removed from the * 'typesForWeaving' list. * * Note: Future gotcha in here ... when supplying partial hierarchies, this algorithm may break down. If you have a hierarchy * A>B>C and only give A and C to the weaver, it may choose to weave them in either order - but you'll probably have other * problems if you are supplying partial hierarchies like that ! */ private void weaveParentsFor(List typesForWeaving, String typeToWeave) { // Look at the supertype first ResolvedType rtx = world.resolve(typeToWeave); ResolvedType superType = rtx.getSuperclass(); if (superType != null && typesForWeaving.contains(superType.getName())) { weaveParentsFor(typesForWeaving, superType.getName()); } // Then look at the superinterface list ResolvedType[] interfaceTypes = rtx.getDeclaredInterfaces(); for (int i = 0; i < interfaceTypes.length; i++) { ResolvedType rtxI = interfaceTypes[i]; if (typesForWeaving.contains(rtxI.getName())) { weaveParentsFor(typesForWeaving, rtxI.getName()); } } ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS, rtx .getName()); weaveParentTypeMungers(rtx); // Now do this type CompilationAndWeavingContext.leavingPhase(tok); typesForWeaving.remove(typeToWeave); // and remove it from the list of // those to process } public void prepareToProcessReweavableState() { } public void processReweavableStateIfPresent(String className, BcelObjectType classType) { // If the class is marked reweavable, check any aspects around when it // was built are in this world WeaverStateInfo wsi = classType.getWeaverState(); if (wsi != null && wsi.isReweavable()) { // Check all necessary types // are around! world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.PROCESSING_REWEAVABLE, className, classType .getSourceLocation().getSourceFile()), null, null); Set aspectsPreviouslyInWorld = wsi.getAspectsAffectingType(); if (aspectsPreviouslyInWorld != null) { // keep track of them just to ensure unique missing aspect error // reporting Set alreadyConfirmedReweavableState = new HashSet(); for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) { String requiredTypeName = (String) iter.next(); if (!alreadyConfirmedReweavableState.contains(requiredTypeName)) { ResolvedType rtx = world.resolve(UnresolvedType.forName(requiredTypeName), true); boolean exists = !rtx.isMissing(); if (!exists) { world.getLint().missingAspectForReweaving.signal(new String[] { requiredTypeName, className }, classType.getSourceLocation(), null); // world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE, // requiredTypeName, className), classType.getSourceLocation(), null); } else { // weaved in aspect that are not declared in aop.xml // trigger an error for now // may cause headhache for LTW and packaged lib // without aop.xml in // see #104218 if (!xcutSet.containsAspect(rtx)) { world.showMessage(IMessage.ERROR, WeaverMessages.format( WeaverMessages.REWEAVABLE_ASPECT_NOT_REGISTERED, requiredTypeName, className), null, null); } else if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.VERIFIED_REWEAVABLE_TYPE, requiredTypeName, rtx.getSourceLocation().getSourceFile()), null, null); alreadyConfirmedReweavableState.add(requiredTypeName); } } } } // old: // classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass // ().getFileName(), wsi.getUnwovenClassFileData())); // new: reweavable default with clever diff classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi .getUnwovenClassFileData(classType.getJavaClass().getBytes()))); // } else { // classType.resetState(); } } private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType, IWeaveRequestor requestor) throws IOException { trace.enter("weaveAndNotify", this, new Object[] { classFile, classType, requestor }); ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_TYPE, classType .getResolvedTypeX().getName()); LazyClassGen clazz = weaveWithoutDump(classFile, classType); classType.finishedWith(); // clazz is null if the classfile was unchanged by weaving... if (clazz != null) { UnwovenClassFile[] newClasses = getClassFilesFor(clazz); // OPTIMIZE can we avoid using the string name at all in // UnwovenClassFile instances? // Copy the char[] across as it means the // WeaverAdapter.removeFromMap() can be fast! if (newClasses[0].getClassName().equals(classFile.getClassName())) { newClasses[0].setClassNameAsChars(classFile.getClassNameAsChars()); } for (int i = 0; i < newClasses.length; i++) { requestor.acceptResult(newClasses[i]); } } else { requestor.acceptResult(classFile); } classType.weavingCompleted(); CompilationAndWeavingContext.leavingPhase(tok); trace.exit("weaveAndNotify"); } /** * helper method - will return NULL if the underlying delegate is an EclipseSourceType and not a BcelObjectType */ public BcelObjectType getClassType(String forClass) { return BcelWorld.getBcelObjectType(world.resolve(forClass)); } public void addParentTypeMungers(String typeName) { weaveParentTypeMungers(world.resolve(typeName)); } public void addNormalTypeMungers(String typeName) { weaveNormalTypeMungers(world.resolve(typeName)); } public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) { List childClasses = clazz.getChildClasses(world); UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()]; ret[0] = new UnwovenClassFile(clazz.getFileName(), clazz.getClassName(), clazz.getJavaClassBytesIncludingReweavable(world)); int index = 1; for (Iterator iter = childClasses.iterator(); iter.hasNext();) { UnwovenClassFile.ChildClass element = (UnwovenClassFile.ChildClass) iter.next(); UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes); ret[index++] = childClass; } return ret; } /** * Weaves new parents and annotations onto a type ("declare parents" and "declare @type") * * Algorithm: 1. First pass, do parents then do annotations. During this pass record: - any parent mungers that don't match but * have a non-wild annotation type pattern - any annotation mungers that don't match 2. Multiple subsequent passes which go over * the munger lists constructed in the first pass, repeatedly applying them until nothing changes. FIXME asc confirm that * algorithm is optimal ?? */ public void weaveParentTypeMungers(ResolvedType onType) { if (onType.isRawType()) onType = onType.getGenericType(); onType.clearInterTypeMungers(); List decpToRepeat = new ArrayList(); boolean aParentChangeOccurred = false; boolean anAnnotationChangeOccurred = false; // First pass - apply all decp mungers for (Iterator i = declareParentsList.iterator(); i.hasNext();) { DeclareParents decp = (DeclareParents) i.next(); boolean typeChanged = applyDeclareParents(decp, onType); if (typeChanged) { aParentChangeOccurred = true; } else { decpToRepeat.add(decp); } } // Still first pass - apply all dec @type mungers for (Iterator i = xcutSet.getDeclareAnnotationOnTypes().iterator(); i.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation) i.next(); boolean typeChanged = applyDeclareAtType(decA, onType, true); if (typeChanged) { anAnnotationChangeOccurred = true; } } while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) { anAnnotationChangeOccurred = aParentChangeOccurred = false; List decpToRepeatNextTime = new ArrayList(); for (Iterator iter = decpToRepeat.iterator(); iter.hasNext();) { DeclareParents decp = (DeclareParents) iter.next(); boolean typeChanged = applyDeclareParents(decp, onType); if (typeChanged) { aParentChangeOccurred = true; } else { decpToRepeatNextTime.add(decp); } } for (Iterator iter = xcutSet.getDeclareAnnotationOnTypes().iterator(); iter.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation) iter.next(); boolean typeChanged = applyDeclareAtType(decA, onType, false); if (typeChanged) { anAnnotationChangeOccurred = true; } } decpToRepeat = decpToRepeatNextTime; } } /** * Apply a declare @type - return true if we change the type */ private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedType onType, boolean reportProblems) { boolean didSomething = false; if (decA.matches(onType)) { AnnotationAJ theAnnotation = decA.getAnnotationX(); // can be null for broken code! if (theAnnotation == null) { return false; } if (onType.hasAnnotation(theAnnotation.getType())) { // Could put out a lint here for an already annotated type ... // if (reportProblems) { // world.getLint().elementAlreadyAnnotated.signal( // new // String[]{onType.toString(),decA.getAnnotationTypeX().toString // ()}, // onType.getSourceLocation(),new // ISourceLocation[]{decA.getSourceLocation()}); // } return false; } AnnotationAJ annoX = decA.getAnnotationX(); // check the annotation is suitable for the target boolean problemReported = verifyTargetIsOK(decA, onType, annoX, reportProblems); if (!problemReported) { AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(world.getModelAsAsmManager(), decA.getSourceLocation(), onType.getSourceLocation()); // TAG: WeavingMessage if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES, new String[] { onType.toString(), Utility.beautifyLocation(onType.getSourceLocation()), decA.getAnnotationString(), "type", decA.getAspect().toString(), Utility.beautifyLocation(decA.getSourceLocation()) })); } didSomething = true; ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX); newAnnotationTM.setSourceLocation(decA.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM, decA.getAspect().resolve(world))); decA.copyAnnotationTo(onType); } } return didSomething; } /** * Checks for an @target() on the annotation and if found ensures it allows the annotation to be attached to the target type * that matched. */ private boolean verifyTargetIsOK(DeclareAnnotation decA, ResolvedType onType, AnnotationAJ annoX, boolean outputProblems) { boolean problemReported = false; if (annoX.specifiesTarget()) { if ((onType.isAnnotation() && !annoX.allowedOnAnnotationType()) || (!annoX.allowedOnRegularType())) { if (outputProblems) { if (decA.isExactPattern()) { world.getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, onType.getName(), annoX.getTypeName(), annoX.getValidTargets()), decA.getSourceLocation())); } else { if (world.getLint().invalidTargetForAnnotation.isEnabled()) { world.getLint().invalidTargetForAnnotation.signal(new String[] { onType.getName(), annoX.getTypeName(), annoX.getValidTargets() }, decA.getSourceLocation(), new ISourceLocation[] { onType .getSourceLocation() }); } } } problemReported = true; } } return problemReported; } /** * Apply a single declare parents - return true if we change the type */ private boolean applyDeclareParents(DeclareParents p, ResolvedType onType) { boolean didSomething = false; List newParents = p.findMatchingNewParents(onType, true); if (!newParents.isEmpty()) { didSomething = true; BcelObjectType classType = BcelWorld.getBcelObjectType(onType); // System.err.println("need to do declare parents for: " + onType); for (Iterator j = newParents.iterator(); j.hasNext();) { ResolvedType newParent = (ResolvedType) j.next(); // We set it here so that the imminent matching for ITDs can // succeed - we // still haven't done the necessary changes to the class file // itself // (like transform super calls) - that is done in // BcelTypeMunger.mungeNewParent() // classType.addParent(newParent); onType.addParent(newParent); ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent); newParentMunger.setSourceLocation(p.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p))); } } return didSomething; } public void weaveNormalTypeMungers(ResolvedType onType) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS, onType .getName()); if (onType.isRawType() || onType.isParameterizedType()) onType = onType.getGenericType(); for (Iterator i = typeMungerList.iterator(); i.hasNext();) { ConcreteTypeMunger m = (ConcreteTypeMunger) i.next(); if (!m.isLateMunger() && m.matches(onType)) { onType.addInterTypeMunger(m); } } CompilationAndWeavingContext.leavingPhase(tok); } // exposed for ClassLoader dynamic weaving public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { return weave(classFile, classType, false); } // non-private for testing LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { LazyClassGen ret = weave(classFile, classType, true); return ret; } private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException { if (classType.isSynthetic()) { // Don't touch synthetic classes if (dump) dumpUnchanged(classFile); return null; } List shadowMungers = fastMatch(shadowMungerList, classType.getResolvedTypeX()); List typeMungers = classType.getResolvedTypeX().getInterTypeMungers(); classType.getResolvedTypeX().checkInterTypeMungers(); // Decide if we need to do actual weaving for this class boolean mightNeedToWeave = shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect() || world.getDeclareAnnotationOnMethods().size() > 0 || world.getDeclareAnnotationOnFields().size() > 0; // May need bridge methods if on 1.5 and something in our hierarchy is // affected by ITDs boolean mightNeedBridgeMethods = world.isInJava5Mode() && !classType.isInterface() && classType.getResolvedTypeX().getInterTypeMungersIncludingSupers().size() > 0; LazyClassGen clazz = null; if (mightNeedToWeave || mightNeedBridgeMethods) { clazz = classType.getLazyClassGen(); // System.err.println("got lazy gen: " + clazz + ", " + // clazz.getWeaverState()); try { boolean isChanged = false; if (mightNeedToWeave) isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers, lateTypeMungerList); if (mightNeedBridgeMethods) isChanged = BcelClassWeaver.calculateAnyRequiredBridgeMethods(world, clazz) || isChanged; if (isChanged) { if (dump) dump(classFile, clazz); return clazz; } } catch (RuntimeException re) { String classDebugInfo = null; try { classDebugInfo = clazz.toLongString(); } catch (Exception e) { // recover from crash whilst producing debug string classDebugInfo = clazz.getClassName(); } String messageText = "trouble in: \n" + classDebugInfo; getWorld().getMessageHandler().handleMessage(new Message(messageText, IMessage.ABORT, re, null)); } catch (Error re) { String classDebugInfo = null; try { classDebugInfo = clazz.toLongString(); } catch (Exception e) { // recover from crash whilst producing debug string classDebugInfo = clazz.getClassName(); } String messageText = "trouble in: \n" + classDebugInfo; getWorld().getMessageHandler().handleMessage(new Message(messageText, IMessage.ABORT, re, null)); } } // this is very odd return behavior trying to keep everyone happy if (dump) { dumpUnchanged(classFile); return clazz; } else { // ATAJ: the class was not weaved, but since it gets there early it // may have new generated inner classes // attached to it to support LTW perX aspectOf support (see // BcelPerClauseAspectAdder) // that aggressively defines the inner <aspect>$mayHaveAspect // interface. if (clazz != null && !clazz.getChildClasses(world).isEmpty()) { return clazz; } return null; } } // ---- writing private void dumpUnchanged(UnwovenClassFile classFile) throws IOException { if (zipOutputStream != null) { writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes()); } else { classFile.writeUnchangedBytes(); } } private String getEntryName(String className) { // XXX what does bcel's getClassName do for inner names return className.replace('.', '/') + ".class"; } private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException { if (zipOutputStream != null) { String mainClassName = classFile.getJavaClass().getClassName(); writeZipEntry(getEntryName(mainClassName), clazz.getJavaClass(world).getBytes()); if (!clazz.getChildClasses(world).isEmpty()) { for (Iterator i = clazz.getChildClasses(world).iterator(); i.hasNext();) { UnwovenClassFile.ChildClass c = (UnwovenClassFile.ChildClass) i.next(); writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes); } } } else { classFile.writeWovenBytes(clazz.getJavaClass(world).getBytes(), clazz.getChildClasses(world)); } } private void writeZipEntry(String name, byte[] bytes) throws IOException { ZipEntry newEntry = new ZipEntry(name); // ??? get compression scheme // right zipOutputStream.putNextEntry(newEntry); zipOutputStream.write(bytes); zipOutputStream.closeEntry(); } private List fastMatch(List list, ResolvedType type) { if (list == null) return Collections.EMPTY_LIST; // here we do the coarsest grained fast match with no kind constraints // this will remove all obvious non-matches and see if we need to do any // weaving FastMatchInfo info = new FastMatchInfo(type, null); List result = new ArrayList(); Iterator iter = list.iterator(); while (iter.hasNext()) { ShadowMunger munger = (ShadowMunger) iter.next(); FuzzyBoolean fb = munger.getPointcut().fastMatch(info); if (fb.maybeTrue()) { result.add(munger); } } return result; } public void setReweavableMode(boolean xNotReweavable) { if (trace.isTraceEnabled()) trace.enter("setReweavableMode", this, xNotReweavable); inReweavableMode = !xNotReweavable; WeaverStateInfo.setReweavableModeDefaults(!xNotReweavable, false, true); BcelClassWeaver.setReweavableMode(!xNotReweavable); if (trace.isTraceEnabled()) trace.exit("setReweavableMode"); } public boolean isReweavable() { return inReweavableMode; } public World getWorld() { return world; } public void tidyUp() { if (trace.isTraceEnabled()) trace.enter("tidyUp", this); shadowMungerList = null; // setup by prepareForWeave typeMungerList = null; // setup by prepareForWeave lateTypeMungerList = null; // setup by prepareForWeave declareParentsList = null; // setup by prepareForWeave if (trace.isTraceEnabled()) trace.exit("tidyUp"); } }
264,563
Bug 264563 [handles] Remove trailing '/' from source path handles
null
resolved fixed
0af658e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-02-12T17:50:17Z"
"2009-02-11T19:20:00Z"
asm/src/org/aspectj/asm/internal/JDTLikeHandleProvider.java
/******************************************************************** * Copyright (c) 2006 Contributors. All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: IBM Corporation - initial API and implementation * Helen Hawkins - initial version *******************************************************************/ package org.aspectj.asm.internal; import java.io.File; import java.util.Iterator; import java.util.List; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IElementHandleProvider; import org.aspectj.asm.IProgramElement; import org.aspectj.bridge.ISourceLocation; /** * Creates JDT-like handles, for example * * method with string argument: <tjp{Demo.java[Demo~main~\[QString; method with generic argument: * <pkg{MyClass.java[MyClass~myMethod~QList\<QString;>; an aspect: <pkg*A1.aj}A1 advice with Integer arg: * <pkg*A8.aj}A8&afterReturning&QInteger; method call: <pkg*A10.aj[C~m1?method-call(void pkg.C.m2()) * */ public class JDTLikeHandleProvider implements IElementHandleProvider { private final AsmManager asm; // Need to keep our own count of the number of initializers // because this information cannot be gained from the ipe. private int initializerCounter = 0; private final char[] empty = new char[] {}; private final char[] countDelim = new char[] { HandleProviderDelimiter.COUNT.getDelimiter() }; private final String backslash = "\\"; private final String emptyString = ""; public JDTLikeHandleProvider(AsmManager asm) { this.asm = asm; } public String createHandleIdentifier(IProgramElement ipe) { // AjBuildManager.setupModel --> top of the tree is either // <root> or the .lst file if (ipe == null || (ipe.getKind().equals(IProgramElement.Kind.FILE_JAVA) && ipe.getName().equals("<root>"))) { return ""; } else if (ipe.getHandleIdentifier(false) != null) { // have already created the handle for this ipe // therefore just return it return ipe.getHandleIdentifier(); } else if (ipe.getKind().equals(IProgramElement.Kind.FILE_LST)) { String configFile = asm.getHierarchy().getConfigFile(); int start = configFile.lastIndexOf(File.separator); int end = configFile.lastIndexOf(".lst"); if (end != -1) { configFile = configFile.substring(start + 1, end); } else { configFile = new StringBuffer("=").append(configFile.substring(start + 1)).toString(); } ipe.setHandleIdentifier(configFile); return configFile; } else if (ipe.getKind() == IProgramElement.Kind.SOURCE_FOLDER) { StringBuffer sb = new StringBuffer(); sb.append(createHandleIdentifier(ipe.getParent())).append("/"); // pr249216 - escape any embedded slashes String folder = ipe.getName(); if (folder.indexOf("/") != -1) { folder = folder.replace("/", "\\/"); } sb.append(folder); String handle = sb.toString(); ipe.setHandleIdentifier(handle); return handle; } IProgramElement parent = ipe.getParent(); if (parent != null && parent.getKind().equals(IProgramElement.Kind.IMPORT_REFERENCE)) { // want to miss out '#import declaration' in the handle parent = ipe.getParent().getParent(); } StringBuffer handle = new StringBuffer(); // add the handle for the parent handle.append(createHandleIdentifier(parent)); // add the correct delimiter for this ipe handle.append(HandleProviderDelimiter.getDelimiter(ipe)); // add the name and any parameters unless we're an initializer // (initializer's names are '...') if (!ipe.getKind().equals(IProgramElement.Kind.INITIALIZER)) { if (ipe.getKind() == IProgramElement.Kind.CLASS && ipe.getName().endsWith("{..}")) { // format: 'new Runnable() {..}' but its anon-y-mouse // dont append anything, there may be a count to follow though (!<n>) } else { if (ipe.getKind() == IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR) { handle.append(ipe.getName()).append("_new").append(getParameters(ipe)); } else { // if (ipe.getKind() == IProgramElement.Kind.PACKAGE && ipe.getName().equals("DEFAULT")) { // // the delimiter will be in there, but skip the word DEFAULT as it is just a placeholder // } else { if (ipe.getKind().isDeclareAnnotation()) { // escape the @ (pr249216c9) handle.append("declare \\@").append(ipe.getName().substring(9)).append(getParameters(ipe)); } else { handle.append(ipe.getName()).append(getParameters(ipe)); } } // } } } // add the count, for example '!2' if its the second ipe of its // kind in the aspect handle.append(getCount(ipe)); ipe.setHandleIdentifier(handle.toString()); return handle.toString(); } private String getParameters(IProgramElement ipe) { if (ipe.getParameterSignatures() == null || ipe.getParameterSignatures().isEmpty()) { return ""; } StringBuffer sb = new StringBuffer(); List parameterTypes = ipe.getParameterSignatures(); for (Iterator iter = parameterTypes.iterator(); iter.hasNext();) { char[] element = (char[]) iter.next(); sb.append(HandleProviderDelimiter.getDelimiter(ipe)); sb.append(NameConvertor.createShortName(element, false, false)); } return sb.toString(); } /** * Determine a count to be suffixed to the handle, this is only necessary for identical looking entries at the same level in the * model (for example two anonymous class declarations). The format is !<n> where n will be greater than 2. * * @param ipe the program element for which the handle is being constructed * @return a char suffix that will either be empty or of the form "!<n>" */ private char[] getCount(IProgramElement ipe) { // TODO could optimize this code char[] byteCodeName = ipe.getBytecodeName().toCharArray(); if (ipe.getKind().isDeclare()) { int index = CharOperation.lastIndexOf('_', byteCodeName); if (index != -1) { return convertCount(CharOperation.subarray(byteCodeName, index + 1, byteCodeName.length)); } } else if (ipe.getKind().equals(IProgramElement.Kind.ADVICE)) { // Look at any peer advice int count = 1; List kids = ipe.getParent().getChildren(); String ipeSig = ipe.getBytecodeSignature(); // remove return type from the signature - it should not be included in the comparison int idx = 0; if (ipeSig != null && ((idx = ipeSig.indexOf(")")) != -1)) { ipeSig = ipeSig.substring(0, idx); } for (Iterator iterator = kids.iterator(); iterator.hasNext();) { IProgramElement object = (IProgramElement) iterator.next(); if (object.equals(ipe)) { break; } if (object.getKind() == ipe.getKind()) { if (object.getName().equals(ipe.getName())) { String sig1 = object.getBytecodeSignature(); if (sig1 != null && (idx = sig1.indexOf(")")) != -1) { sig1 = sig1.substring(0, idx); } if (sig1 == null && ipeSig == null || (sig1 != null && sig1.equals(ipeSig))) { String existingHandle = object.getHandleIdentifier(); int suffixPosition = existingHandle.indexOf('!'); if (suffixPosition != -1) { count = new Integer(existingHandle.substring(suffixPosition + 1)).intValue() + 1; } else { if (count == 1) { count = 2; } } } } } } if (count > 1) { return CharOperation.concat(countDelim, new Integer(count).toString().toCharArray()); } } else if (ipe.getKind().equals(IProgramElement.Kind.INITIALIZER)) { return String.valueOf(++initializerCounter).toCharArray(); } else if (ipe.getKind().equals(IProgramElement.Kind.CODE)) { int index = CharOperation.lastIndexOf('!', byteCodeName); if (index != -1) { return convertCount(CharOperation.subarray(byteCodeName, index + 1, byteCodeName.length)); } } else if (ipe.getKind() == IProgramElement.Kind.CLASS) { // depends on previous children int count = 1; List kids = ipe.getParent().getChildren(); if (ipe.getName().endsWith("{..}")) { // only depends on previous anonymous children, name irrelevant for (Iterator iterator = kids.iterator(); iterator.hasNext();) { IProgramElement object = (IProgramElement) iterator.next(); if (object.equals(ipe)) { break; } if (object.getKind() == ipe.getKind()) { if (object.getName().endsWith("{..}")) { String existingHandle = object.getHandleIdentifier(); int suffixPosition = existingHandle.lastIndexOf('!'); int lastSquareBracket = existingHandle.lastIndexOf('['); // type delimiter if (suffixPosition != -1 && lastSquareBracket < suffixPosition) { // pr260384 count = new Integer(existingHandle.substring(suffixPosition + 1)).intValue() + 1; } else { if (count == 1) { count = 2; } } } } } } else { for (Iterator iterator = kids.iterator(); iterator.hasNext();) { IProgramElement object = (IProgramElement) iterator.next(); if (object.equals(ipe)) { break; } if (object.getKind() == ipe.getKind()) { if (object.getName().equals(ipe.getName())) { String existingHandle = object.getHandleIdentifier(); int suffixPosition = existingHandle.lastIndexOf('!'); int lastSquareBracket = existingHandle.lastIndexOf('['); // type delimiter if (suffixPosition != -1 && lastSquareBracket < suffixPosition) { // pr260384 count = new Integer(existingHandle.substring(suffixPosition + 1)).intValue() + 1; } else { if (count == 1) { count = 2; } } } } } } if (count > 1) { return CharOperation.concat(countDelim, new Integer(count).toString().toCharArray()); } } return empty; } /** * Only returns the count if it's not equal to 1 */ private char[] convertCount(char[] c) { if ((c.length == 1 && c[0] != ' ' && c[0] != '1') || c.length > 1) { return CharOperation.concat(countDelim, c); } return empty; } public String getFileForHandle(String handle) { IProgramElement node = asm.getHierarchy().getElement(handle); if (node != null) { return asm.getCanonicalFilePath(node.getSourceLocation().getSourceFile()); } else if (handle.charAt(0) == HandleProviderDelimiter.ASPECT_CU.getDelimiter() || handle.charAt(0) == HandleProviderDelimiter.COMPILATIONUNIT.getDelimiter()) { // it's something like *MyAspect.aj or {MyClass.java. In other words // it's a file node that's been created with no children and no // parent return backslash + handle.substring(1); } return emptyString; } public int getLineNumberForHandle(String handle) { IProgramElement node = asm.getHierarchy().getElement(handle); if (node != null) { return node.getSourceLocation().getLine(); } else if (handle.charAt(0) == HandleProviderDelimiter.ASPECT_CU.getDelimiter() || handle.charAt(0) == HandleProviderDelimiter.COMPILATIONUNIT.getDelimiter()) { // it's something like *MyAspect.aj or {MyClass.java. In other words // it's a file node that's been created with no children and no // parent return 1; } return -1; } public int getOffSetForHandle(String handle) { IProgramElement node = asm.getHierarchy().getElement(handle); if (node != null) { return node.getSourceLocation().getOffset(); } else if (handle.charAt(0) == HandleProviderDelimiter.ASPECT_CU.getDelimiter() || handle.charAt(0) == HandleProviderDelimiter.COMPILATIONUNIT.getDelimiter()) { // it's something like *MyAspect.aj or {MyClass.java. In other words // it's a file node that's been created with no children and no // parent return 0; } return -1; } public String createHandleIdentifier(ISourceLocation location) { IProgramElement node = asm.getHierarchy().findElementForSourceLine(location); if (node != null) { return createHandleIdentifier(node); } return null; } public String createHandleIdentifier(File sourceFile, int line, int column, int offset) { IProgramElement node = asm.getHierarchy().findElementForOffSet(sourceFile.getAbsolutePath(), line, offset); if (node != null) { return createHandleIdentifier(node); } return null; } public boolean dependsOnLocation() { // handles are independent of soureLocations therefore return false return false; } public void initialize() { // reset the initializer count. This ensures we return the // same handle as JDT for initializers. initializerCounter = 0; } }
264,869
Bug 264869 AspectJ depends on Class files having a dot in their source file name attribute
The following code in ShadowMunger$getBinaryFile() (line 169 ff) fails if a class file does not contain a proper source file name: if (binaryFile == null) { String s = getDeclaringType().getBinaryPath(); File f = getDeclaringType().getSourceLocation().getSourceFile(); int i = f.getPath().lastIndexOf('.'); String path = f.getPath().substring(0, i) + ".class"; binaryFile = new File(s + "!" + path); } (there is no '.' in the file name, thus this gives a string index out of bounds error).
resolved fixed
9f80317
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-02-17T16:20:49Z"
"2009-02-13T15:46:40Z"
org.aspectj.matcher/src/org/aspectj/weaver/ShadowMunger.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.File; import java.util.Collection; import java.util.Map; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; import org.aspectj.util.PartialOrder; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.TypePattern; /** * For every shadow munger, nothing can be done with it until it is concretized. Then... * * (Then we call fast match.) * * For every shadow munger, for every shadow, first match is called, then (if match returned true) the shadow munger is specialized * for the shadow, which may modify state. Then implement is called. */ public abstract class ShadowMunger implements PartialOrder.PartialComparable, IHasPosition { protected Pointcut pointcut; // these three fields hold the source location of this munger protected int start, end; protected ISourceContext sourceContext; private ISourceLocation sourceLocation; private ISourceLocation binarySourceLocation; private File binaryFile; public String handle = null; private ResolvedType declaringType; // the type that declared this munger. public ShadowMunger(Pointcut pointcut, int start, int end, ISourceContext sourceContext) { this.pointcut = pointcut; this.start = start; this.end = end; this.sourceContext = sourceContext; } public abstract ShadowMunger concretize(ResolvedType fromType, World world, PerClause clause); public abstract void specializeOn(Shadow shadow); /** * Implement this munger at the specified shadow, returning a boolean to indicate success. * * @param shadow the shadow where this munger should be applied * @return true if the munger was successful */ public abstract boolean implementOn(Shadow shadow); /** * All overriding methods should call super */ public boolean match(Shadow shadow, World world) { if (world.isXmlConfigured() && world.isAspectIncluded(declaringType)) { TypePattern scoped = world.getAspectScope(declaringType); if (scoped != null) { boolean b = scoped.matches(shadow.getEnclosingType().resolve(world), TypePattern.STATIC).alwaysTrue(); if (!b) { return false; } } } return pointcut.match(shadow).maybeTrue(); } public abstract ShadowMunger parameterizeWith(ResolvedType declaringType, Map typeVariableMap); public int fallbackCompareTo(Object other) { return toString().compareTo(toString()); } public int getEnd() { return end; } public int getStart() { return start; } public ISourceLocation getSourceLocation() { if (sourceLocation == null) { if (sourceContext != null) { sourceLocation = sourceContext.makeSourceLocation(this); } } if (isBinary()) { if (binarySourceLocation == null) { binarySourceLocation = getBinarySourceLocation(sourceLocation); } return binarySourceLocation; } return sourceLocation; } // ---- fields public static final ShadowMunger[] NONE = new ShadowMunger[0]; public Pointcut getPointcut() { return pointcut; } // pointcut may be updated during rewriting... public void setPointcut(Pointcut pointcut) { this.pointcut = pointcut; } /** * Invoked when the shadow munger of a resolved type are processed. * * @param aType */ public void setDeclaringType(ResolvedType aType) { declaringType = aType; } public ResolvedType getDeclaringType() { return declaringType; } /** * @return a Collection of ResolvedType for all checked exceptions that might be thrown by this munger */ public abstract Collection getThrownExceptions(); /** * Does the munger has to check that its exception are accepted by the shadow ? ATAJ: It s not the case for @AJ around advice * f.e. that can throw Throwable, even if the advised method does not throw any exceptions. * * @return true if munger has to check that its exceptions can be throwned based on the shadow */ public abstract boolean mustCheckExceptions(); /** * Returns the binarySourceLocation for the given sourcelocation. This isn't cached because it's used when faulting in the * binary nodes and is called with ISourceLocations for all advice, pointcuts and deows contained within the * resolvedDeclaringAspect. */ public ISourceLocation getBinarySourceLocation(ISourceLocation sl) { if (sl == null) return null; String sourceFileName = null; if (getDeclaringType() instanceof ReferenceType) { String s = ((ReferenceType) getDeclaringType()).getDelegate().getSourcefilename(); int i = s.lastIndexOf('/'); if (i != -1) { sourceFileName = s.substring(i + 1); } else { sourceFileName = s; } } ISourceLocation sLoc = new SourceLocation(getBinaryFile(), sl.getLine(), sl.getEndLine(), ((sl.getColumn() == 0) ? ISourceLocation.NO_COLUMN : sl.getColumn()), sl.getContext(), sourceFileName); return sLoc; } /** * Returns the File with pathname to the class file, for example either C:\temp * \ajcSandbox\workspace\ajcTest16957.tmp\simple.jar!pkg\BinaryAspect.class if the class file is in a jar file, or * C:\temp\ajcSandbox\workspace\ajcTest16957.tmp!pkg\BinaryAspect.class if the class file is in a directory */ private File getBinaryFile() { if (binaryFile == null) { String s = getDeclaringType().getBinaryPath(); File f = getDeclaringType().getSourceLocation().getSourceFile(); int i = f.getPath().lastIndexOf('.'); String path = f.getPath().substring(0, i) + ".class"; binaryFile = new File(s + "!" + path); } return binaryFile; } /** * Returns whether or not this shadow munger came from a binary aspect - keep a record of whether or not we've checked if we're * binary otherwise we keep caluclating the same thing many times */ public boolean isBinary() { if (!checkedIsBinary) { ResolvedType rt = getDeclaringType(); if (rt != null) { isBinary = ((rt.getBinaryPath() == null) ? false : true); } checkedIsBinary = true; } return isBinary; } private boolean isBinary; private boolean checkedIsBinary; }
266,602
Bug 266602 Problem with incremental itd compilation
Reproduceable from Roo code - commenting out a field after a successful build results in this exception. The underlying cause may also apply to ITD methods (and maybe constructors). org.aspectj.weaver.BCException: Couldn't find ITD init member 'void com.springsource.petclinic.domain.Visit_Roo_Entity_Itd.ajc$interFieldInit$com_springsource_petclinic_domain_Visit_Roo_Entity_Itd$com_springsource_petclinic_domain_Visit$id(com.springsource.petclinic.domain.Visit)' on aspect com.springsource.petclinic.domain.Visit_Roo_Entity_Itd when type munging with (BcelTypeMunger ResolvedTypeMunger(Field, java.lang.Long com.springsource.petclinic.domain.Visit.id)) when weaving type com.springsource.petclinic.domain.Visit when weaving classes when weaving when incrementally building with classpath: C:\temp\petclinic\target\classes;E:/jvms/jdk1.6.0_06/jre/lib/resources.jar;E:/jvms/jdk1.6.0_06/jre/lib/rt.jar;E:/jvms/jdk1.6.0_06/jre/lib/jsse.jar;E:/jvms/jdk1.6.0_06/jre/lib/jce.jar;E:/jvms/jdk1.6.0_06/jre/lib/charsets.jar;E:/jvms/jdk1.6.0_06/jre/lib/ext/dnsns.jar;E:/jvms/jdk1.6.0_06/jre/lib/ext/localedata.jar;E:/jvms/jdk1.6.0_06/jre/lib/ext/sunjce_provider.jar;E:/jvms/jdk1.6.0_06/jre/lib/ext/sunmscapi.jar;E:/jvms/jdk1.6.0_06/jre/lib/ext/sunpkcs11.jar;C:/Users/Andy/.m2/repository/org/antlr/com.springsource.antlr/2.7.6/com.springsource.antlr-2.7.6.jar;C:/Users/Andy/.m2/repository/com/thoughtworks/xstream/com.springsource.com.thoughtworks.xstream/1.3.0/com.springsource.com.thoughtworks.xstream-1.3.0.jar;C:/Users/Andy/.m2/repository/edu/emory/mathcs/backport/com.springsource.edu.emory.mathcs.backport/3.1.0/com.springsource.edu.emory.mathcs.backport-3.1.0.jar;C:/Users/Andy/.m2/repository/edu/oswego/cs/concurrent/com.springsource.edu.oswego.cs.dl.util.concurrent/1.3.4/com.springsource.edu.oswego.cs.dl.util.concurrent-1.3.4.jar;C:/Users/Andy/.m2/repository/org/jboss/javassist/com.springsource.javassist/3.3.0.ga/com.springsource.javassist-3.3.0.ga.jar;C:/Users/Andy/.m2/repository/javax/annotation/com.springsource.javax.annotation/1.0.0/com.springsource.javax.annotation-1.0.0.jar;C:/Users/Andy/.m2/repository/javax/persistence/com.springsource.javax.persistence/1.0.0/com.springsource.javax.persistence-1.0.0.jar;C:/Users/Andy/.m2/repository/javax/servlet/com.springsource.javax.servlet/2.4.0/com.springsource.javax.servlet-2.4.0.jar;C:/Users/Andy/.m2/repository/javax/servlet/com.springsource.javax.servlet.jsp.jstl/1.2.0/com.springsource.javax.servlet.jsp.jstl-1.2.0.jar;C:/Users/Andy/.m2/repository/javax/transaction/com.springsource.javax.transaction/1.1.0/com.springsource.javax.transaction-1.1.0.jar;C:/Users/Andy/.m2/repository/net/sourceforge/cglib/com.springsource.net.sf.cglib/2.1.3/com.springsource.net.sf.cglib-2.1.3.jar;C:/Users/Andy/.m2/repository/net/sourceforge/ehcache/com.springsource.net.sf.ehcache/1.4.1/com.springsource.net.sf.ehcache-1.4.1.jar;C:/Users/Andy/.m2/repository/net/sourceforge/jsr107cache/com.springsource.net.sf.jsr107cache/1.0.0/com.springsource.net.sf.jsr107cache-1.0.0.jar;C:/Users/Andy/.m2/repository/org/antlr/com.springsource.org.antlr/3.0.1/com.springsource.org.antlr-3.0.1.jar;C:/Users/Andy/.m2/repository/org/aopalliance/com.springsource.org.aopalliance/1.0.0/com.springsource.org.aopalliance-1.0.0.jar;C:/Users/Andy/.m2/repository/org/apache/commons/com.springsource.org.apache.commons.collections/3.2.0/com.springsource.org.apache.commons.collections-3.2.0.jar;C:/Users/Andy/.m2/repository/org/apache/commons/com.springsource.org.apache.commons.dbcp/1.2.2.osgi/com.springsource.org.apache.commons.dbcp-1.2.2.osgi.jar;C:/Users/Andy/.m2/repository/org/apache/commons/com.springsource.org.apache.commons.logging/1.1.1/com.springsource.org.apache.commons.logging-1.1.1.jar;C:/Users/Andy/.m2/repository/org/apache/commons/com.springsource.org.apache.commons.pool/1.3.0/com.springsource.org.apache.commons.pool-1.3.0.jar;C:/Users/Andy/.m2/repository/org/apache/log4j/com.springsource.org.apache.log4j/1.2.15/com.springsource.org.apache.log4j-1.2.15.jar;C:/Users/Andy/.m2/repository/org/apache/taglibs/com.springsource.org.apache.taglibs.standard/1.1.2/com.springsource.org.apache.taglibs.standard-1.1.2.jar;C:/Users/Andy/.m2/repository/org/aspectj/com.springsource.org.aspectj.runtime/1.6.2.RELEASE/com.springsource.org.aspectj.runtime-1.6.2.RELEASE.jar;C:/Users/Andy/.m2/repository/org/aspectj/com.springsource.org.aspectj.tools/1.6.2.RELEASE/com.springsource.org.aspectj.tools-1.6.2.RELEASE.jar;C:/Users/Andy/.m2/repository/org/aspectj/com.springsource.org.aspectj.weaver/1.6.2.RELEASE/com.springsource.org.aspectj.weaver-1.6.2.RELEASE.jar;C:/Users/Andy/.m2/repository/org/dom4j/com.springsource.org.dom4j/1.6.1/com.springsource.org.dom4j-1.6.1.jar;C:/Users/Andy/.m2/repository/org/hibernate/com.springsource.org.hibernate/3.2.6.ga/com.springsource.org.hibernate-3.2.6.ga.jar;C:/Users/Andy/.m2/repository/org/hibernate/com.springsource.org.hibernate.annotations/3.3.1.ga/com.springsource.org.hibernate.annotations-3.3.1.ga.jar;C:/Users/Andy/.m2/repository/org/hibernate/com.springsource.org.hibernate.annotations.common/3.3.0.ga/com.springsource.org.hibernate.annotations.common-3.3.0.ga.jar;C:/Users/Andy/.m2/repository/org/hibernate/com.springsource.org.hibernate.ejb/3.3.2.GA/com.springsource.org.hibernate.ejb-3.3.2.GA.jar;C:/Users/Andy/.m2/repository/org/hibernate/com.springsource.org.hibernate.validator/3.0.0.GA/com.springsource.org.hibernate.validator-3.0.0.GA.jar;C:/Users/Andy/.m2/repository/org/hsqldb/com.springsource.org.hsqldb/1.8.0.9/com.springsource.org.hsqldb-1.8.0.9.jar;C:/Users/Andy/.m2/repository/org/jboss/util/com.springsource.org.jboss.util/2.0.4.GA/com.springsource.org.jboss.util-2.0.4.GA.jar;C:/Users/Andy/.m2/repository/org/junit/com.springsource.org.junit/4.4.0/com.springsource.org.junit-4.4.0.jar;C:/Users/Andy/.m2/repository/org/objectweb/asm/com.springsource.org.objectweb.asm/2.2.3/com.springsource.org.objectweb.asm-2.2.3.jar;C:/Users/Andy/.m2/repository/org/objectweb/asm/com.springsource.org.objectweb.asm.attrs/1.5.3/com.springsource.org.objectweb.asm.attrs-1.5.3.jar;C:/Users/Andy/.m2/repository/org/objectweb/asm/com.springsource.org.objectweb.asm.commons/2.2.3/com.springsource.org.objectweb.asm.commons-2.2.3.jar;C:/Users/Andy/.m2/repository/org/xmlpull/com.springsource.org.xmlpull/1.1.3.4-O/com.springsource.org.xmlpull-1.1.3.4-O.jar;C:/Users/Andy/.m2/repository/org/springframework/org.springframework.aop/3.0.0.M1/org.springframework.aop-3.0.0.M1.jar;C:/Users/Andy/.m2/repository/org/springframework/org.springframework.aspects/3.0.0.M1/org.springframework.aspects-3.0.0.M1.jar;C:/Users/Andy/.m2/repository/org/springframework/org.springframework.beans/3.0.0.M1/org.springframework.beans-3.0.0.M1.jar;C:/Users/Andy/.m2/repository/org/springframework/org.springframework.context/3.0.0.M1/org.springframework.context-3.0.0.M1.jar;C:/Users/Andy/.m2/repository/org/springframework/org.springframework.core/3.0.0.M1/org.springframework.core-3.0.0.M1.jar;C:/Users/Andy/.m2/repository/org/springframework/org.springframework.expression/3.0.0.M1/org.springframework.expression-3.0.0.M1.jar;C:/Users/Andy/.m2/repository/org/springframework/org.springframework.jdbc/3.0.0.M1/org.springframework.jdbc-3.0.0.M1.jar;C:/Users/Andy/.m2/repository/org/springframework/org.springframework.orm/3.0.0.M1/org.springframework.orm-3.0.0.M1.jar;C:/Users/Andy/.m2/repository/org/springframework/org.springframework.test/3.0.0.M1/org.springframework.test-3.0.0.M1.jar;C:/Users/Andy/.m2/repository/org/springframework/org.springframework.transaction/3.0.0.M1/org.springframework.transaction-3.0.0.M1.jar;C:/Users/Andy/.m2/repository/org/springframework/org.springframework.web/3.0.0.M1/org.springframework.web-3.0.0.M1.jar;C:/Users/Andy/.m2/repository/org/springframework/org.springframework.web.servlet/3.0.0.M1/org.springframework.web.servlet-3.0.0.M1.jar;C:/Users/Andy/.m2/repository/org/springframework/roo/roo-core/0.2.0-SNAPSHOT/roo-core-0.2.0-SNAPSHOT.jar;F:/eclipse/e342/eclipse/plugins/org.aspectj.runtime_1.6.4.20090205161900/aspectjrt.jar;f:\jvms\jdk1.6.0_06\jre\lib\ext\dnsns.jar;f:\jvms\jdk1.6.0_06\jre\lib\ext\localedata.jar;f:\jvms\jdk1.6.0_06\jre\lib\ext\sunjce_provider.jar;f:\jvms\jdk1.6.0_06\jre\lib\ext\sunmscapi.jar;f:\jvms\jdk1.6.0_06\jre\lib\ext\sunpkcs11.jar;f:\eclipse\e342\eclipse\\plugins\org.eclipse.equinox.launcher_1.0.101.R34x_v20081125.jar; at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewField(BcelTypeMunger.java:1638) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:90) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:441) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:103) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1732) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1693) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1458) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1272) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.weaveQueuedEntries(AjPipeliningCompilerAdapter.java:435) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.queueForWeaving(AjPipeliningCompilerAdapter.java:371) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.afterProcessing(AjPipeliningCompilerAdapter.java:358) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$after$org_aspectj_ajdt_internal_compiler_CompilerAdapter$5$6b855184(CompilerAdapter.aj:98) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:652) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:392) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:977) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performBuild(AjBuildManager.java:301) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:183) at org.aspectj.ajde.core.internal.AjdeCoreBuildManager.performBuild(AjdeCoreBuildManager.java:127) at org.aspectj.ajde.core.AjCompiler.build(AjCompiler.java:88) at org.eclipse.ajdt.core.builder.AJBuilder.build(AJBuilder.java:223) at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:633) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:37) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:170) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:201) at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:253) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:37) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:256) at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:309) at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:341) at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:140) at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:238) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)
resolved fixed
2f36e7f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-03-02T04:00:31Z"
"2009-02-28T22:26:40Z"
weaver/src/org/aspectj/weaver/bcel/BcelTypeMunger.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur @AspectJ ITDs * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.ConstantPool; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen; import org.aspectj.apache.bcel.generic.FieldGen; import org.aspectj.apache.bcel.generic.InstructionBranch; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.Member; import org.aspectj.weaver.MethodDelegateTypeMunger; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.PerObjectInterfaceTypeMunger; import org.aspectj.weaver.PrivilegedAccessMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.model.AsmRelationshipProvider; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.Pointcut; //XXX addLazyMethodGen is probably bad everywhere public class BcelTypeMunger extends ConcreteTypeMunger { public BcelTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType) { super(munger, aspectType); } public String toString() { return "(BcelTypeMunger " + getMunger() + ")"; } public boolean shouldOverwrite() { return false; } public boolean munge(BcelClassWeaver weaver) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MUNGING_WITH, this); boolean changed = false; boolean worthReporting = true; if (munger.getKind() == ResolvedTypeMunger.Field) { changed = mungeNewField(weaver, (NewFieldTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.Method) { changed = mungeNewMethod(weaver, (NewMethodTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.MethodDelegate2) { changed = mungeMethodDelegate(weaver, (MethodDelegateTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.FieldHost) { changed = mungeFieldHost(weaver, (MethodDelegateTypeMunger.FieldHostTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.PerObjectInterface) { changed = mungePerObjectInterface(weaver, (PerObjectInterfaceTypeMunger) munger); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.PerTypeWithinInterface) { // PTWIMPL Transform the target type (add the aspect instance field) changed = mungePerTypeWithinTransformer(weaver); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.PrivilegedAccess) { changed = mungePrivilegedAccess(weaver, (PrivilegedAccessMunger) munger); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.Constructor) { changed = mungeNewConstructor(weaver, (NewConstructorTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.Parent) { changed = mungeNewParent(weaver, (NewParentTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.AnnotationOnType) { changed = mungeNewAnnotationOnType(weaver, (AnnotationOnTypeMunger) munger); worthReporting = false; } else { throw new RuntimeException("unimplemented"); } if (changed && munger.changesPublicSignature()) { WeaverStateInfo info = weaver.getLazyClassGen().getOrCreateWeaverStateInfo(weaver.getReweavableMode()); info.addConcreteMunger(this); } if (changed && worthReporting) { AsmRelationshipProvider.addRelationship(((BcelWorld) getWorld()).getModelAsAsmManager(), weaver.getLazyClassGen() .getType(), munger, getAspectType()); } // TAG: WeavingMessage if (changed && worthReporting && munger != null && !weaver.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { String tName = weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getName(); if (tName.indexOf("no debug info available") != -1) tName = "no debug info available"; else tName = getShortname(weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getPath()); String fName = getShortname(getAspectType().getSourceLocation().getSourceFile().getPath()); if (munger.getKind().equals(ResolvedTypeMunger.Parent)) { // This message could come out of AjLookupEnvironment.addParent // if doing parents // munging at compile time only... NewParentTypeMunger parentTM = (NewParentTypeMunger) munger; if (parentTM.getNewParent().isInterface()) { weaver.getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS, new String[] { weaver.getLazyClassGen().getType().getName(), tName, parentTM.getNewParent().getName(), fName }, weaver.getLazyClassGen().getClassName(), getAspectType().getName())); } else { weaver.getWorld().getMessageHandler().handleMessage( WeaveMessage .constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS, new String[] { weaver.getLazyClassGen().getType().getName(), tName, parentTM.getNewParent().getName(), fName })); // TAG: WeavingMessage DECLARE PARENTS: EXTENDS // reportDeclareParentsMessage(WeaveMessage. // WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent); } } else if (munger.getKind().equals(ResolvedTypeMunger.FieldHost)) { // hidden } else { ResolvedMember declaredSig = munger.getSignature(); // if (declaredSig==null) declaredSig= munger.getSignature(); weaver.getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ITD, new String[] { weaver.getLazyClassGen().getType().getName(), tName, munger.getKind().toString().toLowerCase(), getAspectType().getName(), fName + ":'" + declaredSig + "'" }, weaver.getLazyClassGen() .getClassName(), getAspectType().getName())); } } CompilationAndWeavingContext.leavingPhase(tok); return changed; } private String getShortname(String path) { int takefrom = path.lastIndexOf('/'); if (takefrom == -1) { takefrom = path.lastIndexOf('\\'); } return path.substring(takefrom + 1); } private boolean mungeNewAnnotationOnType(BcelClassWeaver weaver, AnnotationOnTypeMunger munger) { // FIXME asc this has already been done up front, need to do it here // too? weaver.getLazyClassGen().addAnnotation(((BcelAnnotation) munger.getNewAnnotation()).getBcelAnnotation()); return true; } /** * For a long time, AspectJ did not allow binary weaving of declare parents. This restriction is now lifted but could do with * more testing! */ private boolean mungeNewParent(BcelClassWeaver weaver, NewParentTypeMunger munger) { LazyClassGen newParentTarget = weaver.getLazyClassGen(); ResolvedType newParent = munger.getNewParent(); boolean cont = true; // Set to false when we error, so we don't actually // *do* the munge cont = enforceDecpRule1_abstractMethodsImplemented(weaver, munger.getSourceLocation(), newParentTarget, newParent); cont = enforceDecpRule2_cantExtendFinalClass(weaver, munger.getSourceLocation(), newParentTarget, newParent) && cont; List methods = newParent.getMethodsWithoutIterator(false, true); for (Iterator iter = methods.iterator(); iter.hasNext();) { ResolvedMember superMethod = (ResolvedMember) iter.next(); if (!superMethod.getName().equals("<init>")) { LazyMethodGen subMethod = findMatchingMethod(newParentTarget, superMethod); if (subMethod != null && !subMethod.isBridgeMethod()) { // FIXME // asc // is // this // safe // for // all // bridge // methods // ? if (!(subMethod.isSynthetic() && superMethod.isSynthetic())) { if (!(subMethod.isStatic() && subMethod.getName().startsWith("access$"))) { // ignore generated // accessors cont = enforceDecpRule3_visibilityChanges(weaver, newParent, superMethod, subMethod) && cont; cont = enforceDecpRule4_compatibleReturnTypes(weaver, superMethod, subMethod) && cont; cont = enforceDecpRule5_cantChangeFromStaticToNonstatic(weaver, munger.getSourceLocation(), superMethod, subMethod) && cont; } } } } } if (!cont) return false; // A rule was violated and an error message already // reported if (newParent.isClass()) { // Changing the supertype if (!attemptToModifySuperCalls(weaver, newParentTarget, newParent)) return false; newParentTarget.setSuperClass(newParent); } else { // Adding a new interface newParentTarget.addInterface(newParent, getSourceLocation()); } return true; } /** * Rule 1: For the declare parents to be allowed, the target type must override and implement inherited abstract methods (if the * type is not declared abstract) */ private boolean enforceDecpRule1_abstractMethodsImplemented(BcelClassWeaver weaver, ISourceLocation mungerLoc, LazyClassGen newParentTarget, ResolvedType newParent) { boolean ruleCheckingSucceeded = true; if (!(newParentTarget.isAbstract() || newParentTarget.isInterface())) { // Ignore // abstract // classes // or // interfaces List methods = newParent.getMethodsWithoutIterator(false, true); for (Iterator i = methods.iterator(); i.hasNext();) { ResolvedMember o = (ResolvedMember) i.next(); if (o.isAbstract() && !o.getName().startsWith("ajc$interField")) { // Ignore // abstract // methods // of // ajc$interField // prefixed // methods ResolvedMember discoveredImpl = null; List newParentTargetMethods = newParentTarget.getType().getMethodsWithoutIterator(false, true); for (Iterator ii = newParentTargetMethods.iterator(); ii.hasNext() && discoveredImpl == null;) { ResolvedMember gen2 = (ResolvedMember) ii.next(); if (gen2.getName().equals(o.getName()) && gen2.getParameterSignature().equals(o.getParameterSignature()) && !gen2.isAbstract()) { discoveredImpl = gen2; // Found a valid // implementation ! } } if (discoveredImpl == null) { // didnt find a valid implementation, lets check the // ITDs on this type to see if they satisfy it boolean satisfiedByITD = false; for (Iterator ii = newParentTarget.getType().getInterTypeMungersIncludingSupers().iterator(); ii.hasNext();) { ConcreteTypeMunger m = (ConcreteTypeMunger) ii.next(); if (m.getMunger() != null && m.getMunger().getKind() == ResolvedTypeMunger.Method) { ResolvedMember sig = m.getSignature(); if (!Modifier.isAbstract(sig.getModifiers())) { // If the ITD shares a type variable with // some target type, we need to tailor it // for that // type if (m.isTargetTypeParameterized()) { ResolvedType genericOnType = getWorld().resolve(sig.getDeclaringType()).getGenericType(); m = m.parameterizedFor(newParent.discoverActualOccurrenceOfTypeInHierarchy(genericOnType)); sig = m.getSignature(); // possible sig // change when // type // parameters // filled in } if (ResolvedType.matches(AjcMemberMaker.interMethod(sig, m.getAspectType(), sig .getDeclaringType().resolve(weaver.getWorld()).isInterface()), o)) { satisfiedByITD = true; } } } else if (m.getMunger() != null && m.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate2) { satisfiedByITD = true;// AV - that should be // enough, no need to // check more } } if (!satisfiedByITD) { error(weaver, "The type " + newParentTarget.getName() + " must implement the inherited abstract method " + o.getDeclaringType() + "." + o.getName() + o.getParameterSignature(), newParentTarget.getType().getSourceLocation(), new ISourceLocation[] { o.getSourceLocation(), mungerLoc }); ruleCheckingSucceeded = false; } } } } } return ruleCheckingSucceeded; } /** * Rule 2. Can't extend final types */ private boolean enforceDecpRule2_cantExtendFinalClass(BcelClassWeaver weaver, ISourceLocation mungerLoc, LazyClassGen newParentTarget, ResolvedType newParent) { if (newParent.isFinal()) { error(weaver, "Cannot make type " + newParentTarget.getName() + " extend final class " + newParent.getName(), newParentTarget.getType().getSourceLocation(), new ISourceLocation[] { mungerLoc }); return false; } return true; } /** * Rule 3. Can't narrow visibility of methods when overriding */ private boolean enforceDecpRule3_visibilityChanges(BcelClassWeaver weaver, ResolvedType newParent, ResolvedMember superMethod, LazyMethodGen subMethod) { boolean cont = true; if (superMethod.isPublic()) { if (subMethod.isProtected() || subMethod.isDefault() || subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage( MessageUtil.error("Cannot reduce the visibility of the inherited method '" + superMethod + "' from " + newParent.getName(), superMethod.getSourceLocation())); cont = false; } } else if (superMethod.isProtected()) { if (subMethod.isDefault() || subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage( MessageUtil.error("Cannot reduce the visibility of the inherited method '" + superMethod + "' from " + newParent.getName(), superMethod.getSourceLocation())); cont = false; } } else if (superMethod.isDefault()) { if (subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage( MessageUtil.error("Cannot reduce the visibility of the inherited method '" + superMethod + "' from " + newParent.getName(), superMethod.getSourceLocation())); cont = false; } } return cont; } /** * Rule 4. Can't have incompatible return types */ private boolean enforceDecpRule4_compatibleReturnTypes(BcelClassWeaver weaver, ResolvedMember superMethod, LazyMethodGen subMethod) { boolean cont = true; String superReturnTypeSig = superMethod.getGenericReturnType().getSignature(); // eg. Pjava/util/Collection<LFoo;> String subReturnTypeSig = subMethod.getGenericReturnTypeSignature(); superReturnTypeSig = superReturnTypeSig.replace('.', '/'); subReturnTypeSig = subReturnTypeSig.replace('.', '/'); if (!superReturnTypeSig.equals(subReturnTypeSig)) { // Check for covariance ResolvedType subType = weaver.getWorld().resolve(subMethod.getReturnType()); ResolvedType superType = weaver.getWorld().resolve(superMethod.getReturnType()); if (!superType.isAssignableFrom(subType)) { weaver.getWorld().getMessageHandler().handleMessage( MessageUtil.error("The return type is incompatible with " + superMethod.getDeclaringType() + "." + superMethod.getName() + superMethod.getParameterSignature(), subMethod.getSourceLocation())); // this just might be a better error message... // "The return type '"+subReturnTypeSig+ // "' is incompatible with the overridden method " // +superMethod.getDeclaringType()+"."+ // superMethod.getName()+superMethod.getParameterSignature()+ // " which returns '"+superReturnTypeSig+"'", cont = false; } } return cont; } /** * Rule5. Method overrides can't change the staticality (word?) - you can't override and make an instance method static or * override and make a static method an instance method. */ private boolean enforceDecpRule5_cantChangeFromStaticToNonstatic(BcelClassWeaver weaver, ISourceLocation mungerLoc, ResolvedMember superMethod, LazyMethodGen subMethod) { if (superMethod.isStatic() && !subMethod.isStatic()) { error(weaver, "This instance method " + subMethod.getName() + subMethod.getParameterSignature() + " cannot override the static method from " + superMethod.getDeclaringType().getName(), subMethod .getSourceLocation(), new ISourceLocation[] { mungerLoc }); return false; } else if (!superMethod.isStatic() && subMethod.isStatic()) { error(weaver, "The static method " + subMethod.getName() + subMethod.getParameterSignature() + " cannot hide the instance method from " + superMethod.getDeclaringType().getName(), subMethod .getSourceLocation(), new ISourceLocation[] { mungerLoc }); return false; } return true; } public void error(BcelClassWeaver weaver, String text, ISourceLocation primaryLoc, ISourceLocation[] extraLocs) { IMessage msg = new Message(text, primaryLoc, true, extraLocs); weaver.getWorld().getMessageHandler().handleMessage(msg); } /** * Search the specified type for a particular method - do not use the return value in the comparison as it is not considered for * overriding. */ private LazyMethodGen findMatchingMethod(LazyClassGen newParentTarget, ResolvedMember m) { LazyMethodGen found = null; List methodGens = newParentTarget.getMethodGens(); for (Iterator i = methodGens.iterator(); i.hasNext() && found == null;) { LazyMethodGen gen = (LazyMethodGen) i.next(); if (gen.getName().equals(m.getName()) && gen.getParameterSignature().equals(m.getParameterSignature())) { found = gen; } } return found; } /** * The main part of implementing declare parents extends. Modify super ctor calls to target the new type. */ public boolean attemptToModifySuperCalls(BcelClassWeaver weaver, LazyClassGen newParentTarget, ResolvedType newParent) { String currentParent = newParentTarget.getSuperClass().getName();// getName(); if (newParent.getGenericType() != null) newParent = newParent.getGenericType(); // target new super calls at // the generic type if its // raw or parameterized List mgs = newParentTarget.getMethodGens(); // Look for ctors to modify for (Iterator iter = mgs.iterator(); iter.hasNext();) { LazyMethodGen aMethod = (LazyMethodGen) iter.next(); if (aMethod.getName().equals("<init>")) { InstructionList insList = aMethod.getBody(); InstructionHandle handle = insList.getStart(); while (handle != null) { if (handle.getInstruction().opcode == Constants.INVOKESPECIAL) { ConstantPool cpg = newParentTarget.getConstantPool(); InvokeInstruction invokeSpecial = (InvokeInstruction) handle.getInstruction(); if (invokeSpecial.getClassName(cpg).equals(currentParent) && invokeSpecial.getMethodName(cpg).equals("<init>")) { // System.err.println( // "Transforming super call '<init>" // +sp.getSignature(cpg)+"'"); // 1. Check there is a ctor in the new parent with // the same signature ResolvedMember newCtor = getConstructorWithSignature(newParent, invokeSpecial.getSignature(cpg)); if (newCtor == null) { // 2. Check ITDCs to see if the necessary ctor // is provided that way boolean satisfiedByITDC = false; for (Iterator ii = newParentTarget.getType().getInterTypeMungersIncludingSupers().iterator(); ii .hasNext() && !satisfiedByITDC;) { ConcreteTypeMunger m = (ConcreteTypeMunger) ii.next(); if (m.getMunger() instanceof NewConstructorTypeMunger) { if (m.getSignature().getSignature().equals(invokeSpecial.getSignature(cpg))) { satisfiedByITDC = true; } } } if (!satisfiedByITDC) { String csig = createReadableCtorSig(newParent, cpg, invokeSpecial); weaver.getWorld().getMessageHandler().handleMessage( MessageUtil.error("Unable to modify hierarchy for " + newParentTarget.getClassName() + " - the constructor " + csig + " is missing", this.getSourceLocation())); return false; } } int idx = cpg.addMethodref(newParent.getName(), invokeSpecial.getMethodName(cpg), invokeSpecial .getSignature(cpg)); invokeSpecial.setIndex(idx); } } handle = handle.getNext(); } } } return true; } /** * Creates a nice signature for the ctor, something like "(int,Integer,String)" */ private String createReadableCtorSig(ResolvedType newParent, ConstantPool cpg, InvokeInstruction invokeSpecial) { StringBuffer sb = new StringBuffer(); Type[] ctorArgs = invokeSpecial.getArgumentTypes(cpg); sb.append(newParent.getClassName()); sb.append("("); for (int i = 0; i < ctorArgs.length; i++) { String argtype = ctorArgs[i].toString(); if (argtype.lastIndexOf(".") != -1) sb.append(argtype.substring(argtype.lastIndexOf(".") + 1)); else sb.append(argtype); if (i + 1 < ctorArgs.length) sb.append(","); } sb.append(")"); return sb.toString(); } private ResolvedMember getConstructorWithSignature(ResolvedType tx, String signature) { ResolvedMember[] mems = tx.getDeclaredJavaMethods(); for (int i = 0; i < mems.length; i++) { ResolvedMember rm = mems[i]; if (rm.getName().equals("<init>")) { if (rm.getSignature().equals(signature)) return rm; } } return null; } private boolean mungePrivilegedAccess(BcelClassWeaver weaver, PrivilegedAccessMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); ResolvedMember member = munger.getMember(); ResolvedType onType = weaver.getWorld().resolve(member.getDeclaringType(), munger.getSourceLocation()); if (onType.isRawType()) onType = onType.getGenericType(); // System.out.println("munging: " + gen + " with " + member); if (onType.equals(gen.getType())) { if (member.getKind() == Member.FIELD) { // System.out.println("matched: " + gen); addFieldGetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldGet(aspectType, member)); addFieldSetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldSet(aspectType, member)); return true; } else if (member.getKind() == Member.METHOD) { addMethodDispatch(gen, member, AjcMemberMaker.privilegedAccessMethodForMethod(aspectType, member)); return true; } else if (member.getKind() == Member.CONSTRUCTOR) { for (Iterator i = gen.getMethodGens().iterator(); i.hasNext();) { LazyMethodGen m = (LazyMethodGen) i.next(); if (m.getMemberView() != null && m.getMemberView().getKind() == Member.CONSTRUCTOR) { // m.getMemberView().equals(member)) { m.forcePublic(); // return true; } } return true; // throw new BCException("no match for " + member + " in " + // gen); } else if (member.getKind() == Member.STATIC_INITIALIZATION) { gen.forcePublic(); return true; } else { throw new RuntimeException("unimplemented"); } } return false; } private void addFieldGetter(LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); if (field.isStatic()) { il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()), Constants.GETSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()), Constants.GETFIELD)); } il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(field.getType()))); mg.getBody().insert(il); gen.addMethodGen(mg, getSignature().getSourceLocation()); } private void addFieldSetter(LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); Type fieldType = BcelWorld.makeBcelType(field.getType()); if (field.isStatic()) { il.append(InstructionFactory.createLoad(fieldType, 0)); il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), fieldType, Constants.PUTSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(InstructionFactory.createLoad(fieldType, 1)); il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), fieldType, Constants.PUTFIELD)); } il.append(InstructionFactory.createReturn(Type.VOID)); mg.getBody().insert(il); gen.addMethodGen(mg, getSignature().getSourceLocation()); } private void addMethodDispatch(LazyClassGen gen, ResolvedMember method, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); // Type fieldType = BcelWorld.makeBcelType(field.getType()); Type[] paramTypes = BcelWorld.makeBcelTypes(method.getParameterTypes()); int pos = 0; if (!method.isStatic()) { il.append(InstructionConstants.ALOAD_0); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; il.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } il.append(Utility.createInvoke(fact, (BcelWorld) aspectType.getWorld(), method)); il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(method.getReturnType()))); mg.getBody().insert(il); gen.addMethodGen(mg); } protected LazyMethodGen makeMethodGen(LazyClassGen gen, ResolvedMember member) { LazyMethodGen ret = new LazyMethodGen(member.getModifiers(), BcelWorld.makeBcelType(member.getReturnType()), member .getName(), BcelWorld.makeBcelTypes(member.getParameterTypes()), UnresolvedType.getNames(member.getExceptions()), gen); // 43972 : Static crosscutting makes interfaces unusable for javac // ret.makeSynthetic(); return ret; } protected FieldGen makeFieldGen(LazyClassGen gen, ResolvedMember member) { return new FieldGen(member.getModifiers(), BcelWorld.makeBcelType(member.getReturnType()), member.getName(), gen .getConstantPool()); } private boolean mungePerObjectInterface(BcelClassWeaver weaver, PerObjectInterfaceTypeMunger munger) { // System.err.println("Munging perobject ["+munger+"] onto "+weaver. // getLazyClassGen().getClassName()); LazyClassGen gen = weaver.getLazyClassGen(); if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) { FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perObjectField(gen.getType(), aspectType)); gen.addField(fg, getSourceLocation()); Type fieldType = BcelWorld.makeBcelType(aspectType); LazyMethodGen mg = new LazyMethodGen(Modifier.PUBLIC, fieldType, NameMangler.perObjectInterfaceGet(aspectType), new Type[0], new String[0], gen); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD)); il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); LazyMethodGen mg1 = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, NameMangler.perObjectInterfaceSet(aspectType), new Type[] { fieldType, }, new String[0], gen); InstructionList il1 = new InstructionList(); il1.append(InstructionConstants.ALOAD_0); il1.append(InstructionFactory.createLoad(fieldType, 1)); il1.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD)); il1.append(InstructionFactory.createReturn(Type.VOID)); mg1.getBody().insert(il1); gen.addMethodGen(mg1); gen.addInterface(munger.getInterfaceType().resolve(weaver.getWorld()), getSourceLocation()); return true; } else { return false; } } // PTWIMPL Add field to hold aspect instance and an accessor private boolean mungePerTypeWithinTransformer(BcelClassWeaver weaver) { LazyClassGen gen = weaver.getLazyClassGen(); // if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) { // Add (to the target type) the field that will hold the aspect instance // e.g ajc$com_blah_SecurityAspect$ptwAspectInstance FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perTypeWithinField(gen.getType(), aspectType)); gen.addField(fg, getSourceLocation()); // Add an accessor for this new field, the // ajc$<aspectname>$localAspectOf() method // e.g. // "public com_blah_SecurityAspect ajc$com_blah_SecurityAspect$localAspectOf()" Type fieldType = BcelWorld.makeBcelType(aspectType); LazyMethodGen mg = new LazyMethodGen(Modifier.PUBLIC | Modifier.STATIC, fieldType, NameMangler .perTypeWithinLocalAspectOf(aspectType), new Type[0], new String[0], gen); InstructionList il = new InstructionList(); // PTWIMPL ?? Should check if it is null and throw // NoAspectBoundException InstructionFactory fact = gen.getFactory(); il.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.GETSTATIC)); il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); return true; // } else { // return false; // } } // ??? Why do we have this method? I thought by now we would know if it // matched or not private boolean couldMatch(BcelObjectType bcelObjectType, Pointcut pointcut) { return !bcelObjectType.isInterface(); } private boolean mungeNewMethod(BcelClassWeaver weaver, NewMethodTypeMunger munger) { World w = weaver.getWorld(); // Resolving it will sort out the tvars ResolvedMember unMangledInterMethod = munger.getSignature().resolve(w); // do matching on the unMangled one, but actually add them to the // mangled method ResolvedMember interMethodBody = munger.getDeclaredInterMethodBody(aspectType, w); ResolvedMember interMethodDispatcher = munger.getDeclaredInterMethodDispatcher(aspectType, w); ResolvedMember memberHoldingAnyAnnotations = interMethodDispatcher; ResolvedType onType = weaver.getWorld().resolve(unMangledInterMethod.getDeclaringType(), munger.getSourceLocation()); LazyClassGen gen = weaver.getLazyClassGen(); boolean mungingInterface = gen.isInterface(); if (onType.isRawType()) onType = onType.getGenericType(); boolean onInterface = onType.isInterface(); // Simple checks, can't ITD on annotations or enums if (onType.isAnnotation()) { signalError(WeaverMessages.ITDM_ON_ANNOTATION_NOT_ALLOWED, weaver, onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDM_ON_ENUM_NOT_ALLOWED, weaver, onType); return false; } if (onInterface && gen.getLazyMethodGen(unMangledInterMethod.getName(), unMangledInterMethod.getSignature(), true) != null) { // this is ok, we could be providing the default implementation of a // method // that the target has already declared return false; } // If we are processing the intended ITD target type (might be an // interface) if (onType.equals(gen.getType())) { ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, onInterface); LazyMethodGen newMethod = makeMethodGen(gen, mangledInterMethod); if (mungingInterface) { // we want the modifiers of the ITD to be used for all // *implementors* of the // interface, but the method itself we add to the interface must // be public abstract newMethod.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT); } // pr98901 // For copying the annotations across, we have to discover the real // member in the aspect which is holding them. if (weaver.getWorld().isInJava5Mode()) { AnnotationAJ annotationsOnRealMember[] = null; ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) toLookOn = aspectType.getGenericType(); ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn, memberHoldingAnyAnnotations, false); if (realMember == null) throw new BCException("Couldn't find ITD holder member '" + memberHoldingAnyAnnotations + "' on aspect " + aspectType); annotationsOnRealMember = realMember.getAnnotations(); if (annotationsOnRealMember != null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationAJ annotationX = annotationsOnRealMember[i]; AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); newMethod.addAnnotation(new BcelAnnotation(ag, weaver.getWorld())); } } AnnotationAJ[][] pAnnos = realMember.getParameterAnnotations(); int offset = newMethod.isStatic() ? 0 : 1; if (pAnnos != null && pAnnos.length != 0) { int param = 0; for (int i = offset; i < pAnnos.length; i++) { AnnotationAJ[] annosOnParam = pAnnos[i]; if (annosOnParam != null && annosOnParam.length > 0) { for (int j = 0; j < annosOnParam.length; j++) { newMethod.addParameterAnnotation(param, annosOnParam[j]); } } param++; } } // the below loop fixes the very special (and very stupid) // case where an aspect declares an annotation // on an ITD it declared on itself. List allDecams = weaver.getWorld().getDeclareAnnotationOnMethods(); for (Iterator i = allDecams.iterator(); i.hasNext();) { DeclareAnnotation decaMC = (DeclareAnnotation) i.next(); if (decaMC.matches(unMangledInterMethod, weaver.getWorld()) && newMethod.getEnclosingClass().getType() == aspectType) { newMethod.addAnnotation(decaMC.getAnnotationX()); } } } // If it doesn't target an interface and there is a body (i.e. it // isnt abstract) if (!onInterface && !Modifier.isAbstract(mangledInterMethod.getModifiers())) { InstructionList body = newMethod.getBody(); InstructionFactory fact = gen.getFactory(); int pos = 0; if (!unMangledInterMethod.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes()); for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), interMethodBody)); body.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(mangledInterMethod.getReturnType()))); if (weaver.getWorld().isInJava5Mode()) { // Don't need bridge // methods if not in // 1.5 mode. createAnyBridgeMethodsForCovariance(weaver, munger, unMangledInterMethod, onType, gen, paramTypes); } } else { // ??? this is okay // if (!(mg.getBody() == null)) throw new // RuntimeException("bas"); } if (weaver.getWorld().isInJava5Mode()) { String basicSignature = mangledInterMethod.getSignature(); String genericSignature = ((ResolvedMemberImpl) mangledInterMethod).getSignatureForAttribute(); if (!basicSignature.equals(genericSignature)) { // Add a signature attribute to it newMethod.addAttribute(createSignatureAttribute(gen.getConstantPool(), genericSignature)); } } // XXX make sure to check that we set exceptions properly on this // guy. weaver.addLazyMethodGen(newMethod); weaver.getLazyClassGen().warnOnAddedMethod(newMethod.getMethod(), getSignature().getSourceLocation()); addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled()); return true; } else if (onInterface && !Modifier.isAbstract(unMangledInterMethod.getModifiers())) { // This means the 'gen' should be the top most implementor // - if it is *not* then something went wrong after we worked // out that it was the top most implementor (see pr49657) if (!gen.getType().isTopmostImplementor(onType)) { ResolvedType rtx = gen.getType().getTopmostImplementor(onType); if (!rtx.isExposedToWeaver()) { ISourceLocation sLoc = munger.getSourceLocation(); weaver.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_NON_EXPOSED_IMPLEMENTOR, rtx, getAspectType().getName()), (sLoc == null ? getAspectType().getSourceLocation() : sLoc))); } else { // XXX what does this state mean? // We have incorrectly identified what is the top most // implementor and its not because // a type wasn't exposed to the weaver } return false; } else { ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, false); LazyMethodGen mg = makeMethodGen(gen, mangledInterMethod); // From 98901#29 - need to copy annotations across if (weaver.getWorld().isInJava5Mode()) { AnnotationAJ annotationsOnRealMember[] = null; ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) toLookOn = aspectType.getGenericType(); ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn, memberHoldingAnyAnnotations, false); if (realMember == null) throw new BCException("Couldn't find ITD holder member '" + memberHoldingAnyAnnotations + "' on aspect " + aspectType); annotationsOnRealMember = realMember.getAnnotations(); if (annotationsOnRealMember != null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationAJ annotationX = annotationsOnRealMember[i]; AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); mg.addAnnotation(new BcelAnnotation(ag, weaver.getWorld())); } } AnnotationAJ[][] pAnnos = realMember.getParameterAnnotations(); int offset = mg.isStatic() ? 0 : 1; if (pAnnos != null && pAnnos.length != 0) { int param = 0; for (int i = offset; i < pAnnos.length; i++) { AnnotationAJ[] annosOnParam = pAnnos[i]; if (annosOnParam != null && annosOnParam.length > 0) { for (int j = 0; j < annosOnParam.length; j++) { mg.addParameterAnnotation(param, annosOnParam[j]); } } param++; } } } if (mungingInterface) { // we want the modifiers of the ITD to be used for all // *implementors* of the // interface, but the method itself we add to the interface // must be public abstract mg.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT); } Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(mangledInterMethod.getReturnType()); InstructionList body = mg.getBody(); InstructionFactory fact = gen.getFactory(); int pos = 0; if (!mangledInterMethod.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), interMethodBody)); Type t = BcelWorld.makeBcelType(interMethodBody.getReturnType()); if (!t.equals(returnType)) { body.append(fact.createCast(t, returnType)); } body.append(InstructionFactory.createReturn(returnType)); mg.definingType = onType; if (weaver.getWorld().isInJava5Mode()) { String basicSignature = mangledInterMethod.getSignature(); String genericSignature = ((ResolvedMemberImpl) mangledInterMethod).getSignatureForAttribute(); if (!basicSignature.equals(genericSignature)) { // Add a signature attribute to it mg.addAttribute(createSignatureAttribute(gen.getConstantPool(), genericSignature)); } } weaver.addOrReplaceLazyMethodGen(mg); addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled()); // Work out if we need a bridge method for the new method added // to the topmostimplementor. if (munger.getDeclaredSignature() != null) { // Check if the // munger being // processed is // a // parameterized // form of some // original // munger. boolean needsbridging = false; ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null, munger.getSignature().getDeclaringType().resolve(getWorld()), false, munger.getTypeVariableAliases()); if (!toBridgeTo.getReturnType().getErasureSignature().equals( munger.getSignature().getReturnType().getErasureSignature())) needsbridging = true; UnresolvedType[] originalParams = toBridgeTo.getParameterTypes(); UnresolvedType[] newParams = munger.getSignature().getParameterTypes(); for (int ii = 0; ii < originalParams.length; ii++) { if (!originalParams[ii].getErasureSignature().equals(newParams[ii].getErasureSignature())) needsbridging = true; } if (needsbridging) { ResolvedMember bridgerMethod = AjcMemberMaker.bridgerToInterMethod(unMangledInterMethod, gen.getType()); ResolvedMember bridgingSetter = AjcMemberMaker.interMethodBridger(toBridgeTo, aspectType, false); // pr250493 // FIXME asc ----------------8<---------------- extract // method LazyMethodGen bridgeMethod = makeMethodGen(gen, bridgingSetter); paramTypes = BcelWorld.makeBcelTypes(bridgingSetter.getParameterTypes()); Type[] bridgingToParms = BcelWorld.makeBcelTypes(unMangledInterMethod.getParameterTypes()); returnType = BcelWorld.makeBcelType(bridgingSetter.getReturnType()); body = bridgeMethod.getBody(); fact = gen.getFactory(); pos = 0; if (!bridgingSetter.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals( unMangledInterMethod.getParameterTypes()[i].getErasureSignature())) { // System.err.println("Putting in cast from "+ // paramType+" to "+bridgingToParms[i]); body.append(fact.createCast(paramType, bridgingToParms[i])); } pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), bridgerMethod)); body.append(InstructionFactory.createReturn(returnType)); gen.addMethodGen(bridgeMethod); // mg.definingType = onType; // FIXME asc (see above) // ---------------------8<--------------- extract method } } return true; } } else { return false; } } /** * Helper method to create a signature attribute based on a string signature: e.g. "Ljava/lang/Object;LI<Ljava/lang/Double;>;" */ private Signature createSignatureAttribute(ConstantPool cp, String signature) { int nameIndex = cp.addUtf8("Signature"); int sigIndex = cp.addUtf8(signature); return new Signature(nameIndex, 2, sigIndex, cp); } /** * Create any bridge method required because of covariant returns being used. This method is used in the case where an ITD is * applied to some type and it may be in an override relationship with a method from the supertype - but due to covariance there * is a mismatch in return values. Example of when required: Super defines: Object m(String s) Sub defines: String m(String s) * then we need a bridge method in Sub called 'Object m(String s)' that forwards to 'String m(String s)' */ private void createAnyBridgeMethodsForCovariance(BcelClassWeaver weaver, NewMethodTypeMunger munger, ResolvedMember unMangledInterMethod, ResolvedType onType, LazyClassGen gen, Type[] paramTypes) { // PERFORMANCE BOTTLENECK? Might need investigating, method analysis // between types in a hierarchy just seems expensive... // COVARIANCE BRIDGING // Algorithm: Step1. Check in this type - has someone already created // the bridge method? // Step2. Look above us - do we 'override' a method and yet differ in // return type (i.e. covariance) // Step3. Create a forwarding bridge method // ResolvedType superclass = onType.getSuperclass(); boolean quitRightNow = false; String localMethodName = unMangledInterMethod.getName(); String localParameterSig = unMangledInterMethod.getParameterSignature(); String localReturnTypeESig = unMangledInterMethod.getReturnType().getErasureSignature(); // Step1 boolean alreadyDone = false; // Compiler might have done it ResolvedMember[] localMethods = onType.getDeclaredMethods(); for (int i = 0; i < localMethods.length; i++) { ResolvedMember member = localMethods[i]; if (member.getName().equals(localMethodName)) { // Check the params if (member.getParameterSignature().equals(localParameterSig)) alreadyDone = true; } } // Step2 if (!alreadyDone) { // Use the iterator form of 'getMethods()' so we do as little work // as necessary for (Iterator iter = onType.getSuperclass().getMethods(); iter.hasNext() && !quitRightNow;) { ResolvedMember aMethod = (ResolvedMember) iter.next(); if (aMethod.getName().equals(localMethodName) && aMethod.getParameterSignature().equals(localParameterSig)) { // check the return types, if they are different we need a // bridging method. if (!aMethod.getReturnType().getErasureSignature().equals(localReturnTypeESig) && !Modifier.isPrivate(aMethod.getModifiers())) { // Step3 createBridgeMethod(weaver.getWorld(), munger, unMangledInterMethod, gen, paramTypes, aMethod); quitRightNow = true; } } } } } /** * Create a bridge method for a particular munger. * * @param world * @param munger * @param unMangledInterMethod the method to bridge 'to' that we have already created in the 'subtype' * @param clazz the class in which to put the bridge method * @param paramTypes Parameter types for the bridge method, passed in as an optimization since the caller is likely to have * already created them. * @param theBridgeMethod */ private void createBridgeMethod(BcelWorld world, NewMethodTypeMunger munger, ResolvedMember unMangledInterMethod, LazyClassGen clazz, Type[] paramTypes, ResolvedMember theBridgeMethod) { InstructionList body; InstructionFactory fact; int pos = 0; LazyMethodGen bridgeMethod = makeMethodGen(clazz, theBridgeMethod); // The // bridge // method // in // this // type // will // have // the // same // signature // as // the // one // in // the // supertype bridgeMethod.setAccessFlags(bridgeMethod.getAccessFlags() | 0x00000040 /* * BRIDGE = 0x00000040 */); // UnresolvedType[] newParams = // munger.getSignature().getParameterTypes(); Type returnType = BcelWorld.makeBcelType(theBridgeMethod.getReturnType()); body = bridgeMethod.getBody(); fact = clazz.getFactory(); if (!unMangledInterMethod.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); // if (!bridgingSetter.getParameterTypes()[i].getErasureSignature(). // equals // (unMangledInterMethod.getParameterTypes()[i].getErasureSignature // ())) { // System.err.println("Putting in cast from "+paramType+" to "+ // bridgingToParms[i]); // body.append(fact.createCast(paramType,bridgingToParms[i])); // } pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, world, unMangledInterMethod)); body.append(InstructionFactory.createReturn(returnType)); clazz.addMethodGen(bridgeMethod); } // Unlike toString() on a member, this does not include the declaring type private String stringifyMember(ResolvedMember member) { StringBuffer buf = new StringBuffer(); buf.append(member.getReturnType().getName()); buf.append(' '); buf.append(member.getName()); if (member.getKind() != Member.FIELD) { buf.append("("); UnresolvedType[] params = member.getParameterTypes(); if (params.length != 0) { buf.append(params[0]); for (int i = 1, len = params.length; i < len; i++) { buf.append(", "); buf.append(params[i].getName()); } } buf.append(")"); } return buf.toString(); } private boolean mungeMethodDelegate(BcelClassWeaver weaver, MethodDelegateTypeMunger munger) { ResolvedMember introduced = munger.getSignature(); LazyClassGen gen = weaver.getLazyClassGen(); ResolvedType fromType = weaver.getWorld().resolve(introduced.getDeclaringType(), munger.getSourceLocation()); if (fromType.isRawType()) fromType = fromType.getGenericType(); if (gen.getType().isAnnotation() || gen.getType().isEnum()) { // don't signal error as it could be a consequence of a wild type // pattern return false; } boolean shouldApply = munger.matches(weaver.getLazyClassGen().getType(), aspectType); if (shouldApply) { // If no implementation class was specified, the intention was that // the types matching the pattern // already implemented the interface, let's check that now! if (munger.getImplClassName() == null) { boolean isOK = false; List/* LazyMethodGen */existingMethods = gen.getMethodGens(); for (Iterator i = existingMethods.iterator(); i.hasNext() && !isOK;) { LazyMethodGen m = (LazyMethodGen) i.next(); if (m.getName().equals(introduced.getName()) && m.getParameterSignature().equals(introduced.getParameterSignature()) && m.getReturnType().equals(introduced.getReturnType())) { isOK = true; } } if (!isOK) { // the class does not implement this method, they needed to // supply a default impl class IMessage msg = new Message("@DeclareParents: No defaultImpl was specified but the type '" + gen.getName() + "' does not implement the method '" + stringifyMember(introduced) + "' defined on the interface '" + introduced.getDeclaringType() + "'", weaver.getLazyClassGen().getType().getSourceLocation(), true, new ISourceLocation[] { munger.getSourceLocation() }); weaver.getWorld().getMessageHandler().handleMessage(msg); return false; } return true; } LazyMethodGen mg = new LazyMethodGen(introduced.getModifiers() - Modifier.ABSTRACT, BcelWorld.makeBcelType(introduced .getReturnType()), introduced.getName(), BcelWorld.makeBcelTypes(introduced.getParameterTypes()), BcelWorld .makeBcelTypesAsClassNames(introduced.getExceptions()), gen); // annotation copy from annotation on ITD interface if (weaver.getWorld().isInJava5Mode()) { AnnotationAJ annotationsOnRealMember[] = null; ResolvedType toLookOn = weaver.getWorld().lookupOrCreateName(introduced.getDeclaringType()); if (fromType.isRawType()) toLookOn = fromType.getGenericType(); // lookup the method ResolvedMember[] ms = toLookOn.getDeclaredJavaMethods(); for (int i = 0; i < ms.length; i++) { ResolvedMember m = ms[i]; if (introduced.getName().equals(m.getName()) && introduced.getSignature().equals(m.getSignature())) { annotationsOnRealMember = m.getAnnotations(); } } if (annotationsOnRealMember != null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationAJ annotationX = annotationsOnRealMember[i]; AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); mg.addAnnotation(new BcelAnnotation(ag, weaver.getWorld())); } } } InstructionList body = new InstructionList(); InstructionFactory fact = gen.getFactory(); // getfield body.append(InstructionConstants.ALOAD_0); body.append(Utility.createGet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); InstructionBranch ifNonNull = InstructionFactory.createBranchInstruction(Constants.IFNONNULL, null); body.append(ifNonNull); // Create and store a new instance body.append(InstructionConstants.ALOAD_0); body.append(fact.createNew(munger.getImplClassName())); body.append(InstructionConstants.DUP); body.append(fact.createInvoke(munger.getImplClassName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL)); body.append(Utility.createSet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); // if not null use the instance we've got InstructionHandle ifNonNullElse = body.append(InstructionConstants.ALOAD_0); ifNonNull.setTarget(ifNonNullElse); body.append(Utility.createGet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); // args int pos = 0; if (!introduced.isStatic()) { // skip 'this' (?? can this really // happen) // body.append(InstructionFactory.createThis()); pos++; } Type[] paramTypes = BcelWorld.makeBcelTypes(introduced.getParameterTypes()); for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, Constants.INVOKEINTERFACE, introduced)); body.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(introduced.getReturnType()))); mg.getBody().append(body); weaver.addLazyMethodGen(mg); weaver.getLazyClassGen().warnOnAddedMethod(mg.getMethod(), getSignature().getSourceLocation()); return true; } return false; } private boolean mungeFieldHost(BcelClassWeaver weaver, MethodDelegateTypeMunger.FieldHostTypeMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); if (gen.getType().isAnnotation() || gen.getType().isEnum()) { // don't signal error as it could be a consequence of a wild type // pattern return false; } // boolean shouldApply = munger.matches(weaver.getLazyClassGen().getType(), aspectType); // why // do // this? ResolvedMember host = AjcMemberMaker.itdAtDeclareParentsField(weaver.getLazyClassGen().getType(), munger.getSignature() .getType(), aspectType); weaver.getLazyClassGen().addField(makeFieldGen(weaver.getLazyClassGen(), host), null); return true; } private ResolvedMember getRealMemberForITDFromAspect(ResolvedType aspectType, ResolvedMember lookingFor, boolean isCtorRelated) { World world = aspectType.getWorld(); boolean debug = false; if (debug) { System.err.println("Searching for a member on type: " + aspectType); System.err.println("Member we are looking for: " + lookingFor); } ResolvedMember aspectMethods[] = aspectType.getDeclaredMethods(); UnresolvedType[] lookingForParams = lookingFor.getParameterTypes(); ResolvedMember realMember = null; for (int i = 0; realMember == null && i < aspectMethods.length; i++) { ResolvedMember member = aspectMethods[i]; if (member.getName().equals(lookingFor.getName())) { UnresolvedType[] memberParams = member.getGenericParameterTypes(); if (memberParams.length == lookingForParams.length) { if (debug) System.err.println("Reviewing potential candidates: " + member); boolean matchOK = true; // If not related to a ctor ITD then the name is enough to // confirm we have the // right one. If it is ctor related we need to check the // params all match, although // only the erasure. if (isCtorRelated) { for (int j = 0; j < memberParams.length && matchOK; j++) { ResolvedType pMember = memberParams[j].resolve(world); ResolvedType pLookingFor = lookingForParams[j].resolve(world); if (pMember.isTypeVariableReference()) pMember = ((TypeVariableReference) pMember).getTypeVariable().getFirstBound().resolve(world); if (pMember.isParameterizedType() || pMember.isGenericType()) pMember = pMember.getRawType().resolve(aspectType.getWorld()); if (pLookingFor.isTypeVariableReference()) pLookingFor = ((TypeVariableReference) pLookingFor).getTypeVariable().getFirstBound() .resolve(world); if (pLookingFor.isParameterizedType() || pLookingFor.isGenericType()) pLookingFor = pLookingFor.getRawType().resolve(world); if (debug) System.err.println("Comparing parameter " + j + " member=" + pMember + " lookingFor=" + pLookingFor); if (!pMember.equals(pLookingFor)) { matchOK = false; } } } if (matchOK) realMember = member; } } } if (debug && realMember == null) System.err.println("Didn't find a match"); return realMember; } private void addNeededSuperCallMethods(BcelClassWeaver weaver, ResolvedType onType, Set neededSuperCalls) { LazyClassGen gen = weaver.getLazyClassGen(); for (Iterator iter = neededSuperCalls.iterator(); iter.hasNext();) { ResolvedMember superMethod = (ResolvedMember) iter.next(); if (weaver.addDispatchTarget(superMethod)) { // System.err.println("super type: " + // superMethod.getDeclaringType() + ", " + gen.getType()); boolean isSuper = !superMethod.getDeclaringType().equals(gen.getType()); String dispatchName; if (isSuper) dispatchName = NameMangler.superDispatchMethod(onType, superMethod.getName()); else dispatchName = NameMangler.protectedDispatchMethod(onType, superMethod.getName()); superMethod = superMethod.resolve(weaver.getWorld()); LazyMethodGen dispatcher = makeDispatcher(gen, dispatchName, superMethod, weaver.getWorld(), isSuper); weaver.addLazyMethodGen(dispatcher); } } } private void signalError(String msgid, BcelClassWeaver weaver, UnresolvedType onType) { IMessage msg = MessageUtil.error(WeaverMessages.format(msgid, onType.getName()), getSourceLocation()); weaver.getWorld().getMessageHandler().handleMessage(msg); } private boolean mungeNewConstructor(BcelClassWeaver weaver, NewConstructorTypeMunger newConstructorTypeMunger) { final LazyClassGen currentClass = weaver.getLazyClassGen(); final InstructionFactory fact = currentClass.getFactory(); ResolvedMember newConstructorMember = newConstructorTypeMunger.getSyntheticConstructor(); ResolvedType onType = newConstructorMember.getDeclaringType().resolve(weaver.getWorld()); if (onType.isRawType()) onType = onType.getGenericType(); if (onType.isAnnotation()) { signalError(WeaverMessages.ITDC_ON_ANNOTATION_NOT_ALLOWED, weaver, onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDC_ON_ENUM_NOT_ALLOWED, weaver, onType); return false; } if (!onType.equals(currentClass.getType())) return false; ResolvedMember explicitConstructor = newConstructorTypeMunger.getExplicitConstructor(); // int declaredParameterCount = // newConstructorTypeMunger.getDeclaredParameterCount(); LazyMethodGen mg = makeMethodGen(currentClass, newConstructorMember); mg.setEffectiveSignature(newConstructorTypeMunger.getSignature(), Shadow.ConstructorExecution, true); // pr98901 // For copying the annotations across, we have to discover the real // member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()) { ResolvedMember interMethodDispatcher = AjcMemberMaker.postIntroducedConstructor(aspectType, onType, newConstructorTypeMunger.getSignature().getParameterTypes()); AnnotationAJ annotationsOnRealMember[] = null; ResolvedMember realMember = getRealMemberForITDFromAspect(aspectType, interMethodDispatcher, true); if (realMember == null) throw new BCException("Couldn't find ITD holder member '" + interMethodDispatcher + "' on aspect " + aspectType); annotationsOnRealMember = realMember.getAnnotations(); if (annotationsOnRealMember != null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationAJ annotationX = annotationsOnRealMember[i]; AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); mg.addAnnotation(new BcelAnnotation(ag, weaver.getWorld())); } } // the below loop fixes the very special (and very stupid) // case where an aspect declares an annotation // on an ITD it declared on itself. List allDecams = weaver.getWorld().getDeclareAnnotationOnMethods(); for (Iterator i = allDecams.iterator(); i.hasNext();) { DeclareAnnotation decaMC = (DeclareAnnotation) i.next(); if (decaMC.matches(explicitConstructor, weaver.getWorld()) && mg.getEnclosingClass().getType() == aspectType) { mg.addAnnotation(decaMC.getAnnotationX()); } } } currentClass.addMethodGen(mg); // weaver.addLazyMethodGen(freshConstructor); InstructionList body = mg.getBody(); // add to body: push arts for call to pre, from actual args starting at // 1 (skipping this), going to // declared argcount + 1 UnresolvedType[] declaredParams = newConstructorTypeMunger.getSignature().getParameterTypes(); Type[] paramTypes = mg.getArgumentTypes(); int frameIndex = 1; for (int i = 0, len = declaredParams.length; i < len; i++) { body.append(InstructionFactory.createLoad(paramTypes[i], frameIndex)); frameIndex += paramTypes[i].getSize(); } // do call to pre Member preMethod = AjcMemberMaker.preIntroducedConstructor(aspectType, onType, declaredParams); body.append(Utility.createInvoke(fact, null, preMethod)); // create a local, and store return pre stuff into it. int arraySlot = mg.allocateLocal(1); body.append(InstructionFactory.createStore(Type.OBJECT, arraySlot)); // put this on the stack body.append(InstructionConstants.ALOAD_0); // unpack pre args onto stack UnresolvedType[] superParamTypes = explicitConstructor.getParameterTypes(); for (int i = 0, len = superParamTypes.length; i < len; i++) { body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot)); body.append(Utility.createConstant(fact, i)); body.append(InstructionFactory.createArrayLoad(Type.OBJECT)); body.append(Utility.createConversion(fact, Type.OBJECT, BcelWorld.makeBcelType(superParamTypes[i]))); } // call super/this body.append(Utility.createInvoke(fact, null, explicitConstructor)); // put this back on the stack body.append(InstructionConstants.ALOAD_0); // unpack params onto stack Member postMethod = AjcMemberMaker.postIntroducedConstructor(aspectType, onType, declaredParams); UnresolvedType[] postParamTypes = postMethod.getParameterTypes(); for (int i = 1, len = postParamTypes.length; i < len; i++) { body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot)); body.append(Utility.createConstant(fact, superParamTypes.length + i - 1)); body.append(InstructionFactory.createArrayLoad(Type.OBJECT)); body.append(Utility.createConversion(fact, Type.OBJECT, BcelWorld.makeBcelType(postParamTypes[i]))); } // call post body.append(Utility.createInvoke(fact, null, postMethod)); // don't forget to return!! body.append(InstructionConstants.RETURN); return true; } private static LazyMethodGen makeDispatcher(LazyClassGen onGen, String dispatchName, ResolvedMember superMethod, BcelWorld world, boolean isSuper) { Type[] paramTypes = BcelWorld.makeBcelTypes(superMethod.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(superMethod.getReturnType()); int modifiers = Modifier.PUBLIC; if (onGen.isInterface()) modifiers |= Modifier.ABSTRACT; LazyMethodGen mg = new LazyMethodGen(modifiers, returnType, dispatchName, paramTypes, UnresolvedType.getNames(superMethod .getExceptions()), onGen); InstructionList body = mg.getBody(); if (onGen.isInterface()) return mg; // assert (!superMethod.isStatic()) InstructionFactory fact = onGen.getFactory(); int pos = 0; body.append(InstructionFactory.createThis()); pos++; for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } if (isSuper) { body.append(Utility.createSuperInvoke(fact, world, superMethod)); } else { body.append(Utility.createInvoke(fact, world, superMethod)); } body.append(InstructionFactory.createReturn(returnType)); return mg; } private boolean mungeNewField(BcelClassWeaver weaver, NewFieldTypeMunger munger) { /* ResolvedMember initMethod = */munger.getInitMethod(aspectType); LazyClassGen gen = weaver.getLazyClassGen(); ResolvedMember field = munger.getSignature(); ResolvedType onType = weaver.getWorld().resolve(field.getDeclaringType(), munger.getSourceLocation()); if (onType.isRawType()) onType = onType.getGenericType(); boolean onInterface = onType.isInterface(); if (onType.isAnnotation()) { signalError(WeaverMessages.ITDF_ON_ANNOTATION_NOT_ALLOWED, weaver, onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDF_ON_ENUM_NOT_ALLOWED, weaver, onType); return false; } ResolvedMember interMethodBody = munger.getInitMethod(aspectType); AnnotationAJ annotationsOnRealMember[] = null; // pr98901 // For copying the annotations across, we have to discover the real // member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()) { // the below line just gets the method with the same name in // aspectType.getDeclaredMethods(); ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) toLookOn = aspectType.getGenericType(); ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn, interMethodBody, false); if (realMember == null) throw new BCException("Couldn't find ITD init member '" + interMethodBody + "' on aspect " + aspectType); annotationsOnRealMember = realMember.getAnnotations(); } if (onType.equals(gen.getType())) { if (onInterface) { ResolvedMember itdfieldGetter = AjcMemberMaker.interFieldInterfaceGetter(field, onType, aspectType); LazyMethodGen mg = makeMethodGen(gen, itdfieldGetter); gen.addMethodGen(mg); LazyMethodGen mg1 = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceSetter(field, onType, aspectType)); gen.addMethodGen(mg1); } else { weaver.addInitializer(this); FieldGen fg = makeFieldGen(gen, AjcMemberMaker.interFieldClassField(field, aspectType)); if (annotationsOnRealMember != null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationAJ annotationX = annotationsOnRealMember[i]; AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); fg.addAnnotation(ag); } } if (weaver.getWorld().isInJava5Mode()) { String basicSignature = field.getSignature(); String genericSignature = field.getReturnType().resolve(weaver.getWorld()).getSignatureForAttribute(); // String genericSignature = // ((ResolvedMemberImpl)field).getSignatureForAttribute(); if (!basicSignature.equals(genericSignature)) { // Add a signature attribute to it fg.addAttribute(createSignatureAttribute(gen.getConstantPool(), genericSignature)); } } gen.addField(fg, getSourceLocation()); } return true; } else if (onInterface && gen.getType().isTopmostImplementor(onType)) { // wew know that we can't be static since we don't allow statics on // interfaces if (field.isStatic()) throw new RuntimeException("unimplemented"); weaver.addInitializer(this); // System.err.println("impl body on " + gen.getType() + " for " + // munger); Type fieldType = BcelWorld.makeBcelType(field.getType()); FieldGen fg = makeFieldGen(gen, AjcMemberMaker.interFieldInterfaceField(field, onType, aspectType)); if (annotationsOnRealMember != null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationAJ annotationX = annotationsOnRealMember[i]; AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); fg.addAnnotation(ag); } } gen.addField(fg, getSourceLocation()); // this uses a shadow munger to add init method to constructors // weaver.getShadowMungers().add(makeInitCallShadowMunger(initMethod) // ); ResolvedMember itdfieldGetter = AjcMemberMaker.interFieldInterfaceGetter(field, gen.getType()/* onType */, aspectType); LazyMethodGen mg = makeMethodGen(gen, itdfieldGetter); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); if (field.isStatic()) { il.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.GETSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD)); } il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); // Check if we need bridge methods for the field getter and setter if (munger.getDeclaredSignature() != null) { // is this munger a // parameterized // form of some // original munger? ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null, munger.getSignature().getDeclaringType().resolve(getWorld()), false, munger.getTypeVariableAliases()); boolean needsbridging = false; if (!toBridgeTo.getReturnType().getErasureSignature().equals( munger.getSignature().getReturnType().getErasureSignature())) needsbridging = true; if (needsbridging) { ResolvedMember bridgingGetter = AjcMemberMaker.interFieldInterfaceGetter(toBridgeTo, gen.getType(), aspectType); createBridgeMethodForITDF(weaver, gen, itdfieldGetter, bridgingGetter); } } ResolvedMember itdfieldSetter = AjcMemberMaker.interFieldInterfaceSetter(field, gen.getType(), aspectType); LazyMethodGen mg1 = makeMethodGen(gen, itdfieldSetter); InstructionList il1 = new InstructionList(); if (field.isStatic()) { il1.append(InstructionFactory.createLoad(fieldType, 0)); il1.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.PUTSTATIC)); } else { il1.append(InstructionConstants.ALOAD_0); il1.append(InstructionFactory.createLoad(fieldType, 1)); il1.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD)); } il1.append(InstructionFactory.createReturn(Type.VOID)); mg1.getBody().insert(il1); gen.addMethodGen(mg1); if (munger.getDeclaredSignature() != null) { ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null, munger.getSignature().getDeclaringType().resolve(getWorld()), false, munger.getTypeVariableAliases()); boolean needsbridging = false; if (!toBridgeTo.getReturnType().getErasureSignature().equals( munger.getSignature().getReturnType().getErasureSignature())) { needsbridging = true; } if (needsbridging) { ResolvedMember bridgingSetter = AjcMemberMaker.interFieldInterfaceSetter(toBridgeTo, gen.getType(), aspectType); createBridgeMethodForITDF(weaver, gen, itdfieldSetter, bridgingSetter); } } return true; } else { return false; } } // FIXME asc combine with other createBridge.. method in this class, avoid // the duplication... private void createBridgeMethodForITDF(BcelClassWeaver weaver, LazyClassGen gen, ResolvedMember itdfieldSetter, ResolvedMember bridgingSetter) { InstructionFactory fact; LazyMethodGen bridgeMethod = makeMethodGen(gen, bridgingSetter); bridgeMethod.setAccessFlags(bridgeMethod.getAccessFlags() | 0x00000040); // BRIDGE = 0x00000040 Type[] paramTypes = BcelWorld.makeBcelTypes(bridgingSetter.getParameterTypes()); Type[] bridgingToParms = BcelWorld.makeBcelTypes(itdfieldSetter.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(bridgingSetter.getReturnType()); InstructionList body = bridgeMethod.getBody(); fact = gen.getFactory(); int pos = 0; if (!bridgingSetter.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals( itdfieldSetter.getParameterTypes()[i].getErasureSignature())) { body.append(fact.createCast(paramType, bridgingToParms[i])); } pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), itdfieldSetter)); body.append(InstructionFactory.createReturn(returnType)); gen.addMethodGen(bridgeMethod); } public ConcreteTypeMunger parameterizedFor(ResolvedType target) { return new BcelTypeMunger(munger.parameterizedFor(target), aspectType); } public ConcreteTypeMunger parameterizeWith(Map m, World w) { return new BcelTypeMunger(munger.parameterizeWith(m, w), aspectType); } /** * Returns a list of type variable aliases used in this munger. For example, if the ITD is 'int I<A,B>.m(List<A> las,List<B> * lbs) {}' then this returns a list containing the strings "A" and "B". */ public List /* String */getTypeVariableAliases() { return munger.getTypeVariableAliases(); } public boolean equals(Object other) { if (!(other instanceof BcelTypeMunger)) return false; BcelTypeMunger o = (BcelTypeMunger) other; return ((o.getMunger() == null) ? (getMunger() == null) : o.getMunger().equals(getMunger())) && ((o.getAspectType() == null) ? (getAspectType() == null) : o.getAspectType().equals(getAspectType())); // && (AsmManager.getDefault().getHandleProvider().dependsOnLocation() ? ((o.getSourceLocation() == null) ? // (getSourceLocation() == null) // : o.getSourceLocation().equals(getSourceLocation())) // : true); // pr134471 - remove when handles are improved // to be independent of location } private volatile int hashCode = 0; public int hashCode() { if (hashCode == 0) { int result = 17; result = 37 * result + ((getMunger() == null) ? 0 : getMunger().hashCode()); result = 37 * result + ((getAspectType() == null) ? 0 : getAspectType().hashCode()); hashCode = result; } return hashCode; } }
266,996
Bug 266996 AspectJElementHierarchy.java:427 NullPointerException
Since an recent update to eclipse I get errors when using ajdt compile time weaving. Single used aspect is @Configurable from spring 2.5.6. I call this critical because my application wont run without that aspect compiled in. When doing a build two popups "AspectJ Internal Compiler Error" are showing up with instructions to look for and post bugreports. 1st popup: -------------------------------- java.lang.NullPointerException at org.aspectj.asm.internal.AspectJElementHierarchy.findCloserMatchForLineNumber(AspectJElementHierarchy.java:427) at org.aspectj.weaver.model.AsmRelationshipProvider.addRelationship(AsmRelationshipProvider.java:130) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:124) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:441) at org.aspectj.weaver.bcel.BcelClassWeaver.weave( ... end abstract interface org.springframework.beans.factory.aspectj.AbstractInterfaceDrivenDependencyInjectionAspect$ConfigurableDeserializationSupport -------------------------------- 2nd popup -------------------------------- java.lang.NullPointerException at org.aspectj.asm.internal.AspectJElementHierarchy.findCloserMatchForLineNumber(AspectJElementHierarchy.java:427) at org.aspectj.weaver.model.AsmRelationshipProvider.addRelationship(AsmRelationshipProvider.java:130) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:124) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:441) at org.aspectj.weaver.bcel.BcelClassWeaver.weave( ... ibatis/domain/Banf;)I IRETURN end public volatile int compareTo(Object) end public class de.synaix.k070_Banf.ibatis.domain.Banf -------------------------------- Output of AJDT Event trace window: -------------------------------- 11:21:34 Removed problems and tasks for project SOME_webapp 11:21:34 Builder: Tidied output folder(s), removed class files and derived resources 11:21:35 Timer event: 1ms: Delete markers: SOME_webapp (Finished deleting markers for SOME_webapp 11:21:38 Compiler configuration for project SOME_webapp doesn't know previous state, so assuming EVERYTHING has changed. 11:21:38 =========================================================================================== 11:21:38 Build kind = FULLBUILD 11:21:38 Project=SOME_webapp, kind of build requested=Full AspectJ compilation 11:21:38 Builder: Tidied output folder(s), removed class files and derived resources 11:21:38 Timer event: 442ms: Pre compile 11:21:38 Compiler configuration for project SOME_webapp has been read by compiler. Resetting. 11:21:38 Configuration was [PROJECTSOURCEFILES_CHANGED, JAVAOPTIONS_CHANGED, ASPECTPATH_CHANGED, CLASSPATH_CHANGED, INPATH_CHANGED, NONSTANDARDOPTIONS_CHANGED, OUTJAR_CHANGED, PROJECTSOURCERESOURCES_CHANGED, OUTPUTDESTINATIONS_CHANGED, INJARS_CHANGED] 11:21:38 Resetting list of modified source files. Was null 11:21:38 Preparing for build: not going to be incremental because no successful previous full build 11:21:40 Timer event: 1252ms: Time to first compiled message 11:21:40 Timer event: 1276ms: Time to first woven message 11:21:45 AspectJ reports build successful, build was: FULL 11:21:45 AJDE Callback: finish. Was full build: true 11:21:45 Timer event: 6456ms: Total time spent in AJDE 11:21:45 Timer event: 157ms: Refresh after build 11:21:45 Types affected during build = 308 11:21:45 Crosscutting model sanity checked with no problems 11:21:45 Timer event: 0ms: Post compile 11:21:45 Timer event: 7248ms: Total time spent in AJBuilder.build() 11:21:45 Timer event: 2ms: Delete markers: SOME_webapp (Finished deleting markers for SOME_webapp) 11:21:45 Timer event: 179ms: Create markers: SOME_webapp (Finished creating markers for SOME_webapp) --------------------------------
resolved fixed
2309f7b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-03-04T17:12:43Z"
"2009-03-04T09:46:40Z"
asm/src/org/aspectj/asm/internal/AspectJElementHierarchy.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Mik Kersten initial implementation * Andy Clement Extensions for better IDE representation * ******************************************************************/ package org.aspectj.asm.internal; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; /** * @author Mik Kersten */ public class AspectJElementHierarchy implements IHierarchy { private static final long serialVersionUID = 6462734311117048620L; private transient AsmManager asm; protected IProgramElement root = null; protected String configFile = null; private Map fileMap = null; private Map handleMap = new HashMap(); private Map typeMap = null; public AspectJElementHierarchy(AsmManager asm) { this.asm = asm; } public IProgramElement getElement(String handle) { return findElementForHandleOrCreate(handle, false); } public void setAsmManager(AsmManager asm) { // used when deserializing this.asm = asm; } public IProgramElement getRoot() { return root; } public void setRoot(IProgramElement root) { this.root = root; handleMap = new HashMap(); typeMap = new HashMap(); } public void addToFileMap(Object key, Object value) { fileMap.put(key, value); } public boolean removeFromFileMap(Object key) { if (fileMap.containsKey(key)) { return (fileMap.remove(key) != null); } return true; } public void setFileMap(HashMap fileMap) { this.fileMap = fileMap; } public Object findInFileMap(Object key) { return fileMap.get(key); } public Set getFileMapEntrySet() { return fileMap.entrySet(); } public boolean isValid() { return root != null && fileMap != null; } /** * Returns the first match * * @param parent * @param kind not null * @return null if not found */ public IProgramElement findElementForSignature(IProgramElement parent, IProgramElement.Kind kind, String signature) { for (Iterator it = parent.getChildren().iterator(); it.hasNext();) { IProgramElement node = (IProgramElement) it.next(); if (node.getKind() == kind && signature.equals(node.toSignatureString())) { return node; } else { IProgramElement childSearch = findElementForSignature(node, kind, signature); if (childSearch != null) return childSearch; } } return null; } public IProgramElement findElementForLabel(IProgramElement parent, IProgramElement.Kind kind, String label) { for (Iterator it = parent.getChildren().iterator(); it.hasNext();) { IProgramElement node = (IProgramElement) it.next(); if (node.getKind() == kind && label.equals(node.toLabelString())) { return node; } else { IProgramElement childSearch = findElementForLabel(node, kind, label); if (childSearch != null) return childSearch; } } return null; } /** * Find the entry in the model that represents a particular type. * * @param packageName the package in which the type is declared or null for the default package * @param typeName the name of the type * @return the IProgramElement representing the type, or null if not found */ public IProgramElement findElementForType(String packageName, String typeName) { // Build a cache key and check the cache StringBuffer keyb = (packageName == null) ? new StringBuffer() : new StringBuffer(packageName); keyb.append(".").append(typeName); String key = keyb.toString(); IProgramElement cachedValue = (IProgramElement) typeMap.get(key); if (cachedValue != null) { return cachedValue; } List packageNodes = findMatchingPackages(packageName); for (Iterator iterator = packageNodes.iterator(); iterator.hasNext();) { IProgramElement pkg = (IProgramElement) iterator.next(); // this searches each file for a class for (Iterator it = pkg.getChildren().iterator(); it.hasNext();) { IProgramElement fileNode = (IProgramElement) it.next(); IProgramElement cNode = findClassInNodes(fileNode.getChildren(), typeName, typeName); if (cNode != null) { typeMap.put(key, cNode); return cNode; } } } return null; // IProgramElement packageNode = null; // if (packageName == null) { // packageNode = root; // } else { // if (root == null) // return null; // List kids = root.getChildren(); // if (kids == null) { // return null; // } // for (Iterator it = kids.iterator(); it.hasNext() && packageNode == null;) { // IProgramElement node = (IProgramElement) it.next(); // if (packageName.equals(node.getName())) { // packageNode = node; // } // } // if (packageNode == null) { // return null; // } // } // // this searches each file for a class // for (Iterator it = packageNode.getChildren().iterator(); it.hasNext();) { // IProgramElement fileNode = (IProgramElement) it.next(); // IProgramElement cNode = findClassInNodes(fileNode.getChildren(), typeName, typeName); // if (cNode != null) { // typeMap.put(key, cNode); // return cNode; // } // } // return null; } /** * Look for any package nodes matching the specified package name. There may be multiple in the case where the types within a * package are split across source folders. * * @param packagename the packagename being searched for * @return a list of package nodes that match that name */ public List/* IProgramElement */findMatchingPackages(String packagename) { List children = root.getChildren(); // The children might be source folders or packages if (children.size() == 0) { return Collections.EMPTY_LIST; } if (((IProgramElement) children.get(0)).getKind() == IProgramElement.Kind.SOURCE_FOLDER) { // dealing with source folders List matchingPackageNodes = new ArrayList(); for (Iterator iterator = children.iterator(); iterator.hasNext();) { IProgramElement sourceFolder = (IProgramElement) iterator.next(); List possiblePackageNodes = sourceFolder.getChildren(); for (Iterator iterator2 = possiblePackageNodes.iterator(); iterator2.hasNext();) { IProgramElement possiblePackageNode = (IProgramElement) iterator2.next(); if (possiblePackageNode.getKind() == IProgramElement.Kind.PACKAGE) { if (possiblePackageNode.getName().equals(packagename)) { matchingPackageNodes.add(possiblePackageNode); } } } } // 'binaries' will be checked automatically by the code above as it is represented as a SOURCE_FOLDER return matchingPackageNodes; } else { // dealing directly with packages below the root, no source folders. Therefore at most one // thing to return in the list if (packagename == null) { // default package List result = new ArrayList(); result.add(root); return result; } for (Iterator iterator = children.iterator(); iterator.hasNext();) { IProgramElement possiblePackage = (IProgramElement) iterator.next(); if (possiblePackage.getKind() == IProgramElement.Kind.PACKAGE) { if (possiblePackage.getName().equals(packagename)) { List result = new ArrayList(); result.add(possiblePackage); return result; } } if (possiblePackage.getKind() == IProgramElement.Kind.SOURCE_FOLDER) { // might be 'binaries' if (possiblePackage.getName().equals("binaries")) { for (Iterator iter2 = possiblePackage.getChildren().iterator(); iter2.hasNext();) { IProgramElement possiblePackage2 = (IProgramElement) iter2.next(); if (possiblePackage2.getKind() == IProgramElement.Kind.PACKAGE) { if (possiblePackage2.getName().equals(packagename)) { List result = new ArrayList(); result.add(possiblePackage2); return result; } } } } } } } return Collections.EMPTY_LIST; } private IProgramElement findClassInNodes(Collection nodes, String name, String typeName) { String baseName; String innerName; int dollar = name.indexOf('$'); if (dollar == -1) { baseName = name; innerName = null; } else { baseName = name.substring(0, dollar); innerName = name.substring(dollar + 1); } for (Iterator j = nodes.iterator(); j.hasNext();) { IProgramElement classNode = (IProgramElement) j.next(); if (baseName.equals(classNode.getName())) { if (innerName == null) return classNode; else return findClassInNodes(classNode.getChildren(), innerName, typeName); } else if (name.equals(classNode.getName())) { return classNode; } else if (typeName.equals(classNode.getBytecodeSignature())) { return classNode; } else if (classNode.getChildren() != null && !classNode.getChildren().isEmpty()) { IProgramElement node = findClassInNodes(classNode.getChildren(), name, typeName); if (node != null) { return node; } } } return null; } /** * @param sourceFilePath modified to '/' delimited path for consistency * @return a new structure node for the file if it was not found in the model */ public IProgramElement findElementForSourceFile(String sourceFile) { try { if (!isValid() || sourceFile == null) { return IHierarchy.NO_STRUCTURE; } else { String correctedPath = asm.getCanonicalFilePath(new File(sourceFile)); // StructureNode node = (StructureNode)getFileMap().get(correctedPath);//findFileNode(filePath, model); IProgramElement node = (IProgramElement) findInFileMap(correctedPath);// findFileNode(filePath, model); if (node != null) { return node; } else { return createFileStructureNode(correctedPath); } } } catch (Exception e) { return IHierarchy.NO_STRUCTURE; } } /** * TODO: discriminate columns */ public IProgramElement findElementForSourceLine(ISourceLocation location) { try { return findElementForSourceLine(asm.getCanonicalFilePath(location.getSourceFile()), location.getLine()); } catch (Exception e) { return null; } } /** * Never returns null * * @param sourceFilePath canonicalized path for consistency * @param lineNumber if 0 or 1 the corresponding file node will be returned * @return a new structure node for the file if it was not found in the model */ public IProgramElement findElementForSourceLine(String sourceFilePath, int lineNumber) { String canonicalSFP = asm.getCanonicalFilePath(new File(sourceFilePath)); // Used to do this: // IProgramElement node2 = findNodeForSourceLineHelper(root, canonicalSFP, lineNumber, -1); // Find the relevant source file node first IProgramElement node = findNodeForSourceFile(root, canonicalSFP); if (node == null) { return createFileStructureNode(sourceFilePath); } // Check if there is a more accurate child node of that source file node: IProgramElement closernode = findCloserMatchForLineNumber(node, lineNumber); if (closernode == null) { return node; } else { return closernode; } } /** * Discover the node representing a particular source file. * * @param node where in the model to start looking (usually the root on the initial call) * @param sourcefilePath the source file being searched for * @return the node representing that source file or null if it cannot be found */ private IProgramElement findNodeForSourceFile(IProgramElement node, String sourcefilePath) { // 1. why is <root> a sourcefile node? // 2. should isSourceFile() return true for a FILE that is a .class file...? if ((node.getKind().isSourceFile() && !node.getName().equals("<root>")) || node.getKind().isFile()) { ISourceLocation nodeLoc = node.getSourceLocation(); if (nodeLoc != null && nodeLoc.getSourceFile().getAbsolutePath().equals(sourcefilePath)) { return node; } return null; // no need to search children of a source file node } else { // check the children for (Iterator iterator = node.getChildren().iterator(); iterator.hasNext();) { IProgramElement foundit = findNodeForSourceFile((IProgramElement) iterator.next(), sourcefilePath); if (foundit != null) { return foundit; } } return null; } } public IProgramElement findElementForOffSet(String sourceFilePath, int lineNumber, int offSet) { String canonicalSFP = asm.getCanonicalFilePath(new File(sourceFilePath)); IProgramElement node = findNodeForSourceLineHelper(root, canonicalSFP, lineNumber, offSet); if (node != null) { return node; } else { return createFileStructureNode(sourceFilePath); } } private IProgramElement createFileStructureNode(String sourceFilePath) { // SourceFilePath might have originated on windows on linux... int lastSlash = sourceFilePath.lastIndexOf('\\'); if (lastSlash == -1) { lastSlash = sourceFilePath.lastIndexOf('/'); } // '!' is used like in URLs "c:/blahblah/X.jar!a/b.class" int i = sourceFilePath.lastIndexOf('!'); int j = sourceFilePath.indexOf(".class"); if (i > lastSlash && i != -1 && j != -1) { // we are a binary aspect in the default package lastSlash = i; } String fileName = sourceFilePath.substring(lastSlash + 1); IProgramElement fileNode = new ProgramElement(asm, fileName, IProgramElement.Kind.FILE_JAVA, new SourceLocation(new File( sourceFilePath), 1, 1), 0, null, null); // fileNode.setSourceLocation(); fileNode.addChild(NO_STRUCTURE); return fileNode; } /** * For a specified node, check if any of the children more accurately represent the specified line. * * @param node where to start looking * @param lineno the line number * @return any closer match below 'node' or null if nothing is a more accurate match */ public IProgramElement findCloserMatchForLineNumber(IProgramElement node, int lineno) { for (Iterator childrenIter = node.getChildren().iterator(); childrenIter.hasNext();) { IProgramElement child = (IProgramElement) childrenIter.next(); ISourceLocation childLoc = child.getSourceLocation(); if (childLoc != null) { if (childLoc.getLine() <= lineno && childLoc.getEndLine() >= lineno) { // This child is a better match for that line number IProgramElement evenCloserMatch = findCloserMatchForLineNumber(child, lineno); if (evenCloserMatch == null) { return child; } else { return evenCloserMatch; } } else if (child.getKind().isType()) { // types are a bit clueless about where they are... do other nodes have // similar problems?? IProgramElement evenCloserMatch = findCloserMatchForLineNumber(child, lineno); if (evenCloserMatch != null) { return evenCloserMatch; } } } } return null; } private IProgramElement findNodeForSourceLineHelper(IProgramElement node, String sourceFilePath, int lineno, int offset) { if (matches(node, sourceFilePath, lineno, offset) && !hasMoreSpecificChild(node, sourceFilePath, lineno, offset)) { return node; } if (node != null) { for (Iterator it = node.getChildren().iterator(); it.hasNext();) { IProgramElement foundNode = findNodeForSourceLineHelper((IProgramElement) it.next(), sourceFilePath, lineno, offset); if (foundNode != null) { return foundNode; } } } return null; } private boolean matches(IProgramElement node, String sourceFilePath, int lineNumber, int offSet) { // try { // if (node != null && node.getSourceLocation() != null) // System.err.println("====\n1: " + // sourceFilePath + "\n2: " + // node.getSourceLocation().getSourceFile().getCanonicalPath().equals(sourceFilePath) // ); ISourceLocation nodeSourceLocation = (node != null ? node.getSourceLocation() : null); return node != null && nodeSourceLocation != null && nodeSourceLocation.getSourceFile().getAbsolutePath().equals(sourceFilePath) && ((offSet != -1 && nodeSourceLocation.getOffset() == offSet) || offSet == -1) && ((nodeSourceLocation.getLine() <= lineNumber && nodeSourceLocation.getEndLine() >= lineNumber) || (lineNumber <= 1 && node .getKind().isSourceFile())); // } catch (IOException ioe) { // return false; // } } private boolean hasMoreSpecificChild(IProgramElement node, String sourceFilePath, int lineNumber, int offSet) { for (Iterator it = node.getChildren().iterator(); it.hasNext();) { IProgramElement child = (IProgramElement) it.next(); if (matches(child, sourceFilePath, lineNumber, offSet)) return true; } return false; } public String getConfigFile() { return configFile; } public void setConfigFile(String configFile) { this.configFile = configFile; } public IProgramElement findElementForHandle(String handle) { return findElementForHandleOrCreate(handle, true); } // TODO: optimize this lookup // only want to create a file node if can't find the IPE if called through // findElementForHandle() to mirror behaviour before pr141730 public IProgramElement findElementForHandleOrCreate(String handle, boolean create) { // try the cache first... IProgramElement ipe = (IProgramElement) handleMap.get(handle); if (ipe != null) { return ipe; } ipe = findElementForHandle(root, handle); if (ipe == null && create) { ipe = createFileStructureNode(getFilename(handle)); } if (ipe != null) { cache(handle, ipe); } return ipe; } private IProgramElement findElementForHandle(IProgramElement parent, String handle) { for (Iterator it = parent.getChildren().iterator(); it.hasNext();) { IProgramElement node = (IProgramElement) it.next(); String nodeHid = node.getHandleIdentifier(); if (handle.equals(nodeHid)) { return node; } else { if (handle.startsWith(nodeHid)) { // it must be down here if it is anywhere IProgramElement childSearch = findElementForHandle(node, handle); if (childSearch != null) return childSearch; } } } return null; } // // private IProgramElement findElementForBytecodeInfo( // IProgramElement node, // String parentName, // String name, // String signature) { // for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { // IProgramElement curr = (IProgramElement)it.next(); // if (parentName.equals(curr.getParent().getBytecodeName()) // && name.equals(curr.getBytecodeName()) // && signature.equals(curr.getBytecodeSignature())) { // return node; // } else { // IProgramElement childSearch = findElementForBytecodeInfo(curr, parentName, name, signature); // if (childSearch != null) return childSearch; // } // } // return null; // } protected void cache(String handle, IProgramElement pe) { if (!AsmManager.isCompletingTypeBindings()) { handleMap.put(handle, pe); } } public void flushTypeMap() { typeMap.clear(); } public void flushHandleMap() { handleMap.clear(); } public void flushFileMap() { fileMap.clear(); } // TODO rename this method ... it does more than just the handle map public void updateHandleMap(Set deletedFiles) { // Only delete the entries we need to from the handle map - for performance reasons List forRemoval = new ArrayList(); Set k = handleMap.keySet(); for (Iterator iter = k.iterator(); iter.hasNext();) { String handle = (String) iter.next(); IProgramElement ipe = (IProgramElement) handleMap.get(handle); if (deletedFiles.contains(getCanonicalFilePath(ipe))) forRemoval.add(handle); } for (Iterator iter = forRemoval.iterator(); iter.hasNext();) { String handle = (String) iter.next(); handleMap.remove(handle); } forRemoval.clear(); k = typeMap.keySet(); for (Iterator iter = k.iterator(); iter.hasNext();) { String typeName = (String) iter.next(); IProgramElement ipe = (IProgramElement) typeMap.get(typeName); if (deletedFiles.contains(getCanonicalFilePath(ipe))) forRemoval.add(typeName); } for (Iterator iter = forRemoval.iterator(); iter.hasNext();) { String typeName = (String) iter.next(); typeMap.remove(typeName); } forRemoval.clear(); k = fileMap.keySet(); for (Iterator iter = k.iterator(); iter.hasNext();) { String filePath = (String) iter.next(); IProgramElement ipe = (IProgramElement) fileMap.get(filePath); if (deletedFiles.contains(getCanonicalFilePath(ipe))) forRemoval.add(filePath); } for (Iterator iter = forRemoval.iterator(); iter.hasNext();) { String filePath = (String) iter.next(); fileMap.remove(filePath); } } private String getFilename(String hid) { return asm.getHandleProvider().getFileForHandle(hid); } private String getCanonicalFilePath(IProgramElement ipe) { if (ipe.getSourceLocation() != null) { return asm.getCanonicalFilePath(ipe.getSourceLocation().getSourceFile()); } return ""; } }
269,578
Bug 269578 Resource deletion in source folder on full build when source and output folders are the same.
On the clean before a full aspectj build resources are removed from the output folder. This is true even when the output and the source folder are the same. In this case, the resources are deleted from the source folder! When the source and output folders are the same, resources should never be deleted.
resolved fixed
5c49c0b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-03-21T01:38:50Z"
"2009-03-20T20:13:20Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import org.aspectj.ajdt.internal.compiler.AjCompilerAdapter; import org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter; import org.aspectj.ajdt.internal.compiler.IBinarySourceProvider; import org.aspectj.ajdt.internal.compiler.ICompilerAdapter; import org.aspectj.ajdt.internal.compiler.ICompilerAdapterFactory; import org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor; import org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider; import org.aspectj.ajdt.internal.compiler.InterimCompilationResult; import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment; import org.aspectj.ajdt.internal.compiler.lookup.AnonymousClassPublisher; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.internal.ProgramElement; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.CountingMessageHandler; import org.aspectj.bridge.ILifecycleAware; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.SourceLocation; import org.aspectj.bridge.Version; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextFormatter; import org.aspectj.bridge.context.ContextToken; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies; import org.aspectj.org.eclipse.jdt.internal.compiler.ICompilerRequestor; import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.ClasspathLocation; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.CompilationUnit; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.FileSystem; import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilation; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.aspectj.tools.ajc.Main; import org.aspectj.util.FileUtil; import org.aspectj.weaver.CustomMungerFactory; import org.aspectj.weaver.Dump; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.UnwovenClassFile; import org.eclipse.core.runtime.OperationCanceledException; public class AjBuildManager implements IOutputClassFileNameProvider, IBinarySourceProvider, ICompilerAdapterFactory { private static final String CROSSREFS_FILE_NAME = "build.lst"; private static final String CANT_WRITE_RESULT = "unable to write compilation result"; private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; public static boolean COPY_INPATH_DIR_RESOURCES = false; // AJDT doesn't want this check, so Main enables it. private static boolean DO_RUNTIME_VERSION_CHECK = false; // If runtime version check fails, warn or fail? (unset?) static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false; private static final FileFilter binarySourceFilter = new FileFilter() { public boolean accept(File f) { return f.getName().endsWith(".class"); } }; /** * This builder is static so that it can be subclassed and reset. However, note that there is only one builder present, so if * two extendsion reset it, only the latter will get used. */ public static AsmHierarchyBuilder asmHierarchyBuilder = new AsmHierarchyBuilder(); static { // CompilationAndWeavingContext.setMultiThreaded(false); CompilationAndWeavingContext.registerFormatter(CompilationAndWeavingContext.BATCH_BUILD, new AjBuildContexFormatter()); CompilationAndWeavingContext .registerFormatter(CompilationAndWeavingContext.INCREMENTAL_BUILD, new AjBuildContexFormatter()); } private IProgressListener progressListener = null; private boolean environmentSupportsIncrementalCompilation = false; private int compiledCount; private int sourceFileCount; private JarOutputStream zos; private boolean batchCompile = true; private INameEnvironment environment; private Map /* String -> List<UCF> */binarySourcesForTheNextCompile = new HashMap(); // FIXME asc should this really be in here? // private AsmManager structureModel; public AjBuildConfig buildConfig; private boolean ignoreOutxml; private boolean wasFullBuild = true; // true if last build was a full build rather than an incremental build AjState state = new AjState(this); /** * Enable check for runtime version, used only by Ant/command-line Main. * * @param main Main unused except to limit to non-null clients. */ public static void enableRuntimeVersionCheck(Main caller) { DO_RUNTIME_VERSION_CHECK = null != caller; } public BcelWeaver getWeaver() { return state.getWeaver(); } public BcelWorld getBcelWorld() { return state.getBcelWorld(); } public CountingMessageHandler handler; private CustomMungerFactory customMungerFactory; public AjBuildManager(IMessageHandler holder) { super(); this.handler = CountingMessageHandler.makeCountingMessageHandler(holder); } public void environmentSupportsIncrementalCompilation(boolean itDoes) { this.environmentSupportsIncrementalCompilation = itDoes; } /** @return true if we should generate a model as a side-effect */ public boolean doGenerateModel() { return buildConfig.isGenerateModelMode(); } public boolean batchBuild(AjBuildConfig buildConfig, IMessageHandler baseHandler) throws IOException, AbortException { return performBuild(buildConfig, baseHandler, true); } public boolean incrementalBuild(AjBuildConfig buildConfig, IMessageHandler baseHandler) throws IOException, AbortException { return performBuild(buildConfig, baseHandler, false); } /** * Perform a build. * * @return true if the build was successful (ie. no errors) */ private boolean performBuild(AjBuildConfig buildConfig, IMessageHandler baseHandler, boolean isFullBuild) throws IOException, AbortException { boolean ret = true; batchCompile = isFullBuild; wasFullBuild = isFullBuild; if (baseHandler instanceof ILifecycleAware) { ((ILifecycleAware) baseHandler).buildStarting(!isFullBuild); } CompilationAndWeavingContext.reset(); int phase = isFullBuild ? CompilationAndWeavingContext.BATCH_BUILD : CompilationAndWeavingContext.INCREMENTAL_BUILD; ContextToken ct = CompilationAndWeavingContext.enteringPhase(phase, buildConfig); try { if (isFullBuild) { this.state = new AjState(this); } this.state.setCouldBeSubsequentIncrementalBuild(this.environmentSupportsIncrementalCompilation); boolean canIncremental = state.prepareForNextBuild(buildConfig); if (!canIncremental && !isFullBuild) { // retry as batch? CompilationAndWeavingContext.leavingPhase(ct); if (state.listenerDefined()) state.getListener().recordDecision("Falling back to batch compilation"); return performBuild(buildConfig, baseHandler, true); } this.handler = CountingMessageHandler.makeCountingMessageHandler(baseHandler); if (buildConfig == null || buildConfig.isCheckRuntimeVersion()) { if (DO_RUNTIME_VERSION_CHECK) { String check = checkRtJar(buildConfig); if (check != null) { if (FAIL_IF_RUNTIME_NOT_FOUND) { MessageUtil.error(handler, check); CompilationAndWeavingContext.leavingPhase(ct); return false; } else { MessageUtil.warn(handler, check); } } } } // if (batch) { setBuildConfig(buildConfig); // } if (isFullBuild || !AsmManager.attemptIncrementalModelRepairs) { // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { setupModel(buildConfig); // } } if (isFullBuild) { initBcelWorld(handler); } if (handler.hasErrors()) { CompilationAndWeavingContext.leavingPhase(ct); return false; } if (buildConfig.getOutputJar() != null) { if (!openOutputStream(buildConfig.getOutputJar())) { CompilationAndWeavingContext.leavingPhase(ct); return false; } } if (isFullBuild) { // System.err.println("XXXX batch: " + buildConfig.getFiles()); if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { AsmManager.setLastActiveStructureModel(state.getStructureModel()); getWorld().setModel(state.getStructureModel()); // in incremental build, only get updated model? } binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true); performCompilation(buildConfig.getFiles()); state.clearBinarySourceFiles(); // we don't want these hanging around... if (!proceedOnError() && handler.hasErrors()) { CompilationAndWeavingContext.leavingPhase(ct); if (AsmManager.isReporting()) { state.getStructureModel().reportModelInfo("After a batch build"); } return false; } if (AsmManager.isReporting()) { state.getStructureModel().reportModelInfo("After a batch build"); } } else { // done already? // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { // bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel()); // } // System.err.println("XXXX start inc "); AsmManager.setLastActiveStructureModel(state.getStructureModel()); binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true); Set files = state.getFilesToCompile(true); if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { if (AsmManager.attemptIncrementalModelRepairs) { state.getStructureModel().resetDeltaProcessing(); state.getStructureModel().processDelta(files, state.getAddedFiles(), state.getDeletedFiles()); } } boolean hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty()); for (int i = 0; (i < 5) && hereWeGoAgain; i++) { if (state.listenerDefined()) state.getListener() .recordInformation("Starting incremental compilation loop " + (i + 1) + " of possibly 5"); // System.err.println("XXXX inc: " + files); performCompilation(files); if ((!proceedOnError() && handler.hasErrors()) || (progressListener != null && progressListener.isCancelledRequested())) { CompilationAndWeavingContext.leavingPhase(ct); return false; } if (state.requiresFullBatchBuild()) { if (state.listenerDefined()) state.getListener().recordInformation(" Dropping back to full build"); return batchBuild(buildConfig, baseHandler); } binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(false); files = state.getFilesToCompile(false); hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty()); // TODO Andy - Needs some thought here... // I think here we might want to pass empty addedFiles/deletedFiles as they were // dealt with on the first call to processDelta - we are going through this loop // again because in compiling something we found something else we needed to // rebuild. But what case causes this? if (hereWeGoAgain) { if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) if (AsmManager.attemptIncrementalModelRepairs) state.getStructureModel().processDelta(files, state.getAddedFiles(), state.getDeletedFiles()); } } if (!files.isEmpty()) { CompilationAndWeavingContext.leavingPhase(ct); return batchBuild(buildConfig, baseHandler); } else { if (AsmManager.isReporting()) { state.getStructureModel().reportModelInfo("After an incremental build"); } } } // XXX not in Mik's incremental if (buildConfig.isEmacsSymMode()) { new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel(state.getStructureModel()); } // for bug 113554: support ajsym file generation for command line builds if (buildConfig.isGenerateCrossRefsMode()) { File configFileProxy = new File(buildConfig.getOutputDir(), CROSSREFS_FILE_NAME); state.getStructureModel().writeStructureModel(configFileProxy.getAbsolutePath()); } // have to tell state we succeeded or next is not incremental state.successfulCompile(buildConfig, isFullBuild); // For a full compile, copy resources to the destination // - they should not get deleted on incremental and AJDT // will handle changes to them that require a recopying if (isFullBuild) { copyResourcesToDestination(); } if (buildConfig.getOutxmlName() != null) { writeOutxmlFile(); } /* boolean weaved = */// weaveAndGenerateClassFiles(); // if not weaved, then no-op build, no model changes // but always returns true // XXX weaved not in Mik's incremental if (buildConfig.isGenerateModelMode()) { state.getStructureModel().fireModelUpdated(); } CompilationAndWeavingContext.leavingPhase(ct); } finally { if (baseHandler instanceof ILifecycleAware) { ((ILifecycleAware) baseHandler).buildFinished(!isFullBuild); } if (zos != null) { closeOutputStream(buildConfig.getOutputJar()); } ret = !handler.hasErrors(); if (getBcelWorld() != null) getBcelWorld().tidyUp(); if (getWeaver() != null) getWeaver().tidyUp(); // bug 59895, don't release reference to handler as may be needed by a nested call // handler = null; } return ret; } /** * Open an output jar file in which to write the compiler output. * * @param outJar the jar file to open * @return true if successful */ private boolean openOutputStream(File outJar) { try { OutputStream os = FileUtil.makeOutputStream(buildConfig.getOutputJar()); zos = new JarOutputStream(os, getWeaver().getManifest(true)); } catch (IOException ex) { IMessage message = new Message("Unable to open outjar " + outJar.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(outJar, 0), true); handler.handleMessage(message); return false; } return true; } private void closeOutputStream(File outJar) { try { if (zos != null) { zos.close(); } zos = null; /* Ensure we don't write an incomplete JAR bug-71339 */ if (handler.hasErrors()) { outJar.delete(); } } catch (IOException ex) { IMessage message = new Message("Unable to write outjar " + outJar.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(outJar, 0), true); handler.handleMessage(message); } } private void copyResourcesToDestination() throws IOException { // resources that we need to copy are contained in the injars and inpath only for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext();) { File inJar = (File) i.next(); copyResourcesFromJarFile(inJar); } for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext();) { File inPathElement = (File) i.next(); if (inPathElement.isDirectory()) { copyResourcesFromDirectory(inPathElement); } else { copyResourcesFromJarFile(inPathElement); } } if (buildConfig.getSourcePathResources() != null) { for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext();) { String resource = (String) i.next(); File from = (File) buildConfig.getSourcePathResources().get(resource); copyResourcesFromFile(from, resource, from); } } writeManifest(); } private void copyResourcesFromJarFile(File jarFile) throws IOException { JarInputStream inStream = null; try { inStream = new JarInputStream(new FileInputStream(jarFile)); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; String filename = entry.getName(); // System.out.println("? copyResourcesFromJarFile() filename='" + filename +"'"); if (entry.isDirectory()) { writeDirectory(filename, jarFile); } else if (acceptResource(filename, false)) { byte[] bytes = FileUtil.readAsByteArray(inStream); writeResource(filename, bytes, jarFile); } inStream.closeEntry(); } } finally { if (inStream != null) inStream.close(); } } private void copyResourcesFromDirectory(File dir) throws IOException { if (!COPY_INPATH_DIR_RESOURCES) return; // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(dir, new FileFilter() { public boolean accept(File f) { boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")); return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = files[i].getAbsolutePath().substring(dir.getAbsolutePath().length() + 1); copyResourcesFromFile(files[i], filename, dir); } } private void copyResourcesFromFile(File f, String filename, File src) throws IOException { if (!acceptResource(filename, true)) return; FileInputStream fis = null; try { fis = new FileInputStream(f); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); writeResource(filename, bytes, src); } finally { if (fis != null) fis.close(); } } /** * Add a directory entry to the output zip file. Don't do anything if not writing out to a zip file. A directory entry is one * whose filename ends with '/' * * @param directory the directory path * @param srcloc the src of the directory entry, for use when creating a warning message * @throws IOException if something goes wrong creating the new zip entry */ private void writeDirectory(String directory, File srcloc) throws IOException { if (state.hasResource(directory)) { IMessage msg = new Message("duplicate resource: '" + directory + "'", IMessage.WARNING, null, new SourceLocation( srcloc, 0)); handler.handleMessage(msg); return; } if (zos != null) { ZipEntry newEntry = new ZipEntry(directory); zos.putNextEntry(newEntry); zos.closeEntry(); state.recordResource(directory); } // Nothing to do if not writing to a zip file } private void writeResource(String filename, byte[] content, File srcLocation) throws IOException { if (state.hasResource(filename)) { IMessage msg = new Message("duplicate resource: '" + filename + "'", IMessage.WARNING, null, new SourceLocation( srcLocation, 0)); handler.handleMessage(msg); return; } if (filename.equals(buildConfig.getOutxmlName())) { ignoreOutxml = true; IMessage msg = new Message("-outxml/-outxmlfile option ignored because resource already exists: '" + filename + "'", IMessage.WARNING, null, new SourceLocation(srcLocation, 0)); handler.handleMessage(msg); } if (zos != null) { ZipEntry newEntry = new ZipEntry(filename); // ??? get compression scheme right zos.putNextEntry(newEntry); zos.write(content); zos.closeEntry(); } else { File destDir = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { destDir = buildConfig.getCompilationResultDestinationManager().getOutputLocationForResource(srcLocation); } try { OutputStream fos = FileUtil.makeOutputStream(new File(destDir, filename)); fos.write(content); fos.close(); } catch (FileNotFoundException fnfe) { IMessage msg = new Message("unable to copy resource to output folder: '" + filename + "' - reason: " + fnfe.getMessage(), IMessage.ERROR, null, new SourceLocation(srcLocation, 0)); handler.handleMessage(msg); } } state.recordResource(filename); } /* * If we are writing to an output directory copy the manifest but only if we already have one */ private void writeManifest() throws IOException { Manifest manifest = getWeaver().getManifest(false); if (manifest != null && zos == null) { File outputDir = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { // Manifests are only written if we have a jar on the inpath. Therefore, // we write the manifest to the defaultOutputLocation because this is // where we sent the classes that were on the inpath outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation(); } if (outputDir == null) return; OutputStream fos = FileUtil.makeOutputStream(new File(outputDir, MANIFEST_NAME)); manifest.write(fos); fos.close(); } } private boolean acceptResource(String resourceName, boolean fromFile) { if ((resourceName.startsWith("CVS/")) || (resourceName.indexOf("/CVS/") != -1) || (resourceName.endsWith("/CVS")) || (resourceName.endsWith(".class")) || (resourceName.startsWith(".svn/")) || (resourceName.indexOf("/.svn/") != -1) || (resourceName.endsWith("/.svn")) || // Do not copy manifests if either they are coming from a jar or we are writing to a jar (resourceName.toUpperCase().equals(MANIFEST_NAME) && (!fromFile || zos != null))) { return false; } else { return true; } } private void writeOutxmlFile() throws IOException { if (ignoreOutxml) return; String filename = buildConfig.getOutxmlName(); // System.err.println("? AjBuildManager.writeOutxmlFile() outxml=" + filename); Map outputDirsAndAspects = findOutputDirsForAspects(); Set outputDirs = outputDirsAndAspects.entrySet(); for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); File outputDir = (File) entry.getKey(); List aspects = (List) entry.getValue(); ByteArrayOutputStream baos = getOutxmlContents(aspects); if (zos != null) { ZipEntry newEntry = new ZipEntry(filename); zos.putNextEntry(newEntry); zos.write(baos.toByteArray()); zos.closeEntry(); } else { OutputStream fos = FileUtil.makeOutputStream(new File(outputDir, filename)); fos.write(baos.toByteArray()); fos.close(); } } } private ByteArrayOutputStream getOutxmlContents(List aspectNames) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); ps.println("<aspectj>"); ps.println("<aspects>"); if (aspectNames != null) { for (Iterator i = aspectNames.iterator(); i.hasNext();) { String name = (String) i.next(); ps.println("<aspect name=\"" + name + "\"/>"); } } ps.println("</aspects>"); ps.println("</aspectj>"); ps.println(); ps.close(); return baos; } /** * Returns a map where the keys are File objects corresponding to all the output directories and the values are a list of * aspects which are sent to that ouptut directory */ private Map /* File --> List (String) */findOutputDirsForAspects() { Map outputDirsToAspects = new HashMap(); Map aspectNamesToFileNames = state.getAspectNamesToFileNameMap(); if (buildConfig.getCompilationResultDestinationManager() == null || buildConfig.getCompilationResultDestinationManager().getAllOutputLocations().size() == 1) { // we only have one output directory...which simplifies things File outputDir = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation(); } List aspectNames = new ArrayList(); if (aspectNamesToFileNames != null) { Set keys = aspectNamesToFileNames.keySet(); for (Iterator iterator = keys.iterator(); iterator.hasNext();) { String name = (String) iterator.next(); aspectNames.add(name); } } outputDirsToAspects.put(outputDir, aspectNames); } else { List outputDirs = buildConfig.getCompilationResultDestinationManager().getAllOutputLocations(); for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) { File outputDir = (File) iterator.next(); outputDirsToAspects.put(outputDir, new ArrayList()); } Set entrySet = aspectNamesToFileNames.entrySet(); for (Iterator iterator = entrySet.iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String aspectName = (String) entry.getKey(); char[] fileName = (char[]) entry.getValue(); File outputDir = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass( new File(new String(fileName))); if (!outputDirsToAspects.containsKey(outputDir)) { outputDirsToAspects.put(outputDir, new ArrayList()); } ((List) outputDirsToAspects.get(outputDir)).add(aspectName); } } return outputDirsToAspects; } // public static void dumprels() { // IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap(); // int ctr = 1; // Set entries = irm.getEntries(); // for (Iterator iter = entries.iterator(); iter.hasNext();) { // String hid = (String) iter.next(); // List rels = irm.get(hid); // for (Iterator iterator = rels.iterator(); iterator.hasNext();) { // IRelationship ir = (IRelationship) iterator.next(); // List targets = ir.getTargets(); // for (Iterator iterator2 = targets.iterator(); // iterator2.hasNext(); // ) { // String thid = (String) iterator2.next(); // System.err.println("Hid:"+(ctr++)+":(targets="+targets.size()+") "+hid+" ("+ir.getName()+") "+thid); // } // } // } // } /** * Responsible for managing the ASM model between builds. Contains the policy for maintaining the persistance of elements in the * model. * * This code is driven before each 'fresh' (batch) build to create a new model. */ private void setupModel(AjBuildConfig config) { if (!(config.isEmacsSymMode() || config.isGenerateModelMode())) { return; } // AsmManager.setCreatingModel(config.isEmacsSymMode() || config.isGenerateModelMode()); // if (!AsmManager.isCreatingModel()) // return; AsmManager structureModel = AsmManager.createNewStructureModel(); // AsmManager.getDefault().getRelationshipMap().clear(); IHierarchy model = structureModel.getHierarchy(); String rootLabel = "<root>"; IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA; if (buildConfig.getConfigFile() != null) { rootLabel = buildConfig.getConfigFile().getName(); model.setConfigFile(buildConfig.getConfigFile().getAbsolutePath()); kind = IProgramElement.Kind.FILE_LST; } model.setRoot(new ProgramElement(structureModel, rootLabel, kind, new ArrayList())); model.setFileMap(new HashMap()); // setStructureModel(model); state.setStructureModel(structureModel); // state.setRelationshipMap(AsmManager.getDefault().getRelationshipMap()); } // // private void dumplist(List l) { // System.err.println("---- "+l.size()); // for (int i =0 ;i<l.size();i++) System.err.println(i+"\t "+l.get(i)); // } // private void accumulateFileNodes(IProgramElement ipe,List store) { // if (ipe.getKind()==IProgramElement.Kind.FILE_JAVA || // ipe.getKind()==IProgramElement.Kind.FILE_ASPECTJ) { // if (!ipe.getName().equals("<root>")) { // store.add(ipe); // return; // } // } // for (Iterator i = ipe.getChildren().iterator();i.hasNext();) { // accumulateFileNodes((IProgramElement)i.next(),store); // } // } // LTODO delegate to BcelWeaver? // XXX hideous, should not be Object public void setCustomMungerFactory(Object o) { customMungerFactory = (CustomMungerFactory) o; } public Object getCustomMungerFactory() { return customMungerFactory; } /** init only on initial batch compile? no file-specific options */ private void initBcelWorld(IMessageHandler handler) throws IOException { List cp = buildConfig.getFullClasspath(); // pr145693 // buildConfig.getBootclasspath(); // cp.addAll(buildConfig.getClasspath()); BcelWorld bcelWorld = new BcelWorld(cp, handler, null); bcelWorld.setBehaveInJava5Way(buildConfig.getBehaveInJava5Way()); bcelWorld.setAddSerialVerUID(buildConfig.isAddSerialVerUID()); bcelWorld.setXmlConfigured(buildConfig.isXmlConfigured()); bcelWorld.setXmlFiles(buildConfig.getXmlFiles()); bcelWorld.performExtraConfiguration(buildConfig.getXconfigurationInfo()); bcelWorld.setTargetAspectjRuntimeLevel(buildConfig.getTargetAspectjRuntimeLevel()); bcelWorld.setOptionalJoinpoints(buildConfig.getXJoinpoints()); bcelWorld.setXnoInline(buildConfig.isXnoInline()); bcelWorld.setXlazyTjp(buildConfig.isXlazyTjp()); bcelWorld.setXHasMemberSupportEnabled(buildConfig.isXHasMemberEnabled()); bcelWorld.setPinpointMode(buildConfig.isXdevPinpoint()); bcelWorld.setErrorAndWarningThreshold(buildConfig.getOptions().errorThreshold, buildConfig.getOptions().warningThreshold); BcelWeaver bcelWeaver = new BcelWeaver(bcelWorld); bcelWeaver.setCustomMungerFactory(customMungerFactory); state.setWorld(bcelWorld); state.setWeaver(bcelWeaver); state.clearBinarySourceFiles(); if (buildConfig.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT)) { bcelWorld.getLint().loadDefaultProperties(); } else { bcelWorld.getLint().setAll(buildConfig.getLintMode()); } if (buildConfig.getLintSpecFile() != null) { bcelWorld.getLint().setFromProperties(buildConfig.getLintSpecFile()); } for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext();) { File f = (File) i.next(); if (!f.exists()) { IMessage message = new Message("invalid aspectpath entry: " + f.getName(), null, true); handler.handleMessage(message); } else { bcelWeaver.addLibraryJarFile(f); } } // String lintMode = buildConfig.getLintMode(); File outputDir = buildConfig.getOutputDir(); if (outputDir == null && buildConfig.getCompilationResultDestinationManager() != null) { // send all output from injars and inpath to the default output location // (will also later send the manifest there too) outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation(); } // ??? incremental issues for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext();) { File inJar = (File) i.next(); List unwovenClasses = bcelWeaver.addJarFile(inJar, outputDir, false); state.recordBinarySource(inJar.getPath(), unwovenClasses); } for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext();) { File inPathElement = (File) i.next(); if (!inPathElement.isDirectory()) { // its a jar file on the inpath // the weaver method can actually handle dirs, but we don't call it, see next block List unwovenClasses = bcelWeaver.addJarFile(inPathElement, outputDir, true); state.recordBinarySource(inPathElement.getPath(), unwovenClasses); } else { // add each class file in an in-dir individually, this gives us the best error reporting // (they are like 'source' files then), and enables a cleaner incremental treatment of // class file changes in indirs. File[] binSrcs = FileUtil.listFiles(inPathElement, binarySourceFilter); for (int j = 0; j < binSrcs.length; j++) { UnwovenClassFile ucf = bcelWeaver.addClassFile(binSrcs[j], inPathElement, outputDir); List ucfl = new ArrayList(); ucfl.add(ucf); state.recordBinarySource(binSrcs[j].getPath(), ucfl); } } } bcelWeaver.setReweavableMode(buildConfig.isXNotReweavable()); // check for org.aspectj.runtime.JoinPoint ResolvedType joinPoint = bcelWorld.resolve("org.aspectj.lang.JoinPoint"); if (joinPoint.isMissing()) { IMessage message = new Message( "classpath error: unable to find org.aspectj.lang.JoinPoint (check that aspectjrt.jar is in your classpath)", null, true); handler.handleMessage(message); } } public World getWorld() { return getBcelWorld(); } void addAspectClassFilesToWeaver(List addedClassFiles) throws IOException { for (Iterator i = addedClassFiles.iterator(); i.hasNext();) { UnwovenClassFile classFile = (UnwovenClassFile) i.next(); getWeaver().addClassFile(classFile); } } public FileSystem getLibraryAccess(String[] classpaths, String[] filenames) { String defaultEncoding = buildConfig.getOptions().defaultEncoding; if ("".equals(defaultEncoding)) {//$NON-NLS-1$ defaultEncoding = null; } // Bug 46671: We need an array as long as the number of elements in the classpath - *even though* not every // element of the classpath is likely to be a directory. If we ensure every element of the array is set to // only look for BINARY, then we make sure that for any classpath element that is a directory, we won't build // a classpathDirectory object that will attempt to look for source when it can't find binary. // int[] classpathModes = new int[classpaths.length]; // for (int i =0 ;i<classpaths.length;i++) classpathModes[i]=ClasspathDirectory.BINARY; return new FileSystem(classpaths, filenames, defaultEncoding, ClasspathLocation.BINARY); } public IProblemFactory getProblemFactory() { return new DefaultProblemFactory(Locale.getDefault()); } /* * Build the set of compilation source units */ public CompilationUnit[] getCompilationUnits(String[] filenames) { int fileCount = filenames.length; CompilationUnit[] units = new CompilationUnit[fileCount]; // HashtableOfObject knownFileNames = new HashtableOfObject(fileCount); String defaultEncoding = buildConfig.getOptions().defaultEncoding; if ("".equals(defaultEncoding)) {//$NON-NLS-1$ defaultEncoding = null; } for (int i = 0; i < fileCount; i++) { units[i] = new CompilationUnit(null, filenames[i], defaultEncoding); } return units; } public String extractDestinationPathFromSourceFile(CompilationResult result) { ICompilationUnit compilationUnit = result.compilationUnit; if (compilationUnit != null) { char[] fileName = compilationUnit.getFileName(); int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName); if (lastIndex == -1) { return System.getProperty("user.dir"); //$NON-NLS-1$ } return new String(CharOperation.subarray(fileName, 0, lastIndex)); } return System.getProperty("user.dir"); //$NON-NLS-1$ } public void performCompilation(Collection files) { if (progressListener != null) { compiledCount = 0; sourceFileCount = files.size(); progressListener.setText("compiling source files"); } // Translate from strings to File objects String[] filenames = new String[files.size()]; int idx = 0; for (Iterator fIterator = files.iterator(); fIterator.hasNext();) { File f = (File) fIterator.next(); filenames[idx++] = f.getPath(); } environment = state.getNameEnvironment(); boolean environmentNeedsRebuilding = false; // Might be a bit too cautious, but let us see how it goes if (buildConfig.getChanged() != AjBuildConfig.NO_CHANGES) { environmentNeedsRebuilding = true; } if (environment == null || environmentNeedsRebuilding) { List cps = buildConfig.getFullClasspath(); Dump.saveFullClasspath(cps); String[] classpaths = new String[cps.size()]; for (int i = 0; i < cps.size(); i++) { classpaths[i] = (String) cps.get(i); } environment = new StatefulNameEnvironment(getLibraryAccess(classpaths, filenames), state.getClassNameToFileMap(), state); state.setNameEnvironment(environment); } org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(this); org.aspectj.org.eclipse.jdt.internal.compiler.Compiler compiler = new org.aspectj.org.eclipse.jdt.internal.compiler.Compiler( environment, DefaultErrorHandlingPolicies.proceedWithAllProblems(), buildConfig.getOptions().getMap(), getBatchRequestor(), getProblemFactory()); compiler.options.produceReferenceInfo = true; // TODO turn off when not needed try { compiler.compile(getCompilationUnits(filenames)); } catch (OperationCanceledException oce) { handler.handleMessage(new Message("build cancelled:" + oce.getMessage(), IMessage.WARNING, null, null)); } // cleanup org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(null); AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(null); environment.cleanup(); // environment = null; } public void cleanupEnvironment() { if (environment != null) { environment.cleanup(); environment = null; } } /* * Answer the component to which will be handed back compilation results from the compiler */ public IIntermediateResultsRequestor getInterimResultRequestor() { return new IIntermediateResultsRequestor() { public void acceptResult(InterimCompilationResult result) { if (progressListener != null) { compiledCount++; progressListener.setProgress((compiledCount / 2.0) / sourceFileCount); progressListener.setText("compiled: " + result.fileName()); } state.noteResult(result); if (progressListener != null && progressListener.isCancelledRequested()) { throw new AbortCompilation(true, new OperationCanceledException("Compilation cancelled as requested")); } } }; } public ICompilerRequestor getBatchRequestor() { return new ICompilerRequestor() { public void acceptResult(CompilationResult unitResult) { // end of compile, must now write the results to the output destination // this is either a jar file or a file in a directory boolean hasErrors = unitResult.hasErrors(); if (!hasErrors || proceedOnError()) { Collection classFiles = unitResult.compiledTypes.values(); boolean shouldAddAspectName = (buildConfig.getOutxmlName() != null); for (Iterator iter = classFiles.iterator(); iter.hasNext();) { ClassFile classFile = (ClassFile) iter.next(); String filename = new String(classFile.fileName()); String classname = filename.replace('/', '.'); filename = filename.replace('/', File.separatorChar) + ".class"; try { if (buildConfig.getOutputJar() == null) { String outfile = writeDirectoryEntry(unitResult, classFile, filename); if (environmentSupportsIncrementalCompilation) { if (!classname.endsWith("$ajcMightHaveAspect")) { ResolvedType type = getBcelWorld().resolve(classname); if (type.isAspect()) { state.recordAspectClassFile(outfile); } } } } else { writeZipEntry(classFile, filename); } if (shouldAddAspectName && !classname.endsWith("$ajcMightHaveAspect")) addAspectName(classname, unitResult.getFileName()); } catch (IOException ex) { IMessage message = EclipseAdapterUtils.makeErrorMessage(new String(unitResult.fileName), CANT_WRITE_RESULT, ex); handler.handleMessage(message); } } state.noteNewResult(unitResult); unitResult.compiledTypes.clear(); // free up references to AjClassFile instances } if (unitResult.hasProblems() || unitResult.hasTasks()) { IProblem[] problems = unitResult.getAllProblems(); for (int i = 0; i < problems.length; i++) { IMessage message = EclipseAdapterUtils.makeMessage(unitResult.compilationUnit, problems[i], getBcelWorld()); handler.handleMessage(message); } } } private String writeDirectoryEntry(CompilationResult unitResult, ClassFile classFile, String filename) throws IOException { File destinationPath = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { destinationPath = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass( new File(new String(unitResult.fileName))); } String outFile; if (destinationPath == null) { outFile = new File(filename).getName(); outFile = new File(extractDestinationPathFromSourceFile(unitResult), outFile).getPath(); } else { outFile = new File(destinationPath, filename).getPath(); } BufferedOutputStream os = FileUtil.makeOutputStream(new File(outFile)); os.write(classFile.getBytes()); os.close(); if (buildConfig.getCompilationResultDestinationManager() != null) { buildConfig.getCompilationResultDestinationManager().reportClassFileWrite(outFile); } return outFile; } private void writeZipEntry(ClassFile classFile, String name) throws IOException { name = name.replace(File.separatorChar, '/'); ZipEntry newEntry = new ZipEntry(name); // ??? get compression scheme right zos.putNextEntry(newEntry); zos.write(classFile.getBytes()); zos.closeEntry(); } private void addAspectName(String name, char[] fileContainingAspect) { BcelWorld world = getBcelWorld(); ResolvedType type = world.resolve(name); // System.err.println("? writeAspectName() type=" + type); if (type.isAspect()) { if (state.getAspectNamesToFileNameMap() == null) { state.initializeAspectNamesToFileNameMap(); } if (!state.getAspectNamesToFileNameMap().containsKey(name)) { state.getAspectNamesToFileNameMap().put(name, fileContainingAspect); } } } }; } protected boolean proceedOnError() { return buildConfig.getProceedOnError(); } // public void noteClassFiles(AjCompiler.InterimResult result) { // if (result == null) return; // CompilationResult unitResult = result.result; // String sourceFileName = result.fileName(); // if (!(unitResult.hasErrors() && !proceedOnError())) { // List unwovenClassFiles = new ArrayList(); // Enumeration classFiles = unitResult.compiledTypes.elements(); // while (classFiles.hasMoreElements()) { // ClassFile classFile = (ClassFile) classFiles.nextElement(); // String filename = new String(classFile.fileName()); // filename = filename.replace('/', File.separatorChar) + ".class"; // // File destinationPath = buildConfig.getOutputDir(); // if (destinationPath == null) { // filename = new File(filename).getName(); // filename = new File(extractDestinationPathFromSourceFile(unitResult), filename).getPath(); // } else { // filename = new File(destinationPath, filename).getPath(); // } // // //System.out.println("classfile: " + filename); // unwovenClassFiles.add(new UnwovenClassFile(filename, classFile.getBytes())); // } // state.noteClassesFromFile(unitResult, sourceFileName, unwovenClassFiles); // // System.out.println("file: " + sourceFileName); // // for (int i=0; i < unitResult.simpleNameReferences.length; i++) { // // System.out.println("simple: " + new String(unitResult.simpleNameReferences[i])); // // } // // for (int i=0; i < unitResult.qualifiedReferences.length; i++) { // // System.out.println("qualified: " + // // new String(CharOperation.concatWith(unitResult.qualifiedReferences[i], '/'))); // // } // } else { // state.noteClassesFromFile(null, sourceFileName, Collections.EMPTY_LIST); // } // } // private void setBuildConfig(AjBuildConfig buildConfig) { this.buildConfig = buildConfig; if (!this.environmentSupportsIncrementalCompilation) { this.environmentSupportsIncrementalCompilation = (buildConfig.isIncrementalMode() || buildConfig .isIncrementalFileMode()); } handler.reset(); } String makeClasspathString(AjBuildConfig buildConfig) { if (buildConfig == null || buildConfig.getFullClasspath() == null) return ""; StringBuffer buf = new StringBuffer(); boolean first = true; for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext();) { if (first) { first = false; } else { buf.append(File.pathSeparator); } buf.append(it.next().toString()); } return buf.toString(); } /** * This will return null if aspectjrt.jar is present and has the correct version. Otherwise it will return a string message * indicating the problem. */ private String checkRtJar(AjBuildConfig buildConfig) { // omitting dev info if (Version.text.equals(Version.DEVELOPMENT)) { // in the development version we can't do this test usefully // MessageUtil.info(holder, "running development version of aspectj compiler"); return null; } if (buildConfig == null || buildConfig.getFullClasspath() == null) return "no classpath specified"; String ret = null; for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext();) { File p = new File((String) it.next()); // pr112830, allow variations on aspectjrt.jar of the form aspectjrtXXXXXX.jar if (p.isFile() && p.getName().startsWith("aspectjrt") && p.getName().endsWith(".jar")) { try { String version = null; Manifest manifest = new JarFile(p).getManifest(); if (manifest == null) { ret = "no manifest found in " + p.getAbsolutePath() + ", expected " + Version.text; continue; } Attributes attr = manifest.getAttributes("org/aspectj/lang/"); if (null != attr) { version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION); if (null != version) { version = version.trim(); } } // assume that users of development aspectjrt.jar know what they're doing if (Version.DEVELOPMENT.equals(version)) { // MessageUtil.info(holder, // "running with development version of aspectjrt.jar in " + // p.getAbsolutePath()); return null; } else if (!Version.text.equals(version)) { ret = "bad version number found in " + p.getAbsolutePath() + " expected " + Version.text + " found " + version; continue; } } catch (IOException ioe) { ret = "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe; } return null; // this is the "OK" return value! } else { // might want to catch other classpath errors } } if (ret != null) return ret; // last error found in potentially matching jars... return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString(buildConfig); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("AjBuildManager("); buf.append(")"); return buf.toString(); } // // public void setStructureModel(IHierarchy structureModel) { // this.structureModel = structureModel; // } /** * Returns null if there is no structure model */ public AsmManager getStructureModel() { return (state == null ? null : state.getStructureModel()); } public IProgressListener getProgressListener() { return progressListener; } public void setProgressListener(IProgressListener progressListener) { this.progressListener = progressListener; } /* * (non-Javadoc) * * @see org.aspectj.ajdt.internal.compiler.AjCompiler.IOutputClassFileNameProvider#getOutputClassFileName(char[]) */ public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) { String filename = new String(eclipseClassFileName); filename = filename.replace('/', File.separatorChar) + ".class"; File destinationPath = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { File f = new File(new String(result.getFileName())); destinationPath = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass(f); } String outFile; if (destinationPath == null) { outFile = new File(filename).getName(); outFile = new File(extractDestinationPathFromSourceFile(result), outFile).getPath(); } else { outFile = new File(destinationPath, filename).getPath(); } return outFile; } /* * (non-Javadoc) * * @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler) */ public ICompilerAdapter getAdapter(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) { // complete compiler config and return a suitable adapter... populateCompilerOptionsFromLintSettings(forCompiler); AjProblemReporter pr = new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(), forCompiler.options, getProblemFactory()); forCompiler.problemReporter = pr; AjLookupEnvironment le = new AjLookupEnvironment(forCompiler, forCompiler.options, pr, environment); EclipseFactory factory = new EclipseFactory(le, this); le.factory = factory; pr.factory = factory; forCompiler.lookupEnvironment = le; forCompiler.parser = new Parser(pr, forCompiler.options.parseLiteralExpressionsAsConstants); if (getBcelWorld().shouldPipelineCompilation()) { IMessage message = MessageUtil.info("Pipelining compilation"); handler.handleMessage(message); return new AjPipeliningCompilerAdapter(forCompiler, batchCompile, getBcelWorld(), getWeaver(), factory, getInterimResultRequestor(), progressListener, this, // IOutputFilenameProvider this, // IBinarySourceProvider state.getBinarySourceMap(), buildConfig.isTerminateAfterCompilation(), buildConfig.getProceedOnError(), buildConfig.isNoAtAspectJAnnotationProcessing(), state); } else { return new AjCompilerAdapter(forCompiler, batchCompile, getBcelWorld(), getWeaver(), factory, getInterimResultRequestor(), progressListener, this, // IOutputFilenameProvider this, // IBinarySourceProvider state.getBinarySourceMap(), buildConfig.isTerminateAfterCompilation(), buildConfig.getProceedOnError(), buildConfig.isNoAtAspectJAnnotationProcessing(), state); } } /** * Some AspectJ lint options need to be known about in the compiler. This is how we pass them over... * * @param forCompiler */ private void populateCompilerOptionsFromLintSettings(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) { BcelWorld world = this.state.getBcelWorld(); IMessage.Kind swallowedExceptionKind = world.getLint().swallowedExceptionInCatchBlock.getKind(); Map optionsMap = new HashMap(); optionsMap.put(CompilerOptions.OPTION_ReportSwallowedExceptionInCatchBlock, swallowedExceptionKind == null ? "ignore" : swallowedExceptionKind.toString()); forCompiler.options.set(optionsMap); } /* * (non-Javadoc) * * @see org.aspectj.ajdt.internal.compiler.IBinarySourceProvider#getBinarySourcesForThisWeave() */ public Map getBinarySourcesForThisWeave() { return binarySourcesForTheNextCompile; } public static AsmHierarchyBuilder getAsmHierarchyBuilder() { return asmHierarchyBuilder; } /** * Override the the default hierarchy builder. */ public static void setAsmHierarchyBuilder(AsmHierarchyBuilder newBuilder) { asmHierarchyBuilder = newBuilder; } public AjState getState() { return state; } public void setState(AjState buildState) { state = buildState; } private static class AjBuildContexFormatter implements ContextFormatter { public String formatEntry(int phaseId, Object data) { StringBuffer sb = new StringBuffer(); if (phaseId == CompilationAndWeavingContext.BATCH_BUILD) { sb.append("batch building "); } else { sb.append("incrementally building "); } AjBuildConfig config = (AjBuildConfig) data; List classpath = config.getClasspath(); sb.append("with classpath: "); for (Iterator iter = classpath.iterator(); iter.hasNext();) { sb.append(iter.next().toString()); sb.append(File.pathSeparator); } return sb.toString(); } } public boolean wasFullBuild() { return wasFullBuild; } }
269,578
Bug 269578 Resource deletion in source folder on full build when source and output folders are the same.
On the clean before a full aspectj build resources are removed from the output folder. This is true even when the output and the source folder are the same. In this case, the resources are deleted from the source folder! When the source and output folders are the same, resources should never be deleted.
resolved fixed
5c49c0b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-03-21T01:38:50Z"
"2009-03-20T20:13:20Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjState.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.io.IOException; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.ajdt.internal.compiler.InterimCompilationResult; import org.aspectj.asm.AsmManager; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.Message; import org.aspectj.bridge.SourceLocation; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader; import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException; import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryAnnotation; import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryField; import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryMethod; import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryType; import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers; import org.aspectj.org.eclipse.jdt.internal.core.builder.ReferenceCollection; import org.aspectj.org.eclipse.jdt.internal.core.builder.StringSet; import org.aspectj.util.FileUtil; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.UnwovenClassFile; /** * Maintains state needed for incremental compilation */ public class AjState implements CompilerConfigurationChangeFlags { // SECRETAPI configures whether we use state instead of lastModTime - see pr245566 public static boolean CHECK_STATE_FIRST = true; // SECRETAPI static so beware of multi-threading bugs... public static IStateListener stateListener = null; public static boolean FORCE_INCREMENTAL_DURING_TESTING = false; private final AjBuildManager buildManager; private boolean couldBeSubsequentIncrementalBuild = false; private INameEnvironment nameEnvironment; // // private IHierarchy structureModel; // private IRelationshipMap relmap; private AsmManager structureModel; /** * When looking at changes on the classpath, this set accumulates files in our state instance that affected by those changes. * Then if we can do an incremental build - these must be compiled. */ private final Set affectedFiles = new HashSet(); private long lastSuccessfulFullBuildTime = -1; private final Hashtable /* File, long */structuralChangesSinceLastFullBuild = new Hashtable(); private long lastSuccessfulBuildTime = -1; private long currentBuildTime = -1; private AjBuildConfig buildConfig; private boolean batchBuildRequiredThisTime = false; /** * Keeps a list of (FQN,Filename) pairs (as ClassFile objects) for types that resulted from the compilation of the given File. * Note :- the ClassFile objects contain no byte code, they are simply a Filename,typename pair. * * Populated in noteResult and used in addDependentsOf(File) * * Added by AMC during state refactoring, 1Q06. */ private final Map/* <File, List<ClassFile> */fullyQualifiedTypeNamesResultingFromCompilationUnit = new HashMap(); /** * Source files defining aspects * * Populated in noteResult and used in processDeletedFiles * * Added by AMC during state refactoring, 1Q06. */ private final Set/* <File> */sourceFilesDefiningAspects = new HashSet(); /** * Populated in noteResult to record the set of types that should be recompiled if the given file is modified or deleted. * * Refered to during addAffectedSourceFiles when calculating incremental compilation set. */ private final Map/* <File, ReferenceCollection> */references = new HashMap(); /** * Holds UnwovenClassFiles (byte[]s) originating from the given file source. This could be a jar file, a directory, or an * individual .class file. This is an *expensive* map. It is cleared immediately following a batch build, and the cheaper * inputClassFilesBySource map is kept for processing of any subsequent incremental builds. * * Populated during AjBuildManager.initBcelWorld(). * * Passed into AjCompiler adapter as the set of binary input files to reweave if the weaver determines a full weave is required. * * Cleared during initBcelWorld prior to repopulation. * * Used when a file is deleted during incremental compilation to delete all of the class files in the output directory that * resulted from the weaving of File. * * Used during getBinaryFilesToCompile when compiling incrementally to determine which files should be recompiled if a given * input file has changed. * */ private Map/* File, List<UnwovenClassFile> */binarySourceFiles = new HashMap(); /** * Initially a duplicate of the information held in binarySourceFiles, with the key difference that the values are ClassFiles * (type name, File) not UnwovenClassFiles (which also have all the byte code in them). After a batch build, binarySourceFiles * is cleared, leaving just this much lighter weight map to use in processing subsequent incremental builds. */ private final Map/* <File,List<ClassFile> */inputClassFilesBySource = new HashMap(); /** * A list of the .class files created by this state that contain aspects. */ private final List/* <String> */aspectClassFiles = new ArrayList(); /** * Holds structure information on types as they were at the end of the last build. It would be nice to get rid of this too, but * can't see an easy way to do that right now. */ private final Map/* FQN,CompactStructureRepresentation */resolvedTypeStructuresFromLastBuild = new HashMap(); /** * Populated in noteResult to record the set of UnwovenClassFiles (intermediate results) that originated from compilation of the * class with the given fully-qualified name. * * Used in removeAllResultsOfLastBuild to remove .class files from output directory. * * Passed into StatefulNameEnvironment during incremental compilation to support findType lookups. */ private final Map/* <String, File> */classesFromName = new HashMap(); /** * Populated by AjBuildManager to record the aspects with the file name in which they're contained. This is later used when * writing the outxml file in AjBuildManager. Need to record the file name because want to write an outxml file for each of the * output directories and in order to ask the OutputLocationManager for the output location for a given aspect we need the file * in which it is contained. */ private Map /* <String, char[]> */aspectsFromFileNames; private Set/* File */compiledSourceFiles = new HashSet(); private final List/* String */resources = new ArrayList(); // these are references created on a particular compile run - when looping round in // addAffectedSourceFiles(), if some have been created then we look at which source files // touch upon those and get them recompiled. private StringSet qualifiedStrings = new StringSet(3); private StringSet simpleStrings = new StringSet(3); private Set addedFiles; private Set deletedFiles; private Set /* BinarySourceFile */addedBinaryFiles; private Set /* BinarySourceFile */deletedBinaryFiles; private BcelWeaver weaver; private BcelWorld world; public AjState(AjBuildManager buildManager) { this.buildManager = buildManager; } public void setCouldBeSubsequentIncrementalBuild(boolean yesThereCould) { this.couldBeSubsequentIncrementalBuild = yesThereCould; } void successfulCompile(AjBuildConfig config, boolean wasFullBuild) { buildConfig = config; lastSuccessfulBuildTime = currentBuildTime; if (stateListener != null) stateListener.buildSuccessful(wasFullBuild); if (wasFullBuild) lastSuccessfulFullBuildTime = currentBuildTime; } /** * Returns false if a batch build is needed. */ public boolean prepareForNextBuild(AjBuildConfig newBuildConfig) { currentBuildTime = System.currentTimeMillis(); if (!maybeIncremental()) { if (listenerDefined()) getListener().recordDecision( "Preparing for build: not going to be incremental because either not in AJDT or incremental deactivated"); return false; } if (this.batchBuildRequiredThisTime) { this.batchBuildRequiredThisTime = false; if (listenerDefined()) getListener().recordDecision( "Preparing for build: not going to be incremental this time because batch build explicitly forced"); return false; } if (lastSuccessfulBuildTime == -1 || buildConfig == null) { structuralChangesSinceLastFullBuild.clear(); if (listenerDefined()) getListener().recordDecision( "Preparing for build: not going to be incremental because no successful previous full build"); return false; } // we don't support incremental with an outjar yet if (newBuildConfig.getOutputJar() != null) { structuralChangesSinceLastFullBuild.clear(); if (listenerDefined()) getListener().recordDecision("Preparing for build: not going to be incremental because outjar being used"); return false; } affectedFiles.clear(); // we can't do an incremental build if one of our paths // has changed, or a jar on a path has been modified if (pathChange(buildConfig, newBuildConfig)) { // last time we built, .class files and resource files from jars on the // inpath will have been copied to the output directory. // these all need to be deleted in preparation for the clean build that is // coming - otherwise a file that has been deleted from an inpath jar // since the last build will not be deleted from the output directory. removeAllResultsOfLastBuild(); if (stateListener != null) { stateListener.pathChangeDetected(); } structuralChangesSinceLastFullBuild.clear(); if (listenerDefined()) getListener() .recordDecision( "Preparing for build: not going to be incremental because path change detected (one of classpath/aspectpath/inpath/injars)"); return false; } if (simpleStrings.elementSize > 20) { simpleStrings = new StringSet(3); } else { simpleStrings.clear(); } if (qualifiedStrings.elementSize > 20) { qualifiedStrings = new StringSet(3); } else { qualifiedStrings.clear(); } if ((newBuildConfig.getChanged() & PROJECTSOURCEFILES_CHANGED) == 0) { addedFiles = Collections.EMPTY_SET; deletedFiles = Collections.EMPTY_SET; } else { Set oldFiles = new HashSet(buildConfig.getFiles()); Set newFiles = new HashSet(newBuildConfig.getFiles()); addedFiles = new HashSet(newFiles); addedFiles.removeAll(oldFiles); deletedFiles = new HashSet(oldFiles); deletedFiles.removeAll(newFiles); } Set oldBinaryFiles = new HashSet(buildConfig.getBinaryFiles()); Set newBinaryFiles = new HashSet(newBuildConfig.getBinaryFiles()); addedBinaryFiles = new HashSet(newBinaryFiles); addedBinaryFiles.removeAll(oldBinaryFiles); deletedBinaryFiles = new HashSet(oldBinaryFiles); deletedBinaryFiles.removeAll(newBinaryFiles); boolean couldStillBeIncremental = processDeletedFiles(deletedFiles); if (!couldStillBeIncremental) { if (listenerDefined()) getListener().recordDecision("Preparing for build: not going to be incremental because an aspect was deleted"); return false; } if (listenerDefined()) getListener().recordDecision("Preparing for build: planning to be an incremental build"); return true; } /** * Checks if any of the files in the set passed in contains an aspect declaration. If one is found then we start the process of * batch building, i.e. we remove all the results of the last build, call any registered listener to tell them whats happened * and return false. * * @return false if we discovered an aspect declaration */ private boolean processDeletedFiles(Set deletedFiles) { for (Iterator iter = deletedFiles.iterator(); iter.hasNext();) { File aDeletedFile = (File) iter.next(); if (this.sourceFilesDefiningAspects.contains(aDeletedFile)) { removeAllResultsOfLastBuild(); if (stateListener != null) { stateListener.detectedAspectDeleted(aDeletedFile); } return false; } List/* ClassFile */classes = (List) fullyQualifiedTypeNamesResultingFromCompilationUnit.get(aDeletedFile); if (classes != null) { for (Iterator iterator = classes.iterator(); iterator.hasNext();) { ClassFile element = (ClassFile) iterator.next(); resolvedTypeStructuresFromLastBuild.remove(element.fullyQualifiedTypeName); } } } return true; } private Collection getModifiedFiles() { return getModifiedFiles(lastSuccessfulBuildTime); } Collection getModifiedFiles(long lastBuildTime) { Set ret = new HashSet(); // Check if the build configuration knows what files have changed... List/* File */modifiedFiles = buildConfig.getModifiedFiles(); if (modifiedFiles == null) { // do not know, so need to go looking // not our job to account for new and deleted files for (Iterator i = buildConfig.getFiles().iterator(); i.hasNext();) { File file = (File) i.next(); if (!file.exists()) continue; long modTime = file.lastModified(); // System.out.println("check: " + file + " mod " + modTime + " build " + lastBuildTime); // need to add 1000 since lastModTime is only accurate to a second on some (all?) platforms if (modTime + 1000 > lastBuildTime) { ret.add(file); } } } else { ret.addAll(modifiedFiles); } ret.addAll(affectedFiles); return ret; } private Collection getModifiedBinaryFiles() { return getModifiedBinaryFiles(lastSuccessfulBuildTime); } Collection getModifiedBinaryFiles(long lastBuildTime) { List ret = new ArrayList(); // not our job to account for new and deleted files for (Iterator i = buildConfig.getBinaryFiles().iterator(); i.hasNext();) { AjBuildConfig.BinarySourceFile bsfile = (AjBuildConfig.BinarySourceFile) i.next(); File file = bsfile.binSrc; if (!file.exists()) continue; long modTime = file.lastModified(); // System.out.println("check: " + file + " mod " + modTime + " build " + lastBuildTime); // need to add 1000 since lastModTime is only accurate to a second on some (all?) platforms if (modTime + 1000 >= lastBuildTime) { ret.add(bsfile); } } return ret; } private static int CLASS_FILE_NO_CHANGES = 0; private static int CLASS_FILE_CHANGED_THAT_NEEDS_INCREMENTAL_BUILD = 1; private static int CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD = 2; private static int MAX_AFFECTED_FILES_BEFORE_FULL_BUILD = 30; public static final FileFilter classFileFilter = new FileFilter() { public boolean accept(File pathname) { return pathname.getName().endsWith(".class"); } }; /** * Analyse .class files in the directory specified, if they have changed since the last successful build then see if we can * determine which source files in our project depend on the change. If we can then we can still do an incremental build, if we * can't then we have to do a full build. * */ private int classFileChangedInDirSinceLastBuildRequiringFullBuild(File dir) { if (!dir.isDirectory()) { return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD; } // Are we managing that output directory? AjState state = IncrementalStateManager.findStateManagingOutputLocation(dir); if (listenerDefined()) { if (state != null) { getListener().recordDecision("Found state instance managing output location : " + dir); } else { getListener().recordDecision("Failed to find a state instance managing output location : " + dir); } } // pr268827 - this guard will cause us to exit quickly if the state says there really is // nothing of interest. This will not catch the case where a user modifies the .class files outside of // eclipse because the state will not be aware of it. But that seems an unlikely scenario and // we are paying a heavy price to check it if (state != null && !state.hasAnyStructuralChangesSince(lastSuccessfulBuildTime)) { if (listenerDefined()) { getListener().recordDecision("No reported changes in that state"); } return CLASS_FILE_NO_CHANGES; } List classFiles = FileUtil.listClassFiles(dir); for (Iterator iterator = classFiles.iterator(); iterator.hasNext();) { File classFile = (File) iterator.next(); if (CHECK_STATE_FIRST && state != null) { if (state.isAspect(classFile)) { return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD; } if (state.hasStructuralChangedSince(classFile, lastSuccessfulBuildTime)) { if (listenerDefined()) { getListener().recordDecision("Structural change detected in : " + classFile); } if (isTypeWeReferTo(classFile)) { if (affectedFiles.size() > MAX_AFFECTED_FILES_BEFORE_FULL_BUILD) return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD; } // } else { // if (listenerDefined()) // getListener().recordDecision("Change detected in " + classFile + " but it is not structural"); } } else { long modTime = classFile.lastModified(); if ((modTime + 1000) >= lastSuccessfulBuildTime) { // so the class on disk has changed since the last successful build for this state object // BUG? we stop on the first change that leads us to an incremental build, surely we need to continue and look // at all files incase another change means we need to incremental a bit more stuff? // To work out if it is a real change we should ask any state // object managing the output location whether the file has // structurally changed or not if (state != null) { if (state.isAspect(classFile)) { return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD; } if (state.hasStructuralChangedSince(classFile, lastSuccessfulBuildTime)) { if (listenerDefined()) { getListener().recordDecision("Structural change detected in : " + classFile); } if (isTypeWeReferTo(classFile)) { if (affectedFiles.size() > MAX_AFFECTED_FILES_BEFORE_FULL_BUILD) return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD; } } else { if (listenerDefined()) getListener().recordDecision("Change detected in " + classFile + " but it is not structural"); } } else { // No state object to ask, so it only matters if we know which type depends on this file if (isTypeWeReferTo(classFile)) { if (affectedFiles.size() > MAX_AFFECTED_FILES_BEFORE_FULL_BUILD) return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD; return CLASS_FILE_CHANGED_THAT_NEEDS_INCREMENTAL_BUILD; } else { return CLASS_FILE_NO_CHANGES; } } } } } return CLASS_FILE_NO_CHANGES; } private boolean isAspect(File file) { return aspectClassFiles.contains(file.getAbsolutePath()); } public static class SoftHashMap extends AbstractMap { private final Map map; private final ReferenceQueue rq = new ReferenceQueue(); public SoftHashMap(Map map) { this.map = map; } public SoftHashMap() { this(new HashMap()); } public SoftHashMap(Map map, boolean b) { this(map); } class SoftReferenceKnownKey extends SoftReference { private final Object key; SoftReferenceKnownKey(Object k, Object v) { super(v, rq); this.key = k; } } private void processQueue() { SoftReferenceKnownKey sv = null; while ((sv = (SoftReferenceKnownKey) rq.poll()) != null) { map.remove(sv.key); } } public Object get(Object key) { SoftReferenceKnownKey value = (SoftReferenceKnownKey) map.get(key); if (value == null) return null; if (value.get() == null) { // it got GC'd map.remove(value.key); return null; } else { return value.get(); } } public Object put(Object k, Object v) { processQueue(); return map.put(k, new SoftReferenceKnownKey(k, v)); } public Set entrySet() { return map.entrySet(); } public void clear() { processQueue(); map.clear(); } public int size() { processQueue(); return map.size(); } public Object remove(Object k) { processQueue(); SoftReferenceKnownKey value = (SoftReferenceKnownKey) map.remove(k); if (value == null) return null; if (value.get() != null) { return value.get(); } return null; } } SoftHashMap/* <baseDir,SoftHashMap<theFile,className>> */fileToClassNameMap = new SoftHashMap(); /** * If a class file has changed in a path on our classpath, it may not be for a type that any of our source files care about. * This method checks if any of our source files have a dependency on the class in question and if not, we don't consider it an * interesting change. */ private boolean isTypeWeReferTo(File file) { String fpath = file.getAbsolutePath(); int finalSeparator = fpath.lastIndexOf(File.separator); String baseDir = fpath.substring(0, finalSeparator); String theFile = fpath.substring(finalSeparator + 1); SoftHashMap classNames = (SoftHashMap) fileToClassNameMap.get(baseDir); if (classNames == null) { classNames = new SoftHashMap(); fileToClassNameMap.put(baseDir, classNames); } char[] className = (char[]) classNames.get(theFile); if (className == null) { // if (listenerDefined()) // getListener().recordDecision("Cache miss, looking up classname for : " + fpath); ClassFileReader cfr; try { cfr = ClassFileReader.read(file); } catch (ClassFormatException e) { return true; } catch (IOException e) { return true; } className = cfr.getName(); classNames.put(theFile, className); // } else { // if (listenerDefined()) // getListener().recordDecision("Cache hit, looking up classname for : " + fpath); } char[][][] qualifiedNames = null; char[][] simpleNames = null; if (CharOperation.indexOf('/', className) != -1) { qualifiedNames = new char[1][][]; qualifiedNames[0] = CharOperation.splitOn('/', className); qualifiedNames = ReferenceCollection.internQualifiedNames(qualifiedNames); } else { simpleNames = new char[1][]; simpleNames[0] = className; simpleNames = ReferenceCollection.internSimpleNames(simpleNames, true); } for (Iterator i = references.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); ReferenceCollection refs = (ReferenceCollection) entry.getValue(); if (refs != null && refs.includes(qualifiedNames, simpleNames)) { if (listenerDefined()) { getListener().recordDecision( toString() + ": type " + new String(className) + " is depended upon by '" + entry.getKey() + "'"); } affectedFiles.add(entry.getKey()); if (affectedFiles.size() > MAX_AFFECTED_FILES_BEFORE_FULL_BUILD) return true; // return true; } } if (affectedFiles.size() > 0) return true; if (listenerDefined()) getListener().recordDecision(toString() + ": type " + new String(className) + " is not depended upon by this state"); return false; } // /** // * For a given class file, determine which source file it came from. This will only succeed if the class file is from a source // * file within this project. // */ // private File getSourceFileForClassFile(File classfile) { // Set sourceFiles = fullyQualifiedTypeNamesResultingFromCompilationUnit.keySet(); // for (Iterator sourceFileIterator = sourceFiles.iterator(); sourceFileIterator.hasNext();) { // File sourceFile = (File) sourceFileIterator.next(); // List/* ClassFile */classesFromSourceFile = (List/* ClassFile */) fullyQualifiedTypeNamesResultingFromCompilationUnit // .get(sourceFile); // for (int i = 0; i < classesFromSourceFile.size(); i++) { // if (((ClassFile) classesFromSourceFile.get(i)).locationOnDisk.equals(classfile)) // return sourceFile; // } // } // return null; // } public String toString() { StringBuffer sb = new StringBuffer(); // null config means failed build i think as it is only set on successful full build? sb.append("AjState(").append((buildConfig == null ? "NULLCONFIG" : buildConfig.getConfigFile().toString())).append(")"); return sb.toString(); } /** * Determine if a file has changed since a given time, using the local information recorded in the structural changes data * structure. * * @param file the file we are wondering about * @param lastSuccessfulBuildTime the last build time for the state asking the question */ private boolean hasStructuralChangedSince(File file, long lastSuccessfulBuildTime) { // long lastModTime = file.lastModified(); Long l = (Long) structuralChangesSinceLastFullBuild.get(file.getAbsolutePath()); long strucModTime = -1; if (l != null) strucModTime = l.longValue(); else strucModTime = this.lastSuccessfulFullBuildTime; // we now have: // 'strucModTime'-> the last time the class was structurally changed return (strucModTime > lastSuccessfulBuildTime); } /** * Determine if anything has changed since a given time. */ private boolean hasAnyStructuralChangesSince(long lastSuccessfulBuildTime) { Set entries = structuralChangesSinceLastFullBuild.entrySet(); for (Iterator iterator = entries.iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); Long l = (Long) entry.getValue(); if (l != null) { long lvalue = l.longValue(); if (lvalue > lastSuccessfulBuildTime) { if (listenerDefined()) { getListener().recordDecision( "Seems this has changed " + entry.getKey() + "modtime=" + lvalue + " lsbt=" + this.lastSuccessfulFullBuildTime + " incoming check value=" + lastSuccessfulBuildTime); } return true; } } } return (this.lastSuccessfulFullBuildTime > lastSuccessfulBuildTime); } /** * Determine if something has changed on the classpath/inpath/aspectpath and a full build is required rather than an incremental * one. * * @param previousConfig the previous configuration used * @param newConfig the new configuration being used * @return true if full build required */ private boolean pathChange(AjBuildConfig previousConfig, AjBuildConfig newConfig) { int changes = newConfig.getChanged(); if ((changes & (CLASSPATH_CHANGED | ASPECTPATH_CHANGED | INPATH_CHANGED | OUTPUTDESTINATIONS_CHANGED | INJARS_CHANGED)) != 0) { List oldOutputLocs = getOutputLocations(previousConfig); Set alreadyAnalysedPaths = new HashSet(); List oldClasspath = previousConfig.getClasspath(); List newClasspath = newConfig.getClasspath(); if (stateListener != null) stateListener.aboutToCompareClasspaths(oldClasspath, newClasspath); if (classpathChangedAndNeedsFullBuild(oldClasspath, newClasspath, true, oldOutputLocs, alreadyAnalysedPaths)) return true; List oldAspectpath = previousConfig.getAspectpath(); List newAspectpath = newConfig.getAspectpath(); if (changedAndNeedsFullBuild(oldAspectpath, newAspectpath, true, oldOutputLocs, alreadyAnalysedPaths)) return true; List oldInPath = previousConfig.getInpath(); List newInPath = newConfig.getInpath(); if (changedAndNeedsFullBuild(oldInPath, newInPath, false, oldOutputLocs, alreadyAnalysedPaths)) return true; List oldInJars = previousConfig.getInJars(); List newInJars = newConfig.getInJars(); if (changedAndNeedsFullBuild(oldInJars, newInJars, false, oldOutputLocs, alreadyAnalysedPaths)) return true; } else if (newConfig.getClasspathElementsWithModifiedContents() != null) { // Although the classpath entries themselves are the same as before, the contents of one of the // directories on the classpath has changed - rather than go digging around to find it, let's ask // the compiler configuration. This will allow for projects with long classpaths where classpaths // are also capturing project dependencies - when a project we depend on is rebuilt, we can just check // it as a standalone element on our classpath rather than going through them all List/* String */modifiedCpElements = newConfig.getClasspathElementsWithModifiedContents(); for (Iterator iterator = modifiedCpElements.iterator(); iterator.hasNext();) { File cpElement = new File((String) iterator.next()); if (cpElement.exists() && !cpElement.isDirectory()) { if (cpElement.lastModified() > lastSuccessfulBuildTime) { return true; } } else { int classFileChanges = classFileChangedInDirSinceLastBuildRequiringFullBuild(cpElement); if (classFileChanges == CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD) { return true; } } } } return false; } /** * Return a list of the output locations - this includes any 'default' output location and then any known by a registered * CompilationResultDestinationManager. * * @param config the build configuration for which the output locations should be determined * @return a list of file objects */ private List /* File */getOutputLocations(AjBuildConfig config) { List outputLocs = new ArrayList(); // Is there a default location? if (config.getOutputDir() != null) { try { outputLocs.add(config.getOutputDir().getCanonicalFile()); } catch (IOException e) { } } if (config.getCompilationResultDestinationManager() != null) { List dirs = config.getCompilationResultDestinationManager().getAllOutputLocations(); for (Iterator iterator = dirs.iterator(); iterator.hasNext();) { File f = (File) iterator.next(); try { File cf = f.getCanonicalFile(); if (!outputLocs.contains(cf)) { outputLocs.add(cf); } } catch (IOException e) { } } } return outputLocs; } /** * Check the old and new paths, if they vary by length or individual elements then that is considered a change. Or if the last * modified time of a path entry has changed (or last modified time of a classfile in that path entry has changed) then return * true. The outputlocations are supplied so they can be 'ignored' in the comparison. * * @param oldPath * @param newPath * @param checkClassFiles whether to examine individual class files within directories * @param outputLocs the output locations that should be ignored if they occur on the paths being compared * @return true if a change is detected that requires a full build */ private boolean changedAndNeedsFullBuild(List oldPath, List newPath, boolean checkClassFiles, List outputLocs, Set alreadyAnalysedPaths) { // if (oldPath == null) { // oldPath = new ArrayList(); // } // if (newPath == null) { // newPath = new ArrayList(); // } if (oldPath.size() != newPath.size()) { return true; } for (int i = 0; i < oldPath.size(); i++) { if (!oldPath.get(i).equals(newPath.get(i))) { return true; } Object o = oldPath.get(i); // String on classpath, File on other paths File f = null; if (o instanceof String) { f = new File((String) o); } else { f = (File) o; } if (f.exists() && !f.isDirectory() && (f.lastModified() >= lastSuccessfulBuildTime)) { return true; } if (checkClassFiles && f.exists() && f.isDirectory()) { // We should use here a list/set of directories we know have or have not changed - some kind of // List<File> buildConfig.getClasspathEntriesWithChangedContents() // and then only proceed to look inside directories if it is one of these, ignoring others - // that should save a massive amount of processing for incremental builds in a multi project scenario boolean foundMatch = false; for (Iterator iterator = outputLocs.iterator(); !foundMatch && iterator.hasNext();) { File dir = (File) iterator.next(); if (f.equals(dir)) { foundMatch = true; } } if (!foundMatch) { if (!alreadyAnalysedPaths.contains(f.getAbsolutePath())) { // Do not check paths more than once alreadyAnalysedPaths.add(f.getAbsolutePath()); int classFileChanges = classFileChangedInDirSinceLastBuildRequiringFullBuild(f); if (classFileChanges == CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD) return true; } } } } return false; } /** * Check the old and new paths, if they vary by length or individual elements then that is considered a change. Or if the last * modified time of a path entry has changed (or last modified time of a classfile in that path entry has changed) then return * true. The outputlocations are supplied so they can be 'ignored' in the comparison. * * @param oldPath * @param newPath * @param checkClassFiles whether to examine individual class files within directories * @param outputLocs the output locations that should be ignored if they occur on the paths being compared * @return true if a change is detected that requires a full build */ private boolean classpathChangedAndNeedsFullBuild(List oldPath, List newPath, boolean checkClassFiles, List outputLocs, Set alreadyAnalysedPaths) { // if (oldPath == null) { // oldPath = new ArrayList(); // } // if (newPath == null) { // newPath = new ArrayList(); // } if (oldPath.size() != newPath.size()) { return true; } for (int i = 0; i < oldPath.size(); i++) { if (!oldPath.get(i).equals(newPath.get(i))) { return true; } File f = new File((String) oldPath.get(i)); if (f.exists() && !f.isDirectory() && (f.lastModified() >= lastSuccessfulBuildTime)) { return true; } if (checkClassFiles && f.exists() && f.isDirectory()) { // We should use here a list/set of directories we know have or have not changed - some kind of // List<File> buildConfig.getClasspathEntriesWithChangedContents() // and then only proceed to look inside directories if it is one of these, ignoring others - // that should save a massive amount of processing for incremental builds in a multi project scenario boolean foundMatch = false; for (Iterator iterator = outputLocs.iterator(); !foundMatch && iterator.hasNext();) { File dir = (File) iterator.next(); if (f.equals(dir)) { foundMatch = true; } } if (!foundMatch) { if (!alreadyAnalysedPaths.contains(f.getAbsolutePath())) { // Do not check paths more than once alreadyAnalysedPaths.add(f.getAbsolutePath()); int classFileChanges = classFileChangedInDirSinceLastBuildRequiringFullBuild(f); if (classFileChanges == CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD) return true; } } } } return false; } public Set getFilesToCompile(boolean firstPass) { Set thisTime = new HashSet(); if (firstPass) { compiledSourceFiles = new HashSet(); Collection modifiedFiles = getModifiedFiles(); // System.out.println("modified: " + modifiedFiles); thisTime.addAll(modifiedFiles); // ??? eclipse IncrementalImageBuilder appears to do this // for (Iterator i = modifiedFiles.iterator(); i.hasNext();) { // File file = (File) i.next(); // addDependentsOf(file); // } if (addedFiles != null) { for (Iterator fIter = addedFiles.iterator(); fIter.hasNext();) { Object o = fIter.next(); if (!thisTime.contains(o)) thisTime.add(o); } // thisTime.addAll(addedFiles); } deleteClassFiles(); // Do not delete resources on incremental build, AJDT will handle // copying updates to the output folder. AspectJ only does a copy // of them on full build (see copyResourcesToDestination() call // in AjBuildManager) // deleteResources(); addAffectedSourceFiles(thisTime, thisTime); } else { addAffectedSourceFiles(thisTime, compiledSourceFiles); } compiledSourceFiles = thisTime; return thisTime; } private boolean maybeIncremental() { return (FORCE_INCREMENTAL_DURING_TESTING || this.couldBeSubsequentIncrementalBuild); } public Map /* String -> List<ucf> */getBinaryFilesToCompile(boolean firstTime) { if (lastSuccessfulBuildTime == -1 || buildConfig == null || !maybeIncremental()) { return binarySourceFiles; } // else incremental... Map toWeave = new HashMap(); if (firstTime) { List addedOrModified = new ArrayList(); addedOrModified.addAll(addedBinaryFiles); addedOrModified.addAll(getModifiedBinaryFiles()); for (Iterator iter = addedOrModified.iterator(); iter.hasNext();) { AjBuildConfig.BinarySourceFile bsf = (AjBuildConfig.BinarySourceFile) iter.next(); UnwovenClassFile ucf = createUnwovenClassFile(bsf); if (ucf == null) continue; List ucfs = new ArrayList(); ucfs.add(ucf); recordTypeChanged(ucf.getClassName()); binarySourceFiles.put(bsf.binSrc.getPath(), ucfs); List cfs = new ArrayList(1); cfs.add(getClassFileFor(ucf)); this.inputClassFilesBySource.put(bsf.binSrc.getPath(), cfs); toWeave.put(bsf.binSrc.getPath(), ucfs); } deleteBinaryClassFiles(); } else { // return empty set... we've already done our bit. } return toWeave; } /** * Called when a path change is about to trigger a full build, but we haven't cleaned up from the last incremental build... */ private void removeAllResultsOfLastBuild() { // remove all binarySourceFiles, and all classesFromName... for (Iterator iter = this.inputClassFilesBySource.values().iterator(); iter.hasNext();) { List cfs = (List) iter.next(); for (Iterator iterator = cfs.iterator(); iterator.hasNext();) { ClassFile cf = (ClassFile) iterator.next(); cf.deleteFromFileSystem(buildConfig); } } for (Iterator iterator = classesFromName.values().iterator(); iterator.hasNext();) { File f = (File) iterator.next(); new ClassFile("", f).deleteFromFileSystem(buildConfig); } for (Iterator iter = resources.iterator(); iter.hasNext();) { String resource = (String) iter.next(); List outputDirs = getOutputLocations(buildConfig); for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) { File dir = (File) iterator.next(); File f = new File(dir, resource); if (f.exists()) { f.delete(); } } } } private void deleteClassFiles() { if (deletedFiles == null) { return; } for (Iterator i = deletedFiles.iterator(); i.hasNext();) { File deletedFile = (File) i.next(); addDependentsOf(deletedFile); List cfs = (List) this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(deletedFile); this.fullyQualifiedTypeNamesResultingFromCompilationUnit.remove(deletedFile); if (cfs != null) { for (Iterator iter = cfs.iterator(); iter.hasNext();) { ClassFile cf = (ClassFile) iter.next(); deleteClassFile(cf); } } } } private void deleteBinaryClassFiles() { // range of bsf is ucfs, domain is files (.class and jars) in inpath/jars for (Iterator iter = deletedBinaryFiles.iterator(); iter.hasNext();) { AjBuildConfig.BinarySourceFile deletedFile = (AjBuildConfig.BinarySourceFile) iter.next(); List cfs = (List) this.inputClassFilesBySource.get(deletedFile.binSrc.getPath()); for (Iterator iterator = cfs.iterator(); iterator.hasNext();) { deleteClassFile((ClassFile) iterator.next()); } this.inputClassFilesBySource.remove(deletedFile.binSrc.getPath()); } } // private void deleteResources() { // List oldResources = new ArrayList(); // oldResources.addAll(resources); // // // note - this deliberately ignores resources in jars as we don't yet handle jar changes // // with incremental compilation // for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext();) { // File inPathElement = (File) i.next(); // if (inPathElement.isDirectory() && AjBuildManager.COPY_INPATH_DIR_RESOURCES) { // deleteResourcesFromDirectory(inPathElement, oldResources); // } // } // // if (buildConfig.getSourcePathResources() != null) { // for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext();) { // String resource = (String) i.next(); // maybeDeleteResource(resource, oldResources); // } // } // // // oldResources need to be deleted... // for (Iterator iter = oldResources.iterator(); iter.hasNext();) { // String victim = (String) iter.next(); // List outputDirs = getOutputLocations(buildConfig); // for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) { // File dir = (File) iterator.next(); // File f = new File(dir, victim); // if (f.exists()) { // f.delete(); // } // resources.remove(victim); // } // } // } // private void maybeDeleteResource(String resName, List oldResources) { // if (resources.contains(resName)) { // oldResources.remove(resName); // List outputDirs = getOutputLocations(buildConfig); // for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) { // File dir = (File) iterator.next(); // File source = new File(dir, resName); // if (source.exists() && (source.lastModified() >= lastSuccessfulBuildTime)) { // resources.remove(resName); // will ensure it is re-copied // } // } // } // } // private void deleteResourcesFromDirectory(File dir, List oldResources) { // File[] files = FileUtil.listFiles(dir, new FileFilter() { // public boolean accept(File f) { // boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")); // return accept; // } // }); // // // For each file, add it either as a real .class file or as a resource // for (int i = 0; i < files.length; i++) { // // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // // or we are in trouble... // String filename = null; // try { // filename = files[i].getCanonicalPath().substring(dir.getCanonicalPath().length() + 1); // } catch (IOException e) { // // we are in trouble if this happens... // IMessage msg = new Message("call to getCanonicalPath() failed for file " + files[i] + " with: " + e.getMessage(), // new SourceLocation(files[i], 0), false); // buildManager.handler.handleMessage(msg); // filename = files[i].getAbsolutePath().substring(dir.getAbsolutePath().length() + 1); // } // // maybeDeleteResource(filename, oldResources); // } // } private void deleteClassFile(ClassFile cf) { classesFromName.remove(cf.fullyQualifiedTypeName); weaver.deleteClassFile(cf.fullyQualifiedTypeName); cf.deleteFromFileSystem(buildConfig); } private UnwovenClassFile createUnwovenClassFile(AjBuildConfig.BinarySourceFile bsf) { UnwovenClassFile ucf = null; try { File outputDir = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { // createUnwovenClassFile is called only for classes that are on the inpath, // all inpath classes are put in the defaultOutputLocation, therefore, // this is the output dir outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation(); } ucf = weaver.addClassFile(bsf.binSrc, bsf.fromInPathDirectory, outputDir); } catch (IOException ex) { IMessage msg = new Message("can't read class file " + bsf.binSrc.getPath(), new SourceLocation(bsf.binSrc, 0), false); buildManager.handler.handleMessage(msg); } return ucf; } public void noteResult(InterimCompilationResult result) { if (!maybeIncremental()) { return; } File sourceFile = new File(result.fileName()); CompilationResult cr = result.result(); references.put(sourceFile, new ReferenceCollection(cr.qualifiedReferences, cr.simpleNameReferences)); UnwovenClassFile[] unwovenClassFiles = result.unwovenClassFiles(); for (int i = 0; i < unwovenClassFiles.length; i++) { File lastTimeRound = (File) classesFromName.get(unwovenClassFiles[i].getClassName()); recordClassFile(unwovenClassFiles[i], lastTimeRound); classesFromName.put(unwovenClassFiles[i].getClassName(), new File(unwovenClassFiles[i].getFilename())); } // need to do this before types are deleted from the World... recordWhetherCompilationUnitDefinedAspect(sourceFile, cr); deleteTypesThatWereInThisCompilationUnitLastTimeRoundButHaveBeenDeletedInThisIncrement(sourceFile, unwovenClassFiles); recordFQNsResultingFromCompilationUnit(sourceFile, result); } public void noteNewResult(CompilationResult cr) { // if (!maybeIncremental()) { // return; // } // // // File sourceFile = new File(result.fileName()); // // CompilationResult cr = result.result(); // if (new String(cr.getFileName()).indexOf("C") != -1) { // cr.references.put(new String(cr.getFileName()), // new ReferenceCollection(cr.qualifiedReferences, cr.simpleNameReferences)); // int stop = 1; // } // references.put(sourceFile, new ReferenceCollection(cr.qualifiedReferences, cr.simpleNameReferences)); // // UnwovenClassFile[] unwovenClassFiles = cr.unwovenClassFiles(); // for (int i = 0; i < unwovenClassFiles.length; i++) { // File lastTimeRound = (File) classesFromName.get(unwovenClassFiles[i].getClassName()); // recordClassFile(unwovenClassFiles[i], lastTimeRound); // classesFromName.put(unwovenClassFiles[i].getClassName(), new File(unwovenClassFiles[i].getFilename())); // } // need to do this before types are deleted from the World... // recordWhetherCompilationUnitDefinedAspect(sourceFile, cr); // deleteTypesThatWereInThisCompilationUnitLastTimeRoundButHaveBeenDeletedInThisIncrement(sourceFile, unwovenClassFiles); // // recordFQNsResultingFromCompilationUnit(sourceFile, result); } /** * @param sourceFile * @param unwovenClassFiles */ private void deleteTypesThatWereInThisCompilationUnitLastTimeRoundButHaveBeenDeletedInThisIncrement(File sourceFile, UnwovenClassFile[] unwovenClassFiles) { List classFiles = (List) this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(sourceFile); if (classFiles != null) { for (int i = 0; i < unwovenClassFiles.length; i++) { // deleting also deletes types from the weaver... don't do this if they are // still present this time around... removeFromClassFilesIfPresent(unwovenClassFiles[i].getClassName(), classFiles); } for (Iterator iter = classFiles.iterator(); iter.hasNext();) { ClassFile cf = (ClassFile) iter.next(); deleteClassFile(cf); } } } private void removeFromClassFilesIfPresent(String className, List classFiles) { ClassFile victim = null; for (Iterator iter = classFiles.iterator(); iter.hasNext();) { ClassFile cf = (ClassFile) iter.next(); if (cf.fullyQualifiedTypeName.equals(className)) { victim = cf; break; } } if (victim != null) { classFiles.remove(victim); } } /** * Record the fully-qualified names of the types that were declared in the given source file. * * @param sourceFile, the compilation unit * @param icr, the CompilationResult from compiling it */ private void recordFQNsResultingFromCompilationUnit(File sourceFile, InterimCompilationResult icr) { List classFiles = new ArrayList(); UnwovenClassFile[] types = icr.unwovenClassFiles(); for (int i = 0; i < types.length; i++) { classFiles.add(new ClassFile(types[i].getClassName(), new File(types[i].getFilename()))); } this.fullyQualifiedTypeNamesResultingFromCompilationUnit.put(sourceFile, classFiles); } /** * If this compilation unit defined an aspect, we need to know in case it is modified in a future increment. * * @param sourceFile * @param cr */ private void recordWhetherCompilationUnitDefinedAspect(File sourceFile, CompilationResult cr) { this.sourceFilesDefiningAspects.remove(sourceFile); if (cr != null) { Map compiledTypes = cr.compiledTypes; if (compiledTypes != null) { for (Iterator iterator = compiledTypes.keySet().iterator(); iterator.hasNext();) { char[] className = (char[]) iterator.next(); String typeName = new String(className).replace('/', '.'); if (typeName.indexOf(BcelWeaver.SYNTHETIC_CLASS_POSTFIX) == -1) { ResolvedType rt = world.resolve(typeName); if (rt.isMissing()) { // This can happen in a case where another problem has occurred that prevented it being // correctly added to the world. Eg. pr148285. Duplicate types // throw new IllegalStateException("Type '" + rt.getSignature() + "' not found in world!"); } else if (rt.isAspect()) { this.sourceFilesDefiningAspects.add(sourceFile); break; } } } } } } // private UnwovenClassFile removeFromPreviousIfPresent(UnwovenClassFile cf, InterimCompilationResult previous) { // if (previous == null) // return null; // UnwovenClassFile[] unwovenClassFiles = previous.unwovenClassFiles(); // for (int i = 0; i < unwovenClassFiles.length; i++) { // UnwovenClassFile candidate = unwovenClassFiles[i]; // if ((candidate != null) && candidate.getFilename().equals(cf.getFilename())) { // unwovenClassFiles[i] = null; // return candidate; // } // } // return null; // } private void recordClassFile(UnwovenClassFile thisTime, File lastTime) { if (simpleStrings == null) { // batch build // record resolved type for structural comparisions in future increments // this records a second reference to a structure already held in memory // by the world. ResolvedType rType = world.resolve(thisTime.getClassName()); if (!rType.isMissing()) { try { ClassFileReader reader = new ClassFileReader(thisTime.getBytes(), null); this.resolvedTypeStructuresFromLastBuild.put(thisTime.getClassName(), new CompactTypeStructureRepresentation( reader)); } catch (ClassFormatException cfe) { throw new BCException("Unexpected problem processing class", cfe); } } return; } CompactTypeStructureRepresentation existingStructure = (CompactTypeStructureRepresentation) this.resolvedTypeStructuresFromLastBuild .get(thisTime.getClassName()); ResolvedType newResolvedType = world.resolve(thisTime.getClassName()); if (!newResolvedType.isMissing()) { try { ClassFileReader reader = new ClassFileReader(thisTime.getBytes(), null); this.resolvedTypeStructuresFromLastBuild.put(thisTime.getClassName(), new CompactTypeStructureRepresentation(reader)); } catch (ClassFormatException cfe) { throw new BCException("Unexpected problem processing class", cfe); } } if (lastTime == null) { recordTypeChanged(thisTime.getClassName()); return; } if (newResolvedType.isMissing()) { return; } world.ensureAdvancedConfigurationProcessed(); byte[] newBytes = thisTime.getBytes(); try { ClassFileReader reader = new ClassFileReader(newBytes, lastTime.getAbsolutePath().toCharArray()); // ignore local types since they're only visible inside a single method if (!(reader.isLocal() || reader.isAnonymous())) { if (hasStructuralChanges(reader, existingStructure)) { if (world.forDEBUG_structuralChangesCode) System.err.println("Detected a structural change in " + thisTime.getFilename()); structuralChangesSinceLastFullBuild.put(thisTime.getFilename(), new Long(currentBuildTime)); recordTypeChanged(new String(reader.getName()).replace('/', '.')); } } } catch (ClassFormatException e) { recordTypeChanged(thisTime.getClassName()); } } private static final char[][] EMPTY_CHAR_ARRAY = new char[0][]; /** * Compare the class structure of the new intermediate (unwoven) class with the existingResolvedType of the same class that we * have in the world, looking for any structural differences (and ignoring aj members resulting from weaving....) * * Some notes from Andy... lot of problems here, which I've eventually resolved by building the compactstructure based on a * classfilereader, rather than on a ResolvedType. There are accessors for inner types and funky fields that the compiler * creates to support the language - for non-static inner types it also mangles ctors to be prefixed with an instance of the * surrounding type. * * Warning : long but boring method implementation... * * @param reader * @param existingType * @return */ private boolean hasStructuralChanges(ClassFileReader reader, CompactTypeStructureRepresentation existingType) { if (existingType == null) { return true; } // modifiers if (!modifiersEqual(reader.getModifiers(), existingType.modifiers)) { return true; } // generic signature if (!CharOperation.equals(reader.getGenericSignature(), existingType.genericSignature)) { return true; } // superclass name if (!CharOperation.equals(reader.getSuperclassName(), existingType.superclassName)) { return true; } // have annotations changed on the type? IBinaryAnnotation[] newAnnos = reader.getAnnotations(); if (newAnnos == null || newAnnos.length == 0) { if (existingType.annotations != null && existingType.annotations.length != 0) { return true; } } else { IBinaryAnnotation[] existingAnnos = existingType.annotations; if (existingAnnos == null || existingAnnos.length != newAnnos.length) { return true; } // Does not allow for an order switch // Does not cope with a change in values set on the annotation (hard to create a testcase where this is a problem tho) for (int i = 0; i < newAnnos.length; i++) { if (!CharOperation.equals(newAnnos[i].getTypeName(), existingAnnos[i].getTypeName())) { return true; } } } // interfaces char[][] existingIfs = existingType.interfaces; char[][] newIfsAsChars = reader.getInterfaceNames(); if (newIfsAsChars == null) { newIfsAsChars = EMPTY_CHAR_ARRAY; } // damn I'm lazy... if (existingIfs == null) { existingIfs = EMPTY_CHAR_ARRAY; } if (existingIfs.length != newIfsAsChars.length) return true; new_interface_loop: for (int i = 0; i < newIfsAsChars.length; i++) { for (int j = 0; j < existingIfs.length; j++) { if (CharOperation.equals(existingIfs[j], newIfsAsChars[i])) { continue new_interface_loop; } } return true; } // fields // CompactMemberStructureRepresentation[] existingFields = existingType.fields; IBinaryField[] newFields = reader.getFields(); if (newFields == null) { newFields = CompactTypeStructureRepresentation.NoField; } // all redundant for now ... could be an optimization at some point... // remove any ajc$XXX fields from those we compare with // the existing fields - bug 129163 // List nonGenFields = new ArrayList(); // for (int i = 0; i < newFields.length; i++) { // IBinaryField field = newFields[i]; // //if (!CharOperation.prefixEquals(NameMangler.AJC_DOLLAR_PREFIX,field.getName())) { // this would skip ajc$ fields // //if ((field.getModifiers()&0x1000)==0) // 0x1000 => synthetic - this will skip synthetic fields (eg. this$0) // nonGenFields.add(field); // //} // } IBinaryField[] existingFs = existingType.binFields; if (newFields.length != existingFs.length) return true; new_field_loop: for (int i = 0; i < newFields.length; i++) { IBinaryField field = newFields[i]; char[] fieldName = field.getName(); for (int j = 0; j < existingFs.length; j++) { if (CharOperation.equals(existingFs[j].getName(), fieldName)) { if (!modifiersEqual(field.getModifiers(), existingFs[j].getModifiers())) { return true; } if (!CharOperation.equals(existingFs[j].getTypeName(), field.getTypeName())) { return true; } continue new_field_loop; } } return true; } // methods // CompactMemberStructureRepresentation[] existingMethods = existingType.methods; IBinaryMethod[] newMethods = reader.getMethods(); if (newMethods == null) { newMethods = CompactTypeStructureRepresentation.NoMethod; } // all redundant for now ... could be an optimization at some point... // Ctors in a non-static inner type have an 'extra parameter' of the enclosing type. // If skippableDescriptorPrefix gets set here then it is set to the descriptor portion // for this 'extra parameter'. For an inner class of pkg.Foo the skippable descriptor // prefix will be '(Lpkg/Foo;' - so later when comparing <init> methods we know what to // compare. // IF THIS CODE NEEDS TO GET MORE COMPLICATED, I THINK ITS WORTH RIPPING IT ALL OUT AND // CREATING THE STRUCTURAL CHANGES OBJECT BASED ON CLASSREADER OUTPUT RATHER THAN // THE RESOLVEDTYPE - THEN THERE WOULD BE NO NEED TO TREAT SOME METHODS IN A PECULIAR // WAY. // char[] skippableDescriptorPrefix = null; // char[] enclosingTypeName = reader.getEnclosingTypeName(); // boolean isStaticType = Modifier.isStatic(reader.getModifiers()); // if (!isStaticType && enclosingTypeName!=null) { // StringBuffer sb = new StringBuffer(); // sb.append("(L").append(new String(enclosingTypeName)).append(";"); // skippableDescriptorPrefix = sb.toString().toCharArray(); // } // // // // remove the aspectOf, hasAspect, clinit and ajc$XXX methods // // from those we compare with the existing methods - bug 129163 // List nonGenMethods = new ArrayList(); // for (int i = 0; i < newMethods.length; i++) { // IBinaryMethod method = newMethods[i]; // // if ((method.getModifiers() & 0x1000)!=0) continue; // 0x1000 => synthetic - will cause us to skip access$0 - is this // always safe? // char[] methodName = method.getSelector(); // // if (!CharOperation.equals(methodName,NameMangler.METHOD_ASPECTOF) && // // !CharOperation.equals(methodName,NameMangler.METHOD_HASASPECT) && // // !CharOperation.equals(methodName,NameMangler.STATIC_INITIALIZER) && // // !CharOperation.prefixEquals(NameMangler.AJC_DOLLAR_PREFIX,methodName) && // // !CharOperation.prefixEquals(NameMangler.CLINIT,methodName)) { // nonGenMethods.add(method); // // } // } IBinaryMethod[] existingMs = existingType.binMethods; if (newMethods.length != existingMs.length) return true; new_method_loop: for (int i = 0; i < newMethods.length; i++) { IBinaryMethod method = newMethods[i]; char[] methodName = method.getSelector(); for (int j = 0; j < existingMs.length; j++) { if (CharOperation.equals(existingMs[j].getSelector(), methodName)) { // candidate match if (!CharOperation.equals(method.getMethodDescriptor(), existingMs[j].getMethodDescriptor())) { // ok, the descriptors don't match, but is this a funky ctor on a non-static inner // type? // boolean mightBeOK = // skippableDescriptorPrefix!=null && // set for inner types // CharOperation.equals(methodName,NameMangler.INIT) && // ctor // CharOperation.prefixEquals(skippableDescriptorPrefix,method.getMethodDescriptor()); // checking for // prefix on the descriptor // if (mightBeOK) { // // OK, so the descriptor starts something like '(Lpkg/Foo;' - we now may need to look at the rest of the // // descriptor if it takes >1 parameter. // // eg. could be (Lpkg/C;Ljava/lang/String;) where the skippablePrefix is (Lpkg/C; // char [] md = method.getMethodDescriptor(); // char[] remainder = CharOperation.subarray(md, skippableDescriptorPrefix.length, md.length); // if (CharOperation.equals(remainder,BRACKET_V)) continue new_method_loop; // no other parameters to worry // about // char[] comparableSig = CharOperation.subarray(existingMethods[j].signature, 1, // existingMethods[j].signature.length); // boolean match = CharOperation.equals(comparableSig, remainder); // if (match) continue new_method_loop; // } continue; // might be overloading } else { // matching sigs if (!modifiersEqual(method.getModifiers(), existingMs[j].getModifiers())) { return true; } continue new_method_loop; } } } return true; // (no match found) } return false; } private boolean modifiersEqual(int eclipseModifiers, int resolvedTypeModifiers) { resolvedTypeModifiers = resolvedTypeModifiers & ExtraCompilerModifiers.AccJustFlag; eclipseModifiers = eclipseModifiers & ExtraCompilerModifiers.AccJustFlag; // if ((eclipseModifiers & CompilerModifiers.AccSuper) != 0) { // eclipseModifiers -= CompilerModifiers.AccSuper; // } return (eclipseModifiers == resolvedTypeModifiers); } // private static StringSet makeStringSet(List strings) { // StringSet ret = new StringSet(strings.size()); // for (Iterator iter = strings.iterator(); iter.hasNext();) { // String element = (String) iter.next(); // ret.add(element); // } // return ret; // } private String stringifyList(Set l) { StringBuffer sb = new StringBuffer(); sb.append("{"); for (Iterator iter = l.iterator(); iter.hasNext();) { Object el = iter.next(); sb.append(el); if (iter.hasNext()) sb.append(","); } sb.append("}"); return sb.toString(); } protected void addAffectedSourceFiles(Set addTo, Set lastTimeSources) { if (qualifiedStrings.elementSize == 0 && simpleStrings.elementSize == 0) return; if (listenerDefined()) getListener().recordDecision( "Examining whether any other files now need compilation based on just compiling: '" + stringifyList(lastTimeSources) + "'"); // the qualifiedStrings are of the form 'p1/p2' & the simpleStrings are just 'X' char[][][] qualifiedNames = ReferenceCollection.internQualifiedNames(qualifiedStrings); // if a well known qualified name was found then we can skip over these if (qualifiedNames.length < qualifiedStrings.elementSize) qualifiedNames = null; char[][] simpleNames = ReferenceCollection.internSimpleNames(simpleStrings); // if a well known name was found then we can skip over these if (simpleNames.length < simpleStrings.elementSize) simpleNames = null; // System.err.println("simple: " + simpleStrings); // System.err.println("qualif: " + qualifiedStrings); for (Iterator i = references.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); ReferenceCollection refs = (ReferenceCollection) entry.getValue(); if (refs != null && refs.includes(qualifiedNames, simpleNames)) { File file = (File) entry.getKey(); if (file.exists()) { if (!lastTimeSources.contains(file)) { // ??? O(n**2) if (listenerDefined()) { getListener().recordDecision("Need to recompile '" + file.getName().toString() + "'"); } addTo.add(file); } } } } // add in the things we compiled previously - I know that seems crap but otherwise we may pull woven // stuff off disk (since we no longer have UnwovenClassFile objects) in order to satisfy references // in the new files we are about to compile (see pr133532) if (addTo.size() > 0) addTo.addAll(lastTimeSources); // // XXX Promote addTo to a Set - then we don't need this rubbish? but does it need to be ordered? // if (addTo.size()>0) { // for (Iterator iter = lastTimeSources.iterator(); iter.hasNext();) { // Object element = (Object) iter.next(); // if (!addTo.contains(element)) addTo.add(element); // } // } qualifiedStrings.clear(); simpleStrings.clear(); } /** * Record that a particular type has been touched during a compilation run. Information is used to ensure any types depending * upon this one are also recompiled. * * @param typename (possibly qualified) type name */ protected void recordTypeChanged(String typename) { int lastDot = typename.lastIndexOf('.'); String typeName; if (lastDot != -1) { String packageName = typename.substring(0, lastDot).replace('.', '/'); qualifiedStrings.add(packageName); typeName = typename.substring(lastDot + 1); } else { qualifiedStrings.add(""); typeName = typename; } int memberIndex = typeName.indexOf('$'); if (memberIndex > 0) typeName = typeName.substring(0, memberIndex); simpleStrings.add(typeName); } protected void addDependentsOf(File sourceFile) { List cfs = (List) this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(sourceFile); if (cfs != null) { for (Iterator iter = cfs.iterator(); iter.hasNext();) { ClassFile cf = (ClassFile) iter.next(); recordTypeChanged(cf.fullyQualifiedTypeName); } } } public void setStructureModel(AsmManager structureModel) { this.structureModel = structureModel; } public AsmManager getStructureModel() { return structureModel; } public void setWeaver(BcelWeaver bw) { weaver = bw; } public BcelWeaver getWeaver() { return weaver; } public void setWorld(BcelWorld bw) { world = bw; } public BcelWorld getBcelWorld() { return world; } // // public void setRelationshipMap(IRelationshipMap irm) { // relmap = irm; // } // // public IRelationshipMap getRelationshipMap() { // return relmap; // } public int getNumberOfStructuralChangesSinceLastFullBuild() { return structuralChangesSinceLastFullBuild.size(); } /** Returns last time we did a full or incremental build. */ public long getLastBuildTime() { return lastSuccessfulBuildTime; } /** Returns last time we did a full build */ public long getLastFullBuildTime() { return lastSuccessfulFullBuildTime; } /** * @return Returns the buildConfig. */ public AjBuildConfig getBuildConfig() { return this.buildConfig; } public void clearBinarySourceFiles() { this.binarySourceFiles = new HashMap(); } public void recordBinarySource(String fromPathName, List unwovenClassFiles) { this.binarySourceFiles.put(fromPathName, unwovenClassFiles); if (this.maybeIncremental()) { List simpleClassFiles = new LinkedList(); for (Iterator iter = unwovenClassFiles.iterator(); iter.hasNext();) { UnwovenClassFile ucf = (UnwovenClassFile) iter.next(); ClassFile cf = getClassFileFor(ucf); simpleClassFiles.add(cf); } this.inputClassFilesBySource.put(fromPathName, simpleClassFiles); } } /** * @param ucf * @return */ private ClassFile getClassFileFor(UnwovenClassFile ucf) { return new ClassFile(ucf.getClassName(), new File(ucf.getFilename())); } public Map getBinarySourceMap() { return this.binarySourceFiles; } public Map getClassNameToFileMap() { return this.classesFromName; } public boolean hasResource(String resourceName) { return this.resources.contains(resourceName); } public void recordResource(String resourceName) { this.resources.add(resourceName); } /** * @return Returns the addedFiles. */ public Set getAddedFiles() { return this.addedFiles; } /** * @return Returns the deletedFiles. */ public Set getDeletedFiles() { return this.deletedFiles; } public void forceBatchBuildNextTimeAround() { this.batchBuildRequiredThisTime = true; } public boolean requiresFullBatchBuild() { return this.batchBuildRequiredThisTime; } private static class ClassFile { public String fullyQualifiedTypeName; public File locationOnDisk; public ClassFile(String fqn, File location) { this.fullyQualifiedTypeName = fqn; this.locationOnDisk = location; } public void deleteFromFileSystem(AjBuildConfig buildConfig) { String namePrefix = locationOnDisk.getName(); namePrefix = namePrefix.substring(0, namePrefix.lastIndexOf('.')); final String targetPrefix = namePrefix + BcelWeaver.CLOSURE_CLASS_PREFIX; File dir = locationOnDisk.getParentFile(); if (dir != null) { File[] weaverGenerated = dir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith(targetPrefix); } }); if (weaverGenerated != null) { for (int i = 0; i < weaverGenerated.length; i++) { weaverGenerated[i].delete(); if (buildConfig != null && buildConfig.getCompilationResultDestinationManager() != null) { buildConfig.getCompilationResultDestinationManager() .reportClassFileRemove(weaverGenerated[i].getPath()); } } } } locationOnDisk.delete(); if (buildConfig != null && buildConfig.getCompilationResultDestinationManager() != null) { buildConfig.getCompilationResultDestinationManager().reportClassFileRemove(locationOnDisk.getPath()); } } } public void wipeAllKnowledge() { buildManager.state = null; // buildManager.setStructureModel(null); } public Map getAspectNamesToFileNameMap() { return aspectsFromFileNames; } public void initializeAspectNamesToFileNameMap() { this.aspectsFromFileNames = new HashMap(); } // Will allow us to record decisions made during incremental processing, hopefully aid in debugging public boolean listenerDefined() { return stateListener != null; } public IStateListener getListener() { return stateListener; } public IBinaryType checkPreviousBuild(String name) { return (IBinaryType) resolvedTypeStructuresFromLastBuild.get(name); } public AjBuildManager getAjBuildManager() { return buildManager; } public INameEnvironment getNameEnvironment() { return this.nameEnvironment; } public void setNameEnvironment(INameEnvironment nameEnvironment) { this.nameEnvironment = nameEnvironment; } /** * Record an aspect that came in on the aspect path. When a .class file changes on the aspect path we can then recognize it as * an aspect and know to do more than just a tiny incremental build. <br> * TODO but this doesn't allow for a new aspect created on the aspectpath? * * @param aspectFile path to the file, eg. c:/temp/foo/Fred.class */ public void recordAspectClassFile(String aspectFile) { aspectClassFiles.add(aspectFile); } }
269,840
Bug 269840 [model] package search fails in binary aspect in same package as a source type
If type a.b.c.C is advised by an aspect a.b.c.X from the aspectpath the model search logic breaks for finding 'X' because it hits the package node for a.b.c and stops looking
resolved fixed
7a7d6f0
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-03-24T16:43:38Z"
"2009-03-24T15:53:20Z"
asm/src/org/aspectj/asm/internal/AspectJElementHierarchy.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Mik Kersten initial implementation * Andy Clement Extensions for better IDE representation * ******************************************************************/ package org.aspectj.asm.internal; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; /** * @author Mik Kersten */ public class AspectJElementHierarchy implements IHierarchy { private static final long serialVersionUID = 6462734311117048620L; private transient AsmManager asm; protected IProgramElement root = null; protected String configFile = null; private Map fileMap = null; private Map handleMap = new HashMap(); private Map typeMap = null; public AspectJElementHierarchy(AsmManager asm) { this.asm = asm; } public IProgramElement getElement(String handle) { return findElementForHandleOrCreate(handle, false); } public void setAsmManager(AsmManager asm) { // used when deserializing this.asm = asm; } public IProgramElement getRoot() { return root; } public void setRoot(IProgramElement root) { this.root = root; handleMap = new HashMap(); typeMap = new HashMap(); } public void addToFileMap(Object key, Object value) { fileMap.put(key, value); } public boolean removeFromFileMap(Object key) { if (fileMap.containsKey(key)) { return (fileMap.remove(key) != null); } return true; } public void setFileMap(HashMap fileMap) { this.fileMap = fileMap; } public Object findInFileMap(Object key) { return fileMap.get(key); } public Set getFileMapEntrySet() { return fileMap.entrySet(); } public boolean isValid() { return root != null && fileMap != null; } /** * Returns the first match * * @param parent * @param kind not null * @return null if not found */ public IProgramElement findElementForSignature(IProgramElement parent, IProgramElement.Kind kind, String signature) { for (Iterator it = parent.getChildren().iterator(); it.hasNext();) { IProgramElement node = (IProgramElement) it.next(); if (node.getKind() == kind && signature.equals(node.toSignatureString())) { return node; } else { IProgramElement childSearch = findElementForSignature(node, kind, signature); if (childSearch != null) return childSearch; } } return null; } public IProgramElement findElementForLabel(IProgramElement parent, IProgramElement.Kind kind, String label) { for (Iterator it = parent.getChildren().iterator(); it.hasNext();) { IProgramElement node = (IProgramElement) it.next(); if (node.getKind() == kind && label.equals(node.toLabelString())) { return node; } else { IProgramElement childSearch = findElementForLabel(node, kind, label); if (childSearch != null) return childSearch; } } return null; } /** * Find the entry in the model that represents a particular type. * * @param packageName the package in which the type is declared or null for the default package * @param typeName the name of the type * @return the IProgramElement representing the type, or null if not found */ public IProgramElement findElementForType(String packageName, String typeName) { // Build a cache key and check the cache StringBuffer keyb = (packageName == null) ? new StringBuffer() : new StringBuffer(packageName); keyb.append(".").append(typeName); String key = keyb.toString(); IProgramElement cachedValue = (IProgramElement) typeMap.get(key); if (cachedValue != null) { return cachedValue; } List packageNodes = findMatchingPackages(packageName); for (Iterator iterator = packageNodes.iterator(); iterator.hasNext();) { IProgramElement pkg = (IProgramElement) iterator.next(); // this searches each file for a class for (Iterator it = pkg.getChildren().iterator(); it.hasNext();) { IProgramElement fileNode = (IProgramElement) it.next(); IProgramElement cNode = findClassInNodes(fileNode.getChildren(), typeName, typeName); if (cNode != null) { typeMap.put(key, cNode); return cNode; } } } return null; // IProgramElement packageNode = null; // if (packageName == null) { // packageNode = root; // } else { // if (root == null) // return null; // List kids = root.getChildren(); // if (kids == null) { // return null; // } // for (Iterator it = kids.iterator(); it.hasNext() && packageNode == null;) { // IProgramElement node = (IProgramElement) it.next(); // if (packageName.equals(node.getName())) { // packageNode = node; // } // } // if (packageNode == null) { // return null; // } // } // // this searches each file for a class // for (Iterator it = packageNode.getChildren().iterator(); it.hasNext();) { // IProgramElement fileNode = (IProgramElement) it.next(); // IProgramElement cNode = findClassInNodes(fileNode.getChildren(), typeName, typeName); // if (cNode != null) { // typeMap.put(key, cNode); // return cNode; // } // } // return null; } /** * Look for any package nodes matching the specified package name. There may be multiple in the case where the types within a * package are split across source folders. * * @param packagename the packagename being searched for * @return a list of package nodes that match that name */ public List/* IProgramElement */findMatchingPackages(String packagename) { List children = root.getChildren(); // The children might be source folders or packages if (children.size() == 0) { return Collections.EMPTY_LIST; } if (((IProgramElement) children.get(0)).getKind() == IProgramElement.Kind.SOURCE_FOLDER) { // dealing with source folders List matchingPackageNodes = new ArrayList(); for (Iterator iterator = children.iterator(); iterator.hasNext();) { IProgramElement sourceFolder = (IProgramElement) iterator.next(); List possiblePackageNodes = sourceFolder.getChildren(); for (Iterator iterator2 = possiblePackageNodes.iterator(); iterator2.hasNext();) { IProgramElement possiblePackageNode = (IProgramElement) iterator2.next(); if (possiblePackageNode.getKind() == IProgramElement.Kind.PACKAGE) { if (possiblePackageNode.getName().equals(packagename)) { matchingPackageNodes.add(possiblePackageNode); } } } } // 'binaries' will be checked automatically by the code above as it is represented as a SOURCE_FOLDER return matchingPackageNodes; } else { // dealing directly with packages below the root, no source folders. Therefore at most one // thing to return in the list if (packagename == null) { // default package List result = new ArrayList(); result.add(root); return result; } for (Iterator iterator = children.iterator(); iterator.hasNext();) { IProgramElement possiblePackage = (IProgramElement) iterator.next(); if (possiblePackage.getKind() == IProgramElement.Kind.PACKAGE) { if (possiblePackage.getName().equals(packagename)) { List result = new ArrayList(); result.add(possiblePackage); return result; } } if (possiblePackage.getKind() == IProgramElement.Kind.SOURCE_FOLDER) { // might be 'binaries' if (possiblePackage.getName().equals("binaries")) { for (Iterator iter2 = possiblePackage.getChildren().iterator(); iter2.hasNext();) { IProgramElement possiblePackage2 = (IProgramElement) iter2.next(); if (possiblePackage2.getKind() == IProgramElement.Kind.PACKAGE) { if (possiblePackage2.getName().equals(packagename)) { List result = new ArrayList(); result.add(possiblePackage2); return result; } } } } } } } return Collections.EMPTY_LIST; } private IProgramElement findClassInNodes(Collection nodes, String name, String typeName) { String baseName; String innerName; int dollar = name.indexOf('$'); if (dollar == -1) { baseName = name; innerName = null; } else { baseName = name.substring(0, dollar); innerName = name.substring(dollar + 1); } for (Iterator j = nodes.iterator(); j.hasNext();) { IProgramElement classNode = (IProgramElement) j.next(); if (baseName.equals(classNode.getName())) { if (innerName == null) return classNode; else return findClassInNodes(classNode.getChildren(), innerName, typeName); } else if (name.equals(classNode.getName())) { return classNode; } else if (typeName.equals(classNode.getBytecodeSignature())) { return classNode; } else if (classNode.getChildren() != null && !classNode.getChildren().isEmpty()) { IProgramElement node = findClassInNodes(classNode.getChildren(), name, typeName); if (node != null) { return node; } } } return null; } /** * @param sourceFilePath modified to '/' delimited path for consistency * @return a new structure node for the file if it was not found in the model */ public IProgramElement findElementForSourceFile(String sourceFile) { try { if (!isValid() || sourceFile == null) { return IHierarchy.NO_STRUCTURE; } else { String correctedPath = asm.getCanonicalFilePath(new File(sourceFile)); // StructureNode node = (StructureNode)getFileMap().get(correctedPath);//findFileNode(filePath, model); IProgramElement node = (IProgramElement) findInFileMap(correctedPath);// findFileNode(filePath, model); if (node != null) { return node; } else { return createFileStructureNode(correctedPath); } } } catch (Exception e) { return IHierarchy.NO_STRUCTURE; } } /** * TODO: discriminate columns */ public IProgramElement findElementForSourceLine(ISourceLocation location) { try { return findElementForSourceLine(asm.getCanonicalFilePath(location.getSourceFile()), location.getLine()); } catch (Exception e) { return null; } } /** * Never returns null * * @param sourceFilePath canonicalized path for consistency * @param lineNumber if 0 or 1 the corresponding file node will be returned * @return a new structure node for the file if it was not found in the model */ public IProgramElement findElementForSourceLine(String sourceFilePath, int lineNumber) { String canonicalSFP = asm.getCanonicalFilePath(new File(sourceFilePath)); // Used to do this: // IProgramElement node2 = findNodeForSourceLineHelper(root, canonicalSFP, lineNumber, -1); // Find the relevant source file node first IProgramElement node = findNodeForSourceFile(root, canonicalSFP); if (node == null) { return createFileStructureNode(sourceFilePath); } // Check if there is a more accurate child node of that source file node: IProgramElement closernode = findCloserMatchForLineNumber(node, lineNumber); if (closernode == null) { return node; } else { return closernode; } } /** * Discover the node representing a particular source file. * * @param node where in the model to start looking (usually the root on the initial call) * @param sourcefilePath the source file being searched for * @return the node representing that source file or null if it cannot be found */ private IProgramElement findNodeForSourceFile(IProgramElement node, String sourcefilePath) { // 1. why is <root> a sourcefile node? // 2. should isSourceFile() return true for a FILE that is a .class file...? if ((node.getKind().isSourceFile() && !node.getName().equals("<root>")) || node.getKind().isFile()) { ISourceLocation nodeLoc = node.getSourceLocation(); if (nodeLoc != null && nodeLoc.getSourceFile().getAbsolutePath().equals(sourcefilePath)) { return node; } return null; // no need to search children of a source file node } else { // check the children for (Iterator iterator = node.getChildren().iterator(); iterator.hasNext();) { IProgramElement foundit = findNodeForSourceFile((IProgramElement) iterator.next(), sourcefilePath); if (foundit != null) { return foundit; } } return null; } } public IProgramElement findElementForOffSet(String sourceFilePath, int lineNumber, int offSet) { String canonicalSFP = asm.getCanonicalFilePath(new File(sourceFilePath)); IProgramElement node = findNodeForSourceLineHelper(root, canonicalSFP, lineNumber, offSet); if (node != null) { return node; } else { return createFileStructureNode(sourceFilePath); } } private IProgramElement createFileStructureNode(String sourceFilePath) { // SourceFilePath might have originated on windows on linux... int lastSlash = sourceFilePath.lastIndexOf('\\'); if (lastSlash == -1) { lastSlash = sourceFilePath.lastIndexOf('/'); } // '!' is used like in URLs "c:/blahblah/X.jar!a/b.class" int i = sourceFilePath.lastIndexOf('!'); int j = sourceFilePath.indexOf(".class"); if (i > lastSlash && i != -1 && j != -1) { // we are a binary aspect in the default package lastSlash = i; } String fileName = sourceFilePath.substring(lastSlash + 1); IProgramElement fileNode = new ProgramElement(asm, fileName, IProgramElement.Kind.FILE_JAVA, new SourceLocation(new File( sourceFilePath), 1, 1), 0, null, null); // fileNode.setSourceLocation(); fileNode.addChild(NO_STRUCTURE); return fileNode; } /** * For a specified node, check if any of the children more accurately represent the specified line. * * @param node where to start looking * @param lineno the line number * @return any closer match below 'node' or null if nothing is a more accurate match */ public IProgramElement findCloserMatchForLineNumber(IProgramElement node, int lineno) { if (node == null || node.getChildren() == null) { return null; } for (Iterator childrenIter = node.getChildren().iterator(); childrenIter.hasNext();) { IProgramElement child = (IProgramElement) childrenIter.next(); ISourceLocation childLoc = child.getSourceLocation(); if (childLoc != null) { if (childLoc.getLine() <= lineno && childLoc.getEndLine() >= lineno) { // This child is a better match for that line number IProgramElement evenCloserMatch = findCloserMatchForLineNumber(child, lineno); if (evenCloserMatch == null) { return child; } else { return evenCloserMatch; } } else if (child.getKind().isType()) { // types are a bit clueless about where they are... do other nodes have // similar problems?? IProgramElement evenCloserMatch = findCloserMatchForLineNumber(child, lineno); if (evenCloserMatch != null) { return evenCloserMatch; } } } } return null; } private IProgramElement findNodeForSourceLineHelper(IProgramElement node, String sourceFilePath, int lineno, int offset) { if (matches(node, sourceFilePath, lineno, offset) && !hasMoreSpecificChild(node, sourceFilePath, lineno, offset)) { return node; } if (node != null) { for (Iterator it = node.getChildren().iterator(); it.hasNext();) { IProgramElement foundNode = findNodeForSourceLineHelper((IProgramElement) it.next(), sourceFilePath, lineno, offset); if (foundNode != null) { return foundNode; } } } return null; } private boolean matches(IProgramElement node, String sourceFilePath, int lineNumber, int offSet) { // try { // if (node != null && node.getSourceLocation() != null) // System.err.println("====\n1: " + // sourceFilePath + "\n2: " + // node.getSourceLocation().getSourceFile().getCanonicalPath().equals(sourceFilePath) // ); ISourceLocation nodeSourceLocation = (node != null ? node.getSourceLocation() : null); return node != null && nodeSourceLocation != null && nodeSourceLocation.getSourceFile().getAbsolutePath().equals(sourceFilePath) && ((offSet != -1 && nodeSourceLocation.getOffset() == offSet) || offSet == -1) && ((nodeSourceLocation.getLine() <= lineNumber && nodeSourceLocation.getEndLine() >= lineNumber) || (lineNumber <= 1 && node .getKind().isSourceFile())); // } catch (IOException ioe) { // return false; // } } private boolean hasMoreSpecificChild(IProgramElement node, String sourceFilePath, int lineNumber, int offSet) { for (Iterator it = node.getChildren().iterator(); it.hasNext();) { IProgramElement child = (IProgramElement) it.next(); if (matches(child, sourceFilePath, lineNumber, offSet)) return true; } return false; } public String getConfigFile() { return configFile; } public void setConfigFile(String configFile) { this.configFile = configFile; } public IProgramElement findElementForHandle(String handle) { return findElementForHandleOrCreate(handle, true); } // TODO: optimize this lookup // only want to create a file node if can't find the IPE if called through // findElementForHandle() to mirror behaviour before pr141730 public IProgramElement findElementForHandleOrCreate(String handle, boolean create) { // try the cache first... IProgramElement ipe = (IProgramElement) handleMap.get(handle); if (ipe != null) { return ipe; } ipe = findElementForHandle(root, handle); if (ipe == null && create) { ipe = createFileStructureNode(getFilename(handle)); } if (ipe != null) { cache(handle, ipe); } return ipe; } private IProgramElement findElementForHandle(IProgramElement parent, String handle) { for (Iterator it = parent.getChildren().iterator(); it.hasNext();) { IProgramElement node = (IProgramElement) it.next(); String nodeHid = node.getHandleIdentifier(); if (handle.equals(nodeHid)) { return node; } else { if (handle.startsWith(nodeHid)) { // it must be down here if it is anywhere IProgramElement childSearch = findElementForHandle(node, handle); if (childSearch != null) return childSearch; } } } return null; } // // private IProgramElement findElementForBytecodeInfo( // IProgramElement node, // String parentName, // String name, // String signature) { // for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { // IProgramElement curr = (IProgramElement)it.next(); // if (parentName.equals(curr.getParent().getBytecodeName()) // && name.equals(curr.getBytecodeName()) // && signature.equals(curr.getBytecodeSignature())) { // return node; // } else { // IProgramElement childSearch = findElementForBytecodeInfo(curr, parentName, name, signature); // if (childSearch != null) return childSearch; // } // } // return null; // } protected void cache(String handle, IProgramElement pe) { if (!AsmManager.isCompletingTypeBindings()) { handleMap.put(handle, pe); } } public void flushTypeMap() { typeMap.clear(); } public void flushHandleMap() { handleMap.clear(); } public void flushFileMap() { fileMap.clear(); } // TODO rename this method ... it does more than just the handle map public void updateHandleMap(Set deletedFiles) { // Only delete the entries we need to from the handle map - for performance reasons List forRemoval = new ArrayList(); Set k = handleMap.keySet(); for (Iterator iter = k.iterator(); iter.hasNext();) { String handle = (String) iter.next(); IProgramElement ipe = (IProgramElement) handleMap.get(handle); if (deletedFiles.contains(getCanonicalFilePath(ipe))) forRemoval.add(handle); } for (Iterator iter = forRemoval.iterator(); iter.hasNext();) { String handle = (String) iter.next(); handleMap.remove(handle); } forRemoval.clear(); k = typeMap.keySet(); for (Iterator iter = k.iterator(); iter.hasNext();) { String typeName = (String) iter.next(); IProgramElement ipe = (IProgramElement) typeMap.get(typeName); if (deletedFiles.contains(getCanonicalFilePath(ipe))) forRemoval.add(typeName); } for (Iterator iter = forRemoval.iterator(); iter.hasNext();) { String typeName = (String) iter.next(); typeMap.remove(typeName); } forRemoval.clear(); k = fileMap.keySet(); for (Iterator iter = k.iterator(); iter.hasNext();) { String filePath = (String) iter.next(); IProgramElement ipe = (IProgramElement) fileMap.get(filePath); if (deletedFiles.contains(getCanonicalFilePath(ipe))) forRemoval.add(filePath); } for (Iterator iter = forRemoval.iterator(); iter.hasNext();) { String filePath = (String) iter.next(); fileMap.remove(filePath); } } private String getFilename(String hid) { return asm.getHandleProvider().getFileForHandle(hid); } private String getCanonicalFilePath(IProgramElement ipe) { if (ipe.getSourceLocation() != null) { return asm.getCanonicalFilePath(ipe.getSourceLocation().getSourceFile()); } return ""; } }
269,867
Bug 269867 Non synchronized access to WeakHashMap causes infinite loop
The non synchronized access from AjTypeSystem.getAjType(clazz) to a static instance of WeakHashMap may cause an infinite loop at start up in a multi threaded system. The thread dump shows that 32 of 33 threads of the application stuck in WeakHashMap.get(Object) line 355: "BundleStarterThreadQcCtrl24" prio=3 tid=0x00957c00 nid=0x39 runnable [0xd42fb000..0xd42ffa70] java.lang.Thread.State: RUNNABLE at java.util.WeakHashMap.get(WeakHashMap.java:355) at org.aspectj.lang.reflect.AjTypeSystem.getAjType(AjTypeSystem.java:37) at org.aspectj.weaver.reflect.Java15ReflectionBasedReferenceTypeDelegate.initialize(Java15ReflectionBasedReferenceTypeDelegate.java:66) at org.aspectj.weaver.reflect.ReflectionBasedReferenceTypeDelegateFactory.create15Delegate(ReflectionBasedReferenceTypeDelegateFactory.java:56) at org.aspectj.weaver.reflect.ReflectionBasedReferenceTypeDelegateFactory.createDelegate(ReflectionBasedReferenceTypeDelegateFactory.java:42) at org.aspectj.weaver.reflect.ReflectionWorld.resolveDelegate(ReflectionWorld.java:111) at org.aspectj.weaver.World.resolveToReferenceType(World.java:388) at org.aspectj.weaver.World.resolve(World.java:279) at org.aspectj.weaver.World.resolve(World.java:199) at org.aspectj.weaver.World.resolve(World.java:348) at org.aspectj.weaver.reflect.ReflectionWorld.resolve(ReflectionWorld.java:103) at org.aspectj.weaver.reflect.ReflectionWorld.resolve(ReflectionWorld.java:93) at org.aspectj.weaver.reflect.ReflectionBasedReferenceTypeDelegateFactory.toResolvedTypeArray(ReflectionBasedReferenceTypeDelegateFactory.java:214) at org.aspectj.weaver.reflect.ReflectionBasedReferenceTypeDelegateFactory.createResolvedMethod(ReflectionBasedReferenceTypeDelegateFactory.java:107) at org.aspectj.weaver.reflect.ReflectionBasedReferenceTypeDelegateFactory.createResolvedMember(ReflectionBasedReferenceTypeDelegateFactory.java:98) at org.aspectj.weaver.reflect.ReflectionShadow.makeExecutionShadow(ReflectionShadow.java:53) at org.aspectj.weaver.internal.tools.PointcutExpressionImpl.matchesExecution(PointcutExpressionImpl.java:100) at org.aspectj.weaver.internal.tools.PointcutExpressionImpl.matchesMethodExecution(PointcutExpressionImpl.java:92) at org.springframework.aop.aspectj.AspectJExpressionPointcut.getShadowMatch(AspectJExpressionPointcut.java:370)
resolved fixed
752f895
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-03-24T22:04:41Z"
"2009-03-24T18:40:00Z"
aspectj5rt/java5-src/org/aspectj/lang/reflect/AjTypeSystem.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.lang.reflect; import java.lang.ref.WeakReference; import java.util.Map; import java.util.WeakHashMap; import org.aspectj.internal.lang.reflect.AjTypeImpl; /** * This is the anchor for the AspectJ runtime type system. * Typical usage to get the AjType representation of a given type * at runtime is to call <code>AjType<Foo> fooType = AjTypeSystem.getAjType(Foo.class);</code> */ public class AjTypeSystem { private static Map<Class, WeakReference<AjType>> ajTypes = new WeakHashMap<Class,WeakReference<AjType>>(); /** * Return the AspectJ runtime type representation of the given Java type. * Unlike java.lang.Class, AjType understands pointcuts, advice, declare statements, * and other AspectJ type members. AjType is the recommended reflection API for * AspectJ programs as it offers everything that java.lang.reflect does, with * AspectJ-awareness on top. */ public static <T> AjType<T> getAjType(Class<T> fromClass) { WeakReference<AjType> weakRefToAjType = ajTypes.get(fromClass); if (weakRefToAjType!=null) { AjType<T> theAjType = weakRefToAjType.get(); if (theAjType != null) { return theAjType; } else { theAjType = new AjTypeImpl<T>(fromClass); ajTypes.put(fromClass, new WeakReference<AjType>(theAjType)); return theAjType; } } // neither key nor value was found AjType<T> theAjType = new AjTypeImpl<T>(fromClass); ajTypes.put(fromClass, new WeakReference<AjType>(theAjType)); return theAjType; } }
269,912
Bug 269912 wasted time building message context when it is only used for command line builds
The context for a message is created even when AspectJ is used inside AJDT - but the context only ever gets used when printing messages to System.out. Under AJDT we ought to be able to 'switch it off'
resolved fixed
c732808
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-03-25T16:19:48Z"
"2009-03-25T00:13:20Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import org.aspectj.ajdt.internal.compiler.AjCompilerAdapter; import org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter; import org.aspectj.ajdt.internal.compiler.CompilationResultDestinationManager; import org.aspectj.ajdt.internal.compiler.IBinarySourceProvider; import org.aspectj.ajdt.internal.compiler.ICompilerAdapter; import org.aspectj.ajdt.internal.compiler.ICompilerAdapterFactory; import org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor; import org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider; import org.aspectj.ajdt.internal.compiler.InterimCompilationResult; import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment; import org.aspectj.ajdt.internal.compiler.lookup.AnonymousClassPublisher; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.internal.ProgramElement; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.CountingMessageHandler; import org.aspectj.bridge.ILifecycleAware; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.SourceLocation; import org.aspectj.bridge.Version; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextFormatter; import org.aspectj.bridge.context.ContextToken; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies; import org.aspectj.org.eclipse.jdt.internal.compiler.ICompilerRequestor; import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.ClasspathLocation; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.CompilationUnit; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.FileSystem; import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilation; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.aspectj.tools.ajc.Main; import org.aspectj.util.FileUtil; import org.aspectj.weaver.CustomMungerFactory; import org.aspectj.weaver.Dump; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.UnwovenClassFile; import org.eclipse.core.runtime.OperationCanceledException; public class AjBuildManager implements IOutputClassFileNameProvider, IBinarySourceProvider, ICompilerAdapterFactory { private static final String CROSSREFS_FILE_NAME = "build.lst"; private static final String CANT_WRITE_RESULT = "unable to write compilation result"; private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; public static boolean COPY_INPATH_DIR_RESOURCES = false; // AJDT doesn't want this check, so Main enables it. private static boolean DO_RUNTIME_VERSION_CHECK = false; // If runtime version check fails, warn or fail? (unset?) static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false; private static final FileFilter binarySourceFilter = new FileFilter() { public boolean accept(File f) { return f.getName().endsWith(".class"); } }; /** * This builder is static so that it can be subclassed and reset. However, note that there is only one builder present, so if * two extendsion reset it, only the latter will get used. */ public static AsmHierarchyBuilder asmHierarchyBuilder = new AsmHierarchyBuilder(); static { // CompilationAndWeavingContext.setMultiThreaded(false); CompilationAndWeavingContext.registerFormatter(CompilationAndWeavingContext.BATCH_BUILD, new AjBuildContexFormatter()); CompilationAndWeavingContext .registerFormatter(CompilationAndWeavingContext.INCREMENTAL_BUILD, new AjBuildContexFormatter()); } private IProgressListener progressListener = null; private boolean environmentSupportsIncrementalCompilation = false; private int compiledCount; private int sourceFileCount; private JarOutputStream zos; private boolean batchCompile = true; private INameEnvironment environment; private Map /* String -> List<UCF> */binarySourcesForTheNextCompile = new HashMap(); // FIXME asc should this really be in here? // private AsmManager structureModel; public AjBuildConfig buildConfig; private boolean ignoreOutxml; private boolean wasFullBuild = true; // true if last build was a full build rather than an incremental build AjState state = new AjState(this); /** * Enable check for runtime version, used only by Ant/command-line Main. * * @param main Main unused except to limit to non-null clients. */ public static void enableRuntimeVersionCheck(Main caller) { DO_RUNTIME_VERSION_CHECK = null != caller; } public BcelWeaver getWeaver() { return state.getWeaver(); } public BcelWorld getBcelWorld() { return state.getBcelWorld(); } public CountingMessageHandler handler; private CustomMungerFactory customMungerFactory; public AjBuildManager(IMessageHandler holder) { super(); this.handler = CountingMessageHandler.makeCountingMessageHandler(holder); } public void environmentSupportsIncrementalCompilation(boolean itDoes) { this.environmentSupportsIncrementalCompilation = itDoes; } /** @return true if we should generate a model as a side-effect */ public boolean doGenerateModel() { return buildConfig.isGenerateModelMode(); } public boolean batchBuild(AjBuildConfig buildConfig, IMessageHandler baseHandler) throws IOException, AbortException { return performBuild(buildConfig, baseHandler, true); } public boolean incrementalBuild(AjBuildConfig buildConfig, IMessageHandler baseHandler) throws IOException, AbortException { return performBuild(buildConfig, baseHandler, false); } /** * Perform a build. * * @return true if the build was successful (ie. no errors) */ private boolean performBuild(AjBuildConfig buildConfig, IMessageHandler baseHandler, boolean isFullBuild) throws IOException, AbortException { boolean ret = true; batchCompile = isFullBuild; wasFullBuild = isFullBuild; if (baseHandler instanceof ILifecycleAware) { ((ILifecycleAware) baseHandler).buildStarting(!isFullBuild); } CompilationAndWeavingContext.reset(); int phase = isFullBuild ? CompilationAndWeavingContext.BATCH_BUILD : CompilationAndWeavingContext.INCREMENTAL_BUILD; ContextToken ct = CompilationAndWeavingContext.enteringPhase(phase, buildConfig); try { if (isFullBuild) { this.state = new AjState(this); } this.state.setCouldBeSubsequentIncrementalBuild(this.environmentSupportsIncrementalCompilation); boolean canIncremental = state.prepareForNextBuild(buildConfig); if (!canIncremental && !isFullBuild) { // retry as batch? CompilationAndWeavingContext.leavingPhase(ct); if (state.listenerDefined()) state.getListener().recordDecision("Falling back to batch compilation"); return performBuild(buildConfig, baseHandler, true); } this.handler = CountingMessageHandler.makeCountingMessageHandler(baseHandler); if (buildConfig == null || buildConfig.isCheckRuntimeVersion()) { if (DO_RUNTIME_VERSION_CHECK) { String check = checkRtJar(buildConfig); if (check != null) { if (FAIL_IF_RUNTIME_NOT_FOUND) { MessageUtil.error(handler, check); CompilationAndWeavingContext.leavingPhase(ct); return false; } else { MessageUtil.warn(handler, check); } } } } // if (batch) { setBuildConfig(buildConfig); // } if (isFullBuild || !AsmManager.attemptIncrementalModelRepairs) { // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { setupModel(buildConfig); // } } if (isFullBuild) { initBcelWorld(handler); } if (handler.hasErrors()) { CompilationAndWeavingContext.leavingPhase(ct); return false; } if (buildConfig.getOutputJar() != null) { if (!openOutputStream(buildConfig.getOutputJar())) { CompilationAndWeavingContext.leavingPhase(ct); return false; } } if (isFullBuild) { // System.err.println("XXXX batch: " + buildConfig.getFiles()); if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { AsmManager.setLastActiveStructureModel(state.getStructureModel()); getWorld().setModel(state.getStructureModel()); // in incremental build, only get updated model? } binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true); performCompilation(buildConfig.getFiles()); state.clearBinarySourceFiles(); // we don't want these hanging around... if (!proceedOnError() && handler.hasErrors()) { CompilationAndWeavingContext.leavingPhase(ct); if (AsmManager.isReporting()) { state.getStructureModel().reportModelInfo("After a batch build"); } return false; } if (AsmManager.isReporting()) { state.getStructureModel().reportModelInfo("After a batch build"); } } else { // done already? // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { // bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel()); // } // System.err.println("XXXX start inc "); AsmManager.setLastActiveStructureModel(state.getStructureModel()); binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true); Set files = state.getFilesToCompile(true); if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { if (AsmManager.attemptIncrementalModelRepairs) { state.getStructureModel().resetDeltaProcessing(); state.getStructureModel().processDelta(files, state.getAddedFiles(), state.getDeletedFiles()); } } boolean hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty()); for (int i = 0; (i < 5) && hereWeGoAgain; i++) { if (state.listenerDefined()) state.getListener() .recordInformation("Starting incremental compilation loop " + (i + 1) + " of possibly 5"); // System.err.println("XXXX inc: " + files); performCompilation(files); if ((!proceedOnError() && handler.hasErrors()) || (progressListener != null && progressListener.isCancelledRequested())) { CompilationAndWeavingContext.leavingPhase(ct); return false; } if (state.requiresFullBatchBuild()) { if (state.listenerDefined()) state.getListener().recordInformation(" Dropping back to full build"); return batchBuild(buildConfig, baseHandler); } binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(false); files = state.getFilesToCompile(false); hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty()); // TODO Andy - Needs some thought here... // I think here we might want to pass empty addedFiles/deletedFiles as they were // dealt with on the first call to processDelta - we are going through this loop // again because in compiling something we found something else we needed to // rebuild. But what case causes this? if (hereWeGoAgain) { if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) if (AsmManager.attemptIncrementalModelRepairs) state.getStructureModel().processDelta(files, state.getAddedFiles(), state.getDeletedFiles()); } } if (!files.isEmpty()) { CompilationAndWeavingContext.leavingPhase(ct); return batchBuild(buildConfig, baseHandler); } else { if (AsmManager.isReporting()) { state.getStructureModel().reportModelInfo("After an incremental build"); } } } // XXX not in Mik's incremental if (buildConfig.isEmacsSymMode()) { new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel(state.getStructureModel()); } // for bug 113554: support ajsym file generation for command line builds if (buildConfig.isGenerateCrossRefsMode()) { File configFileProxy = new File(buildConfig.getOutputDir(), CROSSREFS_FILE_NAME); state.getStructureModel().writeStructureModel(configFileProxy.getAbsolutePath()); } // have to tell state we succeeded or next is not incremental state.successfulCompile(buildConfig, isFullBuild); // For a full compile, copy resources to the destination // - they should not get deleted on incremental and AJDT // will handle changes to them that require a recopying if (isFullBuild) { copyResourcesToDestination(); } if (buildConfig.getOutxmlName() != null) { writeOutxmlFile(); } /* boolean weaved = */// weaveAndGenerateClassFiles(); // if not weaved, then no-op build, no model changes // but always returns true // XXX weaved not in Mik's incremental if (buildConfig.isGenerateModelMode()) { state.getStructureModel().fireModelUpdated(); } CompilationAndWeavingContext.leavingPhase(ct); } finally { if (baseHandler instanceof ILifecycleAware) { ((ILifecycleAware) baseHandler).buildFinished(!isFullBuild); } if (zos != null) { closeOutputStream(buildConfig.getOutputJar()); } ret = !handler.hasErrors(); if (getBcelWorld() != null) getBcelWorld().tidyUp(); if (getWeaver() != null) getWeaver().tidyUp(); // bug 59895, don't release reference to handler as may be needed by a nested call // handler = null; } return ret; } /** * Open an output jar file in which to write the compiler output. * * @param outJar the jar file to open * @return true if successful */ private boolean openOutputStream(File outJar) { try { OutputStream os = FileUtil.makeOutputStream(buildConfig.getOutputJar()); zos = new JarOutputStream(os, getWeaver().getManifest(true)); } catch (IOException ex) { IMessage message = new Message("Unable to open outjar " + outJar.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(outJar, 0), true); handler.handleMessage(message); return false; } return true; } private void closeOutputStream(File outJar) { try { if (zos != null) { zos.close(); if (buildConfig.getCompilationResultDestinationManager() != null) { buildConfig.getCompilationResultDestinationManager().reportFileWrite(outJar.getPath(), CompilationResultDestinationManager.FILETYPE_OUTJAR); } } zos = null; /* Ensure we don't write an incomplete JAR bug-71339 */ if (handler.hasErrors()) { outJar.delete(); if (buildConfig.getCompilationResultDestinationManager() != null) { buildConfig.getCompilationResultDestinationManager().reportFileRemove(outJar.getPath(), CompilationResultDestinationManager.FILETYPE_OUTJAR); } } } catch (IOException ex) { IMessage message = new Message("Unable to write outjar " + outJar.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(outJar, 0), true); handler.handleMessage(message); } } private void copyResourcesToDestination() throws IOException { // resources that we need to copy are contained in the injars and inpath only for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext();) { File inJar = (File) i.next(); copyResourcesFromJarFile(inJar); } for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext();) { File inPathElement = (File) i.next(); if (inPathElement.isDirectory()) { copyResourcesFromDirectory(inPathElement); } else { copyResourcesFromJarFile(inPathElement); } } if (buildConfig.getSourcePathResources() != null) { for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext();) { String resource = (String) i.next(); File from = (File) buildConfig.getSourcePathResources().get(resource); copyResourcesFromFile(from, resource, from); } } writeManifest(); } private void copyResourcesFromJarFile(File jarFile) throws IOException { JarInputStream inStream = null; try { inStream = new JarInputStream(new FileInputStream(jarFile)); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; String filename = entry.getName(); // System.out.println("? copyResourcesFromJarFile() filename='" + filename +"'"); if (entry.isDirectory()) { writeDirectory(filename, jarFile); } else if (acceptResource(filename, false)) { byte[] bytes = FileUtil.readAsByteArray(inStream); writeResource(filename, bytes, jarFile); } inStream.closeEntry(); } } finally { if (inStream != null) inStream.close(); } } private void copyResourcesFromDirectory(File dir) throws IOException { if (!COPY_INPATH_DIR_RESOURCES) return; // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(dir, new FileFilter() { public boolean accept(File f) { boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")); return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = files[i].getAbsolutePath().substring(dir.getAbsolutePath().length() + 1); copyResourcesFromFile(files[i], filename, dir); } } private void copyResourcesFromFile(File f, String filename, File src) throws IOException { if (!acceptResource(filename, true)) return; FileInputStream fis = null; try { fis = new FileInputStream(f); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); writeResource(filename, bytes, src); } finally { if (fis != null) fis.close(); } } /** * Add a directory entry to the output zip file. Don't do anything if not writing out to a zip file. A directory entry is one * whose filename ends with '/' * * @param directory the directory path * @param srcloc the src of the directory entry, for use when creating a warning message * @throws IOException if something goes wrong creating the new zip entry */ private void writeDirectory(String directory, File srcloc) throws IOException { if (state.hasResource(directory)) { IMessage msg = new Message("duplicate resource: '" + directory + "'", IMessage.WARNING, null, new SourceLocation( srcloc, 0)); handler.handleMessage(msg); return; } if (zos != null) { ZipEntry newEntry = new ZipEntry(directory); zos.putNextEntry(newEntry); zos.closeEntry(); state.recordResource(directory, srcloc); } // Nothing to do if not writing to a zip file } private void writeResource(String filename, byte[] content, File srcLocation) throws IOException { if (state.hasResource(filename)) { IMessage msg = new Message("duplicate resource: '" + filename + "'", IMessage.WARNING, null, new SourceLocation( srcLocation, 0)); handler.handleMessage(msg); return; } if (filename.equals(buildConfig.getOutxmlName())) { ignoreOutxml = true; IMessage msg = new Message("-outxml/-outxmlfile option ignored because resource already exists: '" + filename + "'", IMessage.WARNING, null, new SourceLocation(srcLocation, 0)); handler.handleMessage(msg); } if (zos != null) { ZipEntry newEntry = new ZipEntry(filename); // ??? get compression scheme right zos.putNextEntry(newEntry); zos.write(content); zos.closeEntry(); } else { File destDir = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { destDir = buildConfig.getCompilationResultDestinationManager().getOutputLocationForResource(srcLocation); } try { File outputLocation = new File(destDir, filename); OutputStream fos = FileUtil.makeOutputStream(outputLocation); fos.write(content); fos.close(); if (buildConfig.getCompilationResultDestinationManager() != null) { buildConfig.getCompilationResultDestinationManager().reportFileWrite(outputLocation.getPath(), CompilationResultDestinationManager.FILETYPE_RESOURCE); } } catch (FileNotFoundException fnfe) { IMessage msg = new Message("unable to copy resource to output folder: '" + filename + "' - reason: " + fnfe.getMessage(), IMessage.ERROR, null, new SourceLocation(srcLocation, 0)); handler.handleMessage(msg); } } state.recordResource(filename, srcLocation); } /* * If we are writing to an output directory copy the manifest but only if we already have one */ private void writeManifest() throws IOException { Manifest manifest = getWeaver().getManifest(false); if (manifest != null && zos == null) { File outputDir = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { // Manifests are only written if we have a jar on the inpath. Therefore, // we write the manifest to the defaultOutputLocation because this is // where we sent the classes that were on the inpath outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation(); } if (outputDir == null) { return; } File outputLocation = new File(outputDir, MANIFEST_NAME); OutputStream fos = FileUtil.makeOutputStream(outputLocation); manifest.write(fos); fos.close(); if (buildConfig.getCompilationResultDestinationManager() != null) { buildConfig.getCompilationResultDestinationManager().reportFileWrite(outputLocation.getPath(), CompilationResultDestinationManager.FILETYPE_RESOURCE); } } } private boolean acceptResource(String resourceName, boolean fromFile) { if ((resourceName.startsWith("CVS/")) || (resourceName.indexOf("/CVS/") != -1) || (resourceName.endsWith("/CVS")) || (resourceName.endsWith(".class")) || (resourceName.startsWith(".svn/")) || (resourceName.indexOf("/.svn/") != -1) || (resourceName.endsWith("/.svn")) || // Do not copy manifests if either they are coming from a jar or we are writing to a jar (resourceName.toUpperCase().equals(MANIFEST_NAME) && (!fromFile || zos != null))) { return false; } else { return true; } } private void writeOutxmlFile() throws IOException { if (ignoreOutxml) return; String filename = buildConfig.getOutxmlName(); // System.err.println("? AjBuildManager.writeOutxmlFile() outxml=" + filename); Map outputDirsAndAspects = findOutputDirsForAspects(); Set outputDirs = outputDirsAndAspects.entrySet(); for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); File outputDir = (File) entry.getKey(); List aspects = (List) entry.getValue(); ByteArrayOutputStream baos = getOutxmlContents(aspects); if (zos != null) { ZipEntry newEntry = new ZipEntry(filename); zos.putNextEntry(newEntry); zos.write(baos.toByteArray()); zos.closeEntry(); } else { File outputFile = new File(outputDir, filename); OutputStream fos = FileUtil.makeOutputStream(outputFile); fos.write(baos.toByteArray()); fos.close(); if (buildConfig.getCompilationResultDestinationManager() != null) { buildConfig.getCompilationResultDestinationManager().reportFileWrite(outputFile.getPath(), CompilationResultDestinationManager.FILETYPE_RESOURCE); } } } } private ByteArrayOutputStream getOutxmlContents(List aspectNames) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); ps.println("<aspectj>"); ps.println("<aspects>"); if (aspectNames != null) { for (Iterator i = aspectNames.iterator(); i.hasNext();) { String name = (String) i.next(); ps.println("<aspect name=\"" + name + "\"/>"); } } ps.println("</aspects>"); ps.println("</aspectj>"); ps.println(); ps.close(); return baos; } /** * Returns a map where the keys are File objects corresponding to all the output directories and the values are a list of * aspects which are sent to that ouptut directory */ private Map /* File --> List (String) */findOutputDirsForAspects() { Map outputDirsToAspects = new HashMap(); Map aspectNamesToFileNames = state.getAspectNamesToFileNameMap(); if (buildConfig.getCompilationResultDestinationManager() == null || buildConfig.getCompilationResultDestinationManager().getAllOutputLocations().size() == 1) { // we only have one output directory...which simplifies things File outputDir = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation(); } List aspectNames = new ArrayList(); if (aspectNamesToFileNames != null) { Set keys = aspectNamesToFileNames.keySet(); for (Iterator iterator = keys.iterator(); iterator.hasNext();) { String name = (String) iterator.next(); aspectNames.add(name); } } outputDirsToAspects.put(outputDir, aspectNames); } else { List outputDirs = buildConfig.getCompilationResultDestinationManager().getAllOutputLocations(); for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) { File outputDir = (File) iterator.next(); outputDirsToAspects.put(outputDir, new ArrayList()); } Set entrySet = aspectNamesToFileNames.entrySet(); for (Iterator iterator = entrySet.iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String aspectName = (String) entry.getKey(); char[] fileName = (char[]) entry.getValue(); File outputDir = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass( new File(new String(fileName))); if (!outputDirsToAspects.containsKey(outputDir)) { outputDirsToAspects.put(outputDir, new ArrayList()); } ((List) outputDirsToAspects.get(outputDir)).add(aspectName); } } return outputDirsToAspects; } // public static void dumprels() { // IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap(); // int ctr = 1; // Set entries = irm.getEntries(); // for (Iterator iter = entries.iterator(); iter.hasNext();) { // String hid = (String) iter.next(); // List rels = irm.get(hid); // for (Iterator iterator = rels.iterator(); iterator.hasNext();) { // IRelationship ir = (IRelationship) iterator.next(); // List targets = ir.getTargets(); // for (Iterator iterator2 = targets.iterator(); // iterator2.hasNext(); // ) { // String thid = (String) iterator2.next(); // System.err.println("Hid:"+(ctr++)+":(targets="+targets.size()+") "+hid+" ("+ir.getName()+") "+thid); // } // } // } // } /** * Responsible for managing the ASM model between builds. Contains the policy for maintaining the persistance of elements in the * model. * * This code is driven before each 'fresh' (batch) build to create a new model. */ private void setupModel(AjBuildConfig config) { if (!(config.isEmacsSymMode() || config.isGenerateModelMode())) { return; } // AsmManager.setCreatingModel(config.isEmacsSymMode() || config.isGenerateModelMode()); // if (!AsmManager.isCreatingModel()) // return; AsmManager structureModel = AsmManager.createNewStructureModel(); // AsmManager.getDefault().getRelationshipMap().clear(); IHierarchy model = structureModel.getHierarchy(); String rootLabel = "<root>"; IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA; if (buildConfig.getConfigFile() != null) { rootLabel = buildConfig.getConfigFile().getName(); model.setConfigFile(buildConfig.getConfigFile().getAbsolutePath()); kind = IProgramElement.Kind.FILE_LST; } model.setRoot(new ProgramElement(structureModel, rootLabel, kind, new ArrayList())); model.setFileMap(new HashMap()); // setStructureModel(model); state.setStructureModel(structureModel); // state.setRelationshipMap(AsmManager.getDefault().getRelationshipMap()); } // // private void dumplist(List l) { // System.err.println("---- "+l.size()); // for (int i =0 ;i<l.size();i++) System.err.println(i+"\t "+l.get(i)); // } // private void accumulateFileNodes(IProgramElement ipe,List store) { // if (ipe.getKind()==IProgramElement.Kind.FILE_JAVA || // ipe.getKind()==IProgramElement.Kind.FILE_ASPECTJ) { // if (!ipe.getName().equals("<root>")) { // store.add(ipe); // return; // } // } // for (Iterator i = ipe.getChildren().iterator();i.hasNext();) { // accumulateFileNodes((IProgramElement)i.next(),store); // } // } // LTODO delegate to BcelWeaver? // XXX hideous, should not be Object public void setCustomMungerFactory(Object o) { customMungerFactory = (CustomMungerFactory) o; } public Object getCustomMungerFactory() { return customMungerFactory; } /** init only on initial batch compile? no file-specific options */ private void initBcelWorld(IMessageHandler handler) throws IOException { List cp = buildConfig.getFullClasspath(); // pr145693 // buildConfig.getBootclasspath(); // cp.addAll(buildConfig.getClasspath()); BcelWorld bcelWorld = new BcelWorld(cp, handler, null); bcelWorld.setBehaveInJava5Way(buildConfig.getBehaveInJava5Way()); bcelWorld.setAddSerialVerUID(buildConfig.isAddSerialVerUID()); bcelWorld.setXmlConfigured(buildConfig.isXmlConfigured()); bcelWorld.setXmlFiles(buildConfig.getXmlFiles()); bcelWorld.performExtraConfiguration(buildConfig.getXconfigurationInfo()); bcelWorld.setTargetAspectjRuntimeLevel(buildConfig.getTargetAspectjRuntimeLevel()); bcelWorld.setOptionalJoinpoints(buildConfig.getXJoinpoints()); bcelWorld.setXnoInline(buildConfig.isXnoInline()); bcelWorld.setXlazyTjp(buildConfig.isXlazyTjp()); bcelWorld.setXHasMemberSupportEnabled(buildConfig.isXHasMemberEnabled()); bcelWorld.setPinpointMode(buildConfig.isXdevPinpoint()); bcelWorld.setErrorAndWarningThreshold(buildConfig.getOptions().errorThreshold, buildConfig.getOptions().warningThreshold); BcelWeaver bcelWeaver = new BcelWeaver(bcelWorld); bcelWeaver.setCustomMungerFactory(customMungerFactory); state.setWorld(bcelWorld); state.setWeaver(bcelWeaver); state.clearBinarySourceFiles(); if (buildConfig.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT)) { bcelWorld.getLint().loadDefaultProperties(); } else { bcelWorld.getLint().setAll(buildConfig.getLintMode()); } if (buildConfig.getLintSpecFile() != null) { bcelWorld.getLint().setFromProperties(buildConfig.getLintSpecFile()); } for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext();) { File f = (File) i.next(); if (!f.exists()) { IMessage message = new Message("invalid aspectpath entry: " + f.getName(), null, true); handler.handleMessage(message); } else { bcelWeaver.addLibraryJarFile(f); } } // String lintMode = buildConfig.getLintMode(); File outputDir = buildConfig.getOutputDir(); if (outputDir == null && buildConfig.getCompilationResultDestinationManager() != null) { // send all output from injars and inpath to the default output location // (will also later send the manifest there too) outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation(); } // ??? incremental issues for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext();) { File inJar = (File) i.next(); List unwovenClasses = bcelWeaver.addJarFile(inJar, outputDir, false); state.recordBinarySource(inJar.getPath(), unwovenClasses); } for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext();) { File inPathElement = (File) i.next(); if (!inPathElement.isDirectory()) { // its a jar file on the inpath // the weaver method can actually handle dirs, but we don't call it, see next block List unwovenClasses = bcelWeaver.addJarFile(inPathElement, outputDir, true); state.recordBinarySource(inPathElement.getPath(), unwovenClasses); } else { // add each class file in an in-dir individually, this gives us the best error reporting // (they are like 'source' files then), and enables a cleaner incremental treatment of // class file changes in indirs. File[] binSrcs = FileUtil.listFiles(inPathElement, binarySourceFilter); for (int j = 0; j < binSrcs.length; j++) { UnwovenClassFile ucf = bcelWeaver.addClassFile(binSrcs[j], inPathElement, outputDir); List ucfl = new ArrayList(); ucfl.add(ucf); state.recordBinarySource(binSrcs[j].getPath(), ucfl); } } } bcelWeaver.setReweavableMode(buildConfig.isXNotReweavable()); // check for org.aspectj.runtime.JoinPoint ResolvedType joinPoint = bcelWorld.resolve("org.aspectj.lang.JoinPoint"); if (joinPoint.isMissing()) { IMessage message = new Message( "classpath error: unable to find org.aspectj.lang.JoinPoint (check that aspectjrt.jar is in your classpath)", null, true); handler.handleMessage(message); } } public World getWorld() { return getBcelWorld(); } void addAspectClassFilesToWeaver(List addedClassFiles) throws IOException { for (Iterator i = addedClassFiles.iterator(); i.hasNext();) { UnwovenClassFile classFile = (UnwovenClassFile) i.next(); getWeaver().addClassFile(classFile); } } public FileSystem getLibraryAccess(String[] classpaths, String[] filenames) { String defaultEncoding = buildConfig.getOptions().defaultEncoding; if ("".equals(defaultEncoding)) {//$NON-NLS-1$ defaultEncoding = null; } // Bug 46671: We need an array as long as the number of elements in the classpath - *even though* not every // element of the classpath is likely to be a directory. If we ensure every element of the array is set to // only look for BINARY, then we make sure that for any classpath element that is a directory, we won't build // a classpathDirectory object that will attempt to look for source when it can't find binary. // int[] classpathModes = new int[classpaths.length]; // for (int i =0 ;i<classpaths.length;i++) classpathModes[i]=ClasspathDirectory.BINARY; return new FileSystem(classpaths, filenames, defaultEncoding, ClasspathLocation.BINARY); } public IProblemFactory getProblemFactory() { return new DefaultProblemFactory(Locale.getDefault()); } /* * Build the set of compilation source units */ public CompilationUnit[] getCompilationUnits(String[] filenames) { int fileCount = filenames.length; CompilationUnit[] units = new CompilationUnit[fileCount]; // HashtableOfObject knownFileNames = new HashtableOfObject(fileCount); String defaultEncoding = buildConfig.getOptions().defaultEncoding; if ("".equals(defaultEncoding)) {//$NON-NLS-1$ defaultEncoding = null; } for (int i = 0; i < fileCount; i++) { units[i] = new CompilationUnit(null, filenames[i], defaultEncoding); } return units; } public String extractDestinationPathFromSourceFile(CompilationResult result) { ICompilationUnit compilationUnit = result.compilationUnit; if (compilationUnit != null) { char[] fileName = compilationUnit.getFileName(); int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName); if (lastIndex == -1) { return System.getProperty("user.dir"); //$NON-NLS-1$ } return new String(CharOperation.subarray(fileName, 0, lastIndex)); } return System.getProperty("user.dir"); //$NON-NLS-1$ } public void performCompilation(Collection files) { if (progressListener != null) { compiledCount = 0; sourceFileCount = files.size(); progressListener.setText("compiling source files"); } // Translate from strings to File objects String[] filenames = new String[files.size()]; int idx = 0; for (Iterator fIterator = files.iterator(); fIterator.hasNext();) { File f = (File) fIterator.next(); filenames[idx++] = f.getPath(); } environment = state.getNameEnvironment(); boolean environmentNeedsRebuilding = false; // Might be a bit too cautious, but let us see how it goes if (buildConfig.getChanged() != AjBuildConfig.NO_CHANGES) { environmentNeedsRebuilding = true; } if (environment == null || environmentNeedsRebuilding) { List cps = buildConfig.getFullClasspath(); Dump.saveFullClasspath(cps); String[] classpaths = new String[cps.size()]; for (int i = 0; i < cps.size(); i++) { classpaths[i] = (String) cps.get(i); } environment = new StatefulNameEnvironment(getLibraryAccess(classpaths, filenames), state.getClassNameToFileMap(), state); state.setNameEnvironment(environment); } org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(this); org.aspectj.org.eclipse.jdt.internal.compiler.Compiler compiler = new org.aspectj.org.eclipse.jdt.internal.compiler.Compiler( environment, DefaultErrorHandlingPolicies.proceedWithAllProblems(), buildConfig.getOptions().getMap(), getBatchRequestor(), getProblemFactory()); compiler.options.produceReferenceInfo = true; // TODO turn off when not needed try { compiler.compile(getCompilationUnits(filenames)); } catch (OperationCanceledException oce) { handler.handleMessage(new Message("build cancelled:" + oce.getMessage(), IMessage.WARNING, null, null)); } // cleanup org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(null); AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(null); environment.cleanup(); // environment = null; } public void cleanupEnvironment() { if (environment != null) { environment.cleanup(); environment = null; } } /* * Answer the component to which will be handed back compilation results from the compiler */ public IIntermediateResultsRequestor getInterimResultRequestor() { return new IIntermediateResultsRequestor() { public void acceptResult(InterimCompilationResult result) { if (progressListener != null) { compiledCount++; progressListener.setProgress((compiledCount / 2.0) / sourceFileCount); progressListener.setText("compiled: " + result.fileName()); } state.noteResult(result); if (progressListener != null && progressListener.isCancelledRequested()) { throw new AbortCompilation(true, new OperationCanceledException("Compilation cancelled as requested")); } } }; } public ICompilerRequestor getBatchRequestor() { return new ICompilerRequestor() { public void acceptResult(CompilationResult unitResult) { // end of compile, must now write the results to the output destination // this is either a jar file or a file in a directory boolean hasErrors = unitResult.hasErrors(); if (!hasErrors || proceedOnError()) { Collection classFiles = unitResult.compiledTypes.values(); boolean shouldAddAspectName = (buildConfig.getOutxmlName() != null); for (Iterator iter = classFiles.iterator(); iter.hasNext();) { ClassFile classFile = (ClassFile) iter.next(); String filename = new String(classFile.fileName()); String classname = filename.replace('/', '.'); filename = filename.replace('/', File.separatorChar) + ".class"; try { if (buildConfig.getOutputJar() == null) { String outfile = writeDirectoryEntry(unitResult, classFile, filename); if (environmentSupportsIncrementalCompilation) { if (!classname.endsWith("$ajcMightHaveAspect")) { ResolvedType type = getBcelWorld().resolve(classname); if (type.isAspect()) { state.recordAspectClassFile(outfile); } } } } else { writeZipEntry(classFile, filename); } if (shouldAddAspectName && !classname.endsWith("$ajcMightHaveAspect")) addAspectName(classname, unitResult.getFileName()); } catch (IOException ex) { IMessage message = EclipseAdapterUtils.makeErrorMessage(new String(unitResult.fileName), CANT_WRITE_RESULT, ex); handler.handleMessage(message); } } state.noteNewResult(unitResult); unitResult.compiledTypes.clear(); // free up references to AjClassFile instances } if (unitResult.hasProblems() || unitResult.hasTasks()) { IProblem[] problems = unitResult.getAllProblems(); for (int i = 0; i < problems.length; i++) { IMessage message = EclipseAdapterUtils.makeMessage(unitResult.compilationUnit, problems[i], getBcelWorld()); handler.handleMessage(message); } } } private String writeDirectoryEntry(CompilationResult unitResult, ClassFile classFile, String filename) throws IOException { File destinationPath = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { destinationPath = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass( new File(new String(unitResult.fileName))); } String outFile; if (destinationPath == null) { outFile = new File(filename).getName(); outFile = new File(extractDestinationPathFromSourceFile(unitResult), outFile).getPath(); } else { outFile = new File(destinationPath, filename).getPath(); } BufferedOutputStream os = FileUtil.makeOutputStream(new File(outFile)); os.write(classFile.getBytes()); os.close(); if (buildConfig.getCompilationResultDestinationManager() != null) { buildConfig.getCompilationResultDestinationManager().reportFileWrite(outFile, CompilationResultDestinationManager.FILETYPE_CLASS); } return outFile; } private void writeZipEntry(ClassFile classFile, String name) throws IOException { name = name.replace(File.separatorChar, '/'); ZipEntry newEntry = new ZipEntry(name); // ??? get compression scheme right zos.putNextEntry(newEntry); zos.write(classFile.getBytes()); zos.closeEntry(); } private void addAspectName(String name, char[] fileContainingAspect) { BcelWorld world = getBcelWorld(); ResolvedType type = world.resolve(name); // System.err.println("? writeAspectName() type=" + type); if (type.isAspect()) { if (state.getAspectNamesToFileNameMap() == null) { state.initializeAspectNamesToFileNameMap(); } if (!state.getAspectNamesToFileNameMap().containsKey(name)) { state.getAspectNamesToFileNameMap().put(name, fileContainingAspect); } } } }; } protected boolean proceedOnError() { return buildConfig.getProceedOnError(); } // public void noteClassFiles(AjCompiler.InterimResult result) { // if (result == null) return; // CompilationResult unitResult = result.result; // String sourceFileName = result.fileName(); // if (!(unitResult.hasErrors() && !proceedOnError())) { // List unwovenClassFiles = new ArrayList(); // Enumeration classFiles = unitResult.compiledTypes.elements(); // while (classFiles.hasMoreElements()) { // ClassFile classFile = (ClassFile) classFiles.nextElement(); // String filename = new String(classFile.fileName()); // filename = filename.replace('/', File.separatorChar) + ".class"; // // File destinationPath = buildConfig.getOutputDir(); // if (destinationPath == null) { // filename = new File(filename).getName(); // filename = new File(extractDestinationPathFromSourceFile(unitResult), filename).getPath(); // } else { // filename = new File(destinationPath, filename).getPath(); // } // // //System.out.println("classfile: " + filename); // unwovenClassFiles.add(new UnwovenClassFile(filename, classFile.getBytes())); // } // state.noteClassesFromFile(unitResult, sourceFileName, unwovenClassFiles); // // System.out.println("file: " + sourceFileName); // // for (int i=0; i < unitResult.simpleNameReferences.length; i++) { // // System.out.println("simple: " + new String(unitResult.simpleNameReferences[i])); // // } // // for (int i=0; i < unitResult.qualifiedReferences.length; i++) { // // System.out.println("qualified: " + // // new String(CharOperation.concatWith(unitResult.qualifiedReferences[i], '/'))); // // } // } else { // state.noteClassesFromFile(null, sourceFileName, Collections.EMPTY_LIST); // } // } // private void setBuildConfig(AjBuildConfig buildConfig) { this.buildConfig = buildConfig; if (!this.environmentSupportsIncrementalCompilation) { this.environmentSupportsIncrementalCompilation = (buildConfig.isIncrementalMode() || buildConfig .isIncrementalFileMode()); } handler.reset(); } String makeClasspathString(AjBuildConfig buildConfig) { if (buildConfig == null || buildConfig.getFullClasspath() == null) return ""; StringBuffer buf = new StringBuffer(); boolean first = true; for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext();) { if (first) { first = false; } else { buf.append(File.pathSeparator); } buf.append(it.next().toString()); } return buf.toString(); } /** * This will return null if aspectjrt.jar is present and has the correct version. Otherwise it will return a string message * indicating the problem. */ private String checkRtJar(AjBuildConfig buildConfig) { // omitting dev info if (Version.text.equals(Version.DEVELOPMENT)) { // in the development version we can't do this test usefully // MessageUtil.info(holder, "running development version of aspectj compiler"); return null; } if (buildConfig == null || buildConfig.getFullClasspath() == null) return "no classpath specified"; String ret = null; for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext();) { File p = new File((String) it.next()); // pr112830, allow variations on aspectjrt.jar of the form aspectjrtXXXXXX.jar if (p.isFile() && p.getName().startsWith("aspectjrt") && p.getName().endsWith(".jar")) { try { String version = null; Manifest manifest = new JarFile(p).getManifest(); if (manifest == null) { ret = "no manifest found in " + p.getAbsolutePath() + ", expected " + Version.text; continue; } Attributes attr = manifest.getAttributes("org/aspectj/lang/"); if (null != attr) { version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION); if (null != version) { version = version.trim(); } } // assume that users of development aspectjrt.jar know what they're doing if (Version.DEVELOPMENT.equals(version)) { // MessageUtil.info(holder, // "running with development version of aspectjrt.jar in " + // p.getAbsolutePath()); return null; } else if (!Version.text.equals(version)) { ret = "bad version number found in " + p.getAbsolutePath() + " expected " + Version.text + " found " + version; continue; } } catch (IOException ioe) { ret = "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe; } return null; // this is the "OK" return value! } else { // might want to catch other classpath errors } } if (ret != null) return ret; // last error found in potentially matching jars... return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString(buildConfig); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("AjBuildManager("); buf.append(")"); return buf.toString(); } // // public void setStructureModel(IHierarchy structureModel) { // this.structureModel = structureModel; // } /** * Returns null if there is no structure model */ public AsmManager getStructureModel() { return (state == null ? null : state.getStructureModel()); } public IProgressListener getProgressListener() { return progressListener; } public void setProgressListener(IProgressListener progressListener) { this.progressListener = progressListener; } /* * (non-Javadoc) * * @see org.aspectj.ajdt.internal.compiler.AjCompiler.IOutputClassFileNameProvider#getOutputClassFileName(char[]) */ public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) { String filename = new String(eclipseClassFileName); filename = filename.replace('/', File.separatorChar) + ".class"; File destinationPath = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { File f = new File(new String(result.getFileName())); destinationPath = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass(f); } String outFile; if (destinationPath == null) { outFile = new File(filename).getName(); outFile = new File(extractDestinationPathFromSourceFile(result), outFile).getPath(); } else { outFile = new File(destinationPath, filename).getPath(); } return outFile; } /* * (non-Javadoc) * * @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler) */ public ICompilerAdapter getAdapter(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) { // complete compiler config and return a suitable adapter... populateCompilerOptionsFromLintSettings(forCompiler); AjProblemReporter pr = new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(), forCompiler.options, getProblemFactory()); forCompiler.problemReporter = pr; AjLookupEnvironment le = new AjLookupEnvironment(forCompiler, forCompiler.options, pr, environment); EclipseFactory factory = new EclipseFactory(le, this); le.factory = factory; pr.factory = factory; forCompiler.lookupEnvironment = le; forCompiler.parser = new Parser(pr, forCompiler.options.parseLiteralExpressionsAsConstants); if (getBcelWorld().shouldPipelineCompilation()) { IMessage message = MessageUtil.info("Pipelining compilation"); handler.handleMessage(message); return new AjPipeliningCompilerAdapter(forCompiler, batchCompile, getBcelWorld(), getWeaver(), factory, getInterimResultRequestor(), progressListener, this, // IOutputFilenameProvider this, // IBinarySourceProvider state.getBinarySourceMap(), buildConfig.isTerminateAfterCompilation(), buildConfig.getProceedOnError(), buildConfig.isNoAtAspectJAnnotationProcessing(), state); } else { return new AjCompilerAdapter(forCompiler, batchCompile, getBcelWorld(), getWeaver(), factory, getInterimResultRequestor(), progressListener, this, // IOutputFilenameProvider this, // IBinarySourceProvider state.getBinarySourceMap(), buildConfig.isTerminateAfterCompilation(), buildConfig.getProceedOnError(), buildConfig.isNoAtAspectJAnnotationProcessing(), state); } } /** * Some AspectJ lint options need to be known about in the compiler. This is how we pass them over... * * @param forCompiler */ private void populateCompilerOptionsFromLintSettings(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) { BcelWorld world = this.state.getBcelWorld(); IMessage.Kind swallowedExceptionKind = world.getLint().swallowedExceptionInCatchBlock.getKind(); Map optionsMap = new HashMap(); optionsMap.put(CompilerOptions.OPTION_ReportSwallowedExceptionInCatchBlock, swallowedExceptionKind == null ? "ignore" : swallowedExceptionKind.toString()); forCompiler.options.set(optionsMap); } /* * (non-Javadoc) * * @see org.aspectj.ajdt.internal.compiler.IBinarySourceProvider#getBinarySourcesForThisWeave() */ public Map getBinarySourcesForThisWeave() { return binarySourcesForTheNextCompile; } public static AsmHierarchyBuilder getAsmHierarchyBuilder() { return asmHierarchyBuilder; } /** * Override the the default hierarchy builder. */ public static void setAsmHierarchyBuilder(AsmHierarchyBuilder newBuilder) { asmHierarchyBuilder = newBuilder; } public AjState getState() { return state; } public void setState(AjState buildState) { state = buildState; } private static class AjBuildContexFormatter implements ContextFormatter { public String formatEntry(int phaseId, Object data) { StringBuffer sb = new StringBuffer(); if (phaseId == CompilationAndWeavingContext.BATCH_BUILD) { sb.append("batch building "); } else { sb.append("incrementally building "); } AjBuildConfig config = (AjBuildConfig) data; List classpath = config.getClasspath(); sb.append("with classpath: "); for (Iterator iter = classpath.iterator(); iter.hasNext();) { sb.append(iter.next().toString()); sb.append(File.pathSeparator); } return sb.toString(); } } public boolean wasFullBuild() { return wasFullBuild; } }
269,912
Bug 269912 wasted time building message context when it is only used for command line builds
The context for a message is created even when AspectJ is used inside AJDT - but the context only ever gets used when printing messages to System.out. Under AJDT we ought to be able to 'switch it off'
resolved fixed
c732808
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-03-25T16:19:48Z"
"2009-03-25T00:13:20Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/EclipseAdapterUtils.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.File; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.SourceLocation; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.aspectj.weaver.LintMessage; import org.aspectj.weaver.World; public class EclipseAdapterUtils { // XXX some cut-and-paste from eclipse sources public static String makeLocationContext(ICompilationUnit compilationUnit, IProblem problem) { // extra from the source the innacurate token // and "highlight" it using some underneath ^^^^^ // put some context around too. // this code assumes that the font used in the console is fixed size // sanity ..... int startPosition = problem.getSourceStart(); int endPosition = problem.getSourceEnd(); if ((startPosition > endPosition) || ((startPosition <= 0) && (endPosition <= 0)) || compilationUnit == null) //return Util.bind("problem.noSourceInformation"); //$NON-NLS-1$ return "(no source information available)"; final char SPACE = '\u0020'; final char MARK = '^'; final char TAB = '\t'; char[] source = compilationUnit.getContents(); // the next code tries to underline the token..... // it assumes (for a good display) that token source does not // contain any \r \n. This is false on statements ! // (the code still works but the display is not optimal !) // compute the how-much-char we are displaying around the inaccurate token int begin = startPosition >= source.length ? source.length - 1 : startPosition; if (begin == -1) return "(no source information available)"; // Dont like this - why does it occur? pr152835 int relativeStart = 0; int end = endPosition >= source.length ? source.length - 1 : endPosition; int relativeEnd = 0; label: for (relativeStart = 0;; relativeStart++) { if (begin == 0) break label; if ((source[begin - 1] == '\n') || (source[begin - 1] == '\r')) break label; begin--; } label: for (relativeEnd = 0;; relativeEnd++) { if ((end + 1) >= source.length) break label; if ((source[end + 1] == '\r') || (source[end + 1] == '\n')) { break label; } end++; } // extract the message form the source char[] extract = new char[end - begin + 1]; System.arraycopy(source, begin, extract, 0, extract.length); char c; // remove all SPACE and TAB that begin the error message... int trimLeftIndex = 0; while ((((c = extract[trimLeftIndex++]) == TAB) || (c == SPACE)) && trimLeftIndex < extract.length) { } if (trimLeftIndex >= extract.length) return new String(extract) + "\n"; System.arraycopy(extract, trimLeftIndex - 1, extract = new char[extract.length - trimLeftIndex + 1], 0, extract.length); relativeStart -= trimLeftIndex; // buffer spaces and tabs in order to reach the error position int pos = 0; char[] underneath = new char[extract.length]; // can't be bigger for (int i = 0; i <= relativeStart; i++) { if (extract[i] == TAB) { underneath[pos++] = TAB; } else { underneath[pos++] = SPACE; } } // mark the error position for (int i = startPosition + trimLeftIndex; // AMC if we took stuff off the start, take it into account! i <= (endPosition >= source.length ? source.length - 1 : endPosition); i++) underneath[pos++] = MARK; // resize underneathto remove 'null' chars System.arraycopy(underneath, 0, underneath = new char[pos], 0, pos); return new String(extract) + "\n" + new String(underneath); //$NON-NLS-2$ //$NON-NLS-1$ } /** * Extract source location file, start and end lines, and context. Column is not extracted correctly. * * @return ISourceLocation with correct file and lines but not column. */ public static ISourceLocation makeSourceLocation(ICompilationUnit unit, IProblem problem) { int line = problem.getSourceLineNumber(); File file = new File(new String(problem.getOriginatingFileName())); String context = makeLocationContext(unit, problem); // XXX 0 column is wrong but recoverable from makeLocationContext return new SourceLocation(file, line, line, 0, context); } /** * Extract message text and source location, including context. * * @param world */ public static IMessage makeMessage(ICompilationUnit unit, IProblem problem, World world) { ISourceLocation sourceLocation = makeSourceLocation(unit, problem); IProblem[] seeAlso = problem.seeAlso(); // If the user has turned off classfile line number gen, then we may not be able to tell them // about all secondary locations (pr209372) int validPlaces = 0; for (int ii = 0; ii < seeAlso.length; ii++) { if (seeAlso[ii].getSourceLineNumber() >= 0) validPlaces++; } ISourceLocation[] seeAlsoLocations = new ISourceLocation[validPlaces]; int pos = 0; for (int i = 0; i < seeAlso.length; i++) { if (seeAlso[i].getSourceLineNumber() >= 0) { seeAlsoLocations[pos++] = new SourceLocation(new File(new String(seeAlso[i].getOriginatingFileName())), seeAlso[i] .getSourceLineNumber()); } } // We transform messages from AJ types to eclipse IProblems // and back to AJ types. During their time as eclipse problems, // we remember whether the message originated from a declare // in the extraDetails. String extraDetails = problem.getSupplementaryMessageInfo(); boolean declared = false; boolean isLintMessage = false; String lintkey = null; if (extraDetails != null && extraDetails.endsWith("[deow=true]")) { declared = true; extraDetails = extraDetails.substring(0, extraDetails.length() - "[deow=true]".length()); } if (extraDetails != null && extraDetails.indexOf("[Xlint:") != -1) { isLintMessage = true; lintkey = extraDetails.substring(extraDetails.indexOf("[Xlint:")); lintkey = lintkey.substring("[Xlint:".length()); lintkey = lintkey.substring(0, lintkey.indexOf("]")); } // If the 'problem' represents a TO DO kind of thing then use the message kind that // represents this so AJDT sees it correctly. IMessage.Kind kind; if (problem.getID() == IProblem.Task) { kind = IMessage.TASKTAG; } else { if (problem.isError()) { kind = IMessage.ERROR; } else { kind = IMessage.WARNING; } } IMessage msg = null; if (isLintMessage) { msg = new LintMessage(problem.getMessage(), extraDetails, world.getLint().fromKey(lintkey), kind, sourceLocation, null, seeAlsoLocations, declared, problem.getID(), problem.getSourceStart(), problem.getSourceEnd()); } else { msg = new Message(problem.getMessage(), extraDetails, kind, sourceLocation, null, seeAlsoLocations, declared, problem .getID(), problem.getSourceStart(), problem.getSourceEnd()); } return msg; } public static IMessage makeErrorMessage(ICompilationUnit unit, String text, Exception ex) { ISourceLocation loc = new SourceLocation(new File(new String(unit.getFileName())), 0, 0, 0, ""); IMessage msg = new Message(text, IMessage.ERROR, ex, loc); return msg; } public static IMessage makeErrorMessage(String srcFile, String text, Exception ex) { ISourceLocation loc = new SourceLocation(new File(srcFile), 0, 0, 0, ""); IMessage msg = new Message(text, IMessage.ERROR, ex, loc); return msg; } private EclipseAdapterUtils() { } }
269,902
Bug 269902 NPE in AsmRelationshipProvider.addRelationship
When doing a clean build of my project, seeing dozens, upwards of 100 of NPEs similar to the following: java.lang.NullPointerException at org.aspectj.weaver.model.AsmRelationshipProvider.addRelationship(AsmRelationshipProvider.java:168) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:124) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:441) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:103) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1732) at org.aspectj.weaver.b ... FWIW, this is seen for Spring-managed auto-injection of beans with the @Configurable annotation. Official AJDT version is: 1.6.4.20090304172355 Version: 3.4.2 Build id: M20090211-17
resolved fixed
d5e900d
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-03-26T02:25:32Z"
"2009-03-24T21:26:40Z"
weaver/src/org/aspectj/weaver/model/AsmRelationshipProvider.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.model; import java.io.File; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.IRelationship; import org.aspectj.asm.IRelationshipMap; import org.aspectj.asm.internal.ProgramElement; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.Checker; import org.aspectj.weaver.Lint; import org.aspectj.weaver.Member; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelShadow; import org.aspectj.weaver.bcel.BcelTypeMunger; import org.aspectj.weaver.patterns.DeclareErrorOrWarning; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.Pointcut; public class AsmRelationshipProvider { public static final String ADVISES = "advises"; public static final String ADVISED_BY = "advised by"; public static final String DECLARES_ON = "declares on"; public static final String DECLAREDY_BY = "declared by"; public static final String SOFTENS = "softens"; public static final String SOFTENED_BY = "softened by"; public static final String MATCHED_BY = "matched by"; public static final String MATCHES_DECLARE = "matches declare"; public static final String INTER_TYPE_DECLARES = "declared on"; public static final String INTER_TYPE_DECLARED_BY = "aspect declarations"; public static final String ANNOTATES = "annotates"; public static final String ANNOTATED_BY = "annotated by"; /** * Add a relationship for a declare error or declare warning */ public static void addDeclareErrorOrWarningRelationship(AsmManager model, Shadow affectedShadow, Checker deow) { if (model == null) { return; } if (affectedShadow.getSourceLocation() == null || deow.getSourceLocation() == null) { return; } if (World.createInjarHierarchy) { createHierarchyForBinaryAspect(model, deow); } IProgramElement targetNode = getNode(model, affectedShadow); if (targetNode == null) { return; } String targetHandle = model.getHandleProvider().createHandleIdentifier(targetNode); if (targetHandle == null) { return; } IProgramElement sourceNode = model.getHierarchy().findElementForSourceLine(deow.getSourceLocation()); String sourceHandle = model.getHandleProvider().createHandleIdentifier(sourceNode); if (sourceHandle == null) { return; } IRelationshipMap relmap = model.getRelationshipMap(); IRelationship foreward = relmap.get(sourceHandle, IRelationship.Kind.DECLARE, MATCHED_BY, false, true); foreward.addTarget(targetHandle); IRelationship back = relmap.get(targetHandle, IRelationship.Kind.DECLARE, MATCHES_DECLARE, false, true); if (back != null && back.getTargets() != null) { back.addTarget(sourceHandle); } if (sourceNode.getSourceLocation() != null) { model.addAspectInEffectThisBuild(sourceNode.getSourceLocation().getSourceFile()); } } /** * Add a relationship for a type transformation (declare parents, intertype method declaration, declare annotation on type). */ public static void addRelationship(AsmManager model, ResolvedType onType, ResolvedTypeMunger typeTransformer, ResolvedType originatingAspect) { if (model == null) { return; } if (World.createInjarHierarchy && isBinaryAspect(originatingAspect)) { createHierarchy(model, typeTransformer, originatingAspect); } if (originatingAspect.getSourceLocation() != null) { String sourceHandle = ""; IProgramElement sourceNode = null; if (typeTransformer.getSourceLocation() != null && typeTransformer.getSourceLocation().getOffset() != -1) { sourceNode = model.getHierarchy().findElementForType(originatingAspect.getPackageName(), originatingAspect.getClassName()); IProgramElement closer = model.getHierarchy().findCloserMatchForLineNumber(sourceNode, typeTransformer.getSourceLocation().getLine()); if (closer != null) { sourceNode = closer; } sourceHandle = model.getHandleProvider().createHandleIdentifier(sourceNode); } else { sourceNode = model.getHierarchy().findElementForType(originatingAspect.getPackageName(), originatingAspect.getClassName()); // sourceNode = // asm.getHierarchy().findElementForSourceLine(originatingAspect // .getSourceLocation()); sourceHandle = model.getHandleProvider().createHandleIdentifier(sourceNode); } // sourceNode = // asm.getHierarchy().findElementForType(originatingAspect // .getPackageName(), // originatingAspect.getClassName()); // // sourceNode = // asm.getHierarchy().findElementForSourceLine(munger // .getSourceLocation()); // sourceHandle = // asm.getHandleProvider().createHandleIdentifier(sourceNode); if (sourceHandle == null) return; IProgramElement targetNode = model.getHierarchy().findElementForSourceLine(onType.getSourceLocation()); String targetHandle = model.getHandleProvider().createHandleIdentifier(targetNode); if (targetHandle == null) return; IRelationshipMap mapper = model.getRelationshipMap(); IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARES, false, true); foreward.addTarget(targetHandle); IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARED_BY, false, true); back.addTarget(sourceHandle); model.addAspectInEffectThisBuild(sourceNode.getSourceLocation().getSourceFile()); } } private static boolean isBinaryAspect(ResolvedType aspect) { return aspect.getBinaryPath() != null; } /** * Returns the binarySourceLocation for the given sourcelocation. This isn't cached because it's used when faulting in the * binary nodes and is called with ISourceLocations for all advice, pointcuts and deows contained within the * resolvedDeclaringAspect. */ private static ISourceLocation getBinarySourceLocation(ResolvedType aspect, ISourceLocation sl) { if (sl == null) { return null; } String sourceFileName = null; if (aspect instanceof ReferenceType) { String s = ((ReferenceType) aspect).getDelegate().getSourcefilename(); int i = s.lastIndexOf('/'); if (i != -1) { sourceFileName = s.substring(i + 1); } else { sourceFileName = s; } } ISourceLocation sLoc = new SourceLocation(getBinaryFile(aspect), sl.getLine(), sl.getEndLine(), ((sl.getColumn() == 0) ? ISourceLocation.NO_COLUMN : sl.getColumn()), sl.getContext(), sourceFileName); return sLoc; } private static ISourceLocation createSourceLocation(String sourcefilename, ResolvedType aspect, ISourceLocation sl) { ISourceLocation sLoc = new SourceLocation(getBinaryFile(aspect), sl.getLine(), sl.getEndLine(), ((sl.getColumn() == 0) ? ISourceLocation.NO_COLUMN : sl.getColumn()), sl.getContext(), sourcefilename); return sLoc; } private static String getSourceFileName(ResolvedType aspect) { String sourceFileName = null; if (aspect instanceof ReferenceType) { String s = ((ReferenceType) aspect).getDelegate().getSourcefilename(); int i = s.lastIndexOf('/'); if (i != -1) { sourceFileName = s.substring(i + 1); } else { sourceFileName = s; } } return sourceFileName; } /** * Returns the File with pathname to the class file, for example either C:\temp * \ajcSandbox\workspace\ajcTest16957.tmp\simple.jar!pkg\BinaryAspect.class if the class file is in a jar file, or * C:\temp\ajcSandbox\workspace\ajcTest16957.tmp!pkg\BinaryAspect.class if the class file is in a directory */ private static File getBinaryFile(ResolvedType aspect) { String s = aspect.getBinaryPath(); File f = aspect.getSourceLocation().getSourceFile(); // Replace the source file suffix with .class int i = f.getPath().lastIndexOf('.'); String path = null; if (i != -1) { path = f.getPath().substring(0, i) + ".class"; } else { path = f.getPath() + ".class"; } return new File(s + "!" + path); } /** * Create a basic hierarchy to represent an aspect only available in binary (from the aspectpath). */ private static void createHierarchy(AsmManager model, ResolvedTypeMunger typeTransformer, ResolvedType aspect) { // assert aspect != null; // Check if already defined in the model // IProgramElement filenode = // model.getHierarchy().findElementForType(aspect.getPackageName(), // aspect.getClassName()); // SourceLine(typeTransformer.getSourceLocation()); IProgramElement filenode = model.getHierarchy().findElementForSourceLine(typeTransformer.getSourceLocation()); // the call to findElementForSourceLine(ISourceLocation) returns a file // node // if it can't find a node in the hierarchy for the given // sourcelocation. // Therefore, if this is returned, we know we can't find one and have to // // continue to fault in the model. // if (filenode != null) { // if (!filenode.getKind().equals(IProgramElement.Kind.FILE_JAVA)) { return; } // create the class file node IProgramElement classFileNode = new ProgramElement(model, filenode.getName(), IProgramElement.Kind.FILE, getBinarySourceLocation(aspect, aspect.getSourceLocation()), 0, null, null); // create package ipe if one exists.... IProgramElement root = model.getHierarchy().getRoot(); IProgramElement binaries = model.getHierarchy().findElementForLabel(root, IProgramElement.Kind.SOURCE_FOLDER, "binaries"); if (binaries == null) { binaries = new ProgramElement(model, "binaries", IProgramElement.Kind.SOURCE_FOLDER, new ArrayList()); root.addChild(binaries); } // if (aspect.getPackageName() != null) { String packagename = aspect.getPackageName() == null ? "" : aspect.getPackageName(); // check that there doesn't already exist a node with this name IProgramElement pkgNode = model.getHierarchy().findElementForLabel(binaries, IProgramElement.Kind.PACKAGE, packagename); // note packages themselves have no source location if (pkgNode == null) { pkgNode = new ProgramElement(model, packagename, IProgramElement.Kind.PACKAGE, new ArrayList()); binaries.addChild(pkgNode); pkgNode.addChild(classFileNode); } else { // need to add it first otherwise the handle for classFileNode // may not be generated correctly if it uses information from // it's parent node pkgNode.addChild(classFileNode); for (Iterator iter = pkgNode.getChildren().iterator(); iter.hasNext();) { IProgramElement element = (IProgramElement) iter.next(); if (!element.equals(classFileNode) && element.getHandleIdentifier().equals(classFileNode.getHandleIdentifier())) { // already added the classfile so have already // added the structure for this aspect pkgNode.removeChild(classFileNode); return; } } } // } else { // // need to add it first otherwise the handle for classFileNode // // may not be generated correctly if it uses information from // // it's parent node // root.addChild(classFileNode); // for (Iterator iter = root.getChildren().iterator(); iter.hasNext();) // { // IProgramElement element = (IProgramElement) iter.next(); // if (!element.equals(classFileNode) && // element.getHandleIdentifier().equals // (classFileNode.getHandleIdentifier())) { // // already added the sourcefile so have already // // added the structure for this aspect // root.removeChild(classFileNode); // return; // } // } // } // add and create empty import declaration ipe // no import container for binary type - 265693 // classFileNode.addChild(new ProgramElement(model, "import declarations", IProgramElement.Kind.IMPORT_REFERENCE, null, 0, // null, null)); // add and create aspect ipe IProgramElement aspectNode = new ProgramElement(model, aspect.getSimpleName(), IProgramElement.Kind.ASPECT, getBinarySourceLocation(aspect, aspect.getSourceLocation()), aspect.getModifiers(), null, null); classFileNode.addChild(aspectNode); addChildNodes(model, aspect, aspectNode, aspect.getDeclaredPointcuts()); addChildNodes(model, aspect, aspectNode, aspect.getDeclaredAdvice()); addChildNodes(model, aspect, aspectNode, aspect.getDeclares()); addChildNodes(model, aspect, aspectNode, aspect.getTypeMungers()); } /** * Adds a declare annotation relationship, sometimes entities don't have source locs (methods/fields) so use other variants of * this method if that is the case as they will look the entities up in the structure model. */ public static void addDeclareAnnotationRelationship(AsmManager model, ISourceLocation declareAnnotationLocation, ISourceLocation annotatedLocation) { if (model == null) { return; } IProgramElement sourceNode = model.getHierarchy().findElementForSourceLine(declareAnnotationLocation); String sourceHandle = model.getHandleProvider().createHandleIdentifier(sourceNode); if (sourceHandle == null) { return; } IProgramElement targetNode = model.getHierarchy().findElementForSourceLine(annotatedLocation); String targetHandle = model.getHandleProvider().createHandleIdentifier(targetNode); if (targetHandle == null) { return; } IRelationshipMap mapper = model.getRelationshipMap(); IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATES, false, true); foreward.addTarget(targetHandle); IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATED_BY, false, true); back.addTarget(sourceHandle); if (sourceNode.getSourceLocation() != null) { model.addAspectInEffectThisBuild(sourceNode.getSourceLocation().getSourceFile()); } } /** * Creates the hierarchy for binary aspects */ public static void createHierarchyForBinaryAspect(AsmManager asm, ShadowMunger munger) { if (!munger.isBinary()) { return; } IProgramElement sourceFileNode = asm.getHierarchy().findElementForSourceLine(munger.getSourceLocation()); // the call to findElementForSourceLine(ISourceLocation) returns a file // node // if it can't find a node in the hierarchy for the given // sourcelocation. // Therefore, if this is returned, we know we can't find one and have to // continue to fault in the model. if (!sourceFileNode.getKind().equals(IProgramElement.Kind.FILE_JAVA)) { return; } ResolvedType aspect = munger.getDeclaringType(); // create the class file node IProgramElement classFileNode = new ProgramElement(asm, sourceFileNode.getName(), IProgramElement.Kind.FILE, munger .getBinarySourceLocation(aspect.getSourceLocation()), 0, null, null); // create package ipe if one exists.... IProgramElement root = asm.getHierarchy().getRoot(); IProgramElement binaries = asm.getHierarchy().findElementForLabel(root, IProgramElement.Kind.SOURCE_FOLDER, "binaries"); if (binaries == null) { binaries = new ProgramElement(asm, "binaries", IProgramElement.Kind.SOURCE_FOLDER, new ArrayList()); root.addChild(binaries); } // if (aspect.getPackageName() != null) { String packagename = aspect.getPackageName() == null ? "" : aspect.getPackageName(); // check that there doesn't already exist a node with this name IProgramElement pkgNode = asm.getHierarchy().findElementForLabel(binaries, IProgramElement.Kind.PACKAGE, packagename); // note packages themselves have no source location if (pkgNode == null) { pkgNode = new ProgramElement(asm, packagename, IProgramElement.Kind.PACKAGE, new ArrayList()); binaries.addChild(pkgNode); pkgNode.addChild(classFileNode); } else { // need to add it first otherwise the handle for classFileNode // may not be generated correctly if it uses information from // it's parent node pkgNode.addChild(classFileNode); for (Iterator iter = pkgNode.getChildren().iterator(); iter.hasNext();) { IProgramElement element = (IProgramElement) iter.next(); if (!element.equals(classFileNode) && element.getHandleIdentifier().equals(classFileNode.getHandleIdentifier())) { // already added the classfile so have already // added the structure for this aspect pkgNode.removeChild(classFileNode); return; } } } // } else { // // need to add it first otherwise the handle for classFileNode // // may not be generated correctly if it uses information from // // it's parent node // root.addChild(classFileNode); // for (Iterator iter = root.getChildren().iterator(); iter.hasNext();) // { // IProgramElement element = (IProgramElement) iter.next(); // if (!element.equals(classFileNode) && // element.getHandleIdentifier().equals // (classFileNode.getHandleIdentifier())) { // // already added the sourcefile so have already // // added the structure for this aspect // root.removeChild(classFileNode); // return; // } // } // } // add and create empty import declaration ipe // classFileNode.addChild(new ProgramElement(asm, "import declarations", IProgramElement.Kind.IMPORT_REFERENCE, null, 0, // null, // null)); // add and create aspect ipe IProgramElement aspectNode = new ProgramElement(asm, aspect.getSimpleName(), IProgramElement.Kind.ASPECT, munger .getBinarySourceLocation(aspect.getSourceLocation()), aspect.getModifiers(), null, null); classFileNode.addChild(aspectNode); String sourcefilename = getSourceFileName(aspect); addPointcuts(asm, sourcefilename, aspect, aspectNode, aspect.getDeclaredPointcuts()); addChildNodes(asm, aspect, aspectNode, aspect.getDeclaredAdvice()); addChildNodes(asm, aspect, aspectNode, aspect.getDeclares()); addChildNodes(asm, aspect, aspectNode, aspect.getTypeMungers()); } private static void addPointcuts(AsmManager model, String sourcefilename, ResolvedType aspect, IProgramElement containingAspect, ResolvedMember[] pointcuts) { for (int i = 0; i < pointcuts.length; i++) { ResolvedMember pointcut = pointcuts[i]; if (pointcut instanceof ResolvedPointcutDefinition) { ResolvedPointcutDefinition rpcd = (ResolvedPointcutDefinition) pointcut; Pointcut p = rpcd.getPointcut(); ISourceLocation sLoc = (p == null ? null : p.getSourceLocation()); if (sLoc == null) { sLoc = rpcd.getSourceLocation(); } ISourceLocation pointcutLocation = createSourceLocation(sourcefilename, aspect, sLoc); ProgramElement pointcutElement = new ProgramElement(model, pointcut.getName(), IProgramElement.Kind.POINTCUT, pointcutLocation, pointcut.getModifiers(), NO_COMMENT, Collections.EMPTY_LIST); containingAspect.addChild(pointcutElement); } } } private static final String NO_COMMENT = null; private static void addChildNodes(AsmManager asm, ResolvedType aspect, IProgramElement parent, ResolvedMember[] children) { for (int i = 0; i < children.length; i++) { ResolvedMember pcd = children[i]; if (pcd instanceof ResolvedPointcutDefinition) { ResolvedPointcutDefinition rpcd = (ResolvedPointcutDefinition) pcd; Pointcut p = rpcd.getPointcut(); ISourceLocation sLoc = (p == null ? null : p.getSourceLocation()); if (sLoc == null) { sLoc = rpcd.getSourceLocation(); } parent.addChild(new ProgramElement(asm, pcd.getName(), IProgramElement.Kind.POINTCUT, getBinarySourceLocation( aspect, sLoc), pcd.getModifiers(), null, Collections.EMPTY_LIST)); } } } private static void addChildNodes(AsmManager asm, ResolvedType aspect, IProgramElement parent, Collection children) { int deCtr = 1; int dwCtr = 1; for (Iterator iter = children.iterator(); iter.hasNext();) { Object element = iter.next(); if (element instanceof DeclareErrorOrWarning) { DeclareErrorOrWarning decl = (DeclareErrorOrWarning) element; int counter = 0; if (decl.isError()) { counter = deCtr++; } else { counter = dwCtr++; } parent.addChild(createDeclareErrorOrWarningChild(asm, aspect, decl, counter)); } else if (element instanceof Advice) { Advice advice = (Advice) element; parent.addChild(createAdviceChild(asm, advice)); } else if (element instanceof DeclareParents) { parent.addChild(createDeclareParentsChild(asm, (DeclareParents) element)); } else if (element instanceof BcelTypeMunger) { parent.addChild(createIntertypeDeclaredChild(asm, aspect, (BcelTypeMunger) element)); } } } // private static IProgramElement // createDeclareErrorOrWarningChild(AsmManager asm, ShadowMunger munger, // DeclareErrorOrWarning decl, int count) { // IProgramElement deowNode = new ProgramElement(asm, decl.getName(), // decl.isError() ? IProgramElement.Kind.DECLARE_ERROR // : IProgramElement.Kind.DECLARE_WARNING, // munger.getBinarySourceLocation(decl.getSourceLocation()), decl // .getDeclaringType().getModifiers(), null, null); // deowNode.setDetails("\"" + // AsmRelationshipUtils.genDeclareMessage(decl.getMessage()) + "\""); // if (count != -1) { // deowNode.setBytecodeName(decl.getName() + "_" + count); // } // return deowNode; // } private static IProgramElement createDeclareErrorOrWarningChild(AsmManager model, ResolvedType aspect, DeclareErrorOrWarning decl, int count) { IProgramElement deowNode = new ProgramElement(model, decl.getName(), decl.isError() ? IProgramElement.Kind.DECLARE_ERROR : IProgramElement.Kind.DECLARE_WARNING, getBinarySourceLocation(aspect, decl.getSourceLocation()), decl .getDeclaringType().getModifiers(), null, null); deowNode.setDetails("\"" + AsmRelationshipUtils.genDeclareMessage(decl.getMessage()) + "\""); if (count != -1) { deowNode.setBytecodeName(decl.getName() + "_" + count); } return deowNode; } private static IProgramElement createAdviceChild(AsmManager model, Advice advice) { IProgramElement adviceNode = new ProgramElement(model, advice.getKind().getName(), IProgramElement.Kind.ADVICE, advice .getBinarySourceLocation(advice.getSourceLocation()), advice.getSignature().getModifiers(), null, Collections.EMPTY_LIST); adviceNode.setDetails(AsmRelationshipUtils.genPointcutDetails(advice.getPointcut())); adviceNode.setBytecodeName(advice.getSignature().getName()); return adviceNode; } /** * Half baked implementation - will need completing if we go down this route rather than replacing it all for binary aspects. * Doesn't attempt to get parameter names correct - they may have been lost during (de)serialization of the munger, but the * member could still be located so they might be retrievable. */ private static IProgramElement createIntertypeDeclaredChild(AsmManager model, ResolvedType aspect, BcelTypeMunger itd) { ResolvedTypeMunger rtMunger = itd.getMunger(); ResolvedMember sig = rtMunger.getSignature(); if (rtMunger.getKind() == ResolvedTypeMunger.Field) { // ITD FIELD // String name = rtMunger.getSignature().toString(); String name = sig.getDeclaringType().getClassName() + "." + sig.getName(); if (name.indexOf("$") != -1) { name = name.substring(name.indexOf("$") + 1); } IProgramElement pe = new ProgramElement(model, name, IProgramElement.Kind.INTER_TYPE_FIELD, getBinarySourceLocation( aspect, itd.getSourceLocation()), rtMunger.getSignature().getModifiers(), null, Collections.EMPTY_LIST); pe.setCorrespondingType(sig.getReturnType().getName()); return pe; } else if (rtMunger.getKind() == ResolvedTypeMunger.Method) { // ITD // METHOD String name = sig.getDeclaringType().getClassName() + "." + sig.getName(); if (name.indexOf("$") != -1) { name = name.substring(name.indexOf("$") + 1); } IProgramElement pe = new ProgramElement(model, name, IProgramElement.Kind.INTER_TYPE_METHOD, getBinarySourceLocation( aspect, itd.getSourceLocation()), rtMunger.getSignature().getModifiers(), null, Collections.EMPTY_LIST); setParams(pe, sig); return pe; } else if (rtMunger.getKind() == ResolvedTypeMunger.Constructor) { String name = sig.getDeclaringType().getClassName() + "." + sig.getDeclaringType().getClassName(); if (name.indexOf("$") != -1) { name = name.substring(name.indexOf("$") + 1); } IProgramElement pe = new ProgramElement(model, name, IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR, getBinarySourceLocation(aspect, itd.getSourceLocation()), rtMunger.getSignature().getModifiers(), null, Collections.EMPTY_LIST); setParams(pe, sig); return pe; } // other cases ignored for now return null; } private static void setParams(IProgramElement pe, ResolvedMember sig) { // do it for itds too UnresolvedType[] ts = sig.getParameterTypes(); pe.setParameterNames(Collections.EMPTY_LIST); String[] pnames = sig.getParameterNames(); if (ts == null) { pe.setParameterSignatures(Collections.EMPTY_LIST, Collections.EMPTY_LIST); } else { List paramSigs = new ArrayList(); List paramNames = new ArrayList(); for (int i = 0; i < ts.length; i++) { paramSigs.add(ts[i].getSignature().toCharArray()); // paramNames.add(pnames[i]); } pe.setParameterSignatures(paramSigs, Collections.EMPTY_LIST); // pe.setParameterNames(paramNames); } pe.setCorrespondingType(sig.getReturnType().getName()); } private static IProgramElement createDeclareParentsChild(AsmManager model, DeclareParents decp) { IProgramElement decpElement = new ProgramElement(model, "declare parents", IProgramElement.Kind.DECLARE_PARENTS, getBinarySourceLocation(decp.getDeclaringType(), decp.getSourceLocation()), Modifier.PUBLIC, null, Collections.EMPTY_LIST); return decpElement; } public static String getHandle(AsmManager asm, Advice advice) { if (null == advice.handle) { ISourceLocation sl = advice.getSourceLocation(); if (sl != null) { IProgramElement ipe = asm.getHierarchy().findElementForSourceLine(sl); advice.handle = asm.getHandleProvider().createHandleIdentifier(ipe); } } return advice.handle; } public static void addAdvisedRelationship(AsmManager model, Shadow matchedShadow, ShadowMunger munger) { if (model == null) { return; } if (munger instanceof Advice) { Advice advice = (Advice) munger; if (advice.getKind().isPerEntry() || advice.getKind().isCflow()) { // TODO: might want to show these in the future return; } if (World.createInjarHierarchy) { createHierarchyForBinaryAspect(model, advice); } IRelationshipMap mapper = model.getRelationshipMap(); IProgramElement targetNode = getNode(model, matchedShadow); if (targetNode == null) { return; } boolean runtimeTest = advice.hasDynamicTests(); IProgramElement.ExtraInformation extra = new IProgramElement.ExtraInformation(); String adviceHandle = getHandle(model, advice); if (adviceHandle == null) { return; } extra.setExtraAdviceInformation(advice.getKind().getName()); IProgramElement adviceElement = model.getHierarchy().findElementForHandle(adviceHandle); if (adviceElement != null) { adviceElement.setExtraInfo(extra); } String targetHandle = targetNode.getHandleIdentifier(); if (advice.getKind().equals(AdviceKind.Softener)) { IRelationship foreward = mapper.get(adviceHandle, IRelationship.Kind.DECLARE_SOFT, SOFTENS, runtimeTest, true); if (foreward != null) { foreward.addTarget(targetHandle); } IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE, SOFTENED_BY, runtimeTest, true); if (back != null) { back.addTarget(adviceHandle); } } else { IRelationship foreward = mapper.get(adviceHandle, IRelationship.Kind.ADVICE, ADVISES, runtimeTest, true); if (foreward != null) { foreward.addTarget(targetHandle); } IRelationship back = mapper.get(targetHandle, IRelationship.Kind.ADVICE, ADVISED_BY, runtimeTest, true); if (back != null) { back.addTarget(adviceHandle); } } if (adviceElement.getSourceLocation() != null) { model.addAspectInEffectThisBuild(adviceElement.getSourceLocation().getSourceFile()); } } } protected static IProgramElement getNode(AsmManager model, Shadow shadow) { Member enclosingMember = shadow.getEnclosingCodeSignature(); // This variant will not be tricked by ITDs that would report they are // in the target type already. // This enables us to discover the ITD declaration (in the aspect) and // advise it appropriately. // Have to be smart here, for a code node within an ITD we want to // lookup the declaration of the // ITD in the aspect in order to add the code node at the right place - // and not lookup the // ITD as it applies in some target type. Due to the use of // effectiveSignature we will find // that shadow.getEnclosingCodeSignature() will return a member // representing the ITD as it will // appear in the target type. So here, we do an extra bit of analysis to // make sure we // do the right thing in the ITD case. IProgramElement enclosingNode = null; if (shadow instanceof BcelShadow) { Member actualEnclosingMember = ((BcelShadow) shadow).getRealEnclosingCodeSignature(); if (actualEnclosingMember == null) { enclosingNode = lookupMember(model.getHierarchy(), shadow.getEnclosingType(), enclosingMember); } else { UnresolvedType type = enclosingMember.getDeclaringType(); UnresolvedType actualType = actualEnclosingMember.getDeclaringType(); // if these are not the same, it is an ITD and we need to use // the latter to lookup if (type.equals(actualType)) { enclosingNode = lookupMember(model.getHierarchy(), shadow.getEnclosingType(), enclosingMember); } else { enclosingNode = lookupMember(model.getHierarchy(), shadow.getEnclosingType(), actualEnclosingMember); } } } else { enclosingNode = lookupMember(model.getHierarchy(), shadow.getEnclosingType(), enclosingMember); } if (enclosingNode == null) { Lint.Kind err = shadow.getIWorld().getLint().shadowNotInStructure; if (err.isEnabled()) { err.signal(shadow.toString(), shadow.getSourceLocation()); } return null; } Member shadowSig = shadow.getSignature(); // pr235204 if (shadow.getKind() == Shadow.MethodCall || shadow.getKind() == Shadow.ConstructorCall || !shadowSig.equals(enclosingMember)) { IProgramElement bodyNode = findOrCreateCodeNode(model, enclosingNode, shadowSig, shadow); return bodyNode; } else { return enclosingNode; } } private static boolean sourceLinesMatch(ISourceLocation location1, ISourceLocation location2) { return (location1.getLine() == location2.getLine()); } /** * Finds or creates a code IProgramElement for the given shadow. * * The byteCodeName of the created node is set to 'shadowSig.getName() + "!" + counter', eg "println!3". The counter is the * occurence count of children within the enclosingNode which have the same name. So, for example, if a method contains two * System.out.println statements, the first one will have byteCodeName 'println!1' and the second will have byteCodeName * 'println!2'. This is to ensure the two nodes have unique handles when the handles do not depend on sourcelocations. * * Currently the shadows are examined in the sequence they appear in the source file. This means that the counters are * consistent over incremental builds. All aspects are compiled up front and any new aspect created will force a full build. * Moreover, if the body of the enclosingShadow is changed, then the model for this is rebuilt from scratch. */ private static IProgramElement findOrCreateCodeNode(AsmManager asm, IProgramElement enclosingNode, Member shadowSig, Shadow shadow) { for (Iterator it = enclosingNode.getChildren().iterator(); it.hasNext();) { IProgramElement node = (IProgramElement) it.next(); int excl = node.getBytecodeName().lastIndexOf('!'); if (((excl != -1 && shadowSig.getName().equals(node.getBytecodeName().substring(0, excl))) || shadowSig.getName() .equals(node.getBytecodeName())) && shadowSig.getSignature().equals(node.getBytecodeSignature()) && sourceLinesMatch(node.getSourceLocation(), shadow.getSourceLocation())) { return node; } } ISourceLocation sl = shadow.getSourceLocation(); // XXX why not use shadow file? new SourceLocation(sl.getSourceFile(), // sl.getLine()), SourceLocation peLoc = new SourceLocation(enclosingNode.getSourceLocation().getSourceFile(), sl.getLine()); peLoc.setOffset(sl.getOffset()); IProgramElement peNode = new ProgramElement(asm, shadow.toString(), IProgramElement.Kind.CODE, peLoc, 0, null, null); // check to see if the enclosing shadow already has children with the // same name. If so we want to add a counter to the byteCodeName // otherwise // we wont get unique handles int numberOfChildrenWithThisName = 0; for (Iterator it = enclosingNode.getChildren().iterator(); it.hasNext();) { IProgramElement child = (IProgramElement) it.next(); if (child.getName().equals(shadow.toString())) { numberOfChildrenWithThisName++; } } peNode.setBytecodeName(shadowSig.getName() + "!" + String.valueOf(numberOfChildrenWithThisName + 1)); peNode.setBytecodeSignature(shadowSig.getSignature()); enclosingNode.addChild(peNode); return peNode; } private static IProgramElement lookupMember(IHierarchy model, UnresolvedType declaringType, Member member) { IProgramElement typeElement = model.findElementForType(declaringType.getPackageName(), declaringType.getClassName()); if (typeElement == null) { return null; } for (Iterator it = typeElement.getChildren().iterator(); it.hasNext();) { IProgramElement element = (IProgramElement) it.next(); if (member.getName().equals(element.getBytecodeName()) && member.getSignature().equals(element.getBytecodeSignature())) { return element; } } // if we can't find the member, we'll just put it in the class return typeElement; } /** * Add a relationship for a matching declare annotation method or declare annotation constructor. Locating the method is a messy * (for messy read 'fragile') bit of code that could break at any moment but it's working for my simple testcase. */ public static void addDeclareAnnotationMethodRelationship(ISourceLocation sourceLocation, String affectedTypeName, ResolvedMember affectedMethod, AsmManager model) { if (model == null) { return; } String pkg = null; String type = affectedTypeName; int packageSeparator = affectedTypeName.lastIndexOf("."); if (packageSeparator != -1) { pkg = affectedTypeName.substring(0, packageSeparator); type = affectedTypeName.substring(packageSeparator + 1); } IHierarchy hierarchy = model.getHierarchy(); IProgramElement typeElem = hierarchy.findElementForType(pkg, type); if (typeElem == null) return; StringBuffer parmString = new StringBuffer("("); UnresolvedType[] args = affectedMethod.getParameterTypes(); // Type[] args = method.getArgumentTypes(); for (int i = 0; i < args.length; i++) { String s = args[i].getName();// Utility.signatureToString(args[i]. // getName()getSignature(), false); parmString.append(s); if ((i + 1) < args.length) parmString.append(","); } parmString.append(")"); IProgramElement methodElem = null; if (affectedMethod.getName().startsWith("<init>")) { // its a ctor methodElem = hierarchy.findElementForSignature(typeElem, IProgramElement.Kind.CONSTRUCTOR, type + parmString); if (methodElem == null && args.length == 0) methodElem = typeElem; // assume default ctor } else { // its a method methodElem = hierarchy.findElementForSignature(typeElem, IProgramElement.Kind.METHOD, affectedMethod.getName() + parmString); } if (methodElem == null) return; try { String targetHandle = methodElem.getHandleIdentifier(); if (targetHandle == null) return; IProgramElement sourceNode = hierarchy.findElementForSourceLine(sourceLocation); String sourceHandle = model.getHandleProvider().createHandleIdentifier(sourceNode); if (sourceHandle == null) return; IRelationshipMap mapper = model.getRelationshipMap(); IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATES, false, true); foreward.addTarget(targetHandle); IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATED_BY, false, true); back.addTarget(sourceHandle); } catch (Throwable t) { // I'm worried about that code above, this will // make sure we don't explode if it plays up t.printStackTrace(); // I know I know .. but I don't want to lose // it! } } /** * Add a relationship for a matching declare ATfield. Locating the field is trickier than it might seem since we have no line * number info for it, we have to dig through the structure model under the fields' type in order to locate it. */ public static void addDeclareAnnotationFieldRelationship(AsmManager model, ISourceLocation declareLocation, String affectedTypeName, ResolvedMember affectedFieldName) { if (model == null) { return; } String pkg = null; String type = affectedTypeName; int packageSeparator = affectedTypeName.lastIndexOf("."); if (packageSeparator != -1) { pkg = affectedTypeName.substring(0, packageSeparator); type = affectedTypeName.substring(packageSeparator + 1); } IHierarchy hierarchy = model.getHierarchy(); IProgramElement typeElem = hierarchy.findElementForType(pkg, type); if (typeElem == null) { return; } IProgramElement fieldElem = hierarchy.findElementForSignature(typeElem, IProgramElement.Kind.FIELD, affectedFieldName .getName()); if (fieldElem == null) { return; } String targetHandle = fieldElem.getHandleIdentifier(); if (targetHandle == null) { return; } IProgramElement sourceNode = hierarchy.findElementForSourceLine(declareLocation); String sourceHandle = model.getHandleProvider().createHandleIdentifier(sourceNode); if (sourceHandle == null) { return; } IRelationshipMap relmap = model.getRelationshipMap(); IRelationship foreward = relmap.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATES, false, true); foreward.addTarget(targetHandle); IRelationship back = relmap.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATED_BY, false, true); back.addTarget(sourceHandle); } }
270,033
Bug 270033 [incremental] Incremental compilation with aspects on an incoming classpath/aspectpath
null
resolved fixed
b23cc1a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-03-26T03:15:47Z"
"2009-03-25T22:26:40Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjState.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.io.IOException; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.ajdt.internal.compiler.CompilationResultDestinationManager; import org.aspectj.ajdt.internal.compiler.InterimCompilationResult; import org.aspectj.asm.AsmManager; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.Message; import org.aspectj.bridge.SourceLocation; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader; import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException; import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryAnnotation; import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryField; import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryMethod; import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryType; import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers; import org.aspectj.org.eclipse.jdt.internal.core.builder.ReferenceCollection; import org.aspectj.org.eclipse.jdt.internal.core.builder.StringSet; import org.aspectj.util.FileUtil; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.UnwovenClassFile; /** * Maintains state needed for incremental compilation */ public class AjState implements CompilerConfigurationChangeFlags { // SECRETAPI configures whether we use state instead of lastModTime - see pr245566 public static boolean CHECK_STATE_FIRST = true; // SECRETAPI static so beware of multi-threading bugs... public static IStateListener stateListener = null; public static boolean FORCE_INCREMENTAL_DURING_TESTING = false; private final AjBuildManager buildManager; private boolean couldBeSubsequentIncrementalBuild = false; private INameEnvironment nameEnvironment; // // private IHierarchy structureModel; // private IRelationshipMap relmap; private AsmManager structureModel; /** * When looking at changes on the classpath, this set accumulates files in our state instance that affected by those changes. * Then if we can do an incremental build - these must be compiled. */ private final Set affectedFiles = new HashSet(); private long lastSuccessfulFullBuildTime = -1; private final Hashtable /* File, long */structuralChangesSinceLastFullBuild = new Hashtable(); private long lastSuccessfulBuildTime = -1; private long currentBuildTime = -1; private AjBuildConfig buildConfig; private boolean batchBuildRequiredThisTime = false; /** * Keeps a list of (FQN,Filename) pairs (as ClassFile objects) for types that resulted from the compilation of the given File. * Note :- the ClassFile objects contain no byte code, they are simply a Filename,typename pair. * * Populated in noteResult and used in addDependentsOf(File) * * Added by AMC during state refactoring, 1Q06. */ private final Map/* <File, List<ClassFile> */fullyQualifiedTypeNamesResultingFromCompilationUnit = new HashMap(); /** * Source files defining aspects * * Populated in noteResult and used in processDeletedFiles * * Added by AMC during state refactoring, 1Q06. */ private final Set/* <File> */sourceFilesDefiningAspects = new HashSet(); /** * Populated in noteResult to record the set of types that should be recompiled if the given file is modified or deleted. * * Refered to during addAffectedSourceFiles when calculating incremental compilation set. */ private final Map/* <File, ReferenceCollection> */references = new HashMap(); /** * Holds UnwovenClassFiles (byte[]s) originating from the given file source. This could be a jar file, a directory, or an * individual .class file. This is an *expensive* map. It is cleared immediately following a batch build, and the cheaper * inputClassFilesBySource map is kept for processing of any subsequent incremental builds. * * Populated during AjBuildManager.initBcelWorld(). * * Passed into AjCompiler adapter as the set of binary input files to reweave if the weaver determines a full weave is required. * * Cleared during initBcelWorld prior to repopulation. * * Used when a file is deleted during incremental compilation to delete all of the class files in the output directory that * resulted from the weaving of File. * * Used during getBinaryFilesToCompile when compiling incrementally to determine which files should be recompiled if a given * input file has changed. * */ private Map/* File, List<UnwovenClassFile> */binarySourceFiles = new HashMap(); /** * Initially a duplicate of the information held in binarySourceFiles, with the key difference that the values are ClassFiles * (type name, File) not UnwovenClassFiles (which also have all the byte code in them). After a batch build, binarySourceFiles * is cleared, leaving just this much lighter weight map to use in processing subsequent incremental builds. */ private final Map/* <File,List<ClassFile> */inputClassFilesBySource = new HashMap(); /** * A list of the .class files created by this state that contain aspects. */ private final List/* <String> */aspectClassFiles = new ArrayList(); /** * Holds structure information on types as they were at the end of the last build. It would be nice to get rid of this too, but * can't see an easy way to do that right now. */ private final Map/* FQN,CompactStructureRepresentation */resolvedTypeStructuresFromLastBuild = new HashMap(); /** * Populated in noteResult to record the set of UnwovenClassFiles (intermediate results) that originated from compilation of the * class with the given fully-qualified name. * * Used in removeAllResultsOfLastBuild to remove .class files from output directory. * * Passed into StatefulNameEnvironment during incremental compilation to support findType lookups. */ private final Map/* <String, File> */classesFromName = new HashMap(); /** * Populated by AjBuildManager to record the aspects with the file name in which they're contained. This is later used when * writing the outxml file in AjBuildManager. Need to record the file name because want to write an outxml file for each of the * output directories and in order to ask the OutputLocationManager for the output location for a given aspect we need the file * in which it is contained. */ private Map /* <String, char[]> */aspectsFromFileNames; private Set/* File */compiledSourceFiles = new HashSet(); private final Map/* String,File sourcelocation */resources = new HashMap(); // these are references created on a particular compile run - when looping round in // addAffectedSourceFiles(), if some have been created then we look at which source files // touch upon those and get them recompiled. private StringSet qualifiedStrings = new StringSet(3); private StringSet simpleStrings = new StringSet(3); private Set addedFiles; private Set deletedFiles; private Set /* BinarySourceFile */addedBinaryFiles; private Set /* BinarySourceFile */deletedBinaryFiles; private BcelWeaver weaver; private BcelWorld world; public AjState(AjBuildManager buildManager) { this.buildManager = buildManager; } public void setCouldBeSubsequentIncrementalBuild(boolean yesThereCould) { this.couldBeSubsequentIncrementalBuild = yesThereCould; } void successfulCompile(AjBuildConfig config, boolean wasFullBuild) { buildConfig = config; lastSuccessfulBuildTime = currentBuildTime; if (stateListener != null) stateListener.buildSuccessful(wasFullBuild); if (wasFullBuild) lastSuccessfulFullBuildTime = currentBuildTime; } /** * Returns false if a batch build is needed. */ public boolean prepareForNextBuild(AjBuildConfig newBuildConfig) { currentBuildTime = System.currentTimeMillis(); if (!maybeIncremental()) { if (listenerDefined()) getListener().recordDecision( "Preparing for build: not going to be incremental because either not in AJDT or incremental deactivated"); return false; } if (this.batchBuildRequiredThisTime) { this.batchBuildRequiredThisTime = false; if (listenerDefined()) getListener().recordDecision( "Preparing for build: not going to be incremental this time because batch build explicitly forced"); return false; } if (lastSuccessfulBuildTime == -1 || buildConfig == null) { structuralChangesSinceLastFullBuild.clear(); if (listenerDefined()) getListener().recordDecision( "Preparing for build: not going to be incremental because no successful previous full build"); return false; } // we don't support incremental with an outjar yet if (newBuildConfig.getOutputJar() != null) { structuralChangesSinceLastFullBuild.clear(); if (listenerDefined()) getListener().recordDecision("Preparing for build: not going to be incremental because outjar being used"); return false; } affectedFiles.clear(); // we can't do an incremental build if one of our paths // has changed, or a jar on a path has been modified if (pathChange(buildConfig, newBuildConfig)) { // last time we built, .class files and resource files from jars on the // inpath will have been copied to the output directory. // these all need to be deleted in preparation for the clean build that is // coming - otherwise a file that has been deleted from an inpath jar // since the last build will not be deleted from the output directory. removeAllResultsOfLastBuild(); if (stateListener != null) { stateListener.pathChangeDetected(); } structuralChangesSinceLastFullBuild.clear(); if (listenerDefined()) getListener() .recordDecision( "Preparing for build: not going to be incremental because path change detected (one of classpath/aspectpath/inpath/injars)"); return false; } if (simpleStrings.elementSize > 20) { simpleStrings = new StringSet(3); } else { simpleStrings.clear(); } if (qualifiedStrings.elementSize > 20) { qualifiedStrings = new StringSet(3); } else { qualifiedStrings.clear(); } if ((newBuildConfig.getChanged() & PROJECTSOURCEFILES_CHANGED) == 0) { addedFiles = Collections.EMPTY_SET; deletedFiles = Collections.EMPTY_SET; } else { Set oldFiles = new HashSet(buildConfig.getFiles()); Set newFiles = new HashSet(newBuildConfig.getFiles()); addedFiles = new HashSet(newFiles); addedFiles.removeAll(oldFiles); deletedFiles = new HashSet(oldFiles); deletedFiles.removeAll(newFiles); } Set oldBinaryFiles = new HashSet(buildConfig.getBinaryFiles()); Set newBinaryFiles = new HashSet(newBuildConfig.getBinaryFiles()); addedBinaryFiles = new HashSet(newBinaryFiles); addedBinaryFiles.removeAll(oldBinaryFiles); deletedBinaryFiles = new HashSet(oldBinaryFiles); deletedBinaryFiles.removeAll(newBinaryFiles); boolean couldStillBeIncremental = processDeletedFiles(deletedFiles); if (!couldStillBeIncremental) { if (listenerDefined()) getListener().recordDecision("Preparing for build: not going to be incremental because an aspect was deleted"); return false; } if (listenerDefined()) getListener().recordDecision("Preparing for build: planning to be an incremental build"); return true; } /** * Checks if any of the files in the set passed in contains an aspect declaration. If one is found then we start the process of * batch building, i.e. we remove all the results of the last build, call any registered listener to tell them whats happened * and return false. * * @return false if we discovered an aspect declaration */ private boolean processDeletedFiles(Set deletedFiles) { for (Iterator iter = deletedFiles.iterator(); iter.hasNext();) { File aDeletedFile = (File) iter.next(); if (this.sourceFilesDefiningAspects.contains(aDeletedFile)) { removeAllResultsOfLastBuild(); if (stateListener != null) { stateListener.detectedAspectDeleted(aDeletedFile); } return false; } List/* ClassFile */classes = (List) fullyQualifiedTypeNamesResultingFromCompilationUnit.get(aDeletedFile); if (classes != null) { for (Iterator iterator = classes.iterator(); iterator.hasNext();) { ClassFile element = (ClassFile) iterator.next(); resolvedTypeStructuresFromLastBuild.remove(element.fullyQualifiedTypeName); } } } return true; } private Collection getModifiedFiles() { return getModifiedFiles(lastSuccessfulBuildTime); } Collection getModifiedFiles(long lastBuildTime) { Set ret = new HashSet(); // Check if the build configuration knows what files have changed... List/* File */modifiedFiles = buildConfig.getModifiedFiles(); if (modifiedFiles == null) { // do not know, so need to go looking // not our job to account for new and deleted files for (Iterator i = buildConfig.getFiles().iterator(); i.hasNext();) { File file = (File) i.next(); if (!file.exists()) continue; long modTime = file.lastModified(); // System.out.println("check: " + file + " mod " + modTime + " build " + lastBuildTime); // need to add 1000 since lastModTime is only accurate to a second on some (all?) platforms if (modTime + 1000 > lastBuildTime) { ret.add(file); } } } else { ret.addAll(modifiedFiles); } ret.addAll(affectedFiles); return ret; } private Collection getModifiedBinaryFiles() { return getModifiedBinaryFiles(lastSuccessfulBuildTime); } Collection getModifiedBinaryFiles(long lastBuildTime) { List ret = new ArrayList(); // not our job to account for new and deleted files for (Iterator i = buildConfig.getBinaryFiles().iterator(); i.hasNext();) { AjBuildConfig.BinarySourceFile bsfile = (AjBuildConfig.BinarySourceFile) i.next(); File file = bsfile.binSrc; if (!file.exists()) continue; long modTime = file.lastModified(); // System.out.println("check: " + file + " mod " + modTime + " build " + lastBuildTime); // need to add 1000 since lastModTime is only accurate to a second on some (all?) platforms if (modTime + 1000 >= lastBuildTime) { ret.add(bsfile); } } return ret; } private static int CLASS_FILE_NO_CHANGES = 0; private static int CLASS_FILE_CHANGED_THAT_NEEDS_INCREMENTAL_BUILD = 1; private static int CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD = 2; private static int MAX_AFFECTED_FILES_BEFORE_FULL_BUILD = 30; public static final FileFilter classFileFilter = new FileFilter() { public boolean accept(File pathname) { return pathname.getName().endsWith(".class"); } }; /** * Analyse .class files in the directory specified, if they have changed since the last successful build then see if we can * determine which source files in our project depend on the change. If we can then we can still do an incremental build, if we * can't then we have to do a full build. * */ private int classFileChangedInDirSinceLastBuildRequiringFullBuild(File dir) { if (!dir.isDirectory()) { return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD; } // Are we managing that output directory? AjState state = IncrementalStateManager.findStateManagingOutputLocation(dir); if (listenerDefined()) { if (state != null) { getListener().recordDecision("Found state instance managing output location : " + dir); } else { getListener().recordDecision("Failed to find a state instance managing output location : " + dir); } } // pr268827 - this guard will cause us to exit quickly if the state says there really is // nothing of interest. This will not catch the case where a user modifies the .class files outside of // eclipse because the state will not be aware of it. But that seems an unlikely scenario and // we are paying a heavy price to check it if (state != null && !state.hasAnyStructuralChangesSince(lastSuccessfulBuildTime)) { if (listenerDefined()) { getListener().recordDecision("No reported changes in that state"); } return CLASS_FILE_NO_CHANGES; } if (state == null) { // This may be because the directory is the output path of a Java project upon which we depend // we need to call back into AJDT to ask about that projects state. CompilationResultDestinationManager crdm = buildConfig.getCompilationResultDestinationManager(); if (crdm!=null) { int i = crdm.discoverChangesSince(dir,lastSuccessfulBuildTime); // 0 = dontknow if it has changed // 1 = definetly not changed at all // further numbers can determine more granular changes if (i==1) { if (listenerDefined()) { getListener().recordDecision("'"+dir+"' is apparently unchanged so not performing timestamp check"); } return CLASS_FILE_NO_CHANGES; } } } List classFiles = FileUtil.listClassFiles(dir); for (Iterator iterator = classFiles.iterator(); iterator.hasNext();) { File classFile = (File) iterator.next(); if (CHECK_STATE_FIRST && state != null) { if (state.isAspect(classFile)) { return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD; } if (state.hasStructuralChangedSince(classFile, lastSuccessfulBuildTime)) { if (listenerDefined()) { getListener().recordDecision("Structural change detected in : " + classFile); } if (isTypeWeReferTo(classFile)) { if (affectedFiles.size() > MAX_AFFECTED_FILES_BEFORE_FULL_BUILD) return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD; } // } else { // if (listenerDefined()) // getListener().recordDecision("Change detected in " + classFile + " but it is not structural"); } } else { long modTime = classFile.lastModified(); if ((modTime + 1000) >= lastSuccessfulBuildTime) { // so the class on disk has changed since the last successful build for this state object // BUG? we stop on the first change that leads us to an incremental build, surely we need to continue and look // at all files incase another change means we need to incremental a bit more stuff? // To work out if it is a real change we should ask any state // object managing the output location whether the file has // structurally changed or not if (state != null) { if (state.isAspect(classFile)) { return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD; } if (state.hasStructuralChangedSince(classFile, lastSuccessfulBuildTime)) { if (listenerDefined()) { getListener().recordDecision("Structural change detected in : " + classFile); } if (isTypeWeReferTo(classFile)) { if (affectedFiles.size() > MAX_AFFECTED_FILES_BEFORE_FULL_BUILD) return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD; } } else { if (listenerDefined()) getListener().recordDecision("Change detected in " + classFile + " but it is not structural"); } } else { // No state object to ask, so it only matters if we know which type depends on this file if (isTypeWeReferTo(classFile)) { if (affectedFiles.size() > MAX_AFFECTED_FILES_BEFORE_FULL_BUILD) return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD; return CLASS_FILE_CHANGED_THAT_NEEDS_INCREMENTAL_BUILD; } else { return CLASS_FILE_NO_CHANGES; } } } } } return CLASS_FILE_NO_CHANGES; } private boolean isAspect(File file) { return aspectClassFiles.contains(file.getAbsolutePath()); } public static class SoftHashMap extends AbstractMap { private final Map map; private final ReferenceQueue rq = new ReferenceQueue(); public SoftHashMap(Map map) { this.map = map; } public SoftHashMap() { this(new HashMap()); } public SoftHashMap(Map map, boolean b) { this(map); } class SoftReferenceKnownKey extends SoftReference { private final Object key; SoftReferenceKnownKey(Object k, Object v) { super(v, rq); this.key = k; } } private void processQueue() { SoftReferenceKnownKey sv = null; while ((sv = (SoftReferenceKnownKey) rq.poll()) != null) { map.remove(sv.key); } } public Object get(Object key) { SoftReferenceKnownKey value = (SoftReferenceKnownKey) map.get(key); if (value == null) return null; if (value.get() == null) { // it got GC'd map.remove(value.key); return null; } else { return value.get(); } } public Object put(Object k, Object v) { processQueue(); return map.put(k, new SoftReferenceKnownKey(k, v)); } public Set entrySet() { return map.entrySet(); } public void clear() { processQueue(); map.clear(); } public int size() { processQueue(); return map.size(); } public Object remove(Object k) { processQueue(); SoftReferenceKnownKey value = (SoftReferenceKnownKey) map.remove(k); if (value == null) return null; if (value.get() != null) { return value.get(); } return null; } } SoftHashMap/* <baseDir,SoftHashMap<theFile,className>> */fileToClassNameMap = new SoftHashMap(); /** * If a class file has changed in a path on our classpath, it may not be for a type that any of our source files care about. * This method checks if any of our source files have a dependency on the class in question and if not, we don't consider it an * interesting change. */ private boolean isTypeWeReferTo(File file) { String fpath = file.getAbsolutePath(); int finalSeparator = fpath.lastIndexOf(File.separator); String baseDir = fpath.substring(0, finalSeparator); String theFile = fpath.substring(finalSeparator + 1); SoftHashMap classNames = (SoftHashMap) fileToClassNameMap.get(baseDir); if (classNames == null) { classNames = new SoftHashMap(); fileToClassNameMap.put(baseDir, classNames); } char[] className = (char[]) classNames.get(theFile); if (className == null) { // if (listenerDefined()) // getListener().recordDecision("Cache miss, looking up classname for : " + fpath); ClassFileReader cfr; try { cfr = ClassFileReader.read(file); } catch (ClassFormatException e) { return true; } catch (IOException e) { return true; } className = cfr.getName(); classNames.put(theFile, className); // } else { // if (listenerDefined()) // getListener().recordDecision("Cache hit, looking up classname for : " + fpath); } char[][][] qualifiedNames = null; char[][] simpleNames = null; if (CharOperation.indexOf('/', className) != -1) { qualifiedNames = new char[1][][]; qualifiedNames[0] = CharOperation.splitOn('/', className); qualifiedNames = ReferenceCollection.internQualifiedNames(qualifiedNames); } else { simpleNames = new char[1][]; simpleNames[0] = className; simpleNames = ReferenceCollection.internSimpleNames(simpleNames, true); } for (Iterator i = references.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); ReferenceCollection refs = (ReferenceCollection) entry.getValue(); if (refs != null && refs.includes(qualifiedNames, simpleNames)) { if (listenerDefined()) { getListener().recordDecision( toString() + ": type " + new String(className) + " is depended upon by '" + entry.getKey() + "'"); } affectedFiles.add(entry.getKey()); if (affectedFiles.size() > MAX_AFFECTED_FILES_BEFORE_FULL_BUILD) return true; // return true; } } if (affectedFiles.size() > 0) return true; if (listenerDefined()) getListener().recordDecision(toString() + ": type " + new String(className) + " is not depended upon by this state"); return false; } // /** // * For a given class file, determine which source file it came from. This will only succeed if the class file is from a source // * file within this project. // */ // private File getSourceFileForClassFile(File classfile) { // Set sourceFiles = fullyQualifiedTypeNamesResultingFromCompilationUnit.keySet(); // for (Iterator sourceFileIterator = sourceFiles.iterator(); sourceFileIterator.hasNext();) { // File sourceFile = (File) sourceFileIterator.next(); // List/* ClassFile */classesFromSourceFile = (List/* ClassFile */) fullyQualifiedTypeNamesResultingFromCompilationUnit // .get(sourceFile); // for (int i = 0; i < classesFromSourceFile.size(); i++) { // if (((ClassFile) classesFromSourceFile.get(i)).locationOnDisk.equals(classfile)) // return sourceFile; // } // } // return null; // } public String toString() { StringBuffer sb = new StringBuffer(); // null config means failed build i think as it is only set on successful full build? sb.append("AjState(").append((buildConfig == null ? "NULLCONFIG" : buildConfig.getConfigFile().toString())).append(")"); return sb.toString(); } /** * Determine if a file has changed since a given time, using the local information recorded in the structural changes data * structure. * * @param file the file we are wondering about * @param lastSuccessfulBuildTime the last build time for the state asking the question */ private boolean hasStructuralChangedSince(File file, long lastSuccessfulBuildTime) { // long lastModTime = file.lastModified(); Long l = (Long) structuralChangesSinceLastFullBuild.get(file.getAbsolutePath()); long strucModTime = -1; if (l != null) strucModTime = l.longValue(); else strucModTime = this.lastSuccessfulFullBuildTime; // we now have: // 'strucModTime'-> the last time the class was structurally changed return (strucModTime > lastSuccessfulBuildTime); } /** * Determine if anything has changed since a given time. */ private boolean hasAnyStructuralChangesSince(long lastSuccessfulBuildTime) { Set entries = structuralChangesSinceLastFullBuild.entrySet(); for (Iterator iterator = entries.iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); Long l = (Long) entry.getValue(); if (l != null) { long lvalue = l.longValue(); if (lvalue > lastSuccessfulBuildTime) { if (listenerDefined()) { getListener().recordDecision( "Seems this has changed " + entry.getKey() + "modtime=" + lvalue + " lsbt=" + this.lastSuccessfulFullBuildTime + " incoming check value=" + lastSuccessfulBuildTime); } return true; } } } return (this.lastSuccessfulFullBuildTime > lastSuccessfulBuildTime); } /** * Determine if something has changed on the classpath/inpath/aspectpath and a full build is required rather than an incremental * one. * * @param previousConfig the previous configuration used * @param newConfig the new configuration being used * @return true if full build required */ private boolean pathChange(AjBuildConfig previousConfig, AjBuildConfig newConfig) { int changes = newConfig.getChanged(); if ((changes & (CLASSPATH_CHANGED | ASPECTPATH_CHANGED | INPATH_CHANGED | OUTPUTDESTINATIONS_CHANGED | INJARS_CHANGED)) != 0) { List oldOutputLocs = getOutputLocations(previousConfig); Set alreadyAnalysedPaths = new HashSet(); List oldClasspath = previousConfig.getClasspath(); List newClasspath = newConfig.getClasspath(); if (stateListener != null) stateListener.aboutToCompareClasspaths(oldClasspath, newClasspath); if (classpathChangedAndNeedsFullBuild(oldClasspath, newClasspath, true, oldOutputLocs, alreadyAnalysedPaths)) return true; List oldAspectpath = previousConfig.getAspectpath(); List newAspectpath = newConfig.getAspectpath(); if (changedAndNeedsFullBuild(oldAspectpath, newAspectpath, true, oldOutputLocs, alreadyAnalysedPaths)) return true; List oldInPath = previousConfig.getInpath(); List newInPath = newConfig.getInpath(); if (changedAndNeedsFullBuild(oldInPath, newInPath, false, oldOutputLocs, alreadyAnalysedPaths)) return true; List oldInJars = previousConfig.getInJars(); List newInJars = newConfig.getInJars(); if (changedAndNeedsFullBuild(oldInJars, newInJars, false, oldOutputLocs, alreadyAnalysedPaths)) return true; } else if (newConfig.getClasspathElementsWithModifiedContents() != null) { // Although the classpath entries themselves are the same as before, the contents of one of the // directories on the classpath has changed - rather than go digging around to find it, let's ask // the compiler configuration. This will allow for projects with long classpaths where classpaths // are also capturing project dependencies - when a project we depend on is rebuilt, we can just check // it as a standalone element on our classpath rather than going through them all List/* String */modifiedCpElements = newConfig.getClasspathElementsWithModifiedContents(); for (Iterator iterator = modifiedCpElements.iterator(); iterator.hasNext();) { File cpElement = new File((String) iterator.next()); if (cpElement.exists() && !cpElement.isDirectory()) { if (cpElement.lastModified() > lastSuccessfulBuildTime) { return true; } } else { int classFileChanges = classFileChangedInDirSinceLastBuildRequiringFullBuild(cpElement); if (classFileChanges == CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD) { return true; } } } } return false; } /** * Return a list of the output locations - this includes any 'default' output location and then any known by a registered * CompilationResultDestinationManager. * * @param config the build configuration for which the output locations should be determined * @return a list of file objects */ private List /* File */getOutputLocations(AjBuildConfig config) { List outputLocs = new ArrayList(); // Is there a default location? if (config.getOutputDir() != null) { try { outputLocs.add(config.getOutputDir().getCanonicalFile()); } catch (IOException e) { } } if (config.getCompilationResultDestinationManager() != null) { List dirs = config.getCompilationResultDestinationManager().getAllOutputLocations(); for (Iterator iterator = dirs.iterator(); iterator.hasNext();) { File f = (File) iterator.next(); try { File cf = f.getCanonicalFile(); if (!outputLocs.contains(cf)) { outputLocs.add(cf); } } catch (IOException e) { } } } return outputLocs; } private File getOutputLocationFor(AjBuildConfig config, File aResourceFile) { List outputLocs = new ArrayList(); if (config.getCompilationResultDestinationManager() != null) { File outputLoc = config.getCompilationResultDestinationManager().getOutputLocationForResource(aResourceFile); if (outputLoc != null) return outputLoc; } // Is there a default location? if (config.getOutputDir() != null) { return config.getOutputDir(); } return null; } /** * Check the old and new paths, if they vary by length or individual elements then that is considered a change. Or if the last * modified time of a path entry has changed (or last modified time of a classfile in that path entry has changed) then return * true. The outputlocations are supplied so they can be 'ignored' in the comparison. * * @param oldPath * @param newPath * @param checkClassFiles whether to examine individual class files within directories * @param outputLocs the output locations that should be ignored if they occur on the paths being compared * @return true if a change is detected that requires a full build */ private boolean changedAndNeedsFullBuild(List oldPath, List newPath, boolean checkClassFiles, List outputLocs, Set alreadyAnalysedPaths) { // if (oldPath == null) { // oldPath = new ArrayList(); // } // if (newPath == null) { // newPath = new ArrayList(); // } if (oldPath.size() != newPath.size()) { return true; } for (int i = 0; i < oldPath.size(); i++) { if (!oldPath.get(i).equals(newPath.get(i))) { return true; } Object o = oldPath.get(i); // String on classpath, File on other paths File f = null; if (o instanceof String) { f = new File((String) o); } else { f = (File) o; } if (f.exists() && !f.isDirectory() && (f.lastModified() >= lastSuccessfulBuildTime)) { return true; } if (checkClassFiles && f.exists() && f.isDirectory()) { // We should use here a list/set of directories we know have or have not changed - some kind of // List<File> buildConfig.getClasspathEntriesWithChangedContents() // and then only proceed to look inside directories if it is one of these, ignoring others - // that should save a massive amount of processing for incremental builds in a multi project scenario boolean foundMatch = false; for (Iterator iterator = outputLocs.iterator(); !foundMatch && iterator.hasNext();) { File dir = (File) iterator.next(); if (f.equals(dir)) { foundMatch = true; } } if (!foundMatch) { if (!alreadyAnalysedPaths.contains(f.getAbsolutePath())) { // Do not check paths more than once alreadyAnalysedPaths.add(f.getAbsolutePath()); int classFileChanges = classFileChangedInDirSinceLastBuildRequiringFullBuild(f); if (classFileChanges == CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD) return true; } } } } return false; } /** * Check the old and new paths, if they vary by length or individual elements then that is considered a change. Or if the last * modified time of a path entry has changed (or last modified time of a classfile in that path entry has changed) then return * true. The outputlocations are supplied so they can be 'ignored' in the comparison. * * @param oldPath * @param newPath * @param checkClassFiles whether to examine individual class files within directories * @param outputLocs the output locations that should be ignored if they occur on the paths being compared * @return true if a change is detected that requires a full build */ private boolean classpathChangedAndNeedsFullBuild(List oldPath, List newPath, boolean checkClassFiles, List outputLocs, Set alreadyAnalysedPaths) { // if (oldPath == null) { // oldPath = new ArrayList(); // } // if (newPath == null) { // newPath = new ArrayList(); // } if (oldPath.size() != newPath.size()) { return true; } for (int i = 0; i < oldPath.size(); i++) { if (!oldPath.get(i).equals(newPath.get(i))) { return true; } File f = new File((String) oldPath.get(i)); if (f.exists() && !f.isDirectory() && (f.lastModified() >= lastSuccessfulBuildTime)) { return true; } if (checkClassFiles && f.exists() && f.isDirectory()) { // We should use here a list/set of directories we know have or have not changed - some kind of // List<File> buildConfig.getClasspathEntriesWithChangedContents() // and then only proceed to look inside directories if it is one of these, ignoring others - // that should save a massive amount of processing for incremental builds in a multi project scenario boolean foundMatch = false; for (Iterator iterator = outputLocs.iterator(); !foundMatch && iterator.hasNext();) { File dir = (File) iterator.next(); if (f.equals(dir)) { foundMatch = true; } } if (!foundMatch) { if (!alreadyAnalysedPaths.contains(f.getAbsolutePath())) { // Do not check paths more than once alreadyAnalysedPaths.add(f.getAbsolutePath()); int classFileChanges = classFileChangedInDirSinceLastBuildRequiringFullBuild(f); if (classFileChanges == CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD) return true; } } } } return false; } public Set getFilesToCompile(boolean firstPass) { Set thisTime = new HashSet(); if (firstPass) { compiledSourceFiles = new HashSet(); Collection modifiedFiles = getModifiedFiles(); // System.out.println("modified: " + modifiedFiles); thisTime.addAll(modifiedFiles); // ??? eclipse IncrementalImageBuilder appears to do this // for (Iterator i = modifiedFiles.iterator(); i.hasNext();) { // File file = (File) i.next(); // addDependentsOf(file); // } if (addedFiles != null) { for (Iterator fIter = addedFiles.iterator(); fIter.hasNext();) { Object o = fIter.next(); if (!thisTime.contains(o)) thisTime.add(o); } // thisTime.addAll(addedFiles); } deleteClassFiles(); // Do not delete resources on incremental build, AJDT will handle // copying updates to the output folder. AspectJ only does a copy // of them on full build (see copyResourcesToDestination() call // in AjBuildManager) // deleteResources(); addAffectedSourceFiles(thisTime, thisTime); } else { addAffectedSourceFiles(thisTime, compiledSourceFiles); } compiledSourceFiles = thisTime; return thisTime; } private boolean maybeIncremental() { return (FORCE_INCREMENTAL_DURING_TESTING || this.couldBeSubsequentIncrementalBuild); } public Map /* String -> List<ucf> */getBinaryFilesToCompile(boolean firstTime) { if (lastSuccessfulBuildTime == -1 || buildConfig == null || !maybeIncremental()) { return binarySourceFiles; } // else incremental... Map toWeave = new HashMap(); if (firstTime) { List addedOrModified = new ArrayList(); addedOrModified.addAll(addedBinaryFiles); addedOrModified.addAll(getModifiedBinaryFiles()); for (Iterator iter = addedOrModified.iterator(); iter.hasNext();) { AjBuildConfig.BinarySourceFile bsf = (AjBuildConfig.BinarySourceFile) iter.next(); UnwovenClassFile ucf = createUnwovenClassFile(bsf); if (ucf == null) continue; List ucfs = new ArrayList(); ucfs.add(ucf); recordTypeChanged(ucf.getClassName()); binarySourceFiles.put(bsf.binSrc.getPath(), ucfs); List cfs = new ArrayList(1); cfs.add(getClassFileFor(ucf)); this.inputClassFilesBySource.put(bsf.binSrc.getPath(), cfs); toWeave.put(bsf.binSrc.getPath(), ucfs); } deleteBinaryClassFiles(); } else { // return empty set... we've already done our bit. } return toWeave; } /** * Called when a path change is about to trigger a full build, but we haven't cleaned up from the last incremental build... */ private void removeAllResultsOfLastBuild() { // remove all binarySourceFiles, and all classesFromName... for (Iterator iter = this.inputClassFilesBySource.values().iterator(); iter.hasNext();) { List cfs = (List) iter.next(); for (Iterator iterator = cfs.iterator(); iterator.hasNext();) { ClassFile cf = (ClassFile) iterator.next(); cf.deleteFromFileSystem(buildConfig); } } for (Iterator iterator = classesFromName.values().iterator(); iterator.hasNext();) { File f = (File) iterator.next(); new ClassFile("", f).deleteFromFileSystem(buildConfig); } Set resourceEntries = resources.entrySet(); for (Iterator iter = resourceEntries.iterator(); iter.hasNext();) { Map.Entry resourcePair = (Map.Entry) iter.next(); File sourcePath = (File) resourcePair.getValue(); File outputLoc = getOutputLocationFor(buildConfig, sourcePath); if (outputLoc != null) { outputLoc = new File(outputLoc, (String) resourcePair.getKey()); if (!outputLoc.getPath().equals(sourcePath.getPath()) && outputLoc.exists()) { outputLoc.delete(); if (buildConfig.getCompilationResultDestinationManager() != null) { buildConfig.getCompilationResultDestinationManager().reportFileRemove(outputLoc.getPath(), CompilationResultDestinationManager.FILETYPE_RESOURCE); } } } } } private void deleteClassFiles() { if (deletedFiles == null) { return; } for (Iterator i = deletedFiles.iterator(); i.hasNext();) { File deletedFile = (File) i.next(); addDependentsOf(deletedFile); List cfs = (List) this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(deletedFile); this.fullyQualifiedTypeNamesResultingFromCompilationUnit.remove(deletedFile); if (cfs != null) { for (Iterator iter = cfs.iterator(); iter.hasNext();) { ClassFile cf = (ClassFile) iter.next(); deleteClassFile(cf); } } } } private void deleteBinaryClassFiles() { // range of bsf is ucfs, domain is files (.class and jars) in inpath/jars for (Iterator iter = deletedBinaryFiles.iterator(); iter.hasNext();) { AjBuildConfig.BinarySourceFile deletedFile = (AjBuildConfig.BinarySourceFile) iter.next(); List cfs = (List) this.inputClassFilesBySource.get(deletedFile.binSrc.getPath()); for (Iterator iterator = cfs.iterator(); iterator.hasNext();) { deleteClassFile((ClassFile) iterator.next()); } this.inputClassFilesBySource.remove(deletedFile.binSrc.getPath()); } } // private void deleteResources() { // List oldResources = new ArrayList(); // oldResources.addAll(resources); // // // note - this deliberately ignores resources in jars as we don't yet handle jar changes // // with incremental compilation // for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext();) { // File inPathElement = (File) i.next(); // if (inPathElement.isDirectory() && AjBuildManager.COPY_INPATH_DIR_RESOURCES) { // deleteResourcesFromDirectory(inPathElement, oldResources); // } // } // // if (buildConfig.getSourcePathResources() != null) { // for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext();) { // String resource = (String) i.next(); // maybeDeleteResource(resource, oldResources); // } // } // // // oldResources need to be deleted... // for (Iterator iter = oldResources.iterator(); iter.hasNext();) { // String victim = (String) iter.next(); // List outputDirs = getOutputLocations(buildConfig); // for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) { // File dir = (File) iterator.next(); // File f = new File(dir, victim); // if (f.exists()) { // f.delete(); // } // resources.remove(victim); // } // } // } // private void maybeDeleteResource(String resName, List oldResources) { // if (resources.contains(resName)) { // oldResources.remove(resName); // List outputDirs = getOutputLocations(buildConfig); // for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) { // File dir = (File) iterator.next(); // File source = new File(dir, resName); // if (source.exists() && (source.lastModified() >= lastSuccessfulBuildTime)) { // resources.remove(resName); // will ensure it is re-copied // } // } // } // } // private void deleteResourcesFromDirectory(File dir, List oldResources) { // File[] files = FileUtil.listFiles(dir, new FileFilter() { // public boolean accept(File f) { // boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")); // return accept; // } // }); // // // For each file, add it either as a real .class file or as a resource // for (int i = 0; i < files.length; i++) { // // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // // or we are in trouble... // String filename = null; // try { // filename = files[i].getCanonicalPath().substring(dir.getCanonicalPath().length() + 1); // } catch (IOException e) { // // we are in trouble if this happens... // IMessage msg = new Message("call to getCanonicalPath() failed for file " + files[i] + " with: " + e.getMessage(), // new SourceLocation(files[i], 0), false); // buildManager.handler.handleMessage(msg); // filename = files[i].getAbsolutePath().substring(dir.getAbsolutePath().length() + 1); // } // // maybeDeleteResource(filename, oldResources); // } // } private void deleteClassFile(ClassFile cf) { classesFromName.remove(cf.fullyQualifiedTypeName); weaver.deleteClassFile(cf.fullyQualifiedTypeName); cf.deleteFromFileSystem(buildConfig); } private UnwovenClassFile createUnwovenClassFile(AjBuildConfig.BinarySourceFile bsf) { UnwovenClassFile ucf = null; try { File outputDir = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { // createUnwovenClassFile is called only for classes that are on the inpath, // all inpath classes are put in the defaultOutputLocation, therefore, // this is the output dir outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation(); } ucf = weaver.addClassFile(bsf.binSrc, bsf.fromInPathDirectory, outputDir); } catch (IOException ex) { IMessage msg = new Message("can't read class file " + bsf.binSrc.getPath(), new SourceLocation(bsf.binSrc, 0), false); buildManager.handler.handleMessage(msg); } return ucf; } public void noteResult(InterimCompilationResult result) { if (!maybeIncremental()) { return; } File sourceFile = new File(result.fileName()); CompilationResult cr = result.result(); references.put(sourceFile, new ReferenceCollection(cr.qualifiedReferences, cr.simpleNameReferences)); UnwovenClassFile[] unwovenClassFiles = result.unwovenClassFiles(); for (int i = 0; i < unwovenClassFiles.length; i++) { File lastTimeRound = (File) classesFromName.get(unwovenClassFiles[i].getClassName()); recordClassFile(unwovenClassFiles[i], lastTimeRound); classesFromName.put(unwovenClassFiles[i].getClassName(), new File(unwovenClassFiles[i].getFilename())); } // need to do this before types are deleted from the World... recordWhetherCompilationUnitDefinedAspect(sourceFile, cr); deleteTypesThatWereInThisCompilationUnitLastTimeRoundButHaveBeenDeletedInThisIncrement(sourceFile, unwovenClassFiles); recordFQNsResultingFromCompilationUnit(sourceFile, result); } public void noteNewResult(CompilationResult cr) { // if (!maybeIncremental()) { // return; // } // // // File sourceFile = new File(result.fileName()); // // CompilationResult cr = result.result(); // if (new String(cr.getFileName()).indexOf("C") != -1) { // cr.references.put(new String(cr.getFileName()), // new ReferenceCollection(cr.qualifiedReferences, cr.simpleNameReferences)); // int stop = 1; // } // references.put(sourceFile, new ReferenceCollection(cr.qualifiedReferences, cr.simpleNameReferences)); // // UnwovenClassFile[] unwovenClassFiles = cr.unwovenClassFiles(); // for (int i = 0; i < unwovenClassFiles.length; i++) { // File lastTimeRound = (File) classesFromName.get(unwovenClassFiles[i].getClassName()); // recordClassFile(unwovenClassFiles[i], lastTimeRound); // classesFromName.put(unwovenClassFiles[i].getClassName(), new File(unwovenClassFiles[i].getFilename())); // } // need to do this before types are deleted from the World... // recordWhetherCompilationUnitDefinedAspect(sourceFile, cr); // deleteTypesThatWereInThisCompilationUnitLastTimeRoundButHaveBeenDeletedInThisIncrement(sourceFile, unwovenClassFiles); // // recordFQNsResultingFromCompilationUnit(sourceFile, result); } /** * @param sourceFile * @param unwovenClassFiles */ private void deleteTypesThatWereInThisCompilationUnitLastTimeRoundButHaveBeenDeletedInThisIncrement(File sourceFile, UnwovenClassFile[] unwovenClassFiles) { List classFiles = (List) this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(sourceFile); if (classFiles != null) { for (int i = 0; i < unwovenClassFiles.length; i++) { // deleting also deletes types from the weaver... don't do this if they are // still present this time around... removeFromClassFilesIfPresent(unwovenClassFiles[i].getClassName(), classFiles); } for (Iterator iter = classFiles.iterator(); iter.hasNext();) { ClassFile cf = (ClassFile) iter.next(); deleteClassFile(cf); } } } private void removeFromClassFilesIfPresent(String className, List classFiles) { ClassFile victim = null; for (Iterator iter = classFiles.iterator(); iter.hasNext();) { ClassFile cf = (ClassFile) iter.next(); if (cf.fullyQualifiedTypeName.equals(className)) { victim = cf; break; } } if (victim != null) { classFiles.remove(victim); } } /** * Record the fully-qualified names of the types that were declared in the given source file. * * @param sourceFile, the compilation unit * @param icr, the CompilationResult from compiling it */ private void recordFQNsResultingFromCompilationUnit(File sourceFile, InterimCompilationResult icr) { List classFiles = new ArrayList(); UnwovenClassFile[] types = icr.unwovenClassFiles(); for (int i = 0; i < types.length; i++) { classFiles.add(new ClassFile(types[i].getClassName(), new File(types[i].getFilename()))); } this.fullyQualifiedTypeNamesResultingFromCompilationUnit.put(sourceFile, classFiles); } /** * If this compilation unit defined an aspect, we need to know in case it is modified in a future increment. * * @param sourceFile * @param cr */ private void recordWhetherCompilationUnitDefinedAspect(File sourceFile, CompilationResult cr) { this.sourceFilesDefiningAspects.remove(sourceFile); if (cr != null) { Map compiledTypes = cr.compiledTypes; if (compiledTypes != null) { for (Iterator iterator = compiledTypes.keySet().iterator(); iterator.hasNext();) { char[] className = (char[]) iterator.next(); String typeName = new String(className).replace('/', '.'); if (typeName.indexOf(BcelWeaver.SYNTHETIC_CLASS_POSTFIX) == -1) { ResolvedType rt = world.resolve(typeName); if (rt.isMissing()) { // This can happen in a case where another problem has occurred that prevented it being // correctly added to the world. Eg. pr148285. Duplicate types // throw new IllegalStateException("Type '" + rt.getSignature() + "' not found in world!"); } else if (rt.isAspect()) { this.sourceFilesDefiningAspects.add(sourceFile); break; } } } } } } // private UnwovenClassFile removeFromPreviousIfPresent(UnwovenClassFile cf, InterimCompilationResult previous) { // if (previous == null) // return null; // UnwovenClassFile[] unwovenClassFiles = previous.unwovenClassFiles(); // for (int i = 0; i < unwovenClassFiles.length; i++) { // UnwovenClassFile candidate = unwovenClassFiles[i]; // if ((candidate != null) && candidate.getFilename().equals(cf.getFilename())) { // unwovenClassFiles[i] = null; // return candidate; // } // } // return null; // } private void recordClassFile(UnwovenClassFile thisTime, File lastTime) { if (simpleStrings == null) { // batch build // record resolved type for structural comparisions in future increments // this records a second reference to a structure already held in memory // by the world. ResolvedType rType = world.resolve(thisTime.getClassName()); if (!rType.isMissing()) { try { ClassFileReader reader = new ClassFileReader(thisTime.getBytes(), null); this.resolvedTypeStructuresFromLastBuild.put(thisTime.getClassName(), new CompactTypeStructureRepresentation( reader)); } catch (ClassFormatException cfe) { throw new BCException("Unexpected problem processing class", cfe); } } return; } CompactTypeStructureRepresentation existingStructure = (CompactTypeStructureRepresentation) this.resolvedTypeStructuresFromLastBuild .get(thisTime.getClassName()); ResolvedType newResolvedType = world.resolve(thisTime.getClassName()); if (!newResolvedType.isMissing()) { try { ClassFileReader reader = new ClassFileReader(thisTime.getBytes(), null); this.resolvedTypeStructuresFromLastBuild.put(thisTime.getClassName(), new CompactTypeStructureRepresentation(reader)); } catch (ClassFormatException cfe) { throw new BCException("Unexpected problem processing class", cfe); } } if (lastTime == null) { recordTypeChanged(thisTime.getClassName()); return; } if (newResolvedType.isMissing()) { return; } world.ensureAdvancedConfigurationProcessed(); byte[] newBytes = thisTime.getBytes(); try { ClassFileReader reader = new ClassFileReader(newBytes, lastTime.getAbsolutePath().toCharArray()); // ignore local types since they're only visible inside a single method if (!(reader.isLocal() || reader.isAnonymous())) { if (hasStructuralChanges(reader, existingStructure)) { if (world.forDEBUG_structuralChangesCode) System.err.println("Detected a structural change in " + thisTime.getFilename()); structuralChangesSinceLastFullBuild.put(thisTime.getFilename(), new Long(currentBuildTime)); recordTypeChanged(new String(reader.getName()).replace('/', '.')); } } } catch (ClassFormatException e) { recordTypeChanged(thisTime.getClassName()); } } private static final char[][] EMPTY_CHAR_ARRAY = new char[0][]; /** * Compare the class structure of the new intermediate (unwoven) class with the existingResolvedType of the same class that we * have in the world, looking for any structural differences (and ignoring aj members resulting from weaving....) * * Some notes from Andy... lot of problems here, which I've eventually resolved by building the compactstructure based on a * classfilereader, rather than on a ResolvedType. There are accessors for inner types and funky fields that the compiler * creates to support the language - for non-static inner types it also mangles ctors to be prefixed with an instance of the * surrounding type. * * Warning : long but boring method implementation... * * @param reader * @param existingType * @return */ private boolean hasStructuralChanges(ClassFileReader reader, CompactTypeStructureRepresentation existingType) { if (existingType == null) { return true; } // modifiers if (!modifiersEqual(reader.getModifiers(), existingType.modifiers)) { return true; } // generic signature if (!CharOperation.equals(reader.getGenericSignature(), existingType.genericSignature)) { return true; } // superclass name if (!CharOperation.equals(reader.getSuperclassName(), existingType.superclassName)) { return true; } // have annotations changed on the type? IBinaryAnnotation[] newAnnos = reader.getAnnotations(); if (newAnnos == null || newAnnos.length == 0) { if (existingType.annotations != null && existingType.annotations.length != 0) { return true; } } else { IBinaryAnnotation[] existingAnnos = existingType.annotations; if (existingAnnos == null || existingAnnos.length != newAnnos.length) { return true; } // Does not allow for an order switch // Does not cope with a change in values set on the annotation (hard to create a testcase where this is a problem tho) for (int i = 0; i < newAnnos.length; i++) { if (!CharOperation.equals(newAnnos[i].getTypeName(), existingAnnos[i].getTypeName())) { return true; } } } // interfaces char[][] existingIfs = existingType.interfaces; char[][] newIfsAsChars = reader.getInterfaceNames(); if (newIfsAsChars == null) { newIfsAsChars = EMPTY_CHAR_ARRAY; } // damn I'm lazy... if (existingIfs == null) { existingIfs = EMPTY_CHAR_ARRAY; } if (existingIfs.length != newIfsAsChars.length) return true; new_interface_loop: for (int i = 0; i < newIfsAsChars.length; i++) { for (int j = 0; j < existingIfs.length; j++) { if (CharOperation.equals(existingIfs[j], newIfsAsChars[i])) { continue new_interface_loop; } } return true; } // fields // CompactMemberStructureRepresentation[] existingFields = existingType.fields; IBinaryField[] newFields = reader.getFields(); if (newFields == null) { newFields = CompactTypeStructureRepresentation.NoField; } // all redundant for now ... could be an optimization at some point... // remove any ajc$XXX fields from those we compare with // the existing fields - bug 129163 // List nonGenFields = new ArrayList(); // for (int i = 0; i < newFields.length; i++) { // IBinaryField field = newFields[i]; // //if (!CharOperation.prefixEquals(NameMangler.AJC_DOLLAR_PREFIX,field.getName())) { // this would skip ajc$ fields // //if ((field.getModifiers()&0x1000)==0) // 0x1000 => synthetic - this will skip synthetic fields (eg. this$0) // nonGenFields.add(field); // //} // } IBinaryField[] existingFs = existingType.binFields; if (newFields.length != existingFs.length) return true; new_field_loop: for (int i = 0; i < newFields.length; i++) { IBinaryField field = newFields[i]; char[] fieldName = field.getName(); for (int j = 0; j < existingFs.length; j++) { if (CharOperation.equals(existingFs[j].getName(), fieldName)) { if (!modifiersEqual(field.getModifiers(), existingFs[j].getModifiers())) { return true; } if (!CharOperation.equals(existingFs[j].getTypeName(), field.getTypeName())) { return true; } continue new_field_loop; } } return true; } // methods // CompactMemberStructureRepresentation[] existingMethods = existingType.methods; IBinaryMethod[] newMethods = reader.getMethods(); if (newMethods == null) { newMethods = CompactTypeStructureRepresentation.NoMethod; } // all redundant for now ... could be an optimization at some point... // Ctors in a non-static inner type have an 'extra parameter' of the enclosing type. // If skippableDescriptorPrefix gets set here then it is set to the descriptor portion // for this 'extra parameter'. For an inner class of pkg.Foo the skippable descriptor // prefix will be '(Lpkg/Foo;' - so later when comparing <init> methods we know what to // compare. // IF THIS CODE NEEDS TO GET MORE COMPLICATED, I THINK ITS WORTH RIPPING IT ALL OUT AND // CREATING THE STRUCTURAL CHANGES OBJECT BASED ON CLASSREADER OUTPUT RATHER THAN // THE RESOLVEDTYPE - THEN THERE WOULD BE NO NEED TO TREAT SOME METHODS IN A PECULIAR // WAY. // char[] skippableDescriptorPrefix = null; // char[] enclosingTypeName = reader.getEnclosingTypeName(); // boolean isStaticType = Modifier.isStatic(reader.getModifiers()); // if (!isStaticType && enclosingTypeName!=null) { // StringBuffer sb = new StringBuffer(); // sb.append("(L").append(new String(enclosingTypeName)).append(";"); // skippableDescriptorPrefix = sb.toString().toCharArray(); // } // // // // remove the aspectOf, hasAspect, clinit and ajc$XXX methods // // from those we compare with the existing methods - bug 129163 // List nonGenMethods = new ArrayList(); // for (int i = 0; i < newMethods.length; i++) { // IBinaryMethod method = newMethods[i]; // // if ((method.getModifiers() & 0x1000)!=0) continue; // 0x1000 => synthetic - will cause us to skip access$0 - is this // always safe? // char[] methodName = method.getSelector(); // // if (!CharOperation.equals(methodName,NameMangler.METHOD_ASPECTOF) && // // !CharOperation.equals(methodName,NameMangler.METHOD_HASASPECT) && // // !CharOperation.equals(methodName,NameMangler.STATIC_INITIALIZER) && // // !CharOperation.prefixEquals(NameMangler.AJC_DOLLAR_PREFIX,methodName) && // // !CharOperation.prefixEquals(NameMangler.CLINIT,methodName)) { // nonGenMethods.add(method); // // } // } IBinaryMethod[] existingMs = existingType.binMethods; if (newMethods.length != existingMs.length) return true; new_method_loop: for (int i = 0; i < newMethods.length; i++) { IBinaryMethod method = newMethods[i]; char[] methodName = method.getSelector(); for (int j = 0; j < existingMs.length; j++) { if (CharOperation.equals(existingMs[j].getSelector(), methodName)) { // candidate match if (!CharOperation.equals(method.getMethodDescriptor(), existingMs[j].getMethodDescriptor())) { // ok, the descriptors don't match, but is this a funky ctor on a non-static inner // type? // boolean mightBeOK = // skippableDescriptorPrefix!=null && // set for inner types // CharOperation.equals(methodName,NameMangler.INIT) && // ctor // CharOperation.prefixEquals(skippableDescriptorPrefix,method.getMethodDescriptor()); // checking for // prefix on the descriptor // if (mightBeOK) { // // OK, so the descriptor starts something like '(Lpkg/Foo;' - we now may need to look at the rest of the // // descriptor if it takes >1 parameter. // // eg. could be (Lpkg/C;Ljava/lang/String;) where the skippablePrefix is (Lpkg/C; // char [] md = method.getMethodDescriptor(); // char[] remainder = CharOperation.subarray(md, skippableDescriptorPrefix.length, md.length); // if (CharOperation.equals(remainder,BRACKET_V)) continue new_method_loop; // no other parameters to worry // about // char[] comparableSig = CharOperation.subarray(existingMethods[j].signature, 1, // existingMethods[j].signature.length); // boolean match = CharOperation.equals(comparableSig, remainder); // if (match) continue new_method_loop; // } continue; // might be overloading } else { // matching sigs if (!modifiersEqual(method.getModifiers(), existingMs[j].getModifiers())) { return true; } continue new_method_loop; } } } return true; // (no match found) } return false; } private boolean modifiersEqual(int eclipseModifiers, int resolvedTypeModifiers) { resolvedTypeModifiers = resolvedTypeModifiers & ExtraCompilerModifiers.AccJustFlag; eclipseModifiers = eclipseModifiers & ExtraCompilerModifiers.AccJustFlag; // if ((eclipseModifiers & CompilerModifiers.AccSuper) != 0) { // eclipseModifiers -= CompilerModifiers.AccSuper; // } return (eclipseModifiers == resolvedTypeModifiers); } // private static StringSet makeStringSet(List strings) { // StringSet ret = new StringSet(strings.size()); // for (Iterator iter = strings.iterator(); iter.hasNext();) { // String element = (String) iter.next(); // ret.add(element); // } // return ret; // } private String stringifyList(Set l) { StringBuffer sb = new StringBuffer(); sb.append("{"); for (Iterator iter = l.iterator(); iter.hasNext();) { Object el = iter.next(); sb.append(el); if (iter.hasNext()) sb.append(","); } sb.append("}"); return sb.toString(); } protected void addAffectedSourceFiles(Set addTo, Set lastTimeSources) { if (qualifiedStrings.elementSize == 0 && simpleStrings.elementSize == 0) return; if (listenerDefined()) getListener().recordDecision( "Examining whether any other files now need compilation based on just compiling: '" + stringifyList(lastTimeSources) + "'"); // the qualifiedStrings are of the form 'p1/p2' & the simpleStrings are just 'X' char[][][] qualifiedNames = ReferenceCollection.internQualifiedNames(qualifiedStrings); // if a well known qualified name was found then we can skip over these if (qualifiedNames.length < qualifiedStrings.elementSize) qualifiedNames = null; char[][] simpleNames = ReferenceCollection.internSimpleNames(simpleStrings); // if a well known name was found then we can skip over these if (simpleNames.length < simpleStrings.elementSize) simpleNames = null; // System.err.println("simple: " + simpleStrings); // System.err.println("qualif: " + qualifiedStrings); for (Iterator i = references.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); ReferenceCollection refs = (ReferenceCollection) entry.getValue(); if (refs != null && refs.includes(qualifiedNames, simpleNames)) { File file = (File) entry.getKey(); if (file.exists()) { if (!lastTimeSources.contains(file)) { // ??? O(n**2) if (listenerDefined()) { getListener().recordDecision("Need to recompile '" + file.getName().toString() + "'"); } addTo.add(file); } } } } // add in the things we compiled previously - I know that seems crap but otherwise we may pull woven // stuff off disk (since we no longer have UnwovenClassFile objects) in order to satisfy references // in the new files we are about to compile (see pr133532) if (addTo.size() > 0) addTo.addAll(lastTimeSources); // // XXX Promote addTo to a Set - then we don't need this rubbish? but does it need to be ordered? // if (addTo.size()>0) { // for (Iterator iter = lastTimeSources.iterator(); iter.hasNext();) { // Object element = (Object) iter.next(); // if (!addTo.contains(element)) addTo.add(element); // } // } qualifiedStrings.clear(); simpleStrings.clear(); } /** * Record that a particular type has been touched during a compilation run. Information is used to ensure any types depending * upon this one are also recompiled. * * @param typename (possibly qualified) type name */ protected void recordTypeChanged(String typename) { int lastDot = typename.lastIndexOf('.'); String typeName; if (lastDot != -1) { String packageName = typename.substring(0, lastDot).replace('.', '/'); qualifiedStrings.add(packageName); typeName = typename.substring(lastDot + 1); } else { qualifiedStrings.add(""); typeName = typename; } int memberIndex = typeName.indexOf('$'); if (memberIndex > 0) typeName = typeName.substring(0, memberIndex); simpleStrings.add(typeName); } protected void addDependentsOf(File sourceFile) { List cfs = (List) this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(sourceFile); if (cfs != null) { for (Iterator iter = cfs.iterator(); iter.hasNext();) { ClassFile cf = (ClassFile) iter.next(); recordTypeChanged(cf.fullyQualifiedTypeName); } } } public void setStructureModel(AsmManager structureModel) { this.structureModel = structureModel; } public AsmManager getStructureModel() { return structureModel; } public void setWeaver(BcelWeaver bw) { weaver = bw; } public BcelWeaver getWeaver() { return weaver; } public void setWorld(BcelWorld bw) { world = bw; } public BcelWorld getBcelWorld() { return world; } // // public void setRelationshipMap(IRelationshipMap irm) { // relmap = irm; // } // // public IRelationshipMap getRelationshipMap() { // return relmap; // } public int getNumberOfStructuralChangesSinceLastFullBuild() { return structuralChangesSinceLastFullBuild.size(); } /** Returns last time we did a full or incremental build. */ public long getLastBuildTime() { return lastSuccessfulBuildTime; } /** Returns last time we did a full build */ public long getLastFullBuildTime() { return lastSuccessfulFullBuildTime; } /** * @return Returns the buildConfig. */ public AjBuildConfig getBuildConfig() { return this.buildConfig; } public void clearBinarySourceFiles() { this.binarySourceFiles = new HashMap(); } public void recordBinarySource(String fromPathName, List unwovenClassFiles) { this.binarySourceFiles.put(fromPathName, unwovenClassFiles); if (this.maybeIncremental()) { List simpleClassFiles = new LinkedList(); for (Iterator iter = unwovenClassFiles.iterator(); iter.hasNext();) { UnwovenClassFile ucf = (UnwovenClassFile) iter.next(); ClassFile cf = getClassFileFor(ucf); simpleClassFiles.add(cf); } this.inputClassFilesBySource.put(fromPathName, simpleClassFiles); } } /** * @param ucf * @return */ private ClassFile getClassFileFor(UnwovenClassFile ucf) { return new ClassFile(ucf.getClassName(), new File(ucf.getFilename())); } public Map getBinarySourceMap() { return this.binarySourceFiles; } public Map getClassNameToFileMap() { return this.classesFromName; } public boolean hasResource(String resourceName) { return this.resources.keySet().contains(resourceName); } public void recordResource(String resourceName, File resourceSourceLocation) { this.resources.put(resourceName, resourceSourceLocation); } /** * @return Returns the addedFiles. */ public Set getAddedFiles() { return this.addedFiles; } /** * @return Returns the deletedFiles. */ public Set getDeletedFiles() { return this.deletedFiles; } public void forceBatchBuildNextTimeAround() { this.batchBuildRequiredThisTime = true; } public boolean requiresFullBatchBuild() { return this.batchBuildRequiredThisTime; } private static class ClassFile { public String fullyQualifiedTypeName; public File locationOnDisk; public ClassFile(String fqn, File location) { this.fullyQualifiedTypeName = fqn; this.locationOnDisk = location; } public void deleteFromFileSystem(AjBuildConfig buildConfig) { String namePrefix = locationOnDisk.getName(); namePrefix = namePrefix.substring(0, namePrefix.lastIndexOf('.')); final String targetPrefix = namePrefix + BcelWeaver.CLOSURE_CLASS_PREFIX; File dir = locationOnDisk.getParentFile(); if (dir != null) { File[] weaverGenerated = dir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith(targetPrefix); } }); if (weaverGenerated != null) { for (int i = 0; i < weaverGenerated.length; i++) { weaverGenerated[i].delete(); if (buildConfig != null && buildConfig.getCompilationResultDestinationManager() != null) { buildConfig.getCompilationResultDestinationManager().reportFileRemove(weaverGenerated[i].getPath(), CompilationResultDestinationManager.FILETYPE_CLASS); } } } } locationOnDisk.delete(); if (buildConfig != null && buildConfig.getCompilationResultDestinationManager() != null) { buildConfig.getCompilationResultDestinationManager().reportFileRemove(locationOnDisk.getPath(), CompilationResultDestinationManager.FILETYPE_CLASS); } } } public void wipeAllKnowledge() { buildManager.state = null; // buildManager.setStructureModel(null); } public Map getAspectNamesToFileNameMap() { return aspectsFromFileNames; } public void initializeAspectNamesToFileNameMap() { this.aspectsFromFileNames = new HashMap(); } // Will allow us to record decisions made during incremental processing, hopefully aid in debugging public boolean listenerDefined() { return stateListener != null; } public IStateListener getListener() { return stateListener; } public IBinaryType checkPreviousBuild(String name) { return (IBinaryType) resolvedTypeStructuresFromLastBuild.get(name); } public AjBuildManager getAjBuildManager() { return buildManager; } public INameEnvironment getNameEnvironment() { return this.nameEnvironment; } public void setNameEnvironment(INameEnvironment nameEnvironment) { this.nameEnvironment = nameEnvironment; } /** * Record an aspect that came in on the aspect path. When a .class file changes on the aspect path we can then recognize it as * an aspect and know to do more than just a tiny incremental build. <br> * TODO but this doesn't allow for a new aspect created on the aspectpath? * * @param aspectFile path to the file, eg. c:/temp/foo/Fred.class */ public void recordAspectClassFile(String aspectFile) { aspectClassFiles.add(aspectFile); } }
269,522
Bug 269522 [handles] Cross reference view and markers mix up joinpoints assigned to advice
Build ID: M20090211-1700 Steps To Reproduce: I have two pieces of after advice in my aspect. In the cross reference view I see all of the joinpoints for both after advice selecting one of the after advice statements. When I select the other after advice statement I see no joinpoints. When I select the marker for either piece of after advice, I see all the joinpoints for both pieces of advice. 1. open and perform a clean compile on the attached project 2. open the xref view 3. select line 22 an note that you see 5 joinpoints (should only be 3) 4. select line 68 and note that you see zero joinpoints (should be 2 here) 5. right click the marker at line 68 and choose "advises" - note you see all 5 joinpoints 6. right click the marker at line 22 and choose "advises" - note you see all 5 joinpoints More information:
resolved fixed
6dbb5f3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-03-26T18:52:57Z"
"2009-03-20T14:40:00Z"
asm/src/org/aspectj/asm/internal/JDTLikeHandleProvider.java
/******************************************************************** * Copyright (c) 2006 Contributors. All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: IBM Corporation - initial API and implementation * Helen Hawkins - initial version *******************************************************************/ package org.aspectj.asm.internal; import java.io.File; import java.util.Iterator; import java.util.List; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IElementHandleProvider; import org.aspectj.asm.IProgramElement; import org.aspectj.bridge.ISourceLocation; /** * Creates JDT-like handles, for example * * method with string argument: <tjp{Demo.java[Demo~main~\[QString; method with generic argument: * <pkg{MyClass.java[MyClass~myMethod~QList\<QString;>; an aspect: <pkg*A1.aj}A1 advice with Integer arg: * <pkg*A8.aj}A8&afterReturning&QInteger; method call: <pkg*A10.aj[C~m1?method-call(void pkg.C.m2()) * */ public class JDTLikeHandleProvider implements IElementHandleProvider { private final AsmManager asm; // Need to keep our own count of the number of initializers // because this information cannot be gained from the ipe. private int initializerCounter = 0; private static final char[] empty = new char[] {}; private static final char[] countDelim = new char[] { HandleProviderDelimiter.COUNT.getDelimiter() }; private static final String backslash = "\\"; private static final String emptyString = ""; public JDTLikeHandleProvider(AsmManager asm) { this.asm = asm; } public String createHandleIdentifier(IProgramElement ipe) { // AjBuildManager.setupModel --> top of the tree is either // <root> or the .lst file if (ipe == null || (ipe.getKind().equals(IProgramElement.Kind.FILE_JAVA) && ipe.getName().equals("<root>"))) { return ""; } else if (ipe.getHandleIdentifier(false) != null) { // have already created the handle for this ipe // therefore just return it return ipe.getHandleIdentifier(); } else if (ipe.getKind().equals(IProgramElement.Kind.FILE_LST)) { String configFile = asm.getHierarchy().getConfigFile(); int start = configFile.lastIndexOf(File.separator); int end = configFile.lastIndexOf(".lst"); if (end != -1) { configFile = configFile.substring(start + 1, end); } else { configFile = new StringBuffer("=").append(configFile.substring(start + 1)).toString(); } ipe.setHandleIdentifier(configFile); return configFile; } else if (ipe.getKind() == IProgramElement.Kind.SOURCE_FOLDER) { StringBuffer sb = new StringBuffer(); sb.append(createHandleIdentifier(ipe.getParent())).append("/"); // pr249216 - escape any embedded slashes String folder = ipe.getName(); if (folder.endsWith("/")) { folder = folder.substring(0, folder.length() - 1); } if (folder.indexOf("/") != -1) { folder = folder.replace("/", "\\/"); } sb.append(folder); String handle = sb.toString(); ipe.setHandleIdentifier(handle); return handle; } IProgramElement parent = ipe.getParent(); if (parent != null && parent.getKind().equals(IProgramElement.Kind.IMPORT_REFERENCE)) { // want to miss out '#import declaration' in the handle parent = ipe.getParent().getParent(); } StringBuffer handle = new StringBuffer(); // add the handle for the parent handle.append(createHandleIdentifier(parent)); // add the correct delimiter for this ipe handle.append(HandleProviderDelimiter.getDelimiter(ipe)); // add the name and any parameters unless we're an initializer // (initializer's names are '...') if (!ipe.getKind().equals(IProgramElement.Kind.INITIALIZER)) { if (ipe.getKind() == IProgramElement.Kind.CLASS && ipe.getName().endsWith("{..}")) { // format: 'new Runnable() {..}' but its anon-y-mouse // dont append anything, there may be a count to follow though (!<n>) } else { if (ipe.getKind() == IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR) { handle.append(ipe.getName()).append("_new").append(getParameters(ipe)); } else { // if (ipe.getKind() == IProgramElement.Kind.PACKAGE && ipe.getName().equals("DEFAULT")) { // // the delimiter will be in there, but skip the word DEFAULT as it is just a placeholder // } else { if (ipe.getKind().isDeclareAnnotation()) { // escape the @ (pr249216c9) handle.append("declare \\@").append(ipe.getName().substring(9)).append(getParameters(ipe)); } else { handle.append(ipe.getName()).append(getParameters(ipe)); } } // } } } // add the count, for example '!2' if its the second ipe of its // kind in the aspect handle.append(getCount(ipe)); ipe.setHandleIdentifier(handle.toString()); return handle.toString(); } private String getParameters(IProgramElement ipe) { if (ipe.getParameterSignatures() == null || ipe.getParameterSignatures().isEmpty()) { return ""; } List sourceRefs = ipe.getParameterSignaturesSourceRefs(); List parameterTypes = ipe.getParameterSignatures(); StringBuffer sb = new StringBuffer(); if (sourceRefs != null) { for (int i = 0; i < sourceRefs.size(); i++) { String sourceRef = (String) sourceRefs.get(i); sb.append(HandleProviderDelimiter.getDelimiter(ipe)); sb.append(sourceRef); } } else { for (Iterator iter = parameterTypes.iterator(); iter.hasNext();) { char[] element = (char[]) iter.next(); sb.append(HandleProviderDelimiter.getDelimiter(ipe)); sb.append(NameConvertor.createShortName(element, false, false)); } } return sb.toString(); } /** * Determine a count to be suffixed to the handle, this is only necessary for identical looking entries at the same level in the * model (for example two anonymous class declarations). The format is !<n> where n will be greater than 2. * * @param ipe the program element for which the handle is being constructed * @return a char suffix that will either be empty or of the form "!<n>" */ private char[] getCount(IProgramElement ipe) { // TODO could optimize this code char[] byteCodeName = ipe.getBytecodeName().toCharArray(); if (ipe.getKind().isDeclare()) { int index = CharOperation.lastIndexOf('_', byteCodeName); if (index != -1) { return convertCount(CharOperation.subarray(byteCodeName, index + 1, byteCodeName.length)); } } else if (ipe.getKind().equals(IProgramElement.Kind.ADVICE)) { // Look at any peer advice int count = 1; List kids = ipe.getParent().getChildren(); String ipeSig = ipe.getBytecodeSignature(); // remove return type from the signature - it should not be included in the comparison int idx = 0; if (ipeSig != null && ((idx = ipeSig.indexOf(")")) != -1)) { ipeSig = ipeSig.substring(0, idx); } for (Iterator iterator = kids.iterator(); iterator.hasNext();) { IProgramElement object = (IProgramElement) iterator.next(); if (object.equals(ipe)) { break; } if (object.getKind() == ipe.getKind()) { if (object.getName().equals(ipe.getName())) { String sig1 = object.getBytecodeSignature(); if (sig1 != null && (idx = sig1.indexOf(")")) != -1) { sig1 = sig1.substring(0, idx); } if (sig1 == null && ipeSig == null || (sig1 != null && sig1.equals(ipeSig))) { String existingHandle = object.getHandleIdentifier(); int suffixPosition = existingHandle.indexOf('!'); if (suffixPosition != -1) { count = new Integer(existingHandle.substring(suffixPosition + 1)).intValue() + 1; } else { if (count == 1) { count = 2; } } } } } } if (count > 1) { return CharOperation.concat(countDelim, new Integer(count).toString().toCharArray()); } } else if (ipe.getKind().equals(IProgramElement.Kind.INITIALIZER)) { return String.valueOf(++initializerCounter).toCharArray(); } else if (ipe.getKind().equals(IProgramElement.Kind.CODE)) { int index = CharOperation.lastIndexOf('!', byteCodeName); if (index != -1) { return convertCount(CharOperation.subarray(byteCodeName, index + 1, byteCodeName.length)); } } else if (ipe.getKind() == IProgramElement.Kind.CLASS) { // depends on previous children int count = 1; List kids = ipe.getParent().getChildren(); if (ipe.getName().endsWith("{..}")) { // only depends on previous anonymous children, name irrelevant for (Iterator iterator = kids.iterator(); iterator.hasNext();) { IProgramElement object = (IProgramElement) iterator.next(); if (object.equals(ipe)) { break; } if (object.getKind() == ipe.getKind()) { if (object.getName().endsWith("{..}")) { String existingHandle = object.getHandleIdentifier(); int suffixPosition = existingHandle.lastIndexOf('!'); int lastSquareBracket = existingHandle.lastIndexOf('['); // type delimiter if (suffixPosition != -1 && lastSquareBracket < suffixPosition) { // pr260384 count = new Integer(existingHandle.substring(suffixPosition + 1)).intValue() + 1; } else { if (count == 1) { count = 2; } } } } } } else { for (Iterator iterator = kids.iterator(); iterator.hasNext();) { IProgramElement object = (IProgramElement) iterator.next(); if (object.equals(ipe)) { break; } if (object.getKind() == ipe.getKind()) { if (object.getName().equals(ipe.getName())) { String existingHandle = object.getHandleIdentifier(); int suffixPosition = existingHandle.lastIndexOf('!'); int lastSquareBracket = existingHandle.lastIndexOf('['); // type delimiter if (suffixPosition != -1 && lastSquareBracket < suffixPosition) { // pr260384 count = new Integer(existingHandle.substring(suffixPosition + 1)).intValue() + 1; } else { if (count == 1) { count = 2; } } } } } } if (count > 1) { return CharOperation.concat(countDelim, new Integer(count).toString().toCharArray()); } } return empty; } /** * Only returns the count if it's not equal to 1 */ private char[] convertCount(char[] c) { if ((c.length == 1 && c[0] != ' ' && c[0] != '1') || c.length > 1) { return CharOperation.concat(countDelim, c); } return empty; } public String getFileForHandle(String handle) { IProgramElement node = asm.getHierarchy().getElement(handle); if (node != null) { return asm.getCanonicalFilePath(node.getSourceLocation().getSourceFile()); } else if (handle.charAt(0) == HandleProviderDelimiter.ASPECT_CU.getDelimiter() || handle.charAt(0) == HandleProviderDelimiter.COMPILATIONUNIT.getDelimiter()) { // it's something like *MyAspect.aj or {MyClass.java. In other words // it's a file node that's been created with no children and no // parent return backslash + handle.substring(1); } return emptyString; } public int getLineNumberForHandle(String handle) { IProgramElement node = asm.getHierarchy().getElement(handle); if (node != null) { return node.getSourceLocation().getLine(); } else if (handle.charAt(0) == HandleProviderDelimiter.ASPECT_CU.getDelimiter() || handle.charAt(0) == HandleProviderDelimiter.COMPILATIONUNIT.getDelimiter()) { // it's something like *MyAspect.aj or {MyClass.java. In other words // it's a file node that's been created with no children and no // parent return 1; } return -1; } public int getOffSetForHandle(String handle) { IProgramElement node = asm.getHierarchy().getElement(handle); if (node != null) { return node.getSourceLocation().getOffset(); } else if (handle.charAt(0) == HandleProviderDelimiter.ASPECT_CU.getDelimiter() || handle.charAt(0) == HandleProviderDelimiter.COMPILATIONUNIT.getDelimiter()) { // it's something like *MyAspect.aj or {MyClass.java. In other words // it's a file node that's been created with no children and no // parent return 0; } return -1; } public String createHandleIdentifier(ISourceLocation location) { IProgramElement node = asm.getHierarchy().findElementForSourceLine(location); if (node != null) { return createHandleIdentifier(node); } return null; } public String createHandleIdentifier(File sourceFile, int line, int column, int offset) { IProgramElement node = asm.getHierarchy().findElementForOffSet(sourceFile.getAbsolutePath(), line, offset); if (node != null) { return createHandleIdentifier(node); } return null; } public boolean dependsOnLocation() { // handles are independent of soureLocations therefore return false return false; } public void initialize() { // reset the initializer count. This ensures we return the // same handle as JDT for initializers. initializerCounter = 0; } }
272,591
Bug 272591 [WARNING] couldn't find aspectjrt.jar on classpath
I am using the aspectj runtime jar that is in the spring source bundle repository. The have renamed their jar to match their naming conventions and it is causing the warning to occur. Their bundle is named com.springsource.org.aspectj.runtime-1.6.3.RELEASE.jar. It would be nice if this warning was not printed out in this case.
resolved fixed
1b663a9
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-04-30T20:44:56Z"
"2009-04-16T22:13:20Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import org.aspectj.ajdt.internal.compiler.AjCompilerAdapter; import org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter; import org.aspectj.ajdt.internal.compiler.CompilationResultDestinationManager; import org.aspectj.ajdt.internal.compiler.IBinarySourceProvider; import org.aspectj.ajdt.internal.compiler.ICompilerAdapter; import org.aspectj.ajdt.internal.compiler.ICompilerAdapterFactory; import org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor; import org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider; import org.aspectj.ajdt.internal.compiler.InterimCompilationResult; import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment; import org.aspectj.ajdt.internal.compiler.lookup.AnonymousClassPublisher; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.internal.ProgramElement; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.CountingMessageHandler; import org.aspectj.bridge.ILifecycleAware; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.SourceLocation; import org.aspectj.bridge.Version; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextFormatter; import org.aspectj.bridge.context.ContextToken; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies; import org.aspectj.org.eclipse.jdt.internal.compiler.ICompilerRequestor; import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.ClasspathLocation; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.CompilationUnit; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.FileSystem; import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilation; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.aspectj.tools.ajc.Main; import org.aspectj.util.FileUtil; import org.aspectj.weaver.CustomMungerFactory; import org.aspectj.weaver.Dump; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.UnwovenClassFile; import org.eclipse.core.runtime.OperationCanceledException; public class AjBuildManager implements IOutputClassFileNameProvider, IBinarySourceProvider, ICompilerAdapterFactory { private static final String CROSSREFS_FILE_NAME = "build.lst"; private static final String CANT_WRITE_RESULT = "unable to write compilation result"; private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; public static boolean COPY_INPATH_DIR_RESOURCES = false; // AJDT doesn't want this check, so Main enables it. private static boolean DO_RUNTIME_VERSION_CHECK = false; // If runtime version check fails, warn or fail? (unset?) static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false; private static final FileFilter binarySourceFilter = new FileFilter() { public boolean accept(File f) { return f.getName().endsWith(".class"); } }; /** * This builder is static so that it can be subclassed and reset. However, note that there is only one builder present, so if * two extendsion reset it, only the latter will get used. */ public static AsmHierarchyBuilder asmHierarchyBuilder = new AsmHierarchyBuilder(); static { // CompilationAndWeavingContext.setMultiThreaded(false); CompilationAndWeavingContext.registerFormatter(CompilationAndWeavingContext.BATCH_BUILD, new AjBuildContexFormatter()); CompilationAndWeavingContext .registerFormatter(CompilationAndWeavingContext.INCREMENTAL_BUILD, new AjBuildContexFormatter()); } private IProgressListener progressListener = null; private boolean environmentSupportsIncrementalCompilation = false; private int compiledCount; private int sourceFileCount; private JarOutputStream zos; private boolean batchCompile = true; private INameEnvironment environment; private Map /* String -> List<UCF> */binarySourcesForTheNextCompile = new HashMap(); // FIXME asc should this really be in here? // private AsmManager structureModel; public AjBuildConfig buildConfig; private boolean ignoreOutxml; private boolean wasFullBuild = true; // true if last build was a full build rather than an incremental build AjState state = new AjState(this); /** * Enable check for runtime version, used only by Ant/command-line Main. * * @param main Main unused except to limit to non-null clients. */ public static void enableRuntimeVersionCheck(Main caller) { DO_RUNTIME_VERSION_CHECK = null != caller; } public BcelWeaver getWeaver() { return state.getWeaver(); } public BcelWorld getBcelWorld() { return state.getBcelWorld(); } public CountingMessageHandler handler; private CustomMungerFactory customMungerFactory; public AjBuildManager(IMessageHandler holder) { super(); this.handler = CountingMessageHandler.makeCountingMessageHandler(holder); } public void environmentSupportsIncrementalCompilation(boolean itDoes) { this.environmentSupportsIncrementalCompilation = itDoes; } /** @return true if we should generate a model as a side-effect */ public boolean doGenerateModel() { return buildConfig.isGenerateModelMode(); } public boolean batchBuild(AjBuildConfig buildConfig, IMessageHandler baseHandler) throws IOException, AbortException { return performBuild(buildConfig, baseHandler, true); } public boolean incrementalBuild(AjBuildConfig buildConfig, IMessageHandler baseHandler) throws IOException, AbortException { return performBuild(buildConfig, baseHandler, false); } /** * Perform a build. * * @return true if the build was successful (ie. no errors) */ private boolean performBuild(AjBuildConfig buildConfig, IMessageHandler baseHandler, boolean isFullBuild) throws IOException, AbortException { boolean ret = true; batchCompile = isFullBuild; wasFullBuild = isFullBuild; if (baseHandler instanceof ILifecycleAware) { ((ILifecycleAware) baseHandler).buildStarting(!isFullBuild); } CompilationAndWeavingContext.reset(); int phase = isFullBuild ? CompilationAndWeavingContext.BATCH_BUILD : CompilationAndWeavingContext.INCREMENTAL_BUILD; ContextToken ct = CompilationAndWeavingContext.enteringPhase(phase, buildConfig); try { if (isFullBuild) { this.state = new AjState(this); } this.state.setCouldBeSubsequentIncrementalBuild(this.environmentSupportsIncrementalCompilation); boolean canIncremental = state.prepareForNextBuild(buildConfig); if (!canIncremental && !isFullBuild) { // retry as batch? CompilationAndWeavingContext.leavingPhase(ct); if (state.listenerDefined()) state.getListener().recordDecision("Falling back to batch compilation"); return performBuild(buildConfig, baseHandler, true); } this.handler = CountingMessageHandler.makeCountingMessageHandler(baseHandler); if (buildConfig == null || buildConfig.isCheckRuntimeVersion()) { if (DO_RUNTIME_VERSION_CHECK) { String check = checkRtJar(buildConfig); if (check != null) { if (FAIL_IF_RUNTIME_NOT_FOUND) { MessageUtil.error(handler, check); CompilationAndWeavingContext.leavingPhase(ct); return false; } else { MessageUtil.warn(handler, check); } } } } // if (batch) { setBuildConfig(buildConfig); // } if (isFullBuild || !AsmManager.attemptIncrementalModelRepairs) { // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { setupModel(buildConfig); // } } if (isFullBuild) { initBcelWorld(handler); } if (handler.hasErrors()) { CompilationAndWeavingContext.leavingPhase(ct); return false; } if (buildConfig.getOutputJar() != null) { if (!openOutputStream(buildConfig.getOutputJar())) { CompilationAndWeavingContext.leavingPhase(ct); return false; } } if (isFullBuild) { // System.err.println("XXXX batch: " + buildConfig.getFiles()); if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { AsmManager.setLastActiveStructureModel(state.getStructureModel()); getWorld().setModel(state.getStructureModel()); // in incremental build, only get updated model? } binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true); performCompilation(buildConfig.getFiles()); state.clearBinarySourceFiles(); // we don't want these hanging around... if (!proceedOnError() && handler.hasErrors()) { CompilationAndWeavingContext.leavingPhase(ct); if (AsmManager.isReporting()) { state.getStructureModel().reportModelInfo("After a batch build"); } return false; } if (AsmManager.isReporting()) { state.getStructureModel().reportModelInfo("After a batch build"); } } else { // done already? // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { // bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel()); // } // System.err.println("XXXX start inc "); AsmManager.setLastActiveStructureModel(state.getStructureModel()); binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true); Set files = state.getFilesToCompile(true); if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { if (AsmManager.attemptIncrementalModelRepairs) { state.getStructureModel().resetDeltaProcessing(); state.getStructureModel().processDelta(files, state.getAddedFiles(), state.getDeletedFiles()); } } boolean hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty()); for (int i = 0; (i < 5) && hereWeGoAgain; i++) { if (state.listenerDefined()) state.getListener() .recordInformation("Starting incremental compilation loop " + (i + 1) + " of possibly 5"); // System.err.println("XXXX inc: " + files); performCompilation(files); if ((!proceedOnError() && handler.hasErrors()) || (progressListener != null && progressListener.isCancelledRequested())) { CompilationAndWeavingContext.leavingPhase(ct); return false; } if (state.requiresFullBatchBuild()) { if (state.listenerDefined()) state.getListener().recordInformation(" Dropping back to full build"); return batchBuild(buildConfig, baseHandler); } binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(false); files = state.getFilesToCompile(false); hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty()); // TODO Andy - Needs some thought here... // I think here we might want to pass empty addedFiles/deletedFiles as they were // dealt with on the first call to processDelta - we are going through this loop // again because in compiling something we found something else we needed to // rebuild. But what case causes this? if (hereWeGoAgain) { if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) if (AsmManager.attemptIncrementalModelRepairs) state.getStructureModel().processDelta(files, state.getAddedFiles(), state.getDeletedFiles()); } } if (!files.isEmpty()) { CompilationAndWeavingContext.leavingPhase(ct); return batchBuild(buildConfig, baseHandler); } else { if (AsmManager.isReporting()) { state.getStructureModel().reportModelInfo("After an incremental build"); } } } // XXX not in Mik's incremental if (buildConfig.isEmacsSymMode()) { new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel(state.getStructureModel()); } // for bug 113554: support ajsym file generation for command line builds if (buildConfig.isGenerateCrossRefsMode()) { File configFileProxy = new File(buildConfig.getOutputDir(), CROSSREFS_FILE_NAME); state.getStructureModel().writeStructureModel(configFileProxy.getAbsolutePath()); } // have to tell state we succeeded or next is not incremental state.successfulCompile(buildConfig, isFullBuild); // For a full compile, copy resources to the destination // - they should not get deleted on incremental and AJDT // will handle changes to them that require a recopying if (isFullBuild) { copyResourcesToDestination(); } if (buildConfig.getOutxmlName() != null) { writeOutxmlFile(); } /* boolean weaved = */// weaveAndGenerateClassFiles(); // if not weaved, then no-op build, no model changes // but always returns true // XXX weaved not in Mik's incremental if (buildConfig.isGenerateModelMode()) { state.getStructureModel().fireModelUpdated(); } CompilationAndWeavingContext.leavingPhase(ct); } finally { if (baseHandler instanceof ILifecycleAware) { ((ILifecycleAware) baseHandler).buildFinished(!isFullBuild); } if (zos != null) { closeOutputStream(buildConfig.getOutputJar()); } ret = !handler.hasErrors(); if (getBcelWorld() != null) getBcelWorld().tidyUp(); if (getWeaver() != null) getWeaver().tidyUp(); // bug 59895, don't release reference to handler as may be needed by a nested call // handler = null; } return ret; } /** * Open an output jar file in which to write the compiler output. * * @param outJar the jar file to open * @return true if successful */ private boolean openOutputStream(File outJar) { try { OutputStream os = FileUtil.makeOutputStream(buildConfig.getOutputJar()); zos = new JarOutputStream(os, getWeaver().getManifest(true)); } catch (IOException ex) { IMessage message = new Message("Unable to open outjar " + outJar.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(outJar, 0), true); handler.handleMessage(message); return false; } return true; } private void closeOutputStream(File outJar) { try { if (zos != null) { zos.close(); if (buildConfig.getCompilationResultDestinationManager() != null) { buildConfig.getCompilationResultDestinationManager().reportFileWrite(outJar.getPath(), CompilationResultDestinationManager.FILETYPE_OUTJAR); } } zos = null; /* Ensure we don't write an incomplete JAR bug-71339 */ if (handler.hasErrors()) { outJar.delete(); if (buildConfig.getCompilationResultDestinationManager() != null) { buildConfig.getCompilationResultDestinationManager().reportFileRemove(outJar.getPath(), CompilationResultDestinationManager.FILETYPE_OUTJAR); } } } catch (IOException ex) { IMessage message = new Message("Unable to write outjar " + outJar.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(outJar, 0), true); handler.handleMessage(message); } } private void copyResourcesToDestination() throws IOException { // resources that we need to copy are contained in the injars and inpath only for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext();) { File inJar = (File) i.next(); copyResourcesFromJarFile(inJar); } for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext();) { File inPathElement = (File) i.next(); if (inPathElement.isDirectory()) { copyResourcesFromDirectory(inPathElement); } else { copyResourcesFromJarFile(inPathElement); } } if (buildConfig.getSourcePathResources() != null) { for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext();) { String resource = (String) i.next(); File from = (File) buildConfig.getSourcePathResources().get(resource); copyResourcesFromFile(from, resource, from); } } writeManifest(); } private void copyResourcesFromJarFile(File jarFile) throws IOException { JarInputStream inStream = null; try { inStream = new JarInputStream(new FileInputStream(jarFile)); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; String filename = entry.getName(); // System.out.println("? copyResourcesFromJarFile() filename='" + filename +"'"); if (entry.isDirectory()) { writeDirectory(filename, jarFile); } else if (acceptResource(filename, false)) { byte[] bytes = FileUtil.readAsByteArray(inStream); writeResource(filename, bytes, jarFile); } inStream.closeEntry(); } } finally { if (inStream != null) inStream.close(); } } private void copyResourcesFromDirectory(File dir) throws IOException { if (!COPY_INPATH_DIR_RESOURCES) return; // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(dir, new FileFilter() { public boolean accept(File f) { boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")); return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = files[i].getAbsolutePath().substring(dir.getAbsolutePath().length() + 1); copyResourcesFromFile(files[i], filename, dir); } } private void copyResourcesFromFile(File f, String filename, File src) throws IOException { if (!acceptResource(filename, true)) return; FileInputStream fis = null; try { fis = new FileInputStream(f); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); writeResource(filename, bytes, src); } finally { if (fis != null) fis.close(); } } /** * Add a directory entry to the output zip file. Don't do anything if not writing out to a zip file. A directory entry is one * whose filename ends with '/' * * @param directory the directory path * @param srcloc the src of the directory entry, for use when creating a warning message * @throws IOException if something goes wrong creating the new zip entry */ private void writeDirectory(String directory, File srcloc) throws IOException { if (state.hasResource(directory)) { IMessage msg = new Message("duplicate resource: '" + directory + "'", IMessage.WARNING, null, new SourceLocation( srcloc, 0)); handler.handleMessage(msg); return; } if (zos != null) { ZipEntry newEntry = new ZipEntry(directory); zos.putNextEntry(newEntry); zos.closeEntry(); state.recordResource(directory, srcloc); } // Nothing to do if not writing to a zip file } private void writeResource(String filename, byte[] content, File srcLocation) throws IOException { if (state.hasResource(filename)) { IMessage msg = new Message("duplicate resource: '" + filename + "'", IMessage.WARNING, null, new SourceLocation( srcLocation, 0)); handler.handleMessage(msg); return; } if (filename.equals(buildConfig.getOutxmlName())) { ignoreOutxml = true; IMessage msg = new Message("-outxml/-outxmlfile option ignored because resource already exists: '" + filename + "'", IMessage.WARNING, null, new SourceLocation(srcLocation, 0)); handler.handleMessage(msg); } if (zos != null) { ZipEntry newEntry = new ZipEntry(filename); // ??? get compression scheme right zos.putNextEntry(newEntry); zos.write(content); zos.closeEntry(); } else { File destDir = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { destDir = buildConfig.getCompilationResultDestinationManager().getOutputLocationForResource(srcLocation); } try { File outputLocation = new File(destDir, filename); OutputStream fos = FileUtil.makeOutputStream(outputLocation); fos.write(content); fos.close(); if (buildConfig.getCompilationResultDestinationManager() != null) { buildConfig.getCompilationResultDestinationManager().reportFileWrite(outputLocation.getPath(), CompilationResultDestinationManager.FILETYPE_RESOURCE); } } catch (FileNotFoundException fnfe) { IMessage msg = new Message("unable to copy resource to output folder: '" + filename + "' - reason: " + fnfe.getMessage(), IMessage.ERROR, null, new SourceLocation(srcLocation, 0)); handler.handleMessage(msg); } } state.recordResource(filename, srcLocation); } /* * If we are writing to an output directory copy the manifest but only if we already have one */ private void writeManifest() throws IOException { Manifest manifest = getWeaver().getManifest(false); if (manifest != null && zos == null) { File outputDir = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { // Manifests are only written if we have a jar on the inpath. Therefore, // we write the manifest to the defaultOutputLocation because this is // where we sent the classes that were on the inpath outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation(); } if (outputDir == null) { return; } File outputLocation = new File(outputDir, MANIFEST_NAME); OutputStream fos = FileUtil.makeOutputStream(outputLocation); manifest.write(fos); fos.close(); if (buildConfig.getCompilationResultDestinationManager() != null) { buildConfig.getCompilationResultDestinationManager().reportFileWrite(outputLocation.getPath(), CompilationResultDestinationManager.FILETYPE_RESOURCE); } } } private boolean acceptResource(String resourceName, boolean fromFile) { if ((resourceName.startsWith("CVS/")) || (resourceName.indexOf("/CVS/") != -1) || (resourceName.endsWith("/CVS")) || (resourceName.endsWith(".class")) || (resourceName.startsWith(".svn/")) || (resourceName.indexOf("/.svn/") != -1) || (resourceName.endsWith("/.svn")) || // Do not copy manifests if either they are coming from a jar or we are writing to a jar (resourceName.toUpperCase().equals(MANIFEST_NAME) && (!fromFile || zos != null))) { return false; } else { return true; } } private void writeOutxmlFile() throws IOException { if (ignoreOutxml) return; String filename = buildConfig.getOutxmlName(); // System.err.println("? AjBuildManager.writeOutxmlFile() outxml=" + filename); Map outputDirsAndAspects = findOutputDirsForAspects(); Set outputDirs = outputDirsAndAspects.entrySet(); for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); File outputDir = (File) entry.getKey(); List aspects = (List) entry.getValue(); ByteArrayOutputStream baos = getOutxmlContents(aspects); if (zos != null) { ZipEntry newEntry = new ZipEntry(filename); zos.putNextEntry(newEntry); zos.write(baos.toByteArray()); zos.closeEntry(); } else { File outputFile = new File(outputDir, filename); OutputStream fos = FileUtil.makeOutputStream(outputFile); fos.write(baos.toByteArray()); fos.close(); if (buildConfig.getCompilationResultDestinationManager() != null) { buildConfig.getCompilationResultDestinationManager().reportFileWrite(outputFile.getPath(), CompilationResultDestinationManager.FILETYPE_RESOURCE); } } } } private ByteArrayOutputStream getOutxmlContents(List aspectNames) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); ps.println("<aspectj>"); ps.println("<aspects>"); if (aspectNames != null) { for (Iterator i = aspectNames.iterator(); i.hasNext();) { String name = (String) i.next(); ps.println("<aspect name=\"" + name + "\"/>"); } } ps.println("</aspects>"); ps.println("</aspectj>"); ps.println(); ps.close(); return baos; } /** * Returns a map where the keys are File objects corresponding to all the output directories and the values are a list of * aspects which are sent to that ouptut directory */ private Map /* File --> List (String) */findOutputDirsForAspects() { Map outputDirsToAspects = new HashMap(); Map aspectNamesToFileNames = state.getAspectNamesToFileNameMap(); if (buildConfig.getCompilationResultDestinationManager() == null || buildConfig.getCompilationResultDestinationManager().getAllOutputLocations().size() == 1) { // we only have one output directory...which simplifies things File outputDir = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation(); } List aspectNames = new ArrayList(); if (aspectNamesToFileNames != null) { Set keys = aspectNamesToFileNames.keySet(); for (Iterator iterator = keys.iterator(); iterator.hasNext();) { String name = (String) iterator.next(); aspectNames.add(name); } } outputDirsToAspects.put(outputDir, aspectNames); } else { List outputDirs = buildConfig.getCompilationResultDestinationManager().getAllOutputLocations(); for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) { File outputDir = (File) iterator.next(); outputDirsToAspects.put(outputDir, new ArrayList()); } Set entrySet = aspectNamesToFileNames.entrySet(); for (Iterator iterator = entrySet.iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String aspectName = (String) entry.getKey(); char[] fileName = (char[]) entry.getValue(); File outputDir = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass( new File(new String(fileName))); if (!outputDirsToAspects.containsKey(outputDir)) { outputDirsToAspects.put(outputDir, new ArrayList()); } ((List) outputDirsToAspects.get(outputDir)).add(aspectName); } } return outputDirsToAspects; } // public static void dumprels() { // IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap(); // int ctr = 1; // Set entries = irm.getEntries(); // for (Iterator iter = entries.iterator(); iter.hasNext();) { // String hid = (String) iter.next(); // List rels = irm.get(hid); // for (Iterator iterator = rels.iterator(); iterator.hasNext();) { // IRelationship ir = (IRelationship) iterator.next(); // List targets = ir.getTargets(); // for (Iterator iterator2 = targets.iterator(); // iterator2.hasNext(); // ) { // String thid = (String) iterator2.next(); // System.err.println("Hid:"+(ctr++)+":(targets="+targets.size()+") "+hid+" ("+ir.getName()+") "+thid); // } // } // } // } /** * Responsible for managing the ASM model between builds. Contains the policy for maintaining the persistance of elements in the * model. * * This code is driven before each 'fresh' (batch) build to create a new model. */ private void setupModel(AjBuildConfig config) { if (!(config.isEmacsSymMode() || config.isGenerateModelMode())) { return; } // AsmManager.setCreatingModel(config.isEmacsSymMode() || config.isGenerateModelMode()); // if (!AsmManager.isCreatingModel()) // return; CompilationResultDestinationManager crdm = config.getCompilationResultDestinationManager(); AsmManager structureModel = AsmManager.createNewStructureModel(crdm==null?Collections.EMPTY_MAP:crdm.getInpathMap()); // AsmManager.getDefault().getRelationshipMap().clear(); IHierarchy model = structureModel.getHierarchy(); String rootLabel = "<root>"; IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA; if (buildConfig.getConfigFile() != null) { rootLabel = buildConfig.getConfigFile().getName(); model.setConfigFile(buildConfig.getConfigFile().getAbsolutePath()); kind = IProgramElement.Kind.FILE_LST; } model.setRoot(new ProgramElement(structureModel, rootLabel, kind, new ArrayList())); model.setFileMap(new HashMap()); // setStructureModel(model); state.setStructureModel(structureModel); // state.setRelationshipMap(AsmManager.getDefault().getRelationshipMap()); } // // private void dumplist(List l) { // System.err.println("---- "+l.size()); // for (int i =0 ;i<l.size();i++) System.err.println(i+"\t "+l.get(i)); // } // private void accumulateFileNodes(IProgramElement ipe,List store) { // if (ipe.getKind()==IProgramElement.Kind.FILE_JAVA || // ipe.getKind()==IProgramElement.Kind.FILE_ASPECTJ) { // if (!ipe.getName().equals("<root>")) { // store.add(ipe); // return; // } // } // for (Iterator i = ipe.getChildren().iterator();i.hasNext();) { // accumulateFileNodes((IProgramElement)i.next(),store); // } // } // LTODO delegate to BcelWeaver? // XXX hideous, should not be Object public void setCustomMungerFactory(Object o) { customMungerFactory = (CustomMungerFactory) o; } public Object getCustomMungerFactory() { return customMungerFactory; } /** init only on initial batch compile? no file-specific options */ private void initBcelWorld(IMessageHandler handler) throws IOException { List cp = buildConfig.getFullClasspath(); // pr145693 // buildConfig.getBootclasspath(); // cp.addAll(buildConfig.getClasspath()); BcelWorld bcelWorld = new BcelWorld(cp, handler, null); bcelWorld.setBehaveInJava5Way(buildConfig.getBehaveInJava5Way()); bcelWorld.setAddSerialVerUID(buildConfig.isAddSerialVerUID()); bcelWorld.setXmlConfigured(buildConfig.isXmlConfigured()); bcelWorld.setXmlFiles(buildConfig.getXmlFiles()); bcelWorld.performExtraConfiguration(buildConfig.getXconfigurationInfo()); bcelWorld.setTargetAspectjRuntimeLevel(buildConfig.getTargetAspectjRuntimeLevel()); bcelWorld.setOptionalJoinpoints(buildConfig.getXJoinpoints()); bcelWorld.setXnoInline(buildConfig.isXnoInline()); bcelWorld.setXlazyTjp(buildConfig.isXlazyTjp()); bcelWorld.setXHasMemberSupportEnabled(buildConfig.isXHasMemberEnabled()); bcelWorld.setPinpointMode(buildConfig.isXdevPinpoint()); bcelWorld.setErrorAndWarningThreshold(buildConfig.getOptions().errorThreshold, buildConfig.getOptions().warningThreshold); BcelWeaver bcelWeaver = new BcelWeaver(bcelWorld); bcelWeaver.setCustomMungerFactory(customMungerFactory); state.setWorld(bcelWorld); state.setWeaver(bcelWeaver); state.clearBinarySourceFiles(); if (buildConfig.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT)) { bcelWorld.getLint().loadDefaultProperties(); } else { bcelWorld.getLint().setAll(buildConfig.getLintMode()); } if (buildConfig.getLintSpecFile() != null) { bcelWorld.getLint().setFromProperties(buildConfig.getLintSpecFile()); } for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext();) { File f = (File) i.next(); if (!f.exists()) { IMessage message = new Message("invalid aspectpath entry: " + f.getName(), null, true); handler.handleMessage(message); } else { bcelWeaver.addLibraryJarFile(f); } } // String lintMode = buildConfig.getLintMode(); File outputDir = buildConfig.getOutputDir(); if (outputDir == null && buildConfig.getCompilationResultDestinationManager() != null) { // send all output from injars and inpath to the default output location // (will also later send the manifest there too) outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation(); } // ??? incremental issues for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext();) { File inJar = (File) i.next(); List unwovenClasses = bcelWeaver.addJarFile(inJar, outputDir, false); state.recordBinarySource(inJar.getPath(), unwovenClasses); } for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext();) { File inPathElement = (File) i.next(); if (!inPathElement.isDirectory()) { // its a jar file on the inpath // the weaver method can actually handle dirs, but we don't call it, see next block List unwovenClasses = bcelWeaver.addJarFile(inPathElement, outputDir, true); state.recordBinarySource(inPathElement.getPath(), unwovenClasses); } else { // add each class file in an in-dir individually, this gives us the best error reporting // (they are like 'source' files then), and enables a cleaner incremental treatment of // class file changes in indirs. File[] binSrcs = FileUtil.listFiles(inPathElement, binarySourceFilter); for (int j = 0; j < binSrcs.length; j++) { UnwovenClassFile ucf = bcelWeaver.addClassFile(binSrcs[j], inPathElement, outputDir); List ucfl = new ArrayList(); ucfl.add(ucf); state.recordBinarySource(binSrcs[j].getPath(), ucfl); } } } bcelWeaver.setReweavableMode(buildConfig.isXNotReweavable()); // check for org.aspectj.runtime.JoinPoint ResolvedType joinPoint = bcelWorld.resolve("org.aspectj.lang.JoinPoint"); if (joinPoint.isMissing()) { IMessage message = new Message( "classpath error: unable to find org.aspectj.lang.JoinPoint (check that aspectjrt.jar is in your classpath)", null, true); handler.handleMessage(message); } } public World getWorld() { return getBcelWorld(); } // void addAspectClassFilesToWeaver(List addedClassFiles) throws IOException { // for (Iterator i = addedClassFiles.iterator(); i.hasNext();) { // UnwovenClassFile classFile = (UnwovenClassFile) i.next(); // getWeaver().addClassFile(classFile); // } // } public FileSystem getLibraryAccess(String[] classpaths, String[] filenames) { String defaultEncoding = buildConfig.getOptions().defaultEncoding; if ("".equals(defaultEncoding)) {//$NON-NLS-1$ defaultEncoding = null; } // Bug 46671: We need an array as long as the number of elements in the classpath - *even though* not every // element of the classpath is likely to be a directory. If we ensure every element of the array is set to // only look for BINARY, then we make sure that for any classpath element that is a directory, we won't build // a classpathDirectory object that will attempt to look for source when it can't find binary. // int[] classpathModes = new int[classpaths.length]; // for (int i =0 ;i<classpaths.length;i++) classpathModes[i]=ClasspathDirectory.BINARY; return new FileSystem(classpaths, filenames, defaultEncoding, ClasspathLocation.BINARY); } public IProblemFactory getProblemFactory() { return new DefaultProblemFactory(Locale.getDefault()); } /* * Build the set of compilation source units */ public CompilationUnit[] getCompilationUnits(String[] filenames) { int fileCount = filenames.length; CompilationUnit[] units = new CompilationUnit[fileCount]; // HashtableOfObject knownFileNames = new HashtableOfObject(fileCount); String defaultEncoding = buildConfig.getOptions().defaultEncoding; if ("".equals(defaultEncoding)) {//$NON-NLS-1$ defaultEncoding = null; } for (int i = 0; i < fileCount; i++) { units[i] = new CompilationUnit(null, filenames[i], defaultEncoding); } return units; } public String extractDestinationPathFromSourceFile(CompilationResult result) { ICompilationUnit compilationUnit = result.compilationUnit; if (compilationUnit != null) { char[] fileName = compilationUnit.getFileName(); int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName); if (lastIndex == -1) { return System.getProperty("user.dir"); //$NON-NLS-1$ } return new String(CharOperation.subarray(fileName, 0, lastIndex)); } return System.getProperty("user.dir"); //$NON-NLS-1$ } public void performCompilation(Collection files) { if (progressListener != null) { compiledCount = 0; sourceFileCount = files.size(); progressListener.setText("compiling source files"); } // Translate from strings to File objects String[] filenames = new String[files.size()]; int idx = 0; for (Iterator fIterator = files.iterator(); fIterator.hasNext();) { File f = (File) fIterator.next(); filenames[idx++] = f.getPath(); } environment = state.getNameEnvironment(); boolean environmentNeedsRebuilding = false; // Might be a bit too cautious, but let us see how it goes if (buildConfig.getChanged() != AjBuildConfig.NO_CHANGES) { environmentNeedsRebuilding = true; } if (environment == null || environmentNeedsRebuilding) { List cps = buildConfig.getFullClasspath(); Dump.saveFullClasspath(cps); String[] classpaths = new String[cps.size()]; for (int i = 0; i < cps.size(); i++) { classpaths[i] = (String) cps.get(i); } environment = new StatefulNameEnvironment(getLibraryAccess(classpaths, filenames), state.getClassNameToFileMap(), state); state.setNameEnvironment(environment); } org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(this); org.aspectj.org.eclipse.jdt.internal.compiler.Compiler compiler = new org.aspectj.org.eclipse.jdt.internal.compiler.Compiler( environment, DefaultErrorHandlingPolicies.proceedWithAllProblems(), buildConfig.getOptions().getMap(), getBatchRequestor(), getProblemFactory()); compiler.options.produceReferenceInfo = true; // TODO turn off when not needed try { compiler.compile(getCompilationUnits(filenames)); } catch (OperationCanceledException oce) { handler.handleMessage(new Message("build cancelled:" + oce.getMessage(), IMessage.WARNING, null, null)); } // cleanup org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(null); AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(null); environment.cleanup(); // environment = null; } public void cleanupEnvironment() { if (environment != null) { environment.cleanup(); environment = null; } } /* * Answer the component to which will be handed back compilation results from the compiler */ public IIntermediateResultsRequestor getInterimResultRequestor() { return new IIntermediateResultsRequestor() { public void acceptResult(InterimCompilationResult result) { if (progressListener != null) { compiledCount++; progressListener.setProgress((compiledCount / 2.0) / sourceFileCount); progressListener.setText("compiled: " + result.fileName()); } state.noteResult(result); if (progressListener != null && progressListener.isCancelledRequested()) { throw new AbortCompilation(true, new OperationCanceledException("Compilation cancelled as requested")); } } }; } public ICompilerRequestor getBatchRequestor() { return new ICompilerRequestor() { public void acceptResult(CompilationResult unitResult) { // end of compile, must now write the results to the output destination // this is either a jar file or a file in a directory boolean hasErrors = unitResult.hasErrors(); if (!hasErrors || proceedOnError()) { Collection classFiles = unitResult.compiledTypes.values(); boolean shouldAddAspectName = (buildConfig.getOutxmlName() != null); for (Iterator iter = classFiles.iterator(); iter.hasNext();) { ClassFile classFile = (ClassFile) iter.next(); String filename = new String(classFile.fileName()); String classname = filename.replace('/', '.'); filename = filename.replace('/', File.separatorChar) + ".class"; try { if (buildConfig.getOutputJar() == null) { String outfile = writeDirectoryEntry(unitResult, classFile, filename); if (environmentSupportsIncrementalCompilation) { if (!classname.endsWith("$ajcMightHaveAspect")) { ResolvedType type = getBcelWorld().resolve(classname); if (type.isAspect()) { state.recordAspectClassFile(outfile); } } } } else { writeZipEntry(classFile, filename); } if (shouldAddAspectName && !classname.endsWith("$ajcMightHaveAspect")) addAspectName(classname, unitResult.getFileName()); } catch (IOException ex) { IMessage message = EclipseAdapterUtils.makeErrorMessage(new String(unitResult.fileName), CANT_WRITE_RESULT, ex); handler.handleMessage(message); } } state.noteNewResult(unitResult); unitResult.compiledTypes.clear(); // free up references to AjClassFile instances } if (unitResult.hasProblems() || unitResult.hasTasks()) { IProblem[] problems = unitResult.getAllProblems(); for (int i = 0; i < problems.length; i++) { IMessage message = EclipseAdapterUtils.makeMessage(unitResult.compilationUnit, problems[i], getBcelWorld(),progressListener); handler.handleMessage(message); } } } private String writeDirectoryEntry(CompilationResult unitResult, ClassFile classFile, String filename) throws IOException { File destinationPath = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { destinationPath = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass( new File(new String(unitResult.fileName))); } String outFile; if (destinationPath == null) { outFile = new File(filename).getName(); outFile = new File(extractDestinationPathFromSourceFile(unitResult), outFile).getPath(); } else { outFile = new File(destinationPath, filename).getPath(); } BufferedOutputStream os = FileUtil.makeOutputStream(new File(outFile)); os.write(classFile.getBytes()); os.close(); if (buildConfig.getCompilationResultDestinationManager() != null) { buildConfig.getCompilationResultDestinationManager().reportFileWrite(outFile, CompilationResultDestinationManager.FILETYPE_CLASS); } return outFile; } private void writeZipEntry(ClassFile classFile, String name) throws IOException { name = name.replace(File.separatorChar, '/'); ZipEntry newEntry = new ZipEntry(name); // ??? get compression scheme right zos.putNextEntry(newEntry); zos.write(classFile.getBytes()); zos.closeEntry(); } private void addAspectName(String name, char[] fileContainingAspect) { BcelWorld world = getBcelWorld(); ResolvedType type = world.resolve(name); // System.err.println("? writeAspectName() type=" + type); if (type.isAspect()) { if (state.getAspectNamesToFileNameMap() == null) { state.initializeAspectNamesToFileNameMap(); } if (!state.getAspectNamesToFileNameMap().containsKey(name)) { state.getAspectNamesToFileNameMap().put(name, fileContainingAspect); } } } }; } protected boolean proceedOnError() { return buildConfig.getProceedOnError(); } // public void noteClassFiles(AjCompiler.InterimResult result) { // if (result == null) return; // CompilationResult unitResult = result.result; // String sourceFileName = result.fileName(); // if (!(unitResult.hasErrors() && !proceedOnError())) { // List unwovenClassFiles = new ArrayList(); // Enumeration classFiles = unitResult.compiledTypes.elements(); // while (classFiles.hasMoreElements()) { // ClassFile classFile = (ClassFile) classFiles.nextElement(); // String filename = new String(classFile.fileName()); // filename = filename.replace('/', File.separatorChar) + ".class"; // // File destinationPath = buildConfig.getOutputDir(); // if (destinationPath == null) { // filename = new File(filename).getName(); // filename = new File(extractDestinationPathFromSourceFile(unitResult), filename).getPath(); // } else { // filename = new File(destinationPath, filename).getPath(); // } // // //System.out.println("classfile: " + filename); // unwovenClassFiles.add(new UnwovenClassFile(filename, classFile.getBytes())); // } // state.noteClassesFromFile(unitResult, sourceFileName, unwovenClassFiles); // // System.out.println("file: " + sourceFileName); // // for (int i=0; i < unitResult.simpleNameReferences.length; i++) { // // System.out.println("simple: " + new String(unitResult.simpleNameReferences[i])); // // } // // for (int i=0; i < unitResult.qualifiedReferences.length; i++) { // // System.out.println("qualified: " + // // new String(CharOperation.concatWith(unitResult.qualifiedReferences[i], '/'))); // // } // } else { // state.noteClassesFromFile(null, sourceFileName, Collections.EMPTY_LIST); // } // } // private void setBuildConfig(AjBuildConfig buildConfig) { this.buildConfig = buildConfig; if (!this.environmentSupportsIncrementalCompilation) { this.environmentSupportsIncrementalCompilation = (buildConfig.isIncrementalMode() || buildConfig .isIncrementalFileMode()); } handler.reset(); } String makeClasspathString(AjBuildConfig buildConfig) { if (buildConfig == null || buildConfig.getFullClasspath() == null) return ""; StringBuffer buf = new StringBuffer(); boolean first = true; for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext();) { if (first) { first = false; } else { buf.append(File.pathSeparator); } buf.append(it.next().toString()); } return buf.toString(); } /** * This will return null if aspectjrt.jar is present and has the correct version. Otherwise it will return a string message * indicating the problem. */ private String checkRtJar(AjBuildConfig buildConfig) { // omitting dev info if (Version.text.equals(Version.DEVELOPMENT)) { // in the development version we can't do this test usefully // MessageUtil.info(holder, "running development version of aspectj compiler"); return null; } if (buildConfig == null || buildConfig.getFullClasspath() == null) return "no classpath specified"; String ret = null; for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext();) { File p = new File((String) it.next()); // pr112830, allow variations on aspectjrt.jar of the form aspectjrtXXXXXX.jar if (p.isFile() && p.getName().startsWith("aspectjrt") && p.getName().endsWith(".jar")) { try { String version = null; Manifest manifest = new JarFile(p).getManifest(); if (manifest == null) { ret = "no manifest found in " + p.getAbsolutePath() + ", expected " + Version.text; continue; } Attributes attr = manifest.getAttributes("org/aspectj/lang/"); if (null != attr) { version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION); if (null != version) { version = version.trim(); } } // assume that users of development aspectjrt.jar know what they're doing if (Version.DEVELOPMENT.equals(version)) { // MessageUtil.info(holder, // "running with development version of aspectjrt.jar in " + // p.getAbsolutePath()); return null; } else if (!Version.text.equals(version)) { ret = "bad version number found in " + p.getAbsolutePath() + " expected " + Version.text + " found " + version; continue; } } catch (IOException ioe) { ret = "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe; } return null; // this is the "OK" return value! } else { // might want to catch other classpath errors } } if (ret != null) return ret; // last error found in potentially matching jars... return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString(buildConfig); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("AjBuildManager("); buf.append(")"); return buf.toString(); } // // public void setStructureModel(IHierarchy structureModel) { // this.structureModel = structureModel; // } /** * Returns null if there is no structure model */ public AsmManager getStructureModel() { return (state == null ? null : state.getStructureModel()); } public IProgressListener getProgressListener() { return progressListener; } public void setProgressListener(IProgressListener progressListener) { this.progressListener = progressListener; } /* * (non-Javadoc) * * @see org.aspectj.ajdt.internal.compiler.AjCompiler.IOutputClassFileNameProvider#getOutputClassFileName(char[]) */ public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) { String filename = new String(eclipseClassFileName); filename = filename.replace('/', File.separatorChar) + ".class"; File destinationPath = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { File f = new File(new String(result.getFileName())); destinationPath = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass(f); } String outFile; if (destinationPath == null) { outFile = new File(filename).getName(); outFile = new File(extractDestinationPathFromSourceFile(result), outFile).getPath(); } else { outFile = new File(destinationPath, filename).getPath(); } return outFile; } /* * (non-Javadoc) * * @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler) */ public ICompilerAdapter getAdapter(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) { // complete compiler config and return a suitable adapter... populateCompilerOptionsFromLintSettings(forCompiler); AjProblemReporter pr = new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(), forCompiler.options, getProblemFactory()); forCompiler.problemReporter = pr; AjLookupEnvironment le = new AjLookupEnvironment(forCompiler, forCompiler.options, pr, environment); EclipseFactory factory = new EclipseFactory(le, this); le.factory = factory; pr.factory = factory; forCompiler.lookupEnvironment = le; forCompiler.parser = new Parser(pr, forCompiler.options.parseLiteralExpressionsAsConstants); if (getBcelWorld().shouldPipelineCompilation()) { IMessage message = MessageUtil.info("Pipelining compilation"); handler.handleMessage(message); return new AjPipeliningCompilerAdapter(forCompiler, batchCompile, getBcelWorld(), getWeaver(), factory, getInterimResultRequestor(), progressListener, this, // IOutputFilenameProvider this, // IBinarySourceProvider state.getBinarySourceMap(), buildConfig.isTerminateAfterCompilation(), buildConfig.getProceedOnError(), buildConfig.isNoAtAspectJAnnotationProcessing(), state); } else { return new AjCompilerAdapter(forCompiler, batchCompile, getBcelWorld(), getWeaver(), factory, getInterimResultRequestor(), progressListener, this, // IOutputFilenameProvider this, // IBinarySourceProvider state.getBinarySourceMap(), buildConfig.isTerminateAfterCompilation(), buildConfig.getProceedOnError(), buildConfig.isNoAtAspectJAnnotationProcessing(), state); } } /** * Some AspectJ lint options need to be known about in the compiler. This is how we pass them over... * * @param forCompiler */ private void populateCompilerOptionsFromLintSettings(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) { BcelWorld world = this.state.getBcelWorld(); IMessage.Kind swallowedExceptionKind = world.getLint().swallowedExceptionInCatchBlock.getKind(); Map optionsMap = new HashMap(); optionsMap.put(CompilerOptions.OPTION_ReportSwallowedExceptionInCatchBlock, swallowedExceptionKind == null ? "ignore" : swallowedExceptionKind.toString()); forCompiler.options.set(optionsMap); } /* * (non-Javadoc) * * @see org.aspectj.ajdt.internal.compiler.IBinarySourceProvider#getBinarySourcesForThisWeave() */ public Map getBinarySourcesForThisWeave() { return binarySourcesForTheNextCompile; } public static AsmHierarchyBuilder getAsmHierarchyBuilder() { return asmHierarchyBuilder; } /** * Override the the default hierarchy builder. */ public static void setAsmHierarchyBuilder(AsmHierarchyBuilder newBuilder) { asmHierarchyBuilder = newBuilder; } public AjState getState() { return state; } public void setState(AjState buildState) { state = buildState; } private static class AjBuildContexFormatter implements ContextFormatter { public String formatEntry(int phaseId, Object data) { StringBuffer sb = new StringBuffer(); if (phaseId == CompilationAndWeavingContext.BATCH_BUILD) { sb.append("batch building "); } else { sb.append("incrementally building "); } AjBuildConfig config = (AjBuildConfig) data; List classpath = config.getClasspath(); sb.append("with classpath: "); for (Iterator iter = classpath.iterator(); iter.hasNext();) { sb.append(iter.next().toString()); sb.append(File.pathSeparator); } return sb.toString(); } } public boolean wasFullBuild() { return wasFullBuild; } }
274,559
Bug 274559 Compile exception when not using debug info
The following project throws a compiler exception when the project property "Add variable attributes to generated class files" is turned off.
resolved fixed
f9578da
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-04-30T21:09:26Z"
"2009-04-30T16:46:40Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/InterTypeMethodDeclaration.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.ast; import java.lang.reflect.Modifier; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.lookup.EclipseTypeMunger; import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter; import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.CodeStream; import org.aspectj.org.eclipse.jdt.internal.compiler.flow.FlowInfo; import org.aspectj.org.eclipse.jdt.internal.compiler.flow.InitializationFlowContext; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilationUnit; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.Constants; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; /** * An inter-type method declaration. * * @author Jim Hugunin */ public class InterTypeMethodDeclaration extends InterTypeDeclaration { public InterTypeMethodDeclaration(CompilationResult result, TypeReference onType) { super(result, onType); } public void parseStatements(Parser parser, CompilationUnitDeclaration unit) { if (ignoreFurtherInvestigation) return; if (!Modifier.isAbstract(declaredModifiers)) { parser.parse(this, unit); } } protected char[] getPrefix() { return (NameMangler.ITD_PREFIX + "interMethod$").toCharArray(); } public boolean isFinal() { return (declaredModifiers & ClassFileConstants.AccFinal) != 0; } public void analyseCode(ClassScope currentScope, InitializationFlowContext flowContext, FlowInfo flowInfo) { if (Modifier.isAbstract(declaredModifiers)) return; super.analyseCode(currentScope, flowContext, flowInfo); } public void resolve(ClassScope upperScope) { if (munger == null) ignoreFurtherInvestigation = true; if (binding == null) ignoreFurtherInvestigation = true; if (ignoreFurtherInvestigation) return; if (!Modifier.isStatic(declaredModifiers)) { this.arguments = AstUtil.insert(AstUtil.makeFinalArgument("ajc$this_".toCharArray(), onTypeBinding), this.arguments); binding.parameters = AstUtil.insert(onTypeBinding, binding.parameters); } super.resolve(upperScope); } public void resolveStatements() { checkAndSetModifiersForMethod(); if ((modifiers & ExtraCompilerModifiers.AccSemicolonBody) != 0) { if ((declaredModifiers & ClassFileConstants.AccAbstract) == 0) scope.problemReporter().methodNeedBody(this); } else { // the method HAS a body --> abstract native modifiers are forbiden if (((declaredModifiers & ClassFileConstants.AccAbstract) != 0)) scope.problemReporter().methodNeedingNoBody(this); } // XXX AMC we need to do this, but I'm not 100% comfortable as I don't // know why the return type is wrong in this case. Also, we don't seem to need // to do it for args... if (munger.getSignature().getReturnType().isRawType()) { if (!binding.returnType.isRawType()) { EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope); binding.returnType = world.makeTypeBinding(munger.getSignature().getReturnType()); } } // check @Override annotation - based on MethodDeclaration.resolveStatements() @Override processing checkOverride: { if (this.binding == null) break checkOverride; if (this.scope.compilerOptions().sourceLevel < ClassFileConstants.JDK1_5) break checkOverride; boolean hasOverrideAnnotation = (this.binding.tagBits & TagBits.AnnotationOverride) != 0; // Need to verify if (hasOverrideAnnotation) { // Work out the real method binding that we can use for comparison EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope); MethodBinding realthing = world.makeMethodBinding(munger.getSignature(), munger.getTypeVariableAliases()); boolean reportError = true; // Go up the hierarchy, looking for something we override ReferenceBinding supertype = onTypeBinding.superclass(); while (supertype != null && reportError) { MethodBinding[] possibles = supertype.getMethods(declaredSelector); for (int i = 0; i < possibles.length; i++) { MethodBinding mb = possibles[i]; boolean couldBeMatch = true; if (mb.parameters.length != realthing.parameters.length) couldBeMatch = false; else { for (int j = 0; j < mb.parameters.length && couldBeMatch; j++) { if (!mb.parameters[j].equals(realthing.parameters[j])) couldBeMatch = false; } } // return types compatible? (allow for covariance) if (couldBeMatch && !returnType.resolvedType.isCompatibleWith(mb.returnType)) couldBeMatch = false; if (couldBeMatch) reportError = false; } supertype = supertype.superclass(); // superclass of object is null } // If we couldn't find something we override, report the error if (reportError) ((AjProblemReporter) this.scope.problemReporter()).itdMethodMustOverride(this, realthing); } } if (!Modifier.isAbstract(declaredModifiers)) super.resolveStatements(); if (Modifier.isStatic(declaredModifiers)) { // Check the target for ITD is not an interface if (onTypeBinding.isInterface()) { scope.problemReporter().signalError(sourceStart, sourceEnd, "methods in interfaces cannot be declared static"); } } } public EclipseTypeMunger build(ClassScope classScope) { EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(classScope); resolveOnType(classScope); if (ignoreFurtherInvestigation) return null; binding = classScope.referenceContext.binding.resolveTypesFor(binding); if (binding == null) { // if binding is null, we failed to find a type used in the method params, this error // has already been reported. this.ignoreFurtherInvestigation = true; // return null; throw new AbortCompilationUnit(compilationResult, null); } if (isTargetAnnotation(classScope, "method")) return null; // Error message output in isTargetAnnotation if (isTargetEnum(classScope, "method")) return null; // Error message output in isTargetEnum if (interTypeScope == null) return null; // We encountered a problem building the scope, don't continue - error already reported // This signature represents what we want consumers of the targetted type to 'see' // must use the factory method to build it since there may be typevariables from the binding // referred to in the parameters/returntype ResolvedMember sig = factory.makeResolvedMemberForITD(binding, onTypeBinding, interTypeScope.getRecoveryAliases()); sig.resetName(new String(declaredSelector)); int resetModifiers = declaredModifiers; if (binding.isVarargs()) resetModifiers = resetModifiers | Constants.ACC_VARARGS; sig.resetModifiers(resetModifiers); NewMethodTypeMunger myMunger = new NewMethodTypeMunger(sig, null, typeVariableAliases); setMunger(myMunger); ResolvedType aspectType = factory.fromEclipse(classScope.referenceContext.binding); ResolvedMember me = myMunger.getInterMethodBody(aspectType); this.selector = binding.selector = me.getName().toCharArray(); return new EclipseTypeMunger(factory, myMunger, aspectType, this); } private AjAttribute makeAttribute() { return new AjAttribute.TypeMunger(munger); } public void generateCode(ClassScope classScope, ClassFile classFile) { if (ignoreFurtherInvestigation) { // System.err.println("no code for " + this); return; } classFile.extraAttributes.add(new EclipseAttributeAdapter(makeAttribute())); if (!Modifier.isAbstract(declaredModifiers)) { super.generateCode(classScope, classFile); // this makes the interMethodBody } // annotations on the ITD declaration get put on this method generateDispatchMethod(classScope, classFile); } public void generateDispatchMethod(ClassScope classScope, ClassFile classFile) { EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope); UnresolvedType aspectType = world.fromBinding(classScope.referenceContext.binding); ResolvedMember signature = munger.getSignature(); ResolvedMember dispatchMember = AjcMemberMaker.interMethodDispatcher(signature, aspectType); MethodBinding dispatchBinding = world.makeMethodBinding(dispatchMember, munger.getTypeVariableAliases(), munger .getSignature().getDeclaringType()); MethodBinding introducedMethod = world.makeMethodBinding(AjcMemberMaker.interMethod(signature, aspectType, onTypeBinding .isInterface()), munger.getTypeVariableAliases()); classFile.generateMethodInfoHeader(dispatchBinding); int methodAttributeOffset = classFile.contentsOffset; // Watch out! We are passing in 'binding' here (instead of dispatchBinding) so that // the dispatch binding attributes will include the annotations from the 'binding'. // There is a chance that something else on the binding (e.g. throws clause) might // damage the attributes generated for the dispatch binding. int attributeNumber = classFile.generateMethodInfoAttribute(binding, false, makeEffectiveSignatureAttribute(signature, Shadow.MethodCall, false)); int codeAttributeOffset = classFile.contentsOffset; classFile.generateCodeAttributeHeader(); CodeStream codeStream = classFile.codeStream; codeStream.reset(this, classFile); codeStream.initializeMaxLocals(dispatchBinding); Argument[] itdArgs = this.arguments; if (itdArgs != null) { for (int a = 0; a < itdArgs.length; a++) { LocalVariableBinding lvb = itdArgs[a].binding; LocalVariableBinding lvbCopy = new LocalVariableBinding(lvb.name, lvb.type, lvb.modifiers, true); codeStream.record(lvbCopy); lvbCopy.recordInitializationStartPC(0); lvbCopy.resolvedPosition = lvb.resolvedPosition; } } MethodBinding methodBinding = introducedMethod; TypeBinding[] parameters = methodBinding.parameters; int length = parameters.length; int resolvedPosition; if (methodBinding.isStatic()) resolvedPosition = 0; else { codeStream.aload_0(); resolvedPosition = 1; } for (int i = 0; i < length; i++) { codeStream.load(parameters[i], resolvedPosition); if ((parameters[i] == TypeBinding.DOUBLE) || (parameters[i] == TypeBinding.LONG)) resolvedPosition += 2; else resolvedPosition++; } // TypeBinding type; if (methodBinding.isStatic()) codeStream.invokestatic(methodBinding); else { if (methodBinding.declaringClass.isInterface()) { codeStream.invokeinterface(methodBinding); } else { codeStream.invokevirtual(methodBinding); } } AstUtil.generateReturn(dispatchBinding.returnType, codeStream); // tag the local variables as used throughout the method if (itdArgs != null) { for (int a = 0; a < itdArgs.length; a++) { codeStream.locals[a].recordInitializationEndPC(codeStream.position); } } classFile.completeCodeAttribute(codeAttributeOffset); attributeNumber++; classFile.completeMethodInfo(methodAttributeOffset, attributeNumber); } protected Shadow.Kind getShadowKindForBody() { return Shadow.MethodExecution; } // XXX this code is copied from MethodScope, with a few adjustments for ITDs... private void checkAndSetModifiersForMethod() { // for reported problems, we want the user to see the declared selector char[] realSelector = this.selector; this.selector = declaredSelector; final ReferenceBinding declaringClass = this.binding.declaringClass; if ((declaredModifiers & ExtraCompilerModifiers.AccAlternateModifierProblem) != 0) scope.problemReporter().duplicateModifierForMethod(onTypeBinding, this); // after this point, tests on the 16 bits reserved. int realModifiers = declaredModifiers & ExtraCompilerModifiers.AccJustFlag; // check for abnormal modifiers int unexpectedModifiers = ~(ClassFileConstants.AccPublic | ClassFileConstants.AccPrivate | ClassFileConstants.AccProtected | ClassFileConstants.AccAbstract | ClassFileConstants.AccStatic | ClassFileConstants.AccFinal | ClassFileConstants.AccSynchronized | ClassFileConstants.AccNative | ClassFileConstants.AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) { scope.problemReporter().illegalModifierForMethod(this); declaredModifiers &= ~ExtraCompilerModifiers.AccJustFlag | ~unexpectedModifiers; } // check for incompatible modifiers in the visibility bits, isolate the visibility bits int accessorBits = realModifiers & (ClassFileConstants.AccPublic | ClassFileConstants.AccProtected | ClassFileConstants.AccPrivate); if ((accessorBits & (accessorBits - 1)) != 0) { scope.problemReporter().illegalVisibilityModifierCombinationForMethod(onTypeBinding, this); // need to keep the less restrictive so disable Protected/Private as necessary if ((accessorBits & ClassFileConstants.AccPublic) != 0) { if ((accessorBits & ClassFileConstants.AccProtected) != 0) declaredModifiers &= ~ClassFileConstants.AccProtected; if ((accessorBits & ClassFileConstants.AccPrivate) != 0) declaredModifiers &= ~ClassFileConstants.AccPrivate; } else if ((accessorBits & ClassFileConstants.AccProtected) != 0 && (accessorBits & ClassFileConstants.AccPrivate) != 0) { declaredModifiers &= ~ClassFileConstants.AccPrivate; } } // check for modifiers incompatible with abstract modifier if ((declaredModifiers & ClassFileConstants.AccAbstract) != 0) { int incompatibleWithAbstract = ClassFileConstants.AccStatic | ClassFileConstants.AccFinal | ClassFileConstants.AccSynchronized | ClassFileConstants.AccNative | ClassFileConstants.AccStrictfp; if ((declaredModifiers & incompatibleWithAbstract) != 0) scope.problemReporter().illegalAbstractModifierCombinationForMethod(onTypeBinding, this); if (!onTypeBinding.isAbstract()) scope.problemReporter().abstractMethodInAbstractClass((SourceTypeBinding) onTypeBinding, this); } /* * DISABLED for backward compatibility with javac (if enabled should also mark private methods as final) // methods from a * final class are final : 8.4.3.3 if (methodBinding.declaringClass.isFinal()) modifiers |= AccFinal; */ // native methods cannot also be tagged as strictfp if ((declaredModifiers & ClassFileConstants.AccNative) != 0 && (declaredModifiers & ClassFileConstants.AccStrictfp) != 0) scope.problemReporter().nativeMethodsCannotBeStrictfp(onTypeBinding, this); // static members are only authorized in a static member or top level type if (((realModifiers & ClassFileConstants.AccStatic) != 0) && declaringClass.isNestedType() && !declaringClass.isStatic()) scope.problemReporter().unexpectedStaticModifierForMethod(onTypeBinding, this); // restore the true selector now that any problems have been reported this.selector = realSelector; } }
274,986
Bug 274986 DocumentParser incorrectly caches DTD InputStream
Build ID: 1.6.3 Steps To Reproduce: Attempt to parse two aop.xml files using two DocumentParsers that are loaded by the same class loader. If the DTD is loaded from a JAR file you'll get an NPE at java.util.zip.Inflater.inflateBytes(Native Method). More information: DocumentParser caches the DTD InputStream in a static final field. Many InputStreams are unusable after being closed so the same instance should not be used here. For InflaterInputStreams there seems to be a bug in the JRE that prevents the stream from reporting itself as closed when you use it again.
resolved fixed
66235e8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-05-05T23:45:14Z"
"2009-05-05T13:26:40Z"
weaver/src/org/aspectj/weaver/loadtime/definition/DocumentParser.java
/******************************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Alexandre Vasseur initial implementation *******************************************************************************/ package org.aspectj.weaver.loadtime.definition; import java.io.InputStream; import java.net.URL; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import org.aspectj.util.LangUtil; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; /** * FIXME AV - doc, concrete aspect * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public class DocumentParser extends DefaultHandler { /** * The current DTD public id. The matching dtd will be searched as a resource. */ private final static String DTD_PUBLIC_ID = "-//AspectJ//DTD 1.5.0//EN"; /** * The DTD alias, for better user experience. */ private final static String DTD_PUBLIC_ID_ALIAS = "-//AspectJ//DTD//EN"; /** * A handler to the DTD stream so that we are only using one file descriptor */ private final static InputStream DTD_STREAM = DocumentParser.class.getResourceAsStream("/aspectj_1_5_0.dtd"); private final static String ASPECTJ_ELEMENT = "aspectj"; private final static String WEAVER_ELEMENT = "weaver"; private final static String DUMP_ELEMENT = "dump"; private final static String DUMP_BEFOREANDAFTER_ATTRIBUTE = "beforeandafter"; private final static String DUMP_PERCLASSLOADERDIR_ATTRIBUTE = "perclassloaderdumpdir"; private final static String INCLUDE_ELEMENT = "include"; private final static String EXCLUDE_ELEMENT = "exclude"; private final static String OPTIONS_ATTRIBUTE = "options"; private final static String ASPECTS_ELEMENT = "aspects"; private final static String ASPECT_ELEMENT = "aspect"; private final static String CONCRETE_ASPECT_ELEMENT = "concrete-aspect"; private final static String NAME_ATTRIBUTE = "name"; private final static String SCOPE_ATTRIBUTE = "scope"; private final static String EXTEND_ATTRIBUTE = "extends"; private final static String PRECEDENCE_ATTRIBUTE = "precedence"; private final static String PERCLAUSE_ATTRIBUTE = "perclause"; private final static String POINTCUT_ELEMENT = "pointcut"; private final static String WITHIN_ATTRIBUTE = "within"; private final static String EXPRESSION_ATTRIBUTE = "expression"; private final Definition m_definition; private boolean m_inAspectJ; private boolean m_inWeaver; private boolean m_inAspects; private Definition.ConcreteAspect m_lastConcreteAspect; private DocumentParser() { m_definition = new Definition(); } public static Definition parse(final URL url) throws Exception { InputStream in = null; try { DocumentParser parser = new DocumentParser(); XMLReader xmlReader = getXMLReader(); xmlReader.setContentHandler(parser); xmlReader.setErrorHandler(parser); try { xmlReader.setFeature("http://xml.org/sax/features/validation", false); } catch (SAXException e) { // fine, the parser don't do validation } try { xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false); } catch (SAXException e) { // fine, the parser don't do validation } try { xmlReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); } catch (SAXException e) { // fine, the parser don't do validation } xmlReader.setEntityResolver(parser); in = url.openStream(); xmlReader.parse(new InputSource(in)); return parser.m_definition; } finally { try { in.close(); } catch (Throwable t) { } } } private static XMLReader getXMLReader() throws SAXException, ParserConfigurationException { XMLReader xmlReader = null; /* Try this first for Java 5 */ try { xmlReader = XMLReaderFactory.createXMLReader(); } /* .. and ignore "System property ... not set" and then try this instead */ catch (SAXException ex) { xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); } return xmlReader; } public InputSource resolveEntity(String publicId, String systemId) throws SAXException { if (publicId.equals(DTD_PUBLIC_ID) || publicId.equals(DTD_PUBLIC_ID_ALIAS)) { InputStream in = DTD_STREAM; if (in == null) { System.err.println("AspectJ - WARN - could not read DTD " + publicId); return null; } else { return new InputSource(in); } } else { System.err.println("AspectJ - WARN - unknown DTD " + publicId + " - consider using " + DTD_PUBLIC_ID); return null; } } public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (ASPECT_ELEMENT.equals(qName)) { String name = attributes.getValue(NAME_ATTRIBUTE); String scopePattern = replaceXmlAnd(attributes.getValue(SCOPE_ATTRIBUTE)); if (!isNull(name)) { m_definition.getAspectClassNames().add(name); if (scopePattern != null) { m_definition.addScopedAspect(name, scopePattern); } } } else if (WEAVER_ELEMENT.equals(qName)) { String options = attributes.getValue(OPTIONS_ATTRIBUTE); if (!isNull(options)) { m_definition.appendWeaverOptions(options); } m_inWeaver = true; } else if (CONCRETE_ASPECT_ELEMENT.equals(qName)) { String name = attributes.getValue(NAME_ATTRIBUTE); String extend = attributes.getValue(EXTEND_ATTRIBUTE); String precedence = attributes.getValue(PRECEDENCE_ATTRIBUTE); String perclause = attributes.getValue(PERCLAUSE_ATTRIBUTE); if (!isNull(name)) { m_lastConcreteAspect = new Definition.ConcreteAspect(name, extend, precedence, perclause); // if (isNull(precedence) && !isNull(extend)) {// if no precedence, then extends must be there // m_lastConcreteAspect = new Definition.ConcreteAspect(name, extend); // } else if (!isNull(precedence)) { // // wether a pure precedence def, or an extendsANDprecedence def. // m_lastConcreteAspect = new Definition.ConcreteAspect(name, extend, precedence, perclause); // } m_definition.getConcreteAspects().add(m_lastConcreteAspect); } } else if (POINTCUT_ELEMENT.equals(qName) && m_lastConcreteAspect != null) { String name = attributes.getValue(NAME_ATTRIBUTE); String expression = attributes.getValue(EXPRESSION_ATTRIBUTE); if (!isNull(name) && !isNull(expression)) { m_lastConcreteAspect.pointcuts.add(new Definition.Pointcut(name, replaceXmlAnd(expression))); } } else if (ASPECTJ_ELEMENT.equals(qName)) { if (m_inAspectJ) { throw new SAXException("Found nested <aspectj> element"); } m_inAspectJ = true; } else if (ASPECTS_ELEMENT.equals(qName)) { m_inAspects = true; } else if (INCLUDE_ELEMENT.equals(qName) && m_inWeaver) { String typePattern = getWithinAttribute(attributes); if (!isNull(typePattern)) { m_definition.getIncludePatterns().add(typePattern); } } else if (EXCLUDE_ELEMENT.equals(qName) && m_inWeaver) { String typePattern = getWithinAttribute(attributes); if (!isNull(typePattern)) { m_definition.getExcludePatterns().add(typePattern); } } else if (DUMP_ELEMENT.equals(qName) && m_inWeaver) { String typePattern = getWithinAttribute(attributes); if (!isNull(typePattern)) { m_definition.getDumpPatterns().add(typePattern); } String beforeAndAfter = attributes.getValue(DUMP_BEFOREANDAFTER_ATTRIBUTE); if (isTrue(beforeAndAfter)) { m_definition.setDumpBefore(true); } String perWeaverDumpDir = attributes.getValue(DUMP_PERCLASSLOADERDIR_ATTRIBUTE); if (isTrue(perWeaverDumpDir)) { m_definition.setCreateDumpDirPerClassloader(true); } } else if (EXCLUDE_ELEMENT.equals(qName) && m_inAspects) { String typePattern = getWithinAttribute(attributes); if (!isNull(typePattern)) { m_definition.getAspectExcludePatterns().add(typePattern); } } else if (INCLUDE_ELEMENT.equals(qName) && m_inAspects) { String typePattern = getWithinAttribute(attributes); if (!isNull(typePattern)) { m_definition.getAspectIncludePatterns().add(typePattern); } } else { throw new SAXException("Unknown element while parsing <aspectj> element: " + qName); } super.startElement(uri, localName, qName, attributes); } private String getWithinAttribute(Attributes attributes) { return replaceXmlAnd(attributes.getValue(WITHIN_ATTRIBUTE)); } public void endElement(String uri, String localName, String qName) throws SAXException { if (CONCRETE_ASPECT_ELEMENT.equals(qName)) { m_lastConcreteAspect = null; } else if (ASPECTJ_ELEMENT.equals(qName)) { m_inAspectJ = false; } else if (WEAVER_ELEMENT.equals(qName)) { m_inWeaver = false; } else if (ASPECTS_ELEMENT.equals(qName)) { m_inAspects = false; } super.endElement(uri, localName, qName); } // TODO AV - define what we want for XML parser error - for now stderr public void warning(SAXParseException e) throws SAXException { super.warning(e); } public void error(SAXParseException e) throws SAXException { super.error(e); } public void fatalError(SAXParseException e) throws SAXException { super.fatalError(e); } private static String replaceXmlAnd(String expression) { // TODO AV do we need to handle "..)AND" or "AND(.." ? return LangUtil.replace(expression, " AND ", " && "); } private boolean isNull(String s) { return (s == null || s.length() <= 0); } private boolean isTrue(String s) { return (s != null && s.equals("true")); } }
279,120
Bug 279120 NPE determining annotation target kind during weaving
reported on the list: Hi, I am using aspectj LTW (aspectjweaver-1.6.1) for weaving an aspect available in another jar within my web application code. While building the jar which contains the aspect, using maven, I have JUnits which run without any problems using LTW. My aspect code looks as below @Around("execution (@com.arisglobal.aglite.annotations.OperationTrail public * *(..)) && this(executor)") public Object auditOperation(ProceedingJoinPoint thisJoinPoint, Object executor) { ... ... aspect code ... } However when I deploy the application in tomcat (with javaagent:aspectjweaver-1.6.1.jar option), I get a NPE which I have pasted below. Jun 4, 2009 12:06:18 PM org.aspectj.weaver.tools.Jdk14Trace error SEVERE: com/arisglobal/aglite/services/actiontrail/ActionTrailAspect java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelObjectType.getAnnotationTargetKinds(BcelO bjectType.java:612) at org.aspectj.weaver.ReferenceType.getAnnotationTargetKinds(ReferenceTy pe.java:265) at org.aspectj.weaver.patterns.SignaturePattern.checkForIncorrectTargetK ind(SignaturePattern.java:112) at org.aspectj.weaver.patterns.SignaturePattern.checkForIncorrectTargetK ind(SignaturePattern.java:94) at org.aspectj.weaver.patterns.SignaturePattern.resolveBindings(Signatur ePattern.java:87) at org.aspectj.weaver.patterns.KindedPointcut.resolveBindings(KindedPoin tcut.java:262) at org.aspectj.weaver.patterns.AndPointcut.resolveBindings(AndPointcut.j ava:75) at org.aspectj.weaver.patterns.Pointcut.resolve(Pointcut.java:196) at org.aspectj.weaver.bcel.AtAjAttributes.handleAroundAnnotation(AtAjAtt ributes.java:1308) at org.aspectj.weaver.bcel.AtAjAttributes.readAj5MethodAttributes(AtAjAt tributes.java:403) at org.aspectj.weaver.bcel.BcelMethod.unpackAjAttributes(BcelMethod.java :189) at org.aspectj.weaver.bcel.BcelMethod.<init>(BcelMethod.java:96) at org.aspectj.weaver.bcel.BcelObjectType.getDeclaredMethods(BcelObjectT ype.java:264) at org.aspectj.weaver.bcel.LazyClassGen.<init>(LazyClassGen.java:303) at org.aspectj.weaver.bcel.BcelObjectType.getLazyClassGen(BcelObjectType .java:524) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1728) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1 696) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:145 8) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1244) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor. java:423) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.jav a:286) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:95) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(C lassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:1 22) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java :155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) I also tried using aspectjweaver-1.6.4 version however got the same error.
resolved fixed
3417cbe
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-06-04T15:43:11Z"
"2009-06-04T15:40:00Z"
weaver/src/org/aspectj/weaver/bcel/BcelObjectType.java
/* ******************************************************************* * Copyright (c) 2002 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * RonBodkin/AndyClement optimizations for memory consumption/speed * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.PrintStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.aspectj.apache.bcel.classfile.AttributeUtils; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen; import org.aspectj.apache.bcel.classfile.annotation.ArrayElementValueGen; import org.aspectj.apache.bcel.classfile.annotation.ElementNameValuePairGen; import org.aspectj.apache.bcel.classfile.annotation.ElementValueGen; import org.aspectj.apache.bcel.classfile.annotation.EnumElementValueGen; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.GenericSignature; import org.aspectj.weaver.AbstractReferenceTypeDelegate; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.AnnotationTargetKind; import org.aspectj.weaver.BCException; import org.aspectj.weaver.BindingScope; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.SourceContextImpl; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelGenericSignatureToTypeXConverter.GenericSignatureFormatException; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.DeclareErrorOrWarning; import org.aspectj.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.FormalBinding; import org.aspectj.weaver.patterns.IScope; import org.aspectj.weaver.patterns.PerClause; public class BcelObjectType extends AbstractReferenceTypeDelegate { public JavaClass javaClass; private LazyClassGen lazyClassGen = null; // set lazily if it's an aspect private int modifiers; private String className; private String superclassSignature; private String superclassName; private String[] interfaceSignatures; private ResolvedMember[] fields = null; private ResolvedMember[] methods = null; private ResolvedType[] annotationTypes = null; private AnnotationAJ[] annotations = null; private TypeVariable[] typeVars = null; private String retentionPolicy; private AnnotationTargetKind[] annotationTargetKinds; // Aspect related stuff (pointcuts *could* be in a java class) private AjAttribute.WeaverVersionInfo wvInfo = AjAttribute.WeaverVersionInfo.UNKNOWN; private ResolvedPointcutDefinition[] pointcuts = null; private ResolvedMember[] privilegedAccess = null; private WeaverStateInfo weaverState = null; private PerClause perClause = null; private List typeMungers = Collections.EMPTY_LIST; private List declares = Collections.EMPTY_LIST; private GenericSignature.FormalTypeParameter[] formalsForResolution = null; private String declaredSignature = null; private boolean hasBeenWoven = false; private boolean isGenericType = false; private boolean isInterface; private boolean isEnum; private boolean isAnnotation; private boolean isAnonymous; private boolean isNested; private boolean isObject = false; // set upon construction private boolean isAnnotationStyleAspect = false;// set upon construction private boolean isCodeStyleAspect = false; // not redundant with field // above! private int bitflag = 0x0000; // discovery bits private static final int DISCOVERED_ANNOTATION_RETENTION_POLICY = 0x0001; private static final int UNPACKED_GENERIC_SIGNATURE = 0x0002; private static final int UNPACKED_AJATTRIBUTES = 0x0004; // see note(1) // below private static final int DISCOVERED_ANNOTATION_TARGET_KINDS = 0x0008; private static final int DISCOVERED_DECLARED_SIGNATURE = 0x0010; private static final int DISCOVERED_WHETHER_ANNOTATION_STYLE = 0x0020; private static final String[] NO_INTERFACE_SIGS = new String[] {}; /* * Notes: note(1): in some cases (perclause inheritance) we encounter unpacked state when calling getPerClause * * note(2): A BcelObjectType is 'damaged' if it has been modified from what was original constructed from the bytecode. This * currently happens if the parents are modified or an annotation is added - ideally BcelObjectType should be immutable but * that's a bigger piece of work. XXX */ // ------------------ construction and initialization BcelObjectType(ReferenceType resolvedTypeX, JavaClass javaClass, boolean exposedToWeaver) { super(resolvedTypeX, exposedToWeaver); this.javaClass = javaClass; initializeFromJavaclass(); // ATAJ: set the delegate right now for @AJ pointcut, else it is done // too late to lookup // @AJ pc refs annotation in class hierarchy resolvedTypeX.setDelegate(this); ISourceContext sourceContext = resolvedTypeX.getSourceContext(); if (sourceContext == SourceContextImpl.UNKNOWN_SOURCE_CONTEXT) { sourceContext = new SourceContextImpl(this); setSourceContext(sourceContext); } // this should only ever be java.lang.Object which is // the only class in Java-1.4 with no superclasses isObject = (javaClass.getSuperclassNameIndex() == 0); ensureAspectJAttributesUnpacked(); // if (sourceContext instanceof SourceContextImpl) { // ((SourceContextImpl)sourceContext).setSourceFileName(javaClass. // getSourceFileName()); // } setSourcefilename(javaClass.getSourceFileName()); } // repeat initialization public void setJavaClass(JavaClass newclass) { this.javaClass = newclass; resetState(); initializeFromJavaclass(); } private void initializeFromJavaclass() { isInterface = javaClass.isInterface(); isEnum = javaClass.isEnum(); isAnnotation = javaClass.isAnnotation(); isAnonymous = javaClass.isAnonymous(); isNested = javaClass.isNested(); modifiers = javaClass.getModifiers(); superclassName = javaClass.getSuperclassName(); className = javaClass.getClassName(); cachedGenericClassTypeSignature = null; } // --- getters // Java related public boolean isInterface() { return isInterface; } public boolean isEnum() { return isEnum; } public boolean isAnnotation() { return isAnnotation; } public boolean isAnonymous() { return isAnonymous; } public boolean isNested() { return isNested; } public int getModifiers() { return modifiers; } /** * Must take into account generic signature */ public ResolvedType getSuperclass() { if (isObject) return null; ensureGenericSignatureUnpacked(); if (superclassSignature == null) { if (superclassName == null) superclassName = javaClass.getSuperclassName(); superclassSignature = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(superclassName)).getSignature(); } World world = getResolvedTypeX().getWorld(); ResolvedType res = world.resolve(UnresolvedType.forSignature(superclassSignature)); return res; } public World getWorld() { return getResolvedTypeX().getWorld(); } /** * Retrieves the declared interfaces - this allows for the generic signature on a type. If specified then the generic signature * is used to work out the types - this gets around the results of erasure when the class was originally compiled. */ public ResolvedType[] getDeclaredInterfaces() { ensureGenericSignatureUnpacked(); ResolvedType[] interfaceTypes = null; if (interfaceSignatures == null) { String[] names = javaClass.getInterfaceNames(); if (names.length == 0) { interfaceSignatures = NO_INTERFACE_SIGS; interfaceTypes = ResolvedType.NONE; } else { interfaceSignatures = new String[names.length]; interfaceTypes = new ResolvedType[names.length]; for (int i = 0, len = names.length; i < len; i++) { interfaceTypes[i] = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(names[i])); interfaceSignatures[i] = interfaceTypes[i].getSignature(); } } } else { interfaceTypes = new ResolvedType[interfaceSignatures.length]; for (int i = 0, len = interfaceSignatures.length; i < len; i++) { if (interfaceSignatures[i] == null) { // debug for NPE String msg = "Null interface signature (element:" + i + " of " + interfaceSignatures.length + "). Type for which we" + "are looking at interfaces is " + this.className + "."; System.err.println(msg); throw new BCException(msg); } interfaceTypes[i] = getResolvedTypeX().getWorld().resolve(UnresolvedType.forSignature(interfaceSignatures[i])); } } return interfaceTypes; } public ResolvedMember[] getDeclaredMethods() { ensureGenericSignatureUnpacked(); if (methods == null) { Method[] ms = javaClass.getMethods(); methods = new ResolvedMember[ms.length]; for (int i = ms.length - 1; i >= 0; i--) { methods[i] = new BcelMethod(this, ms[i]); } } return methods; } public ResolvedMember[] getDeclaredFields() { ensureGenericSignatureUnpacked(); if (fields == null) { Field[] fs = javaClass.getFields(); fields = new ResolvedMember[fs.length]; for (int i = 0, len = fs.length; i < len; i++) { fields[i] = new BcelField(this, fs[i]); } } return fields; } public TypeVariable[] getTypeVariables() { if (!isGeneric()) return TypeVariable.NONE; if (typeVars == null) { GenericSignature.ClassSignature classSig = getGenericClassTypeSignature();// cachedGenericClassTypeSignature // ; // / // / // javaClass // . // getGenericClassTypeSignature(); typeVars = new TypeVariable[classSig.formalTypeParameters.length]; for (int i = 0; i < typeVars.length; i++) { GenericSignature.FormalTypeParameter ftp = classSig.formalTypeParameters[i]; try { typeVars[i] = BcelGenericSignatureToTypeXConverter.formalTypeParameter2TypeVariable(ftp, classSig.formalTypeParameters, getResolvedTypeX().getWorld()); } catch (GenericSignatureFormatException e) { // this is a development bug, so fail fast with good info throw new IllegalStateException("While getting the type variables for type " + this.toString() + " with generic signature " + classSig + " the following error condition was detected: " + e.getMessage()); } } } return typeVars; } // Aspect related public Collection getTypeMungers() { return typeMungers; } public Collection getDeclares() { return declares; } public Collection getPrivilegedAccesses() { if (privilegedAccess == null) return Collections.EMPTY_LIST; return Arrays.asList(privilegedAccess); } public ResolvedMember[] getDeclaredPointcuts() { return pointcuts; } public boolean isAspect() { return perClause != null; } /** * Check if the type is an @AJ aspect (no matter if used from an LTW point of view). Such aspects are annotated with @Aspect * * @return true for @AJ aspect */ public boolean isAnnotationStyleAspect() { if ((bitflag & DISCOVERED_WHETHER_ANNOTATION_STYLE) == 0) { bitflag |= DISCOVERED_WHETHER_ANNOTATION_STYLE; isAnnotationStyleAspect = !isCodeStyleAspect && hasAnnotation(AjcMemberMaker.ASPECT_ANNOTATION); } return isAnnotationStyleAspect; } /** * Process any org.aspectj.weaver attributes stored against the class. */ private void ensureAspectJAttributesUnpacked() { if ((bitflag & UNPACKED_AJATTRIBUTES) != 0) return; bitflag |= UNPACKED_AJATTRIBUTES; IMessageHandler msgHandler = getResolvedTypeX().getWorld().getMessageHandler(); // Pass in empty list that can store things for readAj5 to process List l = Utility.readAjAttributes(className, javaClass.getAttributes(), getResolvedTypeX().getSourceContext(), getResolvedTypeX().getWorld(), AjAttribute.WeaverVersionInfo.UNKNOWN); List pointcuts = new ArrayList(); typeMungers = new ArrayList(); declares = new ArrayList(); processAttributes(l, pointcuts, false); l = AtAjAttributes.readAj5ClassAttributes(((BcelWorld) getResolvedTypeX().getWorld()).getModelAsAsmManager(), javaClass, getResolvedTypeX(), getResolvedTypeX().getSourceContext(), msgHandler, isCodeStyleAspect); AjAttribute.Aspect deferredAspectAttribute = processAttributes(l, pointcuts, true); if (pointcuts.size() == 0) { this.pointcuts = ResolvedPointcutDefinition.NO_POINTCUTS; } else { this.pointcuts = (ResolvedPointcutDefinition[]) pointcuts.toArray(new ResolvedPointcutDefinition[pointcuts.size()]); } resolveAnnotationDeclares(l); if (deferredAspectAttribute != null) { // we can finally process the aspect and its associated perclause... perClause = deferredAspectAttribute.reifyFromAtAspectJ(this.getResolvedTypeX()); } if (isAspect() && !Modifier.isAbstract(getModifiers()) && isGeneric()) { msgHandler.handleMessage(MessageUtil.error("The generic aspect '" + getResolvedTypeX().getName() + "' must be declared abstract", getResolvedTypeX().getSourceLocation())); } } private AjAttribute.Aspect processAttributes(List attributeList, List pointcuts, boolean fromAnnotations) { AjAttribute.Aspect deferredAspectAttribute = null; for (Iterator iter = attributeList.iterator(); iter.hasNext();) { AjAttribute a = (AjAttribute) iter.next(); // System.err.println("unpacking: " + this + " and " + a); if (a instanceof AjAttribute.Aspect) { if (fromAnnotations) { deferredAspectAttribute = (AjAttribute.Aspect) a; } else { perClause = ((AjAttribute.Aspect) a).reify(this.getResolvedTypeX()); isCodeStyleAspect = true; } } else if (a instanceof AjAttribute.PointcutDeclarationAttribute) { pointcuts.add(((AjAttribute.PointcutDeclarationAttribute) a).reify()); } else if (a instanceof AjAttribute.WeaverState) { weaverState = ((AjAttribute.WeaverState) a).reify(); } else if (a instanceof AjAttribute.TypeMunger) { typeMungers.add(((AjAttribute.TypeMunger) a).reify(getResolvedTypeX().getWorld(), getResolvedTypeX())); } else if (a instanceof AjAttribute.DeclareAttribute) { declares.add(((AjAttribute.DeclareAttribute) a).getDeclare()); } else if (a instanceof AjAttribute.PrivilegedAttribute) { privilegedAccess = ((AjAttribute.PrivilegedAttribute) a).getAccessedMembers(); } else if (a instanceof AjAttribute.SourceContextAttribute) { if (getResolvedTypeX().getSourceContext() instanceof SourceContextImpl) { AjAttribute.SourceContextAttribute sca = (AjAttribute.SourceContextAttribute) a; ((SourceContextImpl) getResolvedTypeX().getSourceContext()).configureFromAttribute(sca.getSourceFileName(), sca .getLineBreaks()); setSourcefilename(sca.getSourceFileName()); } } else if (a instanceof AjAttribute.WeaverVersionInfo) { wvInfo = (AjAttribute.WeaverVersionInfo) a; // Set the weaver // version used to // build this type } else { throw new BCException("bad attribute " + a); } } return deferredAspectAttribute; } /** * Extra processing step needed because declares that come from annotations are not pre-resolved. We can't do the resolution * until *after* the pointcuts have been resolved. * * @param attributeList */ private void resolveAnnotationDeclares(List attributeList) { FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; IScope bindingScope = new BindingScope(getResolvedTypeX(), getResolvedTypeX().getSourceContext(), bindings); for (Iterator iter = attributeList.iterator(); iter.hasNext();) { AjAttribute a = (AjAttribute) iter.next(); if (a instanceof AjAttribute.DeclareAttribute) { Declare decl = (((AjAttribute.DeclareAttribute) a).getDeclare()); if (decl instanceof DeclareErrorOrWarning) { decl.resolve(bindingScope); } else if (decl instanceof DeclarePrecedence) { ((DeclarePrecedence) decl).setScopeForResolution(bindingScope); } } } } public PerClause getPerClause() { ensureAspectJAttributesUnpacked(); return perClause; } public JavaClass getJavaClass() { return javaClass; } public void resetState() { if (javaClass == null) { // we might store the classname and allow reloading? // At this point we are relying on the world to not evict if it // might want to reweave multiple times throw new BCException("can't weave evicted type"); } bitflag = 0x0000; this.annotationTypes = null; this.annotations = null; this.interfaceSignatures = null; this.superclassSignature = null; this.superclassName = null; this.fields = null; this.methods = null; this.pointcuts = null; this.perClause = null; this.weaverState = null; this.lazyClassGen = null; hasBeenWoven = false; isObject = (javaClass.getSuperclassNameIndex() == 0); isAnnotationStyleAspect = false; ensureAspectJAttributesUnpacked(); } public void finishedWith() { // memory usage experiments.... // this.interfaces = null; // this.superClass = null; // this.fields = null; // this.methods = null; // this.pointcuts = null; // this.perClause = null; // this.weaverState = null; // this.lazyClassGen = null; // this next line frees up memory, but need to understand incremental // implications // before leaving it in. // getResolvedTypeX().setSourceContext(null); } public WeaverStateInfo getWeaverState() { return weaverState; } void setWeaverState(WeaverStateInfo weaverState) { this.weaverState = weaverState; } public void printWackyStuff(PrintStream out) { if (typeMungers.size() > 0) out.println(" TypeMungers: " + typeMungers); if (declares.size() > 0) out.println(" declares: " + declares); } /** * Return the lazyClassGen associated with this type. For aspect types, this value will be cached, since it is used to inline * advice. For non-aspect types, this lazyClassGen is always newly constructed. */ public LazyClassGen getLazyClassGen() { LazyClassGen ret = lazyClassGen; if (ret == null) { // System.err.println("creating lazy class gen for: " + this); ret = new LazyClassGen(this); // ret.print(System.err); // System.err.println("made LCG from : " + // this.getJavaClass().getSuperclassName ); if (isAspect()) { lazyClassGen = ret; } } return ret; } public boolean isSynthetic() { return getResolvedTypeX().isSynthetic(); } public AjAttribute.WeaverVersionInfo getWeaverVersionAttribute() { return wvInfo; } // -- annotation related public ResolvedType[] getAnnotationTypes() { ensureAnnotationsUnpacked(); return annotationTypes; } public AnnotationAJ[] getAnnotations() { ensureAnnotationsUnpacked(); return annotations; } public boolean hasAnnotation(UnresolvedType ofType) { ensureAnnotationsUnpacked(); for (int i = 0; i < annotationTypes.length; i++) { ResolvedType ax = annotationTypes[i]; if (ax.equals(ofType)) return true; } return false; } public boolean isAnnotationWithRuntimeRetention() { return (getRetentionPolicy() == null ? false : getRetentionPolicy().equals("RUNTIME")); } public String getRetentionPolicy() { if ((bitflag & DISCOVERED_ANNOTATION_RETENTION_POLICY) == 0) { bitflag |= DISCOVERED_ANNOTATION_RETENTION_POLICY; retentionPolicy = null; // null means we have no idea if (isAnnotation()) { ensureAnnotationsUnpacked(); for (int i = annotations.length - 1; i >= 0; i--) { AnnotationAJ ax = annotations[i]; if (ax.getTypeName().equals(UnresolvedType.AT_RETENTION.getName())) { List values = ((BcelAnnotation) ax).getBcelAnnotation().getValues(); for (Iterator it = values.iterator(); it.hasNext();) { ElementNameValuePairGen element = (ElementNameValuePairGen) it.next(); EnumElementValueGen v = (EnumElementValueGen) element.getValue(); retentionPolicy = v.getEnumValueString(); return retentionPolicy; } } } } } return retentionPolicy; } public boolean canAnnotationTargetType() { AnnotationTargetKind[] targetKinds = getAnnotationTargetKinds(); if (targetKinds == null) return true; for (int i = 0; i < targetKinds.length; i++) { if (targetKinds[i].equals(AnnotationTargetKind.TYPE)) { return true; } } return false; } public AnnotationTargetKind[] getAnnotationTargetKinds() { if ((bitflag & DISCOVERED_ANNOTATION_TARGET_KINDS) != 0) return annotationTargetKinds; bitflag |= DISCOVERED_ANNOTATION_TARGET_KINDS; annotationTargetKinds = null; // null means we have no idea or the // @Target annotation hasn't been used List targetKinds = new ArrayList(); if (isAnnotation()) { AnnotationGen[] annotationsOnThisType = javaClass.getAnnotations(); for (int i = 0; i < annotationsOnThisType.length; i++) { AnnotationGen a = annotationsOnThisType[i]; if (a.getTypeName().equals(UnresolvedType.AT_TARGET.getName())) { ArrayElementValueGen arrayValue = (ArrayElementValueGen) ((ElementNameValuePairGen) a.getValues().get(0)) .getValue(); ElementValueGen[] evs = arrayValue.getElementValuesArray(); if (evs != null) { for (int j = 0; j < evs.length; j++) { String targetKind = ((EnumElementValueGen) evs[j]).getEnumValueString(); if (targetKind.equals("ANNOTATION_TYPE")) { targetKinds.add(AnnotationTargetKind.ANNOTATION_TYPE); } else if (targetKind.equals("CONSTRUCTOR")) { targetKinds.add(AnnotationTargetKind.CONSTRUCTOR); } else if (targetKind.equals("FIELD")) { targetKinds.add(AnnotationTargetKind.FIELD); } else if (targetKind.equals("LOCAL_VARIABLE")) { targetKinds.add(AnnotationTargetKind.LOCAL_VARIABLE); } else if (targetKind.equals("METHOD")) { targetKinds.add(AnnotationTargetKind.METHOD); } else if (targetKind.equals("PACKAGE")) { targetKinds.add(AnnotationTargetKind.PACKAGE); } else if (targetKind.equals("PARAMETER")) { targetKinds.add(AnnotationTargetKind.PARAMETER); } else if (targetKind.equals("TYPE")) { targetKinds.add(AnnotationTargetKind.TYPE); } } } } } if (!targetKinds.isEmpty()) { annotationTargetKinds = new AnnotationTargetKind[targetKinds.size()]; return (AnnotationTargetKind[]) targetKinds.toArray(annotationTargetKinds); } } return annotationTargetKinds; } // --- unpacking methods private void ensureAnnotationsUnpacked() { if (annotationTypes == null) { AnnotationGen annos[] = javaClass.getAnnotations(); if (annos == null || annos.length == 0) { annotationTypes = ResolvedType.NONE; annotations = AnnotationAJ.EMPTY_ARRAY; } else { World w = getResolvedTypeX().getWorld(); annotationTypes = new ResolvedType[annos.length]; annotations = new AnnotationAJ[annos.length]; for (int i = 0; i < annos.length; i++) { AnnotationGen annotation = annos[i]; annotationTypes[i] = w.resolve(UnresolvedType.forSignature(annotation.getTypeSignature())); annotations[i] = new BcelAnnotation(annotation, w); } } } } // --- public String getDeclaredGenericSignature() { ensureGenericInfoProcessed(); return declaredSignature; } private void ensureGenericSignatureUnpacked() { if ((bitflag & UNPACKED_GENERIC_SIGNATURE) != 0) return; bitflag |= UNPACKED_GENERIC_SIGNATURE; if (!getResolvedTypeX().getWorld().isInJava5Mode()) return; GenericSignature.ClassSignature cSig = getGenericClassTypeSignature(); if (cSig != null) { formalsForResolution = cSig.formalTypeParameters; if (isNested()) { // we have to find any type variables from the outer type before // proceeding with resolution. GenericSignature.FormalTypeParameter[] extraFormals = getFormalTypeParametersFromOuterClass(); if (extraFormals.length > 0) { List allFormals = new ArrayList(); for (int i = 0; i < formalsForResolution.length; i++) { allFormals.add(formalsForResolution[i]); } for (int i = 0; i < extraFormals.length; i++) { allFormals.add(extraFormals[i]); } formalsForResolution = new GenericSignature.FormalTypeParameter[allFormals.size()]; allFormals.toArray(formalsForResolution); } } GenericSignature.ClassTypeSignature superSig = cSig.superclassSignature; try { // this.superClass = // BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX( // superSig, formalsForResolution, // getResolvedTypeX().getWorld()); ResolvedType rt = BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(superSig, formalsForResolution, getResolvedTypeX().getWorld()); this.superclassSignature = rt.getSignature(); this.superclassName = rt.getName(); } catch (GenericSignatureFormatException e) { // development bug, fail fast with good info throw new IllegalStateException("While determining the generic superclass of " + this.className + " with generic signature " + getDeclaredGenericSignature() + " the following error was detected: " + e.getMessage()); } // this.interfaces = new // ResolvedType[cSig.superInterfaceSignatures.length]; if (cSig.superInterfaceSignatures.length == 0) { this.interfaceSignatures = NO_INTERFACE_SIGS; } else { this.interfaceSignatures = new String[cSig.superInterfaceSignatures.length]; for (int i = 0; i < cSig.superInterfaceSignatures.length; i++) { try { // this.interfaces[i] = // BcelGenericSignatureToTypeXConverter. // classTypeSignature2TypeX( // cSig.superInterfaceSignatures[i], // formalsForResolution, // getResolvedTypeX().getWorld()); this.interfaceSignatures[i] = BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX( cSig.superInterfaceSignatures[i], formalsForResolution, getResolvedTypeX().getWorld()) .getSignature(); } catch (GenericSignatureFormatException e) { // development bug, fail fast with good info throw new IllegalStateException("While determing the generic superinterfaces of " + this.className + " with generic signature " + getDeclaredGenericSignature() + " the following error was detected: " + e.getMessage()); } } } } if (isGeneric()) { // update resolved typex to point at generic type not raw type. ReferenceType genericType = (ReferenceType) this.resolvedTypeX.getGenericType(); // genericType.setSourceContext(this.resolvedTypeX.getSourceContext() // ); genericType.setStartPos(this.resolvedTypeX.getStartPos()); this.resolvedTypeX = genericType; } } public GenericSignature.FormalTypeParameter[] getAllFormals() { ensureGenericSignatureUnpacked(); if (formalsForResolution == null) { return new GenericSignature.FormalTypeParameter[0]; } else { return formalsForResolution; } } public ResolvedType getOuterClass() { if (!isNested()) throw new IllegalStateException("Can't get the outer class of a non-nested type"); int lastDollar = className.lastIndexOf('$'); String superClassName = className.substring(0, lastDollar); UnresolvedType outer = UnresolvedType.forName(superClassName); return outer.resolve(getResolvedTypeX().getWorld()); } private void ensureGenericInfoProcessed() { if ((bitflag & DISCOVERED_DECLARED_SIGNATURE) != 0) return; bitflag |= DISCOVERED_DECLARED_SIGNATURE; Signature sigAttr = AttributeUtils.getSignatureAttribute(javaClass.getAttributes()); declaredSignature = (sigAttr == null ? null : sigAttr.getSignature()); if (declaredSignature != null) isGenericType = (declaredSignature.charAt(0) == '<'); } public boolean isGeneric() { ensureGenericInfoProcessed(); return isGenericType; } public String toString() { return (javaClass == null ? "BcelObjectType" : "BcelObjectTypeFor:" + className); } // --- state management public void evictWeavingState() { // Can't chuck all this away if (getResolvedTypeX().getWorld().couldIncrementalCompileFollow()) return; if (javaClass != null) { // Force retrieval of any lazy information ensureAnnotationsUnpacked(); ensureGenericInfoProcessed(); getDeclaredInterfaces(); getDeclaredFields(); getDeclaredMethods(); // The lazyClassGen is preserved for aspects - it exists to enable // around advice // inlining since the method will need 'injecting' into the affected // class. If // XnoInline is on, we can chuck away the lazyClassGen since it // won't be required // later. if (getResolvedTypeX().getWorld().isXnoInline()) lazyClassGen = null; // discard expensive bytecode array containing reweavable info if (weaverState != null) { weaverState.setReweavable(false); weaverState.setUnwovenClassFileData(null); } for (int i = methods.length - 1; i >= 0; i--) methods[i].evictWeavingState(); for (int i = fields.length - 1; i >= 0; i--) fields[i].evictWeavingState(); javaClass = null; // setSourceContext(SourceContextImpl.UNKNOWN_SOURCE_CONTEXT); // // bit naughty // interfaces=null; // force reinit - may get us the right // instances! // superClass=null; } } public void weavingCompleted() { hasBeenWoven = true; if (getResolvedTypeX().getWorld().isRunMinimalMemory()) evictWeavingState(); if (getSourceContext() != null && !getResolvedTypeX().isAspect()) getSourceContext().tidy(); } public boolean hasBeenWoven() { return hasBeenWoven; } public boolean copySourceContext() { return false; } }
280,783
Bug 280783 JavaDocRunner fails on System.setSecurityManager in Netbeans
null
resolved fixed
59d5c3b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-06-18T18:37:30Z"
"2009-06-18T15:46:40Z"
ajdoc/src/org/aspectj/tools/ajdoc/JavadocRunner.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Xerox/PARC initial implementation * Mik Kersten port to AspectJ 1.1+ code base * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * @author Mik Kersten */ class JavadocRunner { static boolean has14ToolsAvailable() { try { Class jdMainClass = com.sun.tools.javadoc.Main.class; Class[] paramTypes = new Class[] {String[].class}; jdMainClass.getMethod("execute", paramTypes); } catch (NoClassDefFoundError e) { return false; } catch (UnsupportedClassVersionError e) { return false; } catch (NoSuchMethodException e) { return false; } return true; } static void callJavadoc( String[] javadocargs ){ final SecurityManager defaultSecurityManager = System.getSecurityManager(); System.setSecurityManager( new SecurityManager() { public void checkExit(int status) { if (status == 0) { throw new SecurityException(); } else { System.setSecurityManager(defaultSecurityManager); //System.out.println("Error: javadoc exited unexpectedly"); System.exit(0); throw new SecurityException(); } } public void checkPermission( java.security.Permission permission ) { if ( defaultSecurityManager != null ) defaultSecurityManager.checkPermission( permission ); } public void checkPermission( java.security.Permission permission, Object context ) { if ( defaultSecurityManager != null ) defaultSecurityManager.checkPermission( permission, context ); } } ); try { // for JDK 1.4 and above call the execute method... Class jdMainClass = com.sun.tools.javadoc.Main.class; Method executeMethod = null; try { Class[] paramTypes = new Class[] {String[].class}; executeMethod = jdMainClass.getMethod("execute", paramTypes); } catch (NoSuchMethodException e) { com.sun.tools.javadoc.Main.main(javadocargs); // throw new UnsupportedOperationException("ajdoc requires a tools library from JDK 1.4 or later."); } try { executeMethod.invoke(null, new Object[] {javadocargs}); } catch (IllegalArgumentException e1) { throw new RuntimeException("Failed to invoke javadoc"); } catch (IllegalAccessException e1) { throw new RuntimeException("Failed to invoke javadoc"); } catch (InvocationTargetException e1) { throw new RuntimeException("Failed to invoke javadoc"); } // main method is documented as calling System.exit() - which stops us dead in our tracks //com.sun.tools.javadoc.Main.main( javadocargs ); } catch ( SecurityException se ) { // Do nothing since we expect it to be thrown //System.out.println( ">> se: " + se.getMessage() ); } // Set the security manager back System.setSecurityManager( defaultSecurityManager ); } }
285,172
Bug 285172 Sometimes when load-time weaving there will be two ReferenceType objects for the same type
Seen by Ramnivas. A pointcut uses an exact type name for an annotation execution(* (@Controller *..*).*(..)) Resolving this pointcut causes us to construct a ReferenceType for 'Controller'. Then we attempt to populate it by loading the class implementation. This recurses back into the weaver as Controller is loaded and an attempt is made to weave it. This takes a second route through the weaver to build a referencetype again and this second referencetype is cached in the world. When we unwind, we continue building the original referencetype and are left with one in the cache and the one resolved for the pointcut. Due to the use of == for comparison, we fail to match on join points later because they will use the ReferenceType from the cache.
resolved fixed
dd7d879
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-07-30T15:29:40Z"
"2009-07-30T16:06:40Z"
org.aspectj.matcher/src/org/aspectj/weaver/World.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * 2005 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Adrian Colyer, Andy Clement, overhaul for generics * ******************************************************************/ package org.aspectj.weaver; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.WeakHashMap; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.bridge.context.PinpointingMessageHandler; import org.aspectj.util.IStructureModel; import org.aspectj.weaver.UnresolvedType.TypeKind; import org.aspectj.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.TypePattern; import org.aspectj.weaver.tools.PointcutDesignatorHandler; import org.aspectj.weaver.tools.Trace; import org.aspectj.weaver.tools.TraceFactory; /** * A World is a collection of known types and crosscutting members. */ public abstract class World implements Dump.INode { /** handler for any messages produced during resolution etc. */ private IMessageHandler messageHandler = IMessageHandler.SYSTEM_ERR; /** * handler for cross-reference information produced during the weaving process */ private ICrossReferenceHandler xrefHandler = null; /** * Currently 'active' scope in which to lookup (resolve) typevariable references */ private TypeVariableDeclaringElement typeVariableLookupScope; /** The heart of the world, a map from type signatures to resolved types */ protected TypeMap typeMap = new TypeMap(this); // Signature to ResolvedType /** New pointcut designators this world supports */ private Set pointcutDesignators; // see pr145963 /** Should we create the hierarchy for binary classes and aspects */ public static boolean createInjarHierarchy = true; /** Calculator for working out aspect precedence */ private final AspectPrecedenceCalculator precedenceCalculator; /** All of the type and shadow mungers known to us */ private final CrosscuttingMembersSet crosscuttingMembersSet = new CrosscuttingMembersSet(this); /** The structure model for the compilation */ private IStructureModel model = null; /** for processing Xlint messages */ private Lint lint = new Lint(this); /** XnoInline option setting passed down to weaver */ private boolean XnoInline; /** XlazyTjp option setting passed down to weaver */ private boolean XlazyTjp; /** XhasMember option setting passed down to weaver */ private boolean XhasMember = false; /** * Xpinpoint controls whether we put out developer info showing the source of messages */ private boolean Xpinpoint = false; /** When behaving in a Java 5 way autoboxing is considered */ private boolean behaveInJava5Way = false; /** Determines if this world could be used for multiple compiles */ private boolean incrementalCompileCouldFollow = false; /** The level of the aspectjrt.jar the code we generate needs to run on */ private String targetAspectjRuntimeLevel = Constants.RUNTIME_LEVEL_DEFAULT; /** Flags for the new joinpoints that are 'optional' */ private boolean optionalJoinpoint_ArrayConstruction = false; // Command line // flag: // "-Xjoinpoints:arrayconstruction" private boolean optionalJoinpoint_Synchronization = false; // Command line // flag: // "-Xjoinpoints:synchronization" private boolean addSerialVerUID = false; private Properties extraConfiguration = null; private boolean checkedAdvancedConfiguration = false; private boolean synchronizationPointcutsInUse = false; // Xset'table options private boolean runMinimalMemory = false; private boolean shouldPipelineCompilation = true; private boolean shouldGenerateStackMaps = false; protected boolean bcelRepositoryCaching = xsetBCEL_REPOSITORY_CACHING_DEFAULT.equalsIgnoreCase("true"); private boolean fastMethodPacking = false; private boolean completeBinaryTypes = false; public boolean forDEBUG_structuralChangesCode = false; public boolean forDEBUG_bridgingCode = false; private static Trace trace = TraceFactory.getTraceFactory().getTrace(World.class); private long errorThreshold; private long warningThreshold; /** * A list of RuntimeExceptions containing full stack information for every type we couldn't find. */ private List dumpState_cantFindTypeExceptions = null; /** * Play God. On the first day, God created the primitive types and put them in the type map. */ protected World() { super(); if (trace.isTraceEnabled()) trace.enter("<init>", this); Dump.registerNode(this.getClass(), this); typeMap.put("B", ResolvedType.BYTE); typeMap.put("S", ResolvedType.SHORT); typeMap.put("I", ResolvedType.INT); typeMap.put("J", ResolvedType.LONG); typeMap.put("F", ResolvedType.FLOAT); typeMap.put("D", ResolvedType.DOUBLE); typeMap.put("C", ResolvedType.CHAR); typeMap.put("Z", ResolvedType.BOOLEAN); typeMap.put("V", ResolvedType.VOID); precedenceCalculator = new AspectPrecedenceCalculator(this); if (trace.isTraceEnabled()) trace.exit("<init>"); } /** * Dump processing when a fatal error occurs */ public void accept(Dump.IVisitor visitor) { // visitor.visitObject("Extra configuration:"); // visitor.visitList(extraConfiguration.); visitor.visitObject("Shadow mungers:"); visitor.visitList(crosscuttingMembersSet.getShadowMungers()); visitor.visitObject("Type mungers:"); visitor.visitList(crosscuttingMembersSet.getTypeMungers()); visitor.visitObject("Late Type mungers:"); visitor.visitList(crosscuttingMembersSet.getLateTypeMungers()); if (dumpState_cantFindTypeExceptions != null) { visitor.visitObject("Cant find type problems:"); visitor.visitList(dumpState_cantFindTypeExceptions); dumpState_cantFindTypeExceptions = null; } } // ========================================================================== // === // T Y P E R E S O L U T I O N // ========================================================================== // === /** * Resolve a type that we require to be present in the world */ public ResolvedType resolve(UnresolvedType ty) { return resolve(ty, false); } /** * Attempt to resolve a type - the source location gives you some context in which resolution is taking place. In the case of an * error where we can't find the type - we can then at least report why (source location) we were trying to resolve it. */ public ResolvedType resolve(UnresolvedType ty, ISourceLocation isl) { ResolvedType ret = resolve(ty, true); if (ResolvedType.isMissing(ty)) { // IMessage msg = null; getLint().cantFindType.signal(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE, ty.getName()), isl); // if (isl!=null) { // msg = MessageUtil.error(WeaverMessages.format(WeaverMessages. // CANT_FIND_TYPE,ty.getName()),isl); // } else { // msg = MessageUtil.error(WeaverMessages.format(WeaverMessages. // CANT_FIND_TYPE,ty.getName())); // } // messageHandler.handleMessage(msg); } return ret; } /** * Convenience method for resolving an array of unresolved types in one hit. Useful for e.g. resolving type parameters in * signatures. */ public ResolvedType[] resolve(UnresolvedType[] types) { if (types == null) return new ResolvedType[0]; ResolvedType[] ret = new ResolvedType[types.length]; for (int i = 0; i < types.length; i++) { ret[i] = resolve(types[i]); } return ret; } /** * Resolve a type. This the hub of type resolution. The resolved type is added to the type map by signature. */ public ResolvedType resolve(UnresolvedType ty, boolean allowMissing) { // special resolution processing for already resolved types. if (ty instanceof ResolvedType) { ResolvedType rty = (ResolvedType) ty; rty = resolve(rty); return rty; } // dispatch back to the type variable reference to resolve its // constituent parts // don't do this for other unresolved types otherwise you'll end up in a // loop if (ty.isTypeVariableReference()) { return ty.resolve(this); } // if we've already got a resolved type for the signature, just return // it // after updating the world String signature = ty.getSignature(); ResolvedType ret = typeMap.get(signature); if (ret != null) { ret.world = this; // Set the world for the RTX return ret; } else if (signature.equals("?") || signature.equals("*")) { // might be a problem here, not sure '?' should make it to here as a // signature, the // proper signature for wildcard '?' is '*' // fault in generic wildcard, can't be done earlier because of init // issues // TODO ought to be shared single instance representing this ResolvedType something = new BoundedReferenceType("*", "Ljava/lang/Object", this); typeMap.put("?", something); return something; } // no existing resolved type, create one if (ty.isArray()) { ResolvedType componentType = resolve(ty.getComponentType(), allowMissing); // String brackets = // signature.substring(0,signature.lastIndexOf("[")+1); ret = new ArrayReferenceType(signature, "[" + componentType.getErasureSignature(), this, componentType); } else { ret = resolveToReferenceType(ty, allowMissing); if (!allowMissing && ret.isMissing()) { ret = handleRequiredMissingTypeDuringResolution(ty); } if (completeBinaryTypes) { completeBinaryType(ret); } } // Pulling in the type may have already put the right entry in the map if (typeMap.get(signature) == null && !ret.isMissing()) { typeMap.put(signature, ret); } return ret; } /** * Called when a type is resolved - enables its type hierarchy to be finished off before we proceed */ protected void completeBinaryType(ResolvedType ret) { } /** * Return true if the classloader relating to this world is definetly the one that will define the specified class. Return false * otherwise or we don't know for certain. */ public boolean isLocallyDefined(String classname) { return false; } /** * We tried to resolve a type and couldn't find it... */ private ResolvedType handleRequiredMissingTypeDuringResolution(UnresolvedType ty) { // defer the message until someone asks a question of the type that we // can't answer // just from the signature. // MessageUtil.error(messageHandler, // WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName())); if (dumpState_cantFindTypeExceptions == null) { dumpState_cantFindTypeExceptions = new ArrayList(); } if (dumpState_cantFindTypeExceptions.size() < 100) { // limit growth dumpState_cantFindTypeExceptions.add(new RuntimeException("Can't find type " + ty.getName())); } return new MissingResolvedTypeWithKnownSignature(ty.getSignature(), this); } /** * Some TypeFactory operations create resolved types directly, but these won't be in the typeMap - this resolution process puts * them there. Resolved types are also told their world which is needed for the special autoboxing resolved types. */ public ResolvedType resolve(ResolvedType ty) { if (ty.isTypeVariableReference()) return ty; // until type variables have proper sigs... ResolvedType resolved = typeMap.get(ty.getSignature()); if (resolved == null) { typeMap.put(ty.getSignature(), ty); resolved = ty; } resolved.world = this; return resolved; } /** * Convenience method for finding a type by name and resolving it in one step. */ public ResolvedType resolve(String name) { // trace.enter("resolve", this, new Object[] {name}); ResolvedType ret = resolve(UnresolvedType.forName(name)); // trace.exit("resolve", ret); return ret; } public ResolvedType resolve(String name, boolean allowMissing) { return resolve(UnresolvedType.forName(name), allowMissing); } /** * Resolve to a ReferenceType - simple, raw, parameterized, or generic. Raw, parameterized, and generic versions of a type share * a delegate. */ private final ResolvedType resolveToReferenceType(UnresolvedType ty, boolean allowMissing) { if (ty.isParameterizedType()) { // ======= parameterized types ================ ResolvedType rt = resolveGenericTypeFor(ty, allowMissing); if (rt.isMissing()) return rt; ReferenceType genericType = (ReferenceType) rt; ReferenceType parameterizedType = TypeFactory.createParameterizedType(genericType, ty.typeParameters, this); return parameterizedType; } else if (ty.isGenericType()) { // ======= generic types ====================== ReferenceType genericType = (ReferenceType) resolveGenericTypeFor(ty, false); return genericType; } else if (ty.isGenericWildcard()) { // ======= generic wildcard types ============= return resolveGenericWildcardFor((WildcardedUnresolvedType) ty); } else { // ======= simple and raw types =============== String erasedSignature = ty.getErasureSignature(); ReferenceType simpleOrRawType = new ReferenceType(erasedSignature, this); if (ty.needsModifiableDelegate()) simpleOrRawType.setNeedsModifiableDelegate(true); ReferenceTypeDelegate delegate = resolveDelegate(simpleOrRawType); // 117854 // if (delegate == null) return ResolvedType.MISSING; if (delegate == null) return new MissingResolvedTypeWithKnownSignature(ty.getSignature(), erasedSignature, this);// ResolvedType // . // MISSING // ; if (delegate.isGeneric() && behaveInJava5Way) { // ======== raw type =========== simpleOrRawType.typeKind = TypeKind.RAW; ReferenceType genericType = makeGenericTypeFrom(delegate, simpleOrRawType); // name = // ReferenceType.fromTypeX(UnresolvedType.forRawTypeNames( // ty.getName()),this); simpleOrRawType.setDelegate(delegate); genericType.setDelegate(delegate); simpleOrRawType.setGenericType(genericType); return simpleOrRawType; } else { // ======== simple type ========= simpleOrRawType.setDelegate(delegate); return simpleOrRawType; } } } /** * Attempt to resolve a type that should be a generic type. */ public ResolvedType resolveGenericTypeFor(UnresolvedType anUnresolvedType, boolean allowMissing) { // Look up the raw type by signature String rawSignature = anUnresolvedType.getRawType().getSignature(); ResolvedType rawType = typeMap.get(rawSignature); if (rawType == null) { rawType = resolve(UnresolvedType.forSignature(rawSignature), allowMissing); typeMap.put(rawSignature, rawType); } if (rawType.isMissing()) return rawType; // Does the raw type know its generic form? (It will if we created the // raw type from a source type, it won't if its been created just // through // being referenced, e.g. java.util.List ResolvedType genericType = rawType.getGenericType(); // There is a special case to consider here (testGenericsBang_pr95993 // highlights it) // You may have an unresolvedType for a parameterized type but it // is backed by a simple type rather than a generic type. This occurs // for // inner types of generic types that inherit their enclosing types // type variables. if (rawType.isSimpleType() && (anUnresolvedType.typeParameters == null || anUnresolvedType.typeParameters.length == 0)) { rawType.world = this; return rawType; } if (genericType != null) { genericType.world = this; return genericType; } else { // Fault in the generic that underpins the raw type ;) ReferenceTypeDelegate delegate = resolveDelegate((ReferenceType) rawType); ReferenceType genericRefType = makeGenericTypeFrom(delegate, ((ReferenceType) rawType)); ((ReferenceType) rawType).setGenericType(genericRefType); genericRefType.setDelegate(delegate); ((ReferenceType) rawType).setDelegate(delegate); return genericRefType; } } private ReferenceType makeGenericTypeFrom(ReferenceTypeDelegate delegate, ReferenceType rawType) { String genericSig = delegate.getDeclaredGenericSignature(); if (genericSig != null) { return new ReferenceType(UnresolvedType.forGenericTypeSignature(rawType.getSignature(), delegate .getDeclaredGenericSignature()), this); } else { return new ReferenceType(UnresolvedType.forGenericTypeVariables(rawType.getSignature(), delegate.getTypeVariables()), this); } } /** * Go from an unresolved generic wildcard (represented by UnresolvedType) to a resolved version (BoundedReferenceType). */ private ReferenceType resolveGenericWildcardFor(WildcardedUnresolvedType aType) { BoundedReferenceType ret = null; // FIXME asc doesnt take account of additional interface bounds (e.g. ? // super R & Serializable - can you do that?) if (aType.isExtends()) { ReferenceType upperBound = (ReferenceType) resolve(aType.getUpperBound()); ret = new BoundedReferenceType(upperBound, true, this); } else if (aType.isSuper()) { ReferenceType lowerBound = (ReferenceType) resolve(aType.getLowerBound()); ret = new BoundedReferenceType(lowerBound, false, this); } else { // must be ? on its own! ret = new BoundedReferenceType("*", "Ljava/lang/Object", this); } return ret; } /** * Find the ReferenceTypeDelegate behind this reference type so that it can fulfill its contract. */ protected abstract ReferenceTypeDelegate resolveDelegate(ReferenceType ty); /** * Special resolution for "core" types like OBJECT. These are resolved just like any other type, but if they are not found it is * more serious and we issue an error message immediately. */ // OPTIMIZE streamline path for core types? They are just simple types, // could look straight in the typemap? public ResolvedType getCoreType(UnresolvedType tx) { ResolvedType coreTy = resolve(tx, true); if (coreTy.isMissing()) { MessageUtil.error(messageHandler, WeaverMessages.format(WeaverMessages.CANT_FIND_CORE_TYPE, tx.getName())); } return coreTy; } /** * Lookup a type by signature, if not found then build one and put it in the map. */ public ReferenceType lookupOrCreateName(UnresolvedType ty) { String signature = ty.getSignature(); ReferenceType ret = lookupBySignature(signature); if (ret == null) { ret = ReferenceType.fromTypeX(ty, this); typeMap.put(signature, ret); } return ret; } /** * Lookup a reference type in the world by its signature. Returns null if not found. */ public ReferenceType lookupBySignature(String signature) { return (ReferenceType) typeMap.get(signature); } // ========================================================================== // === // T Y P E R E S O L U T I O N -- E N D // ========================================================================== // === /** * Member resolution is achieved by resolving the declaring type and then looking up the member in the resolved declaring type. */ public ResolvedMember resolve(Member member) { ResolvedType declaring = member.getDeclaringType().resolve(this); if (declaring.isRawType()) declaring = declaring.getGenericType(); ResolvedMember ret; if (member.getKind() == Member.FIELD) { ret = declaring.lookupField(member); } else { ret = declaring.lookupMethod(member); } if (ret != null) return ret; return declaring.lookupSyntheticMember(member); } public abstract IWeavingSupport getWeavingSupport(); /** * Create an advice shadow munger from the given advice attribute */ // public abstract Advice createAdviceMunger(AjAttribute.AdviceAttribute // attribute, Pointcut pointcut, Member signature); /** * Create an advice shadow munger for the given advice kind */ public final Advice createAdviceMunger(AdviceKind kind, Pointcut p, Member signature, int extraParameterFlags, IHasSourceLocation loc) { AjAttribute.AdviceAttribute attribute = new AjAttribute.AdviceAttribute(kind, p, extraParameterFlags, loc.getStart(), loc .getEnd(), loc.getSourceContext()); return getWeavingSupport().createAdviceMunger(attribute, p, signature); } /** * Same signature as org.aspectj.util.PartialOrder.PartialComparable.compareTo */ public int compareByPrecedence(ResolvedType aspect1, ResolvedType aspect2) { return precedenceCalculator.compareByPrecedence(aspect1, aspect2); } public Integer getPrecedenceIfAny(ResolvedType aspect1, ResolvedType aspect2) { return precedenceCalculator.getPrecedenceIfAny(aspect1, aspect2); } /** * compares by precedence with the additional rule that a super-aspect is sorted before its sub-aspects */ public int compareByPrecedenceAndHierarchy(ResolvedType aspect1, ResolvedType aspect2) { return precedenceCalculator.compareByPrecedenceAndHierarchy(aspect1, aspect2); } // simple property getter and setters // =========================================================== /** * Nobody should hold onto a copy of this message handler, or setMessageHandler won't work right. */ public IMessageHandler getMessageHandler() { return messageHandler; } public void setMessageHandler(IMessageHandler messageHandler) { if (this.isInPinpointMode()) { this.messageHandler = new PinpointingMessageHandler(messageHandler); } else { this.messageHandler = messageHandler; } } /** * convenenience method for creating and issuing messages via the message handler - if you supply two locations you will get two * messages. */ public void showMessage(Kind kind, String message, ISourceLocation loc1, ISourceLocation loc2) { if (loc1 != null) { messageHandler.handleMessage(new Message(message, kind, null, loc1)); if (loc2 != null) { messageHandler.handleMessage(new Message(message, kind, null, loc2)); } } else { messageHandler.handleMessage(new Message(message, kind, null, loc2)); } } public void setCrossReferenceHandler(ICrossReferenceHandler xrefHandler) { this.xrefHandler = xrefHandler; } /** * Get the cross-reference handler for the world, may be null. */ public ICrossReferenceHandler getCrossReferenceHandler() { return xrefHandler; } public void setTypeVariableLookupScope(TypeVariableDeclaringElement scope) { typeVariableLookupScope = scope; } public TypeVariableDeclaringElement getTypeVariableLookupScope() { return typeVariableLookupScope; } public List getDeclareParents() { return crosscuttingMembersSet.getDeclareParents(); } public List getDeclareAnnotationOnTypes() { return crosscuttingMembersSet.getDeclareAnnotationOnTypes(); } public List getDeclareAnnotationOnFields() { return crosscuttingMembersSet.getDeclareAnnotationOnFields(); } public List getDeclareAnnotationOnMethods() { return crosscuttingMembersSet.getDeclareAnnotationOnMethods(); } public List getDeclareSoft() { return crosscuttingMembersSet.getDeclareSofts(); } public CrosscuttingMembersSet getCrosscuttingMembersSet() { return crosscuttingMembersSet; } public IStructureModel getModel() { return model; } public void setModel(IStructureModel model) { this.model = model; } public Lint getLint() { return lint; } public void setLint(Lint lint) { this.lint = lint; } public boolean isXnoInline() { return XnoInline; } public void setXnoInline(boolean xnoInline) { XnoInline = xnoInline; } public boolean isXlazyTjp() { return XlazyTjp; } public void setXlazyTjp(boolean b) { XlazyTjp = b; } public boolean isHasMemberSupportEnabled() { return XhasMember; } public void setXHasMemberSupportEnabled(boolean b) { XhasMember = b; } public boolean isInPinpointMode() { return Xpinpoint; } public void setPinpointMode(boolean b) { Xpinpoint = b; } public void setBehaveInJava5Way(boolean b) { behaveInJava5Way = b; } /** * Set the error and warning threashold which can be taken from CompilerOptions (see bug 129282) * * @param errorThreshold * @param warningThreshold */ public void setErrorAndWarningThreshold(long errorThreshold, long warningThreshold) { this.errorThreshold = errorThreshold; this.warningThreshold = warningThreshold; } /** * @return true if ignoring the UnusedDeclaredThrownException and false if this compiler option is set to error or warning */ public boolean isIgnoringUnusedDeclaredThrownException() { // the 0x800000 is CompilerOptions.UnusedDeclaredThrownException // which is ASTNode.bit24 if ((errorThreshold & 0x800000) != 0 || (warningThreshold & 0x800000) != 0) return false; return true; } public void performExtraConfiguration(String config) { if (config == null) return; // Bunch of name value pairs to split extraConfiguration = new Properties(); int pos = -1; while ((pos = config.indexOf(",")) != -1) { String nvpair = config.substring(0, pos); int pos2 = nvpair.indexOf("="); if (pos2 != -1) { String n = nvpair.substring(0, pos2); String v = nvpair.substring(pos2 + 1); extraConfiguration.setProperty(n, v); } config = config.substring(pos + 1); } if (config.length() > 0) { int pos2 = config.indexOf("="); if (pos2 != -1) { String n = config.substring(0, pos2); String v = config.substring(pos2 + 1); extraConfiguration.setProperty(n, v); } } ensureAdvancedConfigurationProcessed(); } /** * may return null */ public Properties getExtraConfiguration() { return extraConfiguration; } public final static String xsetWEAVE_JAVA_PACKAGES = "weaveJavaPackages"; // default // false // - // controls // LTW public final static String xsetWEAVE_JAVAX_PACKAGES = "weaveJavaxPackages"; // default // false // - // controls // LTW public final static String xsetCAPTURE_ALL_CONTEXT = "captureAllContext"; // default // false public final static String xsetRUN_MINIMAL_MEMORY = "runMinimalMemory"; // default // true public final static String xsetDEBUG_STRUCTURAL_CHANGES_CODE = "debugStructuralChangesCode"; // default // false public final static String xsetDEBUG_BRIDGING = "debugBridging"; // default // false public final static String xsetBCEL_REPOSITORY_CACHING = "bcelRepositoryCaching"; public final static String xsetPIPELINE_COMPILATION = "pipelineCompilation"; public final static String xsetGENERATE_STACKMAPS = "generateStackMaps"; public final static String xsetPIPELINE_COMPILATION_DEFAULT = "true"; public final static String xsetCOMPLETE_BINARY_TYPES = "completeBinaryTypes"; public final static String xsetCOMPLETE_BINARY_TYPES_DEFAULT = "false"; public final static String xsetTYPE_DEMOTION = "typeDemotion"; public final static String xsetTYPE_DEMOTION_DEBUG = "typeDemotionDebug"; public final static String xsetTYPE_REFS = "useWeakTypeRefs"; public final static String xsetBCEL_REPOSITORY_CACHING_DEFAULT = "true"; public final static String xsetFAST_PACK_METHODS = "fastPackMethods"; // default // TRUE public boolean isInJava5Mode() { return behaveInJava5Way; } public void setTargetAspectjRuntimeLevel(String s) { targetAspectjRuntimeLevel = s; } public void setOptionalJoinpoints(String jps) { if (jps == null) return; if (jps.indexOf("arrayconstruction") != -1) optionalJoinpoint_ArrayConstruction = true; if (jps.indexOf("synchronization") != -1) optionalJoinpoint_Synchronization = true; } public boolean isJoinpointArrayConstructionEnabled() { return optionalJoinpoint_ArrayConstruction; } public boolean isJoinpointSynchronizationEnabled() { return optionalJoinpoint_Synchronization; } public String getTargetAspectjRuntimeLevel() { return targetAspectjRuntimeLevel; } // OPTIMIZE are users falling foul of not supplying -1.5 and so targetting // the old runtime? public boolean isTargettingAspectJRuntime12() { boolean b = false; // pr116679 if (!isInJava5Mode()) b = true; else b = getTargetAspectjRuntimeLevel().equals(org.aspectj.weaver.Constants.RUNTIME_LEVEL_12); // System.err.println("Asked if targetting runtime 1.2 , returning: "+b); return b; } /* * Map of types in the world, can have 'references' to expendable ones which can be garbage collected to recover memory. An * expendable type is a reference type that is not exposed to the weaver (ie just pulled in for type resolution purposes). */ protected static class TypeMap { private static boolean debug = false; private boolean demotionSystemActive = false; private boolean debugDemotion = false; // Strategy for entries in the expendable map public final static int DONT_USE_REFS = 0; // Hang around forever public final static int USE_WEAK_REFS = 1; // Collected asap public final static int USE_SOFT_REFS = 2; // Collected when short on // memory List addedSinceLastDemote; public int policy = USE_SOFT_REFS; // Map of types that never get thrown away final Map /* String -> ResolvedType */tMap = new HashMap(); // Map of types that may be ejected from the cache if we need space final Map expendableMap = Collections.synchronizedMap(new WeakHashMap()); private final World w; // profiling tools... private boolean memoryProfiling = false; private int maxExpendableMapSize = -1; private int collectedTypes = 0; private final ReferenceQueue rq = new ReferenceQueue(); private static Trace trace = TraceFactory.getTraceFactory().getTrace(World.TypeMap.class); TypeMap(World w) { addedSinceLastDemote = new ArrayList(); this.w = w; memoryProfiling = false;// !w.getMessageHandler().isIgnoring(Message. // INFO); } /** * Go through any types added during the previous file weave. If any are suitable for demotion, then put them in the * expendable map where GC can claim them at some point later. Demotion means: the type is not an aspect, the type is not * java.lang.Object, the type is not primitive and the type is not affected by type mungers in any way. Further refinements * of these conditions may allow for more demotions. * * @return number of types demoted */ public int demote() { if (!demotionSystemActive) { return 0; } int demotionCounter = 0; Iterator iter = addedSinceLastDemote.iterator(); do { if (!iter.hasNext()) { break; } String key = (String) iter.next(); ResolvedType type = (ResolvedType) tMap.get(key); if (type != null && !type.isAspect() && !type.equals(UnresolvedType.OBJECT) && !type.isPrimitiveType()) { List typeMungers = type.getInterTypeMungers(); if (typeMungers == null || typeMungers.size() == 0) { tMap.remove(key); if (!expendableMap.containsKey(key)) { if (policy == USE_SOFT_REFS) { expendableMap.put(key, new SoftReference(type)); } else { expendableMap.put(key, new WeakReference(type)); } } demotionCounter++; } } } while (true); if (debugDemotion) { System.out.println("Demoted " + demotionCounter + " types. Types remaining in fixed set #" + tMap.keySet().size()); } addedSinceLastDemote.clear(); return demotionCounter; } /** * Add a new type into the map, the key is the type signature. Some types do *not* go in the map, these are ones involving * *member* type variables. The reason is that when all you have is the signature which gives you a type variable name, you * cannot guarantee you are using the type variable in the same way as someone previously working with a similarly named * type variable. So, these do not go into the map: - TypeVariableReferenceType. - ParameterizedType where a member type * variable is involved. - BoundedReferenceType when one of the bounds is a type variable. * * definition: "member type variables" - a tvar declared on a generic method/ctor as opposed to those you see declared on a * generic type. */ public ResolvedType put(String key, ResolvedType type) { if (type.isParameterizedType() && type.isParameterizedWithTypeVariable()) { if (debug) System.err .println("Not putting a parameterized type that utilises member declared type variables into the typemap: key=" + key + " type=" + type); return type; } if (type.isTypeVariableReference()) { if (debug) System.err.println("Not putting a type variable reference type into the typemap: key=" + key + " type=" + type); return type; } // this test should be improved - only avoid putting them in if one // of the // bounds is a member type variable if (type instanceof BoundedReferenceType) { if (debug) System.err.println("Not putting a bounded reference type into the typemap: key=" + key + " type=" + type); return type; } if (type instanceof MissingResolvedTypeWithKnownSignature) { if (debug) System.err.println("Not putting a missing type into the typemap: key=" + key + " type=" + type); return type; } if ((type instanceof ReferenceType) && (((ReferenceType) type).getDelegate() == null) && w.isExpendable(type)) { if (debug) System.err.println("Not putting expendable ref type with null delegate into typemap: key=" + key + " type=" + type); return type; } if (w.isExpendable(type)) { // Dont use reference queue for tracking if not profiling... if (policy == USE_WEAK_REFS) { if (memoryProfiling) expendableMap.put(key, new WeakReference(type, rq)); else expendableMap.put(key, new WeakReference(type)); } else if (policy == USE_SOFT_REFS) { if (memoryProfiling) expendableMap.put(key, new SoftReference(type, rq)); else expendableMap.put(key, new SoftReference(type)); } else { expendableMap.put(key, type); } if (memoryProfiling && expendableMap.size() > maxExpendableMapSize) { maxExpendableMapSize = expendableMap.size(); } return type; } else { if (demotionSystemActive) { addedSinceLastDemote.add(key); } return (ResolvedType) tMap.put(key, type); } } public void report() { if (!memoryProfiling) return; checkq(); w.getMessageHandler().handleMessage( MessageUtil.info("MEMORY: world expendable type map reached maximum size of #" + maxExpendableMapSize + " entries")); w.getMessageHandler().handleMessage( MessageUtil.info("MEMORY: types collected through garbage collection #" + collectedTypes + " entries")); } public void checkq() { if (!memoryProfiling) return; while (rq.poll() != null) collectedTypes++; } /** * Lookup a type by its signature, always look in the real map before the expendable map */ public ResolvedType get(String key) { checkq(); ResolvedType ret = (ResolvedType) tMap.get(key); if (ret == null) { if (policy == USE_WEAK_REFS) { WeakReference ref = (WeakReference) expendableMap.get(key); if (ref != null) { ret = (ResolvedType) ref.get(); } } else if (policy == USE_SOFT_REFS) { SoftReference ref = (SoftReference) expendableMap.get(key); if (ref != null) { ret = (ResolvedType) ref.get(); } } else { return (ResolvedType) expendableMap.get(key); } } return ret; } /** Remove a type from the map */ public ResolvedType remove(String key) { ResolvedType ret = (ResolvedType) tMap.remove(key); if (ret == null) { if (policy == USE_WEAK_REFS) { WeakReference wref = (WeakReference) expendableMap.remove(key); if (wref != null) ret = (ResolvedType) wref.get(); } else if (policy == USE_SOFT_REFS) { SoftReference wref = (SoftReference) expendableMap.remove(key); if (wref != null) ret = (ResolvedType) wref.get(); } else { ret = (ResolvedType) expendableMap.remove(key); } } return ret; } // public ResolvedType[] getAllTypes() { // List/* ResolvedType */results = new ArrayList(); // // collectTypes(expendableMap, results); // collectTypes(tMap, results); // return (ResolvedType[]) results.toArray(new // ResolvedType[results.size()]); // } // // private void collectTypes(Map map, List/* ResolvedType */results) { // for (Iterator iterator = map.keySet().iterator(); // iterator.hasNext();) { // String key = (String) iterator.next(); // ResolvedType type = get(key); // if (type != null) // results.add(type); // else // System.err.println("null!:" + key); // } // } } /** * This class is used to compute and store precedence relationships between aspects. */ private static class AspectPrecedenceCalculator { private final World world; private final Map cachedResults; public AspectPrecedenceCalculator(World forSomeWorld) { world = forSomeWorld; cachedResults = new HashMap(); } /** * Ask every declare precedence in the world to order the two aspects. If more than one declare precedence gives an * ordering, and the orderings conflict, then that's an error. */ public int compareByPrecedence(ResolvedType firstAspect, ResolvedType secondAspect) { PrecedenceCacheKey key = new PrecedenceCacheKey(firstAspect, secondAspect); if (cachedResults.containsKey(key)) { return ((Integer) cachedResults.get(key)).intValue(); } else { int order = 0; DeclarePrecedence orderer = null; // Records the declare // precedence statement that // gives the first ordering for (Iterator i = world.getCrosscuttingMembersSet().getDeclareDominates().iterator(); i.hasNext();) { DeclarePrecedence d = (DeclarePrecedence) i.next(); int thisOrder = d.compare(firstAspect, secondAspect); if (thisOrder != 0) { if (orderer == null) orderer = d; if (order != 0 && order != thisOrder) { ISourceLocation[] isls = new ISourceLocation[2]; isls[0] = orderer.getSourceLocation(); isls[1] = d.getSourceLocation(); Message m = new Message("conflicting declare precedence orderings for aspects: " + firstAspect.getName() + " and " + secondAspect.getName(), null, true, isls); world.getMessageHandler().handleMessage(m); } else { order = thisOrder; } } } cachedResults.put(key, new Integer(order)); return order; } } public Integer getPrecedenceIfAny(ResolvedType aspect1, ResolvedType aspect2) { return (Integer) cachedResults.get(new PrecedenceCacheKey(aspect1, aspect2)); } public int compareByPrecedenceAndHierarchy(ResolvedType firstAspect, ResolvedType secondAspect) { if (firstAspect.equals(secondAspect)) return 0; int ret = compareByPrecedence(firstAspect, secondAspect); if (ret != 0) return ret; if (firstAspect.isAssignableFrom(secondAspect)) return -1; else if (secondAspect.isAssignableFrom(firstAspect)) return +1; return 0; } private static class PrecedenceCacheKey { public ResolvedType aspect1; public ResolvedType aspect2; public PrecedenceCacheKey(ResolvedType a1, ResolvedType a2) { aspect1 = a1; aspect2 = a2; } public boolean equals(Object obj) { if (!(obj instanceof PrecedenceCacheKey)) return false; PrecedenceCacheKey other = (PrecedenceCacheKey) obj; return (aspect1 == other.aspect1 && aspect2 == other.aspect2); } public int hashCode() { return aspect1.hashCode() + aspect2.hashCode(); } } } public void validateType(UnresolvedType type) { } // --- with java5 we can get into a recursive mess if we aren't careful when // resolving types (*cough* java.lang.Enum) --- // --- this first map is for java15 delegates which may try and recursively // access the same type variables. // --- I would rather stash this against a reference type - but we don't // guarantee referencetypes are unique for // so we can't :( private final Map workInProgress1 = new HashMap(); public TypeVariable[] getTypeVariablesCurrentlyBeingProcessed(Class baseClass) { return (TypeVariable[]) workInProgress1.get(baseClass); } public void recordTypeVariablesCurrentlyBeingProcessed(Class baseClass, TypeVariable[] typeVariables) { workInProgress1.put(baseClass, typeVariables); } public void forgetTypeVariablesCurrentlyBeingProcessed(Class baseClass) { workInProgress1.remove(baseClass); } public void setAddSerialVerUID(boolean b) { addSerialVerUID = b; } public boolean isAddSerialVerUID() { return addSerialVerUID; } /** be careful calling this - pr152257 */ public void flush() { typeMap.expendableMap.clear(); } public void ensureAdvancedConfigurationProcessed() { // Check *once* whether the user has switched asm support off if (!checkedAdvancedConfiguration) { Properties p = getExtraConfiguration(); if (p != null) { String s = p.getProperty(xsetBCEL_REPOSITORY_CACHING, xsetBCEL_REPOSITORY_CACHING_DEFAULT); bcelRepositoryCaching = s.equalsIgnoreCase("true"); if (!bcelRepositoryCaching) { getMessageHandler().handleMessage( MessageUtil .info("[bcelRepositoryCaching=false] AspectJ will not use a bcel cache for class information")); } s = p.getProperty(xsetFAST_PACK_METHODS, "true"); fastMethodPacking = s.equalsIgnoreCase("true"); s = p.getProperty(xsetPIPELINE_COMPILATION, xsetPIPELINE_COMPILATION_DEFAULT); shouldPipelineCompilation = s.equalsIgnoreCase("true"); s = p.getProperty(xsetGENERATE_STACKMAPS, "false"); shouldGenerateStackMaps = s.equalsIgnoreCase("true"); s = p.getProperty(xsetCOMPLETE_BINARY_TYPES, xsetCOMPLETE_BINARY_TYPES_DEFAULT); completeBinaryTypes = s.equalsIgnoreCase("true"); if (completeBinaryTypes) { getMessageHandler().handleMessage( MessageUtil.info("[completeBinaryTypes=true] Completion of binary types activated")); } s = p.getProperty(xsetTYPE_DEMOTION, "false"); if (s.equalsIgnoreCase("true")) { typeMap.demotionSystemActive = true; } s = p.getProperty(xsetTYPE_DEMOTION_DEBUG, "false"); if (s.equalsIgnoreCase("true")) { typeMap.debugDemotion = true; } s = p.getProperty(xsetTYPE_REFS, "false"); if (s.equalsIgnoreCase("true")) { typeMap.policy = TypeMap.USE_WEAK_REFS; } s = p.getProperty(xsetRUN_MINIMAL_MEMORY, "false"); runMinimalMemory = s.equalsIgnoreCase("true"); // if (runMinimalMemory) // getMessageHandler().handleMessage(MessageUtil.info( // "[runMinimalMemory=true] Optimizing bcel processing (and cost of performance) to use less memory" // )); s = p.getProperty(xsetDEBUG_STRUCTURAL_CHANGES_CODE, "false"); forDEBUG_structuralChangesCode = s.equalsIgnoreCase("true"); s = p.getProperty(xsetDEBUG_BRIDGING, "false"); forDEBUG_bridgingCode = s.equalsIgnoreCase("true"); } checkedAdvancedConfiguration = true; } } public boolean isRunMinimalMemory() { ensureAdvancedConfigurationProcessed(); return runMinimalMemory; } public boolean shouldFastPackMethods() { ensureAdvancedConfigurationProcessed(); return fastMethodPacking; } public boolean shouldPipelineCompilation() { ensureAdvancedConfigurationProcessed(); return shouldPipelineCompilation; } public boolean shouldGenerateStackMaps() { ensureAdvancedConfigurationProcessed(); return shouldGenerateStackMaps; } public void setIncrementalCompileCouldFollow(boolean b) { incrementalCompileCouldFollow = b; } public boolean couldIncrementalCompileFollow() { return incrementalCompileCouldFollow; } public void setSynchronizationPointcutsInUse() { if (trace.isTraceEnabled()) trace.enter("setSynchronizationPointcutsInUse", this); synchronizationPointcutsInUse = true; if (trace.isTraceEnabled()) trace.exit("setSynchronizationPointcutsInUse"); } public boolean areSynchronizationPointcutsInUse() { return synchronizationPointcutsInUse; } /** * Register a new pointcut designator handler with the world - this can be used by any pointcut parsers attached to the world. * * @param designatorHandler handler for the new pointcut */ public void registerPointcutHandler(PointcutDesignatorHandler designatorHandler) { if (pointcutDesignators == null) pointcutDesignators = new HashSet(); pointcutDesignators.add(designatorHandler); } public Set getRegisteredPointcutHandlers() { if (pointcutDesignators == null) return Collections.EMPTY_SET; return pointcutDesignators; } public void reportMatch(ShadowMunger munger, Shadow shadow) { } public void reportCheckerMatch(Checker checker, Shadow shadow) { } /** * @return true if this world has the activation and scope of application of the aspects controlled via aop.xml files */ public boolean isXmlConfigured() { return false; } public boolean isAspectIncluded(ResolvedType aspectType) { return true; } public TypePattern getAspectScope(ResolvedType declaringType) { return null; } public Map getFixed() { return typeMap.tMap; } public Map getExpendable() { return typeMap.expendableMap; } /** * Ask the type map to demote any types it can - we don't want them anchored forever. */ public void demote() { typeMap.demote(); } // protected boolean isExpendable(ResolvedType type) { // if (type.equals(UnresolvedType.OBJECT)) // return false; // if (type == null) // return false; // boolean isExposed = type.isExposedToWeaver(); // boolean nullDele = (type instanceof ReferenceType) ? ((ReferenceType) type).getDelegate() != null : true; // if (isExposed || !isExposed && nullDele) // return false; // return !type.isPrimitiveType(); // } /** * Reference types we don't intend to weave may be ejected from the cache if we need the space. */ protected boolean isExpendable(ResolvedType type) { return (!type.equals(UnresolvedType.OBJECT) && (!type.isExposedToWeaver()) && (!type.isPrimitiveType())); } }
287,315
Bug 287315 NPE using declare @type
reported by Ramnivas: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelObjectType.hasAnnotation(BcelObjectType.java:558) at org.aspectj.weaver.ReferenceType.hasAnnotation(ReferenceType.java:161) at org.aspectj.weaver.patterns.ExactAnnotationTypePattern.matches(ExactAnnotationTypePattern.java:101) at org.aspectj.weaver.patterns.ExactAnnotationTypePattern.matches(ExactAnnotationTypePattern.java:94) at org.aspectj.weaver.patterns.AnyWithAnnotationTypePattern.matchesExactly(TypePattern.java:513) at org.aspectj.weaver.patterns.TypePattern.matchesStatically(TypePattern.java:129) at org.aspectj.weaver.patterns.DeclareAnnotation.matches(DeclareAnnotation.java:269) at org.aspectj.weaver.bcel.BcelWeaver.applyDeclareAtType(BcelWeaver.java:1590)
resolved fixed
b664969
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-08-24T18:07:09Z"
"2009-08-21T15:53:20Z"
weaver/src/org/aspectj/weaver/bcel/BcelObjectType.java
/* ******************************************************************* * Copyright (c) 2002 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * RonBodkin/AndyClement optimizations for memory consumption/speed * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.PrintStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.apache.bcel.classfile.AttributeUtils; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen; import org.aspectj.apache.bcel.classfile.annotation.ElementNameValuePairGen; import org.aspectj.apache.bcel.classfile.annotation.EnumElementValueGen; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.GenericSignature; import org.aspectj.weaver.AbstractReferenceTypeDelegate; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.AnnotationTargetKind; import org.aspectj.weaver.BCException; import org.aspectj.weaver.BindingScope; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.SourceContextImpl; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelGenericSignatureToTypeXConverter.GenericSignatureFormatException; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.DeclareErrorOrWarning; import org.aspectj.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.FormalBinding; import org.aspectj.weaver.patterns.IScope; import org.aspectj.weaver.patterns.PerClause; public class BcelObjectType extends AbstractReferenceTypeDelegate { public JavaClass javaClass; private LazyClassGen lazyClassGen = null; // set lazily if it's an aspect private int modifiers; private String className; private String superclassSignature; private String superclassName; private String[] interfaceSignatures; private ResolvedMember[] fields = null; private ResolvedMember[] methods = null; private ResolvedType[] annotationTypes = null; private AnnotationAJ[] annotations = null; private TypeVariable[] typeVars = null; private String retentionPolicy; private AnnotationTargetKind[] annotationTargetKinds; // Aspect related stuff (pointcuts *could* be in a java class) private AjAttribute.WeaverVersionInfo wvInfo = AjAttribute.WeaverVersionInfo.UNKNOWN; private ResolvedPointcutDefinition[] pointcuts = null; private ResolvedMember[] privilegedAccess = null; private WeaverStateInfo weaverState = null; private PerClause perClause = null; private List typeMungers = Collections.EMPTY_LIST; private List declares = Collections.EMPTY_LIST; private GenericSignature.FormalTypeParameter[] formalsForResolution = null; private String declaredSignature = null; private boolean hasBeenWoven = false; private boolean isGenericType = false; private boolean isInterface; private boolean isEnum; private boolean isAnnotation; private boolean isAnonymous; private boolean isNested; private boolean isObject = false; // set upon construction private boolean isAnnotationStyleAspect = false;// set upon construction private boolean isCodeStyleAspect = false; // not redundant with field // above! private int bitflag = 0x0000; // discovery bits private static final int DISCOVERED_ANNOTATION_RETENTION_POLICY = 0x0001; private static final int UNPACKED_GENERIC_SIGNATURE = 0x0002; private static final int UNPACKED_AJATTRIBUTES = 0x0004; // see note(1) // below private static final int DISCOVERED_ANNOTATION_TARGET_KINDS = 0x0008; private static final int DISCOVERED_DECLARED_SIGNATURE = 0x0010; private static final int DISCOVERED_WHETHER_ANNOTATION_STYLE = 0x0020; private static final String[] NO_INTERFACE_SIGS = new String[] {}; /* * Notes: note(1): in some cases (perclause inheritance) we encounter unpacked state when calling getPerClause * * note(2): A BcelObjectType is 'damaged' if it has been modified from what was original constructed from the bytecode. This * currently happens if the parents are modified or an annotation is added - ideally BcelObjectType should be immutable but * that's a bigger piece of work. XXX */ // ------------------ construction and initialization BcelObjectType(ReferenceType resolvedTypeX, JavaClass javaClass, boolean exposedToWeaver) { super(resolvedTypeX, exposedToWeaver); this.javaClass = javaClass; initializeFromJavaclass(); // ATAJ: set the delegate right now for @AJ pointcut, else it is done // too late to lookup // @AJ pc refs annotation in class hierarchy resolvedTypeX.setDelegate(this); ISourceContext sourceContext = resolvedTypeX.getSourceContext(); if (sourceContext == SourceContextImpl.UNKNOWN_SOURCE_CONTEXT) { sourceContext = new SourceContextImpl(this); setSourceContext(sourceContext); } // this should only ever be java.lang.Object which is // the only class in Java-1.4 with no superclasses isObject = (javaClass.getSuperclassNameIndex() == 0); ensureAspectJAttributesUnpacked(); // if (sourceContext instanceof SourceContextImpl) { // ((SourceContextImpl)sourceContext).setSourceFileName(javaClass. // getSourceFileName()); // } setSourcefilename(javaClass.getSourceFileName()); } // repeat initialization public void setJavaClass(JavaClass newclass) { this.javaClass = newclass; resetState(); initializeFromJavaclass(); } private void initializeFromJavaclass() { isInterface = javaClass.isInterface(); isEnum = javaClass.isEnum(); isAnnotation = javaClass.isAnnotation(); isAnonymous = javaClass.isAnonymous(); isNested = javaClass.isNested(); modifiers = javaClass.getModifiers(); superclassName = javaClass.getSuperclassName(); className = javaClass.getClassName(); cachedGenericClassTypeSignature = null; } // --- getters // Java related public boolean isInterface() { return isInterface; } public boolean isEnum() { return isEnum; } public boolean isAnnotation() { return isAnnotation; } public boolean isAnonymous() { return isAnonymous; } public boolean isNested() { return isNested; } public int getModifiers() { return modifiers; } /** * Must take into account generic signature */ public ResolvedType getSuperclass() { if (isObject) return null; ensureGenericSignatureUnpacked(); if (superclassSignature == null) { if (superclassName == null) superclassName = javaClass.getSuperclassName(); superclassSignature = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(superclassName)).getSignature(); } World world = getResolvedTypeX().getWorld(); ResolvedType res = world.resolve(UnresolvedType.forSignature(superclassSignature)); return res; } public World getWorld() { return getResolvedTypeX().getWorld(); } /** * Retrieves the declared interfaces - this allows for the generic signature on a type. If specified then the generic signature * is used to work out the types - this gets around the results of erasure when the class was originally compiled. */ public ResolvedType[] getDeclaredInterfaces() { ensureGenericSignatureUnpacked(); ResolvedType[] interfaceTypes = null; if (interfaceSignatures == null) { String[] names = javaClass.getInterfaceNames(); if (names.length == 0) { interfaceSignatures = NO_INTERFACE_SIGS; interfaceTypes = ResolvedType.NONE; } else { interfaceSignatures = new String[names.length]; interfaceTypes = new ResolvedType[names.length]; for (int i = 0, len = names.length; i < len; i++) { interfaceTypes[i] = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(names[i])); interfaceSignatures[i] = interfaceTypes[i].getSignature(); } } } else { interfaceTypes = new ResolvedType[interfaceSignatures.length]; for (int i = 0, len = interfaceSignatures.length; i < len; i++) { if (interfaceSignatures[i] == null) { // debug for NPE String msg = "Null interface signature (element:" + i + " of " + interfaceSignatures.length + "). Type for which we" + "are looking at interfaces is " + this.className + "."; System.err.println(msg); throw new BCException(msg); } interfaceTypes[i] = getResolvedTypeX().getWorld().resolve(UnresolvedType.forSignature(interfaceSignatures[i])); } } return interfaceTypes; } public ResolvedMember[] getDeclaredMethods() { ensureGenericSignatureUnpacked(); if (methods == null) { Method[] ms = javaClass.getMethods(); methods = new ResolvedMember[ms.length]; for (int i = ms.length - 1; i >= 0; i--) { methods[i] = new BcelMethod(this, ms[i]); } } return methods; } public ResolvedMember[] getDeclaredFields() { ensureGenericSignatureUnpacked(); if (fields == null) { Field[] fs = javaClass.getFields(); fields = new ResolvedMember[fs.length]; for (int i = 0, len = fs.length; i < len; i++) { fields[i] = new BcelField(this, fs[i]); } } return fields; } public TypeVariable[] getTypeVariables() { if (!isGeneric()) return TypeVariable.NONE; if (typeVars == null) { GenericSignature.ClassSignature classSig = getGenericClassTypeSignature();// cachedGenericClassTypeSignature // ; // / // / // javaClass // . // getGenericClassTypeSignature(); typeVars = new TypeVariable[classSig.formalTypeParameters.length]; for (int i = 0; i < typeVars.length; i++) { GenericSignature.FormalTypeParameter ftp = classSig.formalTypeParameters[i]; try { typeVars[i] = BcelGenericSignatureToTypeXConverter.formalTypeParameter2TypeVariable(ftp, classSig.formalTypeParameters, getResolvedTypeX().getWorld()); } catch (GenericSignatureFormatException e) { // this is a development bug, so fail fast with good info throw new IllegalStateException("While getting the type variables for type " + this.toString() + " with generic signature " + classSig + " the following error condition was detected: " + e.getMessage()); } } } return typeVars; } // Aspect related public Collection getTypeMungers() { return typeMungers; } public Collection getDeclares() { return declares; } public Collection getPrivilegedAccesses() { if (privilegedAccess == null) return Collections.EMPTY_LIST; return Arrays.asList(privilegedAccess); } public ResolvedMember[] getDeclaredPointcuts() { return pointcuts; } public boolean isAspect() { return perClause != null; } /** * Check if the type is an @AJ aspect (no matter if used from an LTW point of view). Such aspects are annotated with @Aspect * * @return true for @AJ aspect */ public boolean isAnnotationStyleAspect() { if ((bitflag & DISCOVERED_WHETHER_ANNOTATION_STYLE) == 0) { bitflag |= DISCOVERED_WHETHER_ANNOTATION_STYLE; isAnnotationStyleAspect = !isCodeStyleAspect && hasAnnotation(AjcMemberMaker.ASPECT_ANNOTATION); } return isAnnotationStyleAspect; } /** * Process any org.aspectj.weaver attributes stored against the class. */ private void ensureAspectJAttributesUnpacked() { if ((bitflag & UNPACKED_AJATTRIBUTES) != 0) return; bitflag |= UNPACKED_AJATTRIBUTES; IMessageHandler msgHandler = getResolvedTypeX().getWorld().getMessageHandler(); // Pass in empty list that can store things for readAj5 to process List l = Utility.readAjAttributes(className, javaClass.getAttributes(), getResolvedTypeX().getSourceContext(), getResolvedTypeX().getWorld(), AjAttribute.WeaverVersionInfo.UNKNOWN); List pointcuts = new ArrayList(); typeMungers = new ArrayList(); declares = new ArrayList(); processAttributes(l, pointcuts, false); l = AtAjAttributes.readAj5ClassAttributes(((BcelWorld) getResolvedTypeX().getWorld()).getModelAsAsmManager(), javaClass, getResolvedTypeX(), getResolvedTypeX().getSourceContext(), msgHandler, isCodeStyleAspect); AjAttribute.Aspect deferredAspectAttribute = processAttributes(l, pointcuts, true); if (pointcuts.size() == 0) { this.pointcuts = ResolvedPointcutDefinition.NO_POINTCUTS; } else { this.pointcuts = (ResolvedPointcutDefinition[]) pointcuts.toArray(new ResolvedPointcutDefinition[pointcuts.size()]); } resolveAnnotationDeclares(l); if (deferredAspectAttribute != null) { // we can finally process the aspect and its associated perclause... perClause = deferredAspectAttribute.reifyFromAtAspectJ(this.getResolvedTypeX()); } if (isAspect() && !Modifier.isAbstract(getModifiers()) && isGeneric()) { msgHandler.handleMessage(MessageUtil.error("The generic aspect '" + getResolvedTypeX().getName() + "' must be declared abstract", getResolvedTypeX().getSourceLocation())); } } private AjAttribute.Aspect processAttributes(List attributeList, List pointcuts, boolean fromAnnotations) { AjAttribute.Aspect deferredAspectAttribute = null; for (Iterator iter = attributeList.iterator(); iter.hasNext();) { AjAttribute a = (AjAttribute) iter.next(); // System.err.println("unpacking: " + this + " and " + a); if (a instanceof AjAttribute.Aspect) { if (fromAnnotations) { deferredAspectAttribute = (AjAttribute.Aspect) a; } else { perClause = ((AjAttribute.Aspect) a).reify(this.getResolvedTypeX()); isCodeStyleAspect = true; } } else if (a instanceof AjAttribute.PointcutDeclarationAttribute) { pointcuts.add(((AjAttribute.PointcutDeclarationAttribute) a).reify()); } else if (a instanceof AjAttribute.WeaverState) { weaverState = ((AjAttribute.WeaverState) a).reify(); } else if (a instanceof AjAttribute.TypeMunger) { typeMungers.add(((AjAttribute.TypeMunger) a).reify(getResolvedTypeX().getWorld(), getResolvedTypeX())); } else if (a instanceof AjAttribute.DeclareAttribute) { declares.add(((AjAttribute.DeclareAttribute) a).getDeclare()); } else if (a instanceof AjAttribute.PrivilegedAttribute) { privilegedAccess = ((AjAttribute.PrivilegedAttribute) a).getAccessedMembers(); } else if (a instanceof AjAttribute.SourceContextAttribute) { if (getResolvedTypeX().getSourceContext() instanceof SourceContextImpl) { AjAttribute.SourceContextAttribute sca = (AjAttribute.SourceContextAttribute) a; ((SourceContextImpl) getResolvedTypeX().getSourceContext()).configureFromAttribute(sca.getSourceFileName(), sca .getLineBreaks()); setSourcefilename(sca.getSourceFileName()); } } else if (a instanceof AjAttribute.WeaverVersionInfo) { wvInfo = (AjAttribute.WeaverVersionInfo) a; // Set the weaver // version used to // build this type } else { throw new BCException("bad attribute " + a); } } return deferredAspectAttribute; } /** * Extra processing step needed because declares that come from annotations are not pre-resolved. We can't do the resolution * until *after* the pointcuts have been resolved. * * @param attributeList */ private void resolveAnnotationDeclares(List attributeList) { FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; IScope bindingScope = new BindingScope(getResolvedTypeX(), getResolvedTypeX().getSourceContext(), bindings); for (Iterator iter = attributeList.iterator(); iter.hasNext();) { AjAttribute a = (AjAttribute) iter.next(); if (a instanceof AjAttribute.DeclareAttribute) { Declare decl = (((AjAttribute.DeclareAttribute) a).getDeclare()); if (decl instanceof DeclareErrorOrWarning) { decl.resolve(bindingScope); } else if (decl instanceof DeclarePrecedence) { ((DeclarePrecedence) decl).setScopeForResolution(bindingScope); } } } } public PerClause getPerClause() { ensureAspectJAttributesUnpacked(); return perClause; } public JavaClass getJavaClass() { return javaClass; } public void resetState() { if (javaClass == null) { // we might store the classname and allow reloading? // At this point we are relying on the world to not evict if it // might want to reweave multiple times throw new BCException("can't weave evicted type"); } bitflag = 0x0000; this.annotationTypes = null; this.annotations = null; this.interfaceSignatures = null; this.superclassSignature = null; this.superclassName = null; this.fields = null; this.methods = null; this.pointcuts = null; this.perClause = null; this.weaverState = null; this.lazyClassGen = null; hasBeenWoven = false; isObject = (javaClass.getSuperclassNameIndex() == 0); isAnnotationStyleAspect = false; ensureAspectJAttributesUnpacked(); } public void finishedWith() { // memory usage experiments.... // this.interfaces = null; // this.superClass = null; // this.fields = null; // this.methods = null; // this.pointcuts = null; // this.perClause = null; // this.weaverState = null; // this.lazyClassGen = null; // this next line frees up memory, but need to understand incremental // implications // before leaving it in. // getResolvedTypeX().setSourceContext(null); } public WeaverStateInfo getWeaverState() { return weaverState; } void setWeaverState(WeaverStateInfo weaverState) { this.weaverState = weaverState; } public void printWackyStuff(PrintStream out) { if (typeMungers.size() > 0) out.println(" TypeMungers: " + typeMungers); if (declares.size() > 0) out.println(" declares: " + declares); } /** * Return the lazyClassGen associated with this type. For aspect types, this value will be cached, since it is used to inline * advice. For non-aspect types, this lazyClassGen is always newly constructed. */ public LazyClassGen getLazyClassGen() { LazyClassGen ret = lazyClassGen; if (ret == null) { // System.err.println("creating lazy class gen for: " + this); ret = new LazyClassGen(this); // ret.print(System.err); // System.err.println("made LCG from : " + // this.getJavaClass().getSuperclassName ); if (isAspect()) { lazyClassGen = ret; } } return ret; } public boolean isSynthetic() { return getResolvedTypeX().isSynthetic(); } public AjAttribute.WeaverVersionInfo getWeaverVersionAttribute() { return wvInfo; } // -- annotation related public ResolvedType[] getAnnotationTypes() { ensureAnnotationsUnpacked(); return annotationTypes; } public AnnotationAJ[] getAnnotations() { ensureAnnotationsUnpacked(); return annotations; } public boolean hasAnnotation(UnresolvedType ofType) { ensureAnnotationsUnpacked(); for (int i = 0; i < annotationTypes.length; i++) { ResolvedType ax = annotationTypes[i]; if (ax.equals(ofType)) return true; } return false; } public boolean isAnnotationWithRuntimeRetention() { return (getRetentionPolicy() == null ? false : getRetentionPolicy().equals("RUNTIME")); } public String getRetentionPolicy() { if ((bitflag & DISCOVERED_ANNOTATION_RETENTION_POLICY) == 0) { bitflag |= DISCOVERED_ANNOTATION_RETENTION_POLICY; retentionPolicy = null; // null means we have no idea if (isAnnotation()) { ensureAnnotationsUnpacked(); for (int i = annotations.length - 1; i >= 0; i--) { AnnotationAJ ax = annotations[i]; if (ax.getTypeName().equals(UnresolvedType.AT_RETENTION.getName())) { List values = ((BcelAnnotation) ax).getBcelAnnotation().getValues(); for (Iterator it = values.iterator(); it.hasNext();) { ElementNameValuePairGen element = (ElementNameValuePairGen) it.next(); EnumElementValueGen v = (EnumElementValueGen) element.getValue(); retentionPolicy = v.getEnumValueString(); return retentionPolicy; } } } } } return retentionPolicy; } public boolean canAnnotationTargetType() { AnnotationTargetKind[] targetKinds = getAnnotationTargetKinds(); if (targetKinds == null) return true; for (int i = 0; i < targetKinds.length; i++) { if (targetKinds[i].equals(AnnotationTargetKind.TYPE)) { return true; } } return false; } public AnnotationTargetKind[] getAnnotationTargetKinds() { if ((bitflag & DISCOVERED_ANNOTATION_TARGET_KINDS) != 0) return annotationTargetKinds; bitflag |= DISCOVERED_ANNOTATION_TARGET_KINDS; annotationTargetKinds = null; // null means we have no idea or the // @Target annotation hasn't been used List targetKinds = new ArrayList(); if (isAnnotation()) { AnnotationAJ[] annotationsOnThisType = getAnnotations(); for (int i = 0; i < annotationsOnThisType.length; i++) { AnnotationAJ a = annotationsOnThisType[i]; if (a.getTypeName().equals(UnresolvedType.AT_TARGET.getName())) { Set targets = a.getTargets(); if (targets != null) { for (Iterator iterator = targets.iterator(); iterator.hasNext();) { String targetKind = (String) iterator.next(); if (targetKind.equals("ANNOTATION_TYPE")) { targetKinds.add(AnnotationTargetKind.ANNOTATION_TYPE); } else if (targetKind.equals("CONSTRUCTOR")) { targetKinds.add(AnnotationTargetKind.CONSTRUCTOR); } else if (targetKind.equals("FIELD")) { targetKinds.add(AnnotationTargetKind.FIELD); } else if (targetKind.equals("LOCAL_VARIABLE")) { targetKinds.add(AnnotationTargetKind.LOCAL_VARIABLE); } else if (targetKind.equals("METHOD")) { targetKinds.add(AnnotationTargetKind.METHOD); } else if (targetKind.equals("PACKAGE")) { targetKinds.add(AnnotationTargetKind.PACKAGE); } else if (targetKind.equals("PARAMETER")) { targetKinds.add(AnnotationTargetKind.PARAMETER); } else if (targetKind.equals("TYPE")) { targetKinds.add(AnnotationTargetKind.TYPE); } } } } } if (!targetKinds.isEmpty()) { annotationTargetKinds = new AnnotationTargetKind[targetKinds.size()]; return (AnnotationTargetKind[]) targetKinds.toArray(annotationTargetKinds); } } return annotationTargetKinds; } // --- unpacking methods private void ensureAnnotationsUnpacked() { if (annotationTypes == null) { AnnotationGen annos[] = javaClass.getAnnotations(); if (annos == null || annos.length == 0) { annotationTypes = ResolvedType.NONE; annotations = AnnotationAJ.EMPTY_ARRAY; } else { World w = getResolvedTypeX().getWorld(); annotationTypes = new ResolvedType[annos.length]; annotations = new AnnotationAJ[annos.length]; for (int i = 0; i < annos.length; i++) { AnnotationGen annotation = annos[i]; annotationTypes[i] = w.resolve(UnresolvedType.forSignature(annotation.getTypeSignature())); annotations[i] = new BcelAnnotation(annotation, w); } } } } // --- public String getDeclaredGenericSignature() { ensureGenericInfoProcessed(); return declaredSignature; } private void ensureGenericSignatureUnpacked() { if ((bitflag & UNPACKED_GENERIC_SIGNATURE) != 0) return; bitflag |= UNPACKED_GENERIC_SIGNATURE; if (!getResolvedTypeX().getWorld().isInJava5Mode()) return; GenericSignature.ClassSignature cSig = getGenericClassTypeSignature(); if (cSig != null) { formalsForResolution = cSig.formalTypeParameters; if (isNested()) { // we have to find any type variables from the outer type before // proceeding with resolution. GenericSignature.FormalTypeParameter[] extraFormals = getFormalTypeParametersFromOuterClass(); if (extraFormals.length > 0) { List allFormals = new ArrayList(); for (int i = 0; i < formalsForResolution.length; i++) { allFormals.add(formalsForResolution[i]); } for (int i = 0; i < extraFormals.length; i++) { allFormals.add(extraFormals[i]); } formalsForResolution = new GenericSignature.FormalTypeParameter[allFormals.size()]; allFormals.toArray(formalsForResolution); } } GenericSignature.ClassTypeSignature superSig = cSig.superclassSignature; try { // this.superClass = // BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX( // superSig, formalsForResolution, // getResolvedTypeX().getWorld()); ResolvedType rt = BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(superSig, formalsForResolution, getResolvedTypeX().getWorld()); this.superclassSignature = rt.getSignature(); this.superclassName = rt.getName(); } catch (GenericSignatureFormatException e) { // development bug, fail fast with good info throw new IllegalStateException("While determining the generic superclass of " + this.className + " with generic signature " + getDeclaredGenericSignature() + " the following error was detected: " + e.getMessage()); } // this.interfaces = new // ResolvedType[cSig.superInterfaceSignatures.length]; if (cSig.superInterfaceSignatures.length == 0) { this.interfaceSignatures = NO_INTERFACE_SIGS; } else { this.interfaceSignatures = new String[cSig.superInterfaceSignatures.length]; for (int i = 0; i < cSig.superInterfaceSignatures.length; i++) { try { // this.interfaces[i] = // BcelGenericSignatureToTypeXConverter. // classTypeSignature2TypeX( // cSig.superInterfaceSignatures[i], // formalsForResolution, // getResolvedTypeX().getWorld()); this.interfaceSignatures[i] = BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX( cSig.superInterfaceSignatures[i], formalsForResolution, getResolvedTypeX().getWorld()) .getSignature(); } catch (GenericSignatureFormatException e) { // development bug, fail fast with good info throw new IllegalStateException("While determing the generic superinterfaces of " + this.className + " with generic signature " + getDeclaredGenericSignature() + " the following error was detected: " + e.getMessage()); } } } } if (isGeneric()) { // update resolved typex to point at generic type not raw type. ReferenceType genericType = (ReferenceType) this.resolvedTypeX.getGenericType(); // genericType.setSourceContext(this.resolvedTypeX.getSourceContext() // ); genericType.setStartPos(this.resolvedTypeX.getStartPos()); this.resolvedTypeX = genericType; } } public GenericSignature.FormalTypeParameter[] getAllFormals() { ensureGenericSignatureUnpacked(); if (formalsForResolution == null) { return new GenericSignature.FormalTypeParameter[0]; } else { return formalsForResolution; } } public ResolvedType getOuterClass() { if (!isNested()) throw new IllegalStateException("Can't get the outer class of a non-nested type"); int lastDollar = className.lastIndexOf('$'); String superClassName = className.substring(0, lastDollar); UnresolvedType outer = UnresolvedType.forName(superClassName); return outer.resolve(getResolvedTypeX().getWorld()); } private void ensureGenericInfoProcessed() { if ((bitflag & DISCOVERED_DECLARED_SIGNATURE) != 0) return; bitflag |= DISCOVERED_DECLARED_SIGNATURE; Signature sigAttr = AttributeUtils.getSignatureAttribute(javaClass.getAttributes()); declaredSignature = (sigAttr == null ? null : sigAttr.getSignature()); if (declaredSignature != null) isGenericType = (declaredSignature.charAt(0) == '<'); } public boolean isGeneric() { ensureGenericInfoProcessed(); return isGenericType; } public String toString() { return (javaClass == null ? "BcelObjectType" : "BcelObjectTypeFor:" + className); } // --- state management public void evictWeavingState() { // Can't chuck all this away if (getResolvedTypeX().getWorld().couldIncrementalCompileFollow()) return; if (javaClass != null) { // Force retrieval of any lazy information ensureAnnotationsUnpacked(); ensureGenericInfoProcessed(); getDeclaredInterfaces(); getDeclaredFields(); getDeclaredMethods(); // The lazyClassGen is preserved for aspects - it exists to enable // around advice // inlining since the method will need 'injecting' into the affected // class. If // XnoInline is on, we can chuck away the lazyClassGen since it // won't be required // later. if (getResolvedTypeX().getWorld().isXnoInline()) lazyClassGen = null; // discard expensive bytecode array containing reweavable info if (weaverState != null) { weaverState.setReweavable(false); weaverState.setUnwovenClassFileData(null); } for (int i = methods.length - 1; i >= 0; i--) methods[i].evictWeavingState(); for (int i = fields.length - 1; i >= 0; i--) fields[i].evictWeavingState(); javaClass = null; // setSourceContext(SourceContextImpl.UNKNOWN_SOURCE_CONTEXT); // // bit naughty // interfaces=null; // force reinit - may get us the right // instances! // superClass=null; } } public void weavingCompleted() { hasBeenWoven = true; if (getResolvedTypeX().getWorld().isRunMinimalMemory()) evictWeavingState(); if (getSourceContext() != null && !getResolvedTypeX().isAspect()) getSourceContext().tidy(); } public boolean hasBeenWoven() { return hasBeenWoven; } public boolean copySourceContext() { return false; } }
288,505
Bug 288505 failure to close inputstream
null
resolved fixed
3d3d03b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-09-03T16:21:37Z"
"2009-09-03T15:00:00Z"
org.aspectj.matcher/src/org/aspectj/weaver/Lint.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.text.MessageFormat; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.MessageUtil; import org.aspectj.weaver.tools.Trace; import org.aspectj.weaver.tools.TraceFactory; public class Lint { /* private */Map kinds = new HashMap(); /* private */World world; public final Kind invalidAbsoluteTypeName = new Kind("invalidAbsoluteTypeName", "no match for this type name: {0}"); public final Kind invalidWildcardTypeName = new Kind("invalidWildcardTypeName", "no match for this type pattern: {0}"); public final Kind unresolvableMember = new Kind("unresolvableMember", "can not resolve this member: {0}"); public final Kind typeNotExposedToWeaver = new Kind("typeNotExposedToWeaver", "this affected type is not exposed to the weaver: {0}"); public final Kind shadowNotInStructure = new Kind("shadowNotInStructure", "the shadow for this join point is not exposed in the structure model: {0}"); public final Kind unmatchedSuperTypeInCall = new Kind("unmatchedSuperTypeInCall", "does not match because declaring type is {0}, if match desired use target({1})"); public final Kind unmatchedTargetKind = new Kind("unmatchedTargetKind", "does not match because annotation {0} has @Target{1}"); public final Kind canNotImplementLazyTjp = new Kind("canNotImplementLazyTjp", "can not implement lazyTjp on this joinpoint {0} because around advice is used"); public final Kind multipleAdviceStoppingLazyTjp = new Kind("multipleAdviceStoppingLazyTjp", "can not implement lazyTjp at joinpoint {0} because of advice conflicts, see secondary locations to find conflicting advice"); public final Kind needsSerialVersionUIDField = new Kind("needsSerialVersionUIDField", "serialVersionUID of type {0} needs to be set because of {1}"); public final Kind serialVersionUIDBroken = new Kind("brokeSerialVersionCompatibility", "serialVersionUID of type {0} is broken because of added field {1}"); public final Kind noInterfaceCtorJoinpoint = new Kind("noInterfaceCtorJoinpoint", "no interface constructor-execution join point - use {0}+ for implementing classes"); public final Kind noJoinpointsForBridgeMethods = new Kind( "noJoinpointsForBridgeMethods", "pointcut did not match on the method call to a bridge method. Bridge methods are generated by the compiler and have no join points"); public final Kind enumAsTargetForDecpIgnored = new Kind("enumAsTargetForDecpIgnored", "enum type {0} matches a declare parents type pattern but is being ignored"); public final Kind annotationAsTargetForDecpIgnored = new Kind("annotationAsTargetForDecpIgnored", "annotation type {0} matches a declare parents type pattern but is being ignored"); public final Kind cantMatchArrayTypeOnVarargs = new Kind("cantMatchArrayTypeOnVarargs", "an array type as the last parameter in a signature does not match on the varargs declared method: {0}"); public final Kind adviceDidNotMatch = new Kind("adviceDidNotMatch", "advice defined in {0} has not been applied"); public final Kind invalidTargetForAnnotation = new Kind("invalidTargetForAnnotation", "{0} is not a valid target for annotation {1}, this annotation can only be applied to {2}"); public final Kind elementAlreadyAnnotated = new Kind("elementAlreadyAnnotated", "{0} - already has an annotation of type {1}, cannot add a second instance"); public final Kind runtimeExceptionNotSoftened = new Kind("runtimeExceptionNotSoftened", "{0} will not be softened as it is already a RuntimeException"); public final Kind uncheckedArgument = new Kind("uncheckedArgument", "unchecked match of {0} with {1} when argument is an instance of {2} at join point {3}"); public final Kind uncheckedAdviceConversion = new Kind("uncheckedAdviceConversion", "unchecked conversion when advice applied at shadow {0}, expected {1} but advice uses {2}"); public final Kind noGuardForLazyTjp = new Kind("noGuardForLazyTjp", "can not build thisJoinPoint lazily for this advice since it has no suitable guard"); public final Kind noExplicitConstructorCall = new Kind("noExplicitConstructorCall", "inter-type constructor does not contain explicit constructor call: field initializers in the target type will not be executed"); public final Kind aspectExcludedByConfiguration = new Kind("aspectExcludedByConfiguration", "aspect {0} exluded for class loader {1}"); public final Kind unorderedAdviceAtShadow = new Kind("unorderedAdviceAtShadow", "at this shadow {0} no precedence is specified between advice applying from aspect {1} and aspect {2}"); public final Kind swallowedExceptionInCatchBlock = new Kind("swallowedExceptionInCatchBlock", "exception swallowed in catch block"); public final Kind calculatingSerialVersionUID = new Kind("calculatingSerialVersionUID", "calculated SerialVersionUID for type {0} to be {1}"); // there are a lot of messages in the cant find type family - I'm defining an umbrella lint warning that // allows a user to control their severity (for e.g. ltw or binary weaving) public final Kind cantFindType = new Kind("cantFindType", "{0}"); public final Kind cantFindTypeAffectingJoinPointMatch = new Kind("cantFindTypeAffectingJPMatch", "{0}"); public final Kind advisingSynchronizedMethods = new Kind("advisingSynchronizedMethods", "advice matching the synchronized method shadow ''{0}'' will be executed outside the lock rather than inside (compiler limitation)"); public final Kind mustWeaveXmlDefinedAspects = new Kind( "mustWeaveXmlDefinedAspects", "XML Defined aspects must be woven in cases where cflow pointcuts are involved. Currently the include/exclude patterns exclude ''{0}''"); public final Kind cannotAdviseJoinpointInInterfaceWithAroundAdvice = new Kind( "cannotAdviseJoinpointInInterfaceWithAroundAdvice", "The joinpoint ''{0}'' cannot be advised and is being skipped as the compiler implementation will lead to creation of methods with bodies in an interface (compiler limitation)"); /** * Indicates an aspect could not be found when attempting reweaving. */ public final Kind missingAspectForReweaving = new Kind("missingAspectForReweaving", "aspect {0} cannot be found when reweaving {1}"); private static Trace trace = TraceFactory.getTraceFactory().getTrace(Lint.class); public Lint(World world) { if (trace.isTraceEnabled()) trace.enter("<init>", this, world); this.world = world; if (trace.isTraceEnabled()) trace.exit("<init>"); } public void setAll(String messageKind) { if (trace.isTraceEnabled()) trace.enter("setAll", this, messageKind); setAll(getMessageKind(messageKind)); if (trace.isTraceEnabled()) trace.exit("setAll"); } private void setAll(IMessage.Kind messageKind) { for (Iterator i = kinds.values().iterator(); i.hasNext();) { Kind kind = (Kind) i.next(); kind.setKind(messageKind); } } public void setFromProperties(File file) { if (trace.isTraceEnabled()) trace.enter("setFromProperties", this, file); try { InputStream s = new FileInputStream(file); setFromProperties(s); } catch (IOException ioe) { MessageUtil.error(world.getMessageHandler(), WeaverMessages.format(WeaverMessages.XLINT_LOAD_ERROR, file.getPath(), ioe .getMessage())); } if (trace.isTraceEnabled()) trace.exit("setFromProperties"); } public void loadDefaultProperties() { InputStream s = getClass().getResourceAsStream("XlintDefault.properties"); if (s == null) { MessageUtil.warn(world.getMessageHandler(), WeaverMessages.format(WeaverMessages.XLINTDEFAULT_LOAD_ERROR)); return; } try { setFromProperties(s); } catch (IOException ioe) { MessageUtil.error(world.getMessageHandler(), WeaverMessages.format(WeaverMessages.XLINTDEFAULT_LOAD_PROBLEM, ioe .getMessage())); } } private void setFromProperties(InputStream s) throws IOException { Properties p = new Properties(); p.load(s); setFromProperties(p); } public void setFromProperties(Properties properties) { for (Iterator i = properties.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); Kind kind = (Kind) kinds.get(entry.getKey()); if (kind == null) { MessageUtil.error(world.getMessageHandler(), WeaverMessages.format(WeaverMessages.XLINT_KEY_ERROR, entry.getKey())); } else { kind.setKind(getMessageKind((String) entry.getValue())); } } } public Collection allKinds() { return kinds.values(); } public Kind getLintKind(String name) { return (Kind) kinds.get(name); } // temporarily suppress the given lint messages public void suppressKinds(Collection lintKind) { if (lintKind.isEmpty()) return; for (Iterator iter = lintKind.iterator(); iter.hasNext();) { Kind k = (Kind) iter.next(); k.setSuppressed(true); } } // remove any suppression of lint warnings in place public void clearAllSuppressions() { for (Iterator iter = kinds.values().iterator(); iter.hasNext();) { Kind k = (Kind) iter.next(); k.setSuppressed(false); } } public void clearSuppressions(Collection lintKind) { if (lintKind.isEmpty()) return; for (Iterator iter = lintKind.iterator(); iter.hasNext();) { Kind k = (Kind) iter.next(); k.setSuppressed(false); } } private IMessage.Kind getMessageKind(String v) { if (v.equals("ignore")) return null; else if (v.equals("warning")) return IMessage.WARNING; else if (v.equals("error")) return IMessage.ERROR; MessageUtil.error(world.getMessageHandler(), WeaverMessages.format(WeaverMessages.XLINT_VALUE_ERROR, v)); return null; } public Kind fromKey(String lintkey) { return (Lint.Kind) kinds.get(lintkey); } public class Kind { private final String name; private final String message; private IMessage.Kind kind = IMessage.WARNING; private boolean isSupressed = false; // by SuppressAjWarnings public Kind(String name, String message) { this.name = name; this.message = message; kinds.put(this.name, this); } public void setSuppressed(boolean shouldBeSuppressed) { this.isSupressed = shouldBeSuppressed; } public boolean isEnabled() { return (kind != null) && !isSupressed(); } private boolean isSupressed() { // can't suppress errors! return isSupressed && (kind != IMessage.ERROR); } public String getName() { return name; } public IMessage.Kind getKind() { return kind; } public void setKind(IMessage.Kind kind) { this.kind = kind; } public void signal(String info, ISourceLocation location) { if (kind == null) return; String text = MessageFormat.format(message, new Object[] { info }); text += " [Xlint:" + name + "]"; world.getMessageHandler().handleMessage(new LintMessage(text, kind, location, null, getLintKind(name))); } public void signal(String[] infos, ISourceLocation location, ISourceLocation[] extraLocations) { if (kind == null) return; String text = MessageFormat.format(message, (Object[]) infos); text += " [Xlint:" + name + "]"; world.getMessageHandler().handleMessage(new LintMessage(text, kind, location, extraLocations, getLintKind(name))); } } }
288,198
Bug 288198 LangUtils JVM version detection cannot handle Java 7
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-GB; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 Build Identifier: 1.6.4 The JVM detection in LangUtils is currently unable to handle Java7, whilst this is naturally an unreleased version of the JVM, the fix is trivial. Reproducible: Always Steps to Reproduce: Attempt to use the LangUtils java version support on java7
resolved fixed
b29f839
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-09-04T16:36:07Z"
"2009-09-01T01:53:20Z"
util/src/org/aspectj/util/LangUtil.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.util; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.security.PrivilegedActionException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; /** * */ public class LangUtil { // /** map from String version to String class implemented in that version // or later */ // private static final Map VM_CLASSES; public static final String EOL; static { StringWriter buf = new StringWriter(); PrintWriter writer = new PrintWriter(buf); writer.println(""); String eol = "\n"; try { buf.close(); StringBuffer sb = buf.getBuffer(); if (sb != null) { eol = buf.toString(); } } catch (Throwable t) { } EOL = eol; // HashMap map = new HashMap(); // map.put("1.2", "java.lang.ref.Reference"); // map.put("1.3", "java.lang.reflect.Proxy"); // map.put("1.4", "java.nio.Buffer"); // map.put("1.5", "java.lang.annotation.Annotation"); // // VM_CLASSES = Collections.unmodifiableMap(map); } // /** // * Detect whether Java version is supported. // * @param version String "1.2" or "1.3" or "1.4" // * @return true if the currently-running VM supports the version // * @throws IllegalArgumentException if version is not known // */ // public static final boolean supportsJava(String version) { // LangUtil.throwIaxIfNull(version, "version"); // String className = (String) VM_CLASSES.get(version); // if (null == className) { // throw new IllegalArgumentException("unknown version: " + version); // } // try { // Class.forName(className); // return true; // } catch (Throwable t) { // return false; // } // } private static boolean is13VMOrGreater = true; private static boolean is14VMOrGreater = true; private static boolean is15VMOrGreater = false; private static boolean is16VMOrGreater = false; static { String vm = System.getProperty("java.version"); // JLS 20.18.7 if (vm == null) vm = System.getProperty("java.runtime.version"); if (vm == null) vm = System.getProperty("java.vm.version"); if (vm.startsWith("1.3")) { is14VMOrGreater = false; } else if (vm.startsWith("1.5") || vm.startsWith("1.6")) { is15VMOrGreater = true; is16VMOrGreater = true; } } public static boolean is13VMOrGreater() { return is13VMOrGreater; } public static boolean is14VMOrGreater() { return is14VMOrGreater; } public static boolean is15VMOrGreater() { return is15VMOrGreater; } public static boolean is16VMOrGreater() { return is16VMOrGreater; } /** * Shorthand for "if null, throw IllegalArgumentException" * * @throws IllegalArgumentException "null {name}" if o is null */ public static final void throwIaxIfNull(final Object o, final String name) { if (null == o) { String message = "null " + (null == name ? "input" : name); throw new IllegalArgumentException(message); } } /** * Shorthand for * "if not null or not assignable, throw IllegalArgumentException" * * @param c the Class to check - use null to ignore type check * @throws IllegalArgumentException "null {name}" if o is null */ public static final void throwIaxIfNotAssignable(final Object ra[], final Class c, final String name) { throwIaxIfNull(ra, name); String label = (null == name ? "input" : name); for (int i = 0; i < ra.length; i++) { if (null == ra[i]) { String m = " null " + label + "[" + i + "]"; throw new IllegalArgumentException(m); } else if (null != c) { Class actualClass = ra[i].getClass(); if (!c.isAssignableFrom(actualClass)) { String message = label + " not assignable to " + c.getName(); throw new IllegalArgumentException(message); } } } } /** * Shorthand for * "if not null or not assignable, throw IllegalArgumentException" * * @throws IllegalArgumentException "null {name}" if o is null */ public static final void throwIaxIfNotAssignable(final Object o, final Class c, final String name) { throwIaxIfNull(o, name); if (null != c) { Class actualClass = o.getClass(); if (!c.isAssignableFrom(actualClass)) { String message = name + " not assignable to " + c.getName(); throw new IllegalArgumentException(message); } } } // /** // * Shorthand for // "if any not null or not assignable, throw IllegalArgumentException" // * @throws IllegalArgumentException "{name} is not assignable to {c}" // */ // public static final void throwIaxIfNotAllAssignable(final Collection // collection, // final Class c, final String name) { // throwIaxIfNull(collection, name); // if (null != c) { // for (Iterator iter = collection.iterator(); iter.hasNext();) { // throwIaxIfNotAssignable(iter.next(), c, name); // // } // } // } /** * Shorthand for "if false, throw IllegalArgumentException" * * @throws IllegalArgumentException "{message}" if test is false */ public static final void throwIaxIfFalse(final boolean test, final String message) { if (!test) { throw new IllegalArgumentException(message); } } // /** @return ((null == s) || (0 == s.trim().length())); */ // public static boolean isEmptyTrimmed(String s) { // return ((null == s) || (0 == s.length()) // || (0 == s.trim().length())); // } /** @return ((null == s) || (0 == s.length())); */ public static boolean isEmpty(String s) { return ((null == s) || (0 == s.length())); } /** @return ((null == ra) || (0 == ra.length)) */ public static boolean isEmpty(Object[] ra) { return ((null == ra) || (0 == ra.length)); } /** @return ((null == collection) || (0 == collection.size())) */ public static boolean isEmpty(Collection collection) { return ((null == collection) || (0 == collection.size())); } /** * Splits <code>text</code> at whitespace. * * @param text <code>String</code> to split. */ public static String[] split(String text) { return (String[]) strings(text).toArray(new String[0]); } /** * Splits <code>input</code> at commas, trimming any white space. * * @param input <code>String</code> to split. * @return List of String of elements. */ public static List commaSplit(String input) { return anySplit(input, ","); } /** * Split string as classpath, delimited at File.pathSeparator. Entries are * not trimmed, but empty entries are ignored. * * @param classpath the String to split - may be null or empty * @return String[] of classpath entries */ public static String[] splitClasspath(String classpath) { if (LangUtil.isEmpty(classpath)) { return new String[0]; } StringTokenizer st = new StringTokenizer(classpath, File.pathSeparator); ArrayList result = new ArrayList(st.countTokens()); while (st.hasMoreTokens()) { String entry = st.nextToken(); if (!LangUtil.isEmpty(entry)) { result.add(entry); } } return (String[]) result.toArray(new String[0]); } /** * Get System property as boolean, but use default value where the system * property is not set. * * @return true if value is set to true, false otherwise */ public static boolean getBoolean(String propertyName, boolean defaultValue) { if (null != propertyName) { try { String value = System.getProperty(propertyName); if (null != value) { return Boolean.valueOf(value).booleanValue(); } } catch (Throwable t) { // default below } } return defaultValue; } /** * Splits <code>input</code>, removing delimiter and trimming any white * space. Returns an empty collection if the input is null. If delimiter is * null or empty or if the input contains no delimiters, the input itself is * returned after trimming white space. * * @param input <code>String</code> to split. * @param delim <code>String</code> separators for input. * @return List of String of elements. */ public static List anySplit(String input, String delim) { if (null == input) { return Collections.EMPTY_LIST; } ArrayList result = new ArrayList(); if (LangUtil.isEmpty(delim) || (-1 == input.indexOf(delim))) { result.add(input.trim()); } else { StringTokenizer st = new StringTokenizer(input, delim); while (st.hasMoreTokens()) { result.add(st.nextToken().trim()); } } return result; } /** * Splits strings into a <code>List</code> using a * <code>StringTokenizer</code>. * * @param text <code>String</code> to split. */ public static List strings(String text) { if (LangUtil.isEmpty(text)) { return Collections.EMPTY_LIST; } List strings = new ArrayList(); StringTokenizer tok = new StringTokenizer(text); while (tok.hasMoreTokens()) { strings.add(tok.nextToken()); } return strings; } /** @return a non-null unmodifiable List */ public static List safeList(List list) { return (null == list ? Collections.EMPTY_LIST : Collections.unmodifiableList(list)); } // /** // * Select from input String[] based on suffix-matching // * @param inputs String[] of input - null ignored // * @param suffixes String[] of suffix selectors - null ignored // * @param ignoreCase if true, ignore case // * @return String[] of input that end with any input // */ // public static String[] endsWith(String[] inputs, String[] suffixes, // boolean ignoreCase) { // if (LangUtil.isEmpty(inputs) || LangUtil.isEmpty(suffixes)) { // return new String[0]; // } // if (ignoreCase) { // String[] temp = new String[suffixes.length]; // for (int i = 0; i < temp.length; i++) { // String suff = suffixes[i]; // temp[i] = (null == suff ? null : suff.toLowerCase()); // } // suffixes = temp; // } // ArrayList result = new ArrayList(); // for (int i = 0; i < inputs.length; i++) { // String input = inputs[i]; // if (null == input) { // continue; // } // if (!ignoreCase) { // input = input.toLowerCase(); // } // for (int j = 0; j < suffixes.length; j++) { // String suffix = suffixes[j]; // if (null == suffix) { // continue; // } // if (input.endsWith(suffix)) { // result.add(input); // break; // } // } // } // return (String[]) result.toArray(new String[0]); // } // // /** // * Select from input String[] if readable directories // * @param inputs String[] of input - null ignored // * @param baseDir the base directory of the input // * @return String[] of input that end with any input // */ // public static String[] selectDirectories(String[] inputs, File baseDir) { // if (LangUtil.isEmpty(inputs)) { // return new String[0]; // } // ArrayList result = new ArrayList(); // for (int i = 0; i < inputs.length; i++) { // String input = inputs[i]; // if (null == input) { // continue; // } // File inputFile = new File(baseDir, input); // if (inputFile.canRead() && inputFile.isDirectory()) { // result.add(input); // } // } // return (String[]) result.toArray(new String[0]); // } /** * copy non-null two-dimensional String[][] * * @see extractOptions(String[], String[][]) */ public static String[][] copyStrings(String[][] in) { String[][] out = new String[in.length][]; for (int i = 0; i < out.length; i++) { out[i] = new String[in[i].length]; System.arraycopy(in[i], 0, out[i], 0, out[i].length); } return out; } /** * Extract options and arguments to input option list, returning remainder. * The input options will be nullified if not found. e.g., * * <pre> * String[] options = new String[][] { new String[] { &quot;-verbose&quot; }, new String[] { &quot;-classpath&quot;, null } }; * String[] args = extractOptions(args, options); * boolean verbose = null != options[0][0]; * boolean classpath = options[1][1]; * </pre> * * @param args the String[] input options * @param options the String[][]options to find in the input args - not null * for each String[] component the first subcomponent is the * option itself, and there is one String subcomponent for each * additional argument. * @return String[] of args remaining after extracting options to extracted */ public static String[] extractOptions(String[] args, String[][] options) { if (LangUtil.isEmpty(args) || LangUtil.isEmpty(options)) { return args; } BitSet foundSet = new BitSet(); String[] result = new String[args.length]; int resultIndex = 0; for (int j = 0; j < args.length; j++) { boolean found = false; for (int i = 0; !found && (i < options.length); i++) { String[] option = options[i]; LangUtil.throwIaxIfFalse(!LangUtil.isEmpty(option), "options"); String sought = option[0]; found = sought.equals(args[j]); if (found) { foundSet.set(i); int doMore = option.length - 1; if (0 < doMore) { final int MAX = j + doMore; if (MAX >= args.length) { String s = "expecting " + doMore + " args after "; throw new IllegalArgumentException(s + args[j]); } for (int k = 1; k < option.length; k++) { option[k] = args[++j]; } } } } if (!found) { result[resultIndex++] = args[j]; } } // unset any not found for (int i = 0; i < options.length; i++) { if (!foundSet.get(i)) { options[i][0] = null; } } // fixup remainder if (resultIndex < args.length) { String[] temp = new String[resultIndex]; System.arraycopy(result, 0, temp, 0, resultIndex); args = temp; } return args; } // // /** // * Extract options and arguments to input parameter list, returning // remainder. // * @param args the String[] input options // * @param validOptions the String[] options to find in the input args - // not null // * @param optionArgs the int[] number of arguments for each option in // validOptions // * (if null, then no arguments for any option) // * @param extracted the List for the matched options // * @return String[] of args remaining after extracting options to // extracted // */ // public static String[] extractOptions(String[] args, String[] // validOptions, // int[] optionArgs, List extracted) { // if (LangUtil.isEmpty(args) // || LangUtil.isEmpty(validOptions) ) { // return args; // } // if (null != optionArgs) { // if (optionArgs.length != validOptions.length) { // throw new IllegalArgumentException("args must match options"); // } // } // String[] result = new String[args.length]; // int resultIndex = 0; // for (int j = 0; j < args.length; j++) { // boolean found = false; // for (int i = 0; !found && (i < validOptions.length); i++) { // String sought = validOptions[i]; // int doMore = (null == optionArgs ? 0 : optionArgs[i]); // if (LangUtil.isEmpty(sought)) { // continue; // } // found = sought.equals(args[j]); // if (found) { // if (null != extracted) { // extracted.add(sought); // } // if (0 < doMore) { // final int MAX = j + doMore; // if (MAX >= args.length) { // String s = "expecting " + doMore + " args after "; // throw new IllegalArgumentException(s + args[j]); // } // if (null != extracted) { // while (j < MAX) { // extracted.add(args[++j]); // } // } else { // j = MAX; // } // } // break; // } // } // if (!found) { // result[resultIndex++] = args[j]; // } // } // if (resultIndex < args.length) { // String[] temp = new String[resultIndex]; // System.arraycopy(result, 0, temp, 0, resultIndex); // args = temp; // } // return args; // } // /** @return String[] of entries in validOptions found in args */ // public static String[] selectOptions(String[] args, String[] // validOptions) { // if (LangUtil.isEmpty(args) || LangUtil.isEmpty(validOptions)) { // return new String[0]; // } // ArrayList result = new ArrayList(); // for (int i = 0; i < validOptions.length; i++) { // String sought = validOptions[i]; // if (LangUtil.isEmpty(sought)) { // continue; // } // for (int j = 0; j < args.length; j++) { // if (sought.equals(args[j])) { // result.add(sought); // break; // } // } // } // return (String[]) result.toArray(new String[0]); // } // /** @return String[] of entries in validOptions found in args */ // public static String[] selectOptions(List args, String[] validOptions) { // if (LangUtil.isEmpty(args) || LangUtil.isEmpty(validOptions)) { // return new String[0]; // } // ArrayList result = new ArrayList(); // for (int i = 0; i < validOptions.length; i++) { // String sought = validOptions[i]; // if (LangUtil.isEmpty(sought)) { // continue; // } // for (Iterator iter = args.iterator(); iter.hasNext();) { // String arg = (String) iter.next(); // if (sought.equals(arg)) { // result.add(sought); // break; // } // } // } // return (String[]) result.toArray(new String[0]); // } // /** // * Generate variants of String[] options by creating an extra set for // * each option that ends with "-". If none end with "-", then an // * array equal to <code>new String[][] { options }</code> is returned; // * if one ends with "-", then two sets are returned, // * three causes eight sets, etc. // * @return String[][] with each option set. // * @throws IllegalArgumentException if any option is null or empty. // */ // public static String[][] optionVariants(String[] options) { // if ((null == options) || (0 == options.length)) { // return new String[][] { new String[0]}; // } // // be nice, don't stomp input // String[] temp = new String[options.length]; // System.arraycopy(options, 0, temp, 0, temp.length); // options = temp; // boolean[] dup = new boolean[options.length]; // int numDups = 0; // // for (int i = 0; i < options.length; i++) { // String option = options[i]; // if (LangUtil.isEmpty(option)) { // throw new IllegalArgumentException("empty option at " + i); // } // if (option.endsWith("-")) { // options[i] = option.substring(0, option.length()-1); // dup[i] = true; // numDups++; // } // } // final String[] NONE = new String[0]; // final int variants = exp(2, numDups); // final String[][] result = new String[variants][]; // // variant is a bitmap wrt doing extra value when dup[k]=true // for (int variant = 0; variant < variants; variant++) { // ArrayList next = new ArrayList(); // int nextOption = 0; // for (int k = 0; k < options.length; k++) { // if (!dup[k] || (0 != (variant & (1 << (nextOption++))))) { // next.add(options[k]); // } // } // result[variant] = (String[]) next.toArray(NONE); // } // return result; // } // // private static int exp(int base, int power) { // not in Math? // if (0 > power) { // throw new IllegalArgumentException("negative power: " + power); // } // int result = 1; // while (0 < power--) { // result *= base; // } // return result; // } // /** // * Make a copy of the array. // * @return an array with the same component type as source // * containing same elements, even if null. // * @throws IllegalArgumentException if source is null // */ // public static final Object[] copy(Object[] source) { // LangUtil.throwIaxIfNull(source, "source"); // final Class c = source.getClass().getComponentType(); // Object[] result = (Object[]) Array.newInstance(c, source.length); // System.arraycopy(source, 0, result, 0, result.length); // return result; // } /** * Convert arrays safely. The number of elements in the result will be 1 * smaller for each element that is null or not assignable. This will use * sink if it has exactly the right size. The result will always have the * same component type as sink. * * @return an array with the same component type as sink containing any * assignable elements in source (in the same order). * @throws IllegalArgumentException if either is null */ public static Object[] safeCopy(Object[] source, Object[] sink) { final Class sinkType = (null == sink ? Object.class : sink.getClass().getComponentType()); final int sourceLength = (null == source ? 0 : source.length); final int sinkLength = (null == sink ? 0 : sink.length); final int resultSize; ArrayList result = null; if (0 == sourceLength) { resultSize = 0; } else { result = new ArrayList(sourceLength); for (int i = 0; i < sourceLength; i++) { if ((null != source[i]) && (sinkType.isAssignableFrom(source[i].getClass()))) { result.add(source[i]); } } resultSize = result.size(); } if (resultSize != sinkLength) { sink = (Object[]) Array.newInstance(sinkType, result.size()); } if (0 < resultSize) { sink = result.toArray(sink); } return sink; } /** * @return a String with the unqualified class name of the class (or "null") */ public static String unqualifiedClassName(Class c) { if (null == c) { return "null"; } String name = c.getName(); int loc = name.lastIndexOf("."); if (-1 != loc) { name = name.substring(1 + loc); } return name; } /** * @return a String with the unqualified class name of the object (or * "null") */ public static String unqualifiedClassName(Object o) { return LangUtil.unqualifiedClassName(null == o ? null : o.getClass()); } /** inefficient way to replace all instances of sought with replace */ public static String replace(String in, String sought, String replace) { if (LangUtil.isEmpty(in) || LangUtil.isEmpty(sought)) { return in; } StringBuffer result = new StringBuffer(); final int len = sought.length(); int start = 0; int loc; while (-1 != (loc = in.indexOf(sought, start))) { result.append(in.substring(start, loc)); if (!LangUtil.isEmpty(replace)) { result.append(replace); } start = loc + len; } result.append(in.substring(start)); return result.toString(); } /** render i right-justified with a given width less than about 40 */ public static String toSizedString(long i, int width) { String result = "" + i; int size = result.length(); if (width > size) { final String pad = " "; final int padLength = pad.length(); if (width > padLength) { width = padLength; } int topad = width - size; result = pad.substring(0, topad) + result; } return result; } // /** clip StringBuffer to maximum number of lines */ // static String clipBuffer(StringBuffer buffer, int maxLines) { // if ((null == buffer) || (1 > buffer.length())) return ""; // StringBuffer result = new StringBuffer(); // int j = 0; // final int MAX = maxLines; // final int N = buffer.length(); // for (int i = 0, srcBegin = 0; i < MAX; srcBegin += j) { // // todo: replace with String variant if/since getting char? // char[] chars = new char[128]; // int srcEnd = srcBegin+chars.length; // if (srcEnd >= N) { // srcEnd = N-1; // } // if (srcBegin == srcEnd) break; // //log("srcBegin:" + srcBegin + ":srcEnd:" + srcEnd); // buffer.getChars(srcBegin, srcEnd, chars, 0); // for (j = 0; j < srcEnd-srcBegin/*chars.length*/; j++) { // char c = chars[j]; // if (c == '\n') { // i++; // j++; // break; // } // } // try { result.append(chars, 0, j); } // catch (Throwable t) { } // } // return result.toString(); // } /** * @return "({UnqualifiedExceptionClass}) {message}" */ public static String renderExceptionShort(Throwable e) { if (null == e) return "(Throwable) null"; return "(" + LangUtil.unqualifiedClassName(e) + ") " + e.getMessage(); } /** * Renders exception <code>t</code> after unwrapping and eliding any test * packages. * * @param t <code>Throwable</code> to print. * @see #maxStackTrace */ public static String renderException(Throwable t) { return renderException(t, true); } /** * Renders exception <code>t</code>, unwrapping, optionally eliding and * limiting total number of lines. * * @param t <code>Throwable</code> to print. * @param elide true to limit to 100 lines and elide test packages * @see StringChecker#TEST_PACKAGES */ public static String renderException(Throwable t, boolean elide) { if (null == t) return "null throwable"; t = unwrapException(t); StringBuffer stack = stackToString(t, false); if (elide) { elideEndingLines(StringChecker.TEST_PACKAGES, stack, 100); } return stack.toString(); } /** * Trim ending lines from a StringBuffer, clipping to maxLines and further * removing any number of trailing lines accepted by checker. * * @param checker returns true if trailing line should be elided. * @param stack StringBuffer with lines to elide * @param maxLines int for maximum number of resulting lines */ static void elideEndingLines(StringChecker checker, StringBuffer stack, int maxLines) { if (null == checker || (null == stack) || (0 == stack.length())) { return; } final LinkedList lines = new LinkedList(); StringTokenizer st = new StringTokenizer(stack.toString(), "\n\r"); while (st.hasMoreTokens() && (0 < --maxLines)) { lines.add(st.nextToken()); } st = null; String line; int elided = 0; while (!lines.isEmpty()) { line = (String) lines.getLast(); if (!checker.acceptString(line)) { break; } else { elided++; lines.removeLast(); } } if ((elided > 0) || (maxLines < 1)) { final int EOL_LEN = EOL.length(); int totalLength = 0; while (!lines.isEmpty()) { totalLength += EOL_LEN + ((String) lines.getFirst()).length(); lines.removeFirst(); } if (stack.length() > totalLength) { stack.setLength(totalLength); if (elided > 0) { stack.append(" (... " + elided + " lines...)"); } } } } /** Dump message and stack to StringBuffer. */ public static StringBuffer stackToString(Throwable throwable, boolean skipMessage) { if (null == throwable) { return new StringBuffer(); } StringWriter buf = new StringWriter(); PrintWriter writer = new PrintWriter(buf); if (!skipMessage) { writer.println(throwable.getMessage()); } throwable.printStackTrace(writer); try { buf.close(); } catch (IOException ioe) { } // ignored return buf.getBuffer(); } /** @return Throwable input or tail of any wrapped exception chain */ public static Throwable unwrapException(Throwable t) { Throwable current = t; Throwable next = null; while (current != null) { // Java 1.2 exceptions that carry exceptions if (current instanceof InvocationTargetException) { next = ((InvocationTargetException) current).getTargetException(); } else if (current instanceof ClassNotFoundException) { next = ((ClassNotFoundException) current).getException(); } else if (current instanceof ExceptionInInitializerError) { next = ((ExceptionInInitializerError) current).getException(); } else if (current instanceof PrivilegedActionException) { next = ((PrivilegedActionException) current).getException(); } else if (current instanceof SQLException) { next = ((SQLException) current).getNextException(); } // ...getException(): // javax.naming.event.NamingExceptionEvent // javax.naming.ldap.UnsolicitedNotification // javax.xml.parsers.FactoryConfigurationError // javax.xml.transform.TransformerFactoryConfigurationError // javax.xml.transform.TransformerException // org.xml.sax.SAXException // 1.4: Throwable.getCause // java.util.logging.LogRecord.getThrown() if (null == next) { break; } else { current = next; next = null; } } return current; } /** * Replacement for Arrays.asList(..) which gacks on null and returns a List * in which remove is an unsupported operation. * * @param array the Object[] to convert (may be null) * @return the List corresponding to array (never null) */ public static List arrayAsList(Object[] array) { if ((null == array) || (1 > array.length)) { return Collections.EMPTY_LIST; } ArrayList list = new ArrayList(); list.addAll(Arrays.asList(array)); return list; } /** check if input contains any packages to elide. */ public static class StringChecker { static StringChecker TEST_PACKAGES = new StringChecker(new String[] { "org.aspectj.testing", "org.eclipse.jdt.internal.junit", "junit.framework.", "org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner" }); String[] infixes; /** @param infixes adopted */ StringChecker(String[] infixes) { this.infixes = infixes; } /** @return true if input contains infixes */ public boolean acceptString(String input) { boolean result = false; if (!LangUtil.isEmpty(input)) { for (int i = 0; !result && (i < infixes.length); i++) { result = (-1 != input.indexOf(infixes[i])); } } return result; } } /** * Gen classpath. * * @param bootclasspath * @param classpath * @param classesDir * @param outputJar * @return String combining classpath elements */ public static String makeClasspath( // XXX dumb implementation String bootclasspath, String classpath, String classesDir, String outputJar) { StringBuffer sb = new StringBuffer(); addIfNotEmpty(bootclasspath, sb, File.pathSeparator); addIfNotEmpty(classpath, sb, File.pathSeparator); if (!addIfNotEmpty(classesDir, sb, File.pathSeparator)) { addIfNotEmpty(outputJar, sb, File.pathSeparator); } return sb.toString(); } /** * @param input ignored if null * @param sink the StringBuffer to add input to - return false if null * @param delimiter the String to append to input when added - ignored if * empty * @return true if input + delimiter added to sink */ private static boolean addIfNotEmpty(String input, StringBuffer sink, String delimiter) { if (LangUtil.isEmpty(input) || (null == sink)) { return false; } sink.append(input); if (!LangUtil.isEmpty(delimiter)) { sink.append(delimiter); } return true; } /** * Create or initialize a process controller to run a process in another VM * asynchronously. * * @param controller the ProcessController to initialize, if not null * @param classpath * @param mainClass * @param args * @return initialized ProcessController */ public static ProcessController makeProcess(ProcessController controller, String classpath, String mainClass, String[] args) { File java = LangUtil.getJavaExecutable(); ArrayList cmd = new ArrayList(); cmd.add(java.getAbsolutePath()); cmd.add("-classpath"); cmd.add(classpath); cmd.add(mainClass); if (!LangUtil.isEmpty(args)) { cmd.addAll(Arrays.asList(args)); } String[] command = (String[]) cmd.toArray(new String[0]); if (null == controller) { controller = new ProcessController(); } controller.init(command, mainClass); return controller; } // /** // * Create a process to run asynchronously. // * @param controller if not null, initialize this one // * @param command the String[] command to run // * @param controller the ProcessControl for streams and results // */ // public static ProcessController makeProcess( // not needed? // ProcessController controller, // String[] command, // String label) { // if (null == controller) { // controller = new ProcessController(); // } // controller.init(command, label); // return controller; // } /** * Find java executable File path from java.home system property. * * @return File associated with the java command, or null if not found. */ public static File getJavaExecutable() { String javaHome = null; File result = null; // java.home // java.class.path // java.ext.dirs try { javaHome = System.getProperty("java.home"); } catch (Throwable t) { // ignore } if (null != javaHome) { File binDir = new File(javaHome, "bin"); if (binDir.isDirectory() && binDir.canRead()) { String[] execs = new String[] { "java", "java.exe" }; for (int i = 0; i < execs.length; i++) { result = new File(binDir, execs[i]); if (result.canRead()) { break; } } } } return result; } // /** // * Sleep for a particular period (in milliseconds). // * // * @param time the long time in milliseconds to sleep // * @return true if delay succeeded, false if interrupted 100 times // */ // public static boolean sleep(long milliseconds) { // if (milliseconds == 0) { // return true; // } else if (milliseconds < 0) { // throw new IllegalArgumentException("negative: " + milliseconds); // } // return sleepUntil(milliseconds + System.currentTimeMillis()); // } /** * Sleep until a particular time. * * @param time the long time in milliseconds to sleep until * @return true if delay succeeded, false if interrupted 100 times */ public static boolean sleepUntil(long time) { if (time == 0) { return true; } else if (time < 0) { throw new IllegalArgumentException("negative: " + time); } // final Thread thread = Thread.currentThread(); long curTime = System.currentTimeMillis(); for (int i = 0; (i < 100) && (curTime < time); i++) { try { Thread.sleep(time - curTime); } catch (InterruptedException e) { // ignore } curTime = System.currentTimeMillis(); } return (curTime >= time); } /** * Handle an external process asynchrously. <code>start()</code> launches a * main thread to wait for the process and pipes streams (in child threads) * through to the corresponding streams (e.g., the process System.err to * this System.err). This can complete normally, by exception, or on demand * by a client. Clients can implement <code>doCompleting(..)</code> to get * notice when the process completes. * <p> * The following sample code creates a process with a completion callback * starts it, and some time later retries the process. * * <pre> * LangUtil.ProcessController controller = new LangUtil.ProcessController() { * protected void doCompleting(LangUtil.ProcessController.Thrown thrown, int result) { * // signal result * } * }; * controller.init(new String[] { &quot;java&quot;, &quot;-version&quot; }, &quot;java version&quot;); * controller.start(); * // some time later... * // retry... * if (!controller.completed()) { * controller.stop(); * controller.reinit(); * controller.start(); * } * </pre> * * <u>warning</u>: Currently this does not close the input or output * streams, since doing so prevents their use later. */ public static class ProcessController { /* * XXX not verified thread-safe, but should be. Known problems: - user * stops (completed = true) then exception thrown from destroying * process (stop() expects !completed) ... */ private String[] command; private String[] envp; private String label; private boolean init; private boolean started; private boolean completed; /** if true, stopped by user when not completed */ private boolean userStopped; private Process process; private FileUtil.Pipe errStream; private FileUtil.Pipe outStream; private FileUtil.Pipe inStream; private ByteArrayOutputStream errSnoop; private ByteArrayOutputStream outSnoop; private int result; private Thrown thrown; public ProcessController() { } /** * Permit re-running using the same command if this is not started or if * completed. Can also call this when done with results to release * references associated with results (e.g., stack traces). */ public final void reinit() { if (!init) { throw new IllegalStateException("must init(..) before reinit()"); } if (started && !completed) { throw new IllegalStateException("not completed - do stop()"); } // init everything but command and label started = false; completed = false; result = Integer.MIN_VALUE; thrown = null; process = null; errStream = null; outStream = null; inStream = null; } public final void init(String classpath, String mainClass, String[] args) { init(LangUtil.getJavaExecutable(), classpath, mainClass, args); } public final void init(File java, String classpath, String mainClass, String[] args) { LangUtil.throwIaxIfNull(java, "java"); LangUtil.throwIaxIfNull(mainClass, "mainClass"); LangUtil.throwIaxIfNull(args, "args"); ArrayList cmd = new ArrayList(); cmd.add(java.getAbsolutePath()); cmd.add("-classpath"); cmd.add(classpath); cmd.add(mainClass); if (!LangUtil.isEmpty(args)) { cmd.addAll(Arrays.asList(args)); } init((String[]) cmd.toArray(new String[0]), mainClass); } public final void init(String[] command, String label) { this.command = (String[]) LangUtil.safeCopy(command, new String[0]); if (1 > this.command.length) { throw new IllegalArgumentException("empty command"); } this.label = LangUtil.isEmpty(label) ? command[0] : label; init = true; reinit(); } public final void setEnvp(String[] envp) { this.envp = (String[]) LangUtil.safeCopy(envp, new String[0]); if (1 > this.envp.length) { throw new IllegalArgumentException("empty envp"); } } public final void setErrSnoop(ByteArrayOutputStream snoop) { errSnoop = snoop; if (null != errStream) { errStream.setSnoop(errSnoop); } } public final void setOutSnoop(ByteArrayOutputStream snoop) { outSnoop = snoop; if (null != outStream) { outStream.setSnoop(outSnoop); } } /** * Start running the process and pipes asynchronously. * * @return Thread started or null if unable to start thread (results * available via <code>getThrown()</code>, etc.) */ public final Thread start() { if (!init) { throw new IllegalStateException("not initialized"); } synchronized (this) { if (started) { throw new IllegalStateException("already started"); } started = true; } try { process = Runtime.getRuntime().exec(command); } catch (IOException e) { stop(e, Integer.MIN_VALUE); return null; } errStream = new FileUtil.Pipe(process.getErrorStream(), System.err); if (null != errSnoop) { errStream.setSnoop(errSnoop); } outStream = new FileUtil.Pipe(process.getInputStream(), System.out); if (null != outSnoop) { outStream.setSnoop(outSnoop); } inStream = new FileUtil.Pipe(System.in, process.getOutputStream()); // start 4 threads, process & pipes for in, err, out Runnable processRunner = new Runnable() { public void run() { Throwable thrown = null; int result = Integer.MIN_VALUE; try { // pipe threads are children new Thread(errStream).start(); new Thread(outStream).start(); new Thread(inStream).start(); process.waitFor(); result = process.exitValue(); } catch (Throwable e) { thrown = e; } finally { stop(thrown, result); } } }; Thread result = new Thread(processRunner, label); result.start(); return result; } /** * Destroy any process, stop any pipes. This waits for the pipes to * clear (reading until no more input is available), but does not wait * for the input stream for the pipe to close (i.e., not waiting for * end-of-file on input stream). */ public final synchronized void stop() { if (completed) { return; } userStopped = true; stop(null, Integer.MIN_VALUE); } public final String[] getCommand() { String[] toCopy = command; if (LangUtil.isEmpty(toCopy)) { return new String[0]; } String[] result = new String[toCopy.length]; System.arraycopy(toCopy, 0, result, 0, result.length); return result; } public final boolean completed() { return completed; } public final boolean started() { return started; } public final boolean userStopped() { return userStopped; } /** * Get any Throwable thrown. Note that the process can complete normally * (with a valid return value), at the same time the pipes throw * exceptions, and that this may return some exceptions even if the * process is not complete. * * @return null if not complete or Thrown containing exceptions thrown * by the process and streams. */ public final Thrown getThrown() { // cache this return makeThrown(null); } public final int getResult() { return result; } /** * Subclasses implement this to get synchronous notice of completion. * All pipes and processes should be complete at this time. To get the * exceptions thrown for the pipes, use <code>getThrown()</code>. If * there is an exception, the process completed abruptly (including * side-effects of the user halting the process). If * <code>userStopped()</code> is true, then some client asked that the * process be destroyed using <code>stop()</code>. Otherwise, the result * code should be the result value returned by the process. * * @param thrown same as <code>getThrown().fromProcess</code>. * @param result same as <code>getResult()</code> * @see getThrown() * @see getResult() * @see stop() */ protected void doCompleting(Thrown thrown, int result) { } /** * Handle termination (on-demand, abrupt, or normal) by destroying * and/or halting process and pipes. * * @param thrown ignored if null * @param result ignored if Integer.MIN_VALUE */ private final synchronized void stop(Throwable thrown, int result) { if (completed) { throw new IllegalStateException("already completed"); } else if (null != this.thrown) { throw new IllegalStateException("already set thrown: " + thrown); } // assert null == this.thrown this.thrown = makeThrown(thrown); if (null != process) { process.destroy(); } if (null != inStream) { inStream.halt(false, true); // this will block if waiting inStream = null; } if (null != outStream) { outStream.halt(true, true); outStream = null; } if (null != errStream) { errStream.halt(true, true); errStream = null; } if (Integer.MIN_VALUE != result) { this.result = result; } completed = true; doCompleting(this.thrown, result); } /** * Create snapshot of Throwable's thrown. * * @param thrown ignored if null or if this.thrown is not null */ private final synchronized Thrown makeThrown(Throwable processThrown) { if (null != thrown) { return thrown; } return new Thrown(processThrown, (null == outStream ? null : outStream.getThrown()), (null == errStream ? null : errStream.getThrown()), (null == inStream ? null : inStream.getThrown())); } public static class Thrown { public final Throwable fromProcess; public final Throwable fromErrPipe; public final Throwable fromOutPipe; public final Throwable fromInPipe; /** true only if some Throwable is not null */ public final boolean thrown; private Thrown(Throwable fromProcess, Throwable fromOutPipe, Throwable fromErrPipe, Throwable fromInPipe) { this.fromProcess = fromProcess; this.fromErrPipe = fromErrPipe; this.fromOutPipe = fromOutPipe; this.fromInPipe = fromInPipe; thrown = ((null != fromProcess) || (null != fromInPipe) || (null != fromOutPipe) || (null != fromErrPipe)); } public String toString() { StringBuffer sb = new StringBuffer(); append(sb, fromProcess, "process"); append(sb, fromOutPipe, " stdout"); append(sb, fromErrPipe, " stderr"); append(sb, fromInPipe, " stdin"); if (0 == sb.length()) { return "Thrown (none)"; } else { return sb.toString(); } } private void append(StringBuffer sb, Throwable thrown, String label) { if (null != thrown) { sb.append("from " + label + ": "); sb.append(LangUtil.renderExceptionShort(thrown)); sb.append(LangUtil.EOL); } } } // class Thrown } }
289,816
Bug 289816 Potentially unclosed stream in org.aspectj.weaver.bcel.BcelWorld
null
resolved fixed
67ffda8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-09-18T23:05:59Z"
"2009-09-18T07:46:40Z"
weaver/src/org/aspectj/weaver/bcel/BcelWorld.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur perClause support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.File; import java.io.IOException; import java.lang.reflect.Modifier; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.ConstantPool; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.INVOKEINTERFACE; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.MULTIANEWARRAY; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.util.ClassLoaderReference; import org.aspectj.apache.bcel.util.ClassLoaderRepository; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.NonCachingClassLoaderRepository; import org.aspectj.apache.bcel.util.Repository; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IRelationship; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.WeaveMessage; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.BCException; import org.aspectj.weaver.Checker; import org.aspectj.weaver.ICrossReferenceHandler; import org.aspectj.weaver.IWeavingSupport; import org.aspectj.weaver.Member; import org.aspectj.weaver.MemberImpl; import org.aspectj.weaver.MemberKind; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.loadtime.definition.Definition; import org.aspectj.weaver.loadtime.definition.DocumentParser; import org.aspectj.weaver.model.AsmRelationshipProvider; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.ParserException; import org.aspectj.weaver.patterns.PatternParser; import org.aspectj.weaver.patterns.TypePattern; import org.aspectj.weaver.tools.Trace; import org.aspectj.weaver.tools.TraceFactory; public class BcelWorld extends World implements Repository { private final ClassPathManager classPath; protected Repository delegate; private BcelWeakClassLoaderReference loaderRef; private final BcelWeavingSupport bcelWeavingSupport = new BcelWeavingSupport(); private boolean isXmlConfiguredWorld = false; private WeavingXmlConfig xmlConfiguration; private static Trace trace = TraceFactory.getTraceFactory().getTrace(BcelWorld.class); public BcelWorld() { this(""); } public BcelWorld(String cp) { this(makeDefaultClasspath(cp), IMessageHandler.THROW, null); } public IRelationship.Kind determineRelKind(ShadowMunger munger) { AdviceKind ak = ((Advice) munger).getKind(); if (ak.getKey() == AdviceKind.Before.getKey()) return IRelationship.Kind.ADVICE_BEFORE; else if (ak.getKey() == AdviceKind.After.getKey()) return IRelationship.Kind.ADVICE_AFTER; else if (ak.getKey() == AdviceKind.AfterThrowing.getKey()) return IRelationship.Kind.ADVICE_AFTERTHROWING; else if (ak.getKey() == AdviceKind.AfterReturning.getKey()) return IRelationship.Kind.ADVICE_AFTERRETURNING; else if (ak.getKey() == AdviceKind.Around.getKey()) return IRelationship.Kind.ADVICE_AROUND; else if (ak.getKey() == AdviceKind.CflowEntry.getKey() || ak.getKey() == AdviceKind.CflowBelowEntry.getKey() || ak.getKey() == AdviceKind.InterInitializer.getKey() || ak.getKey() == AdviceKind.PerCflowEntry.getKey() || ak.getKey() == AdviceKind.PerCflowBelowEntry.getKey() || ak.getKey() == AdviceKind.PerThisEntry.getKey() || ak.getKey() == AdviceKind.PerTargetEntry.getKey() || ak.getKey() == AdviceKind.Softener.getKey() || ak.getKey() == AdviceKind.PerTypeWithinEntry.getKey()) { // System.err.println("Dont want a message about this: "+ak); return null; } throw new RuntimeException("Shadow.determineRelKind: What the hell is it? " + ak); } @Override public void reportMatch(ShadowMunger munger, Shadow shadow) { if (getCrossReferenceHandler() != null) { getCrossReferenceHandler().addCrossReference(munger.getSourceLocation(), // What is being applied shadow.getSourceLocation(), // Where is it being applied determineRelKind(munger).getName(), // What kind of advice? ((Advice) munger).hasDynamicTests() // Is a runtime test being stuffed in the code? ); } if (!getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { reportWeavingMessage(munger, shadow); } if (getModel() != null) { AsmRelationshipProvider.addAdvisedRelationship(getModelAsAsmManager(), shadow, munger); } } /* * Report a message about the advice weave that has occurred. Some messing about to make it pretty ! This code is just asking * for an NPE to occur ... */ private void reportWeavingMessage(ShadowMunger munger, Shadow shadow) { Advice advice = (Advice) munger; AdviceKind aKind = advice.getKind(); // Only report on interesting advice kinds ... if (aKind == null || advice.getConcreteAspect() == null) { // We suspect someone is programmatically driving the weaver // (e.g. IdWeaveTestCase in the weaver testcases) return; } if (!(aKind.equals(AdviceKind.Before) || aKind.equals(AdviceKind.After) || aKind.equals(AdviceKind.AfterReturning) || aKind.equals(AdviceKind.AfterThrowing) || aKind.equals(AdviceKind.Around) || aKind.equals(AdviceKind.Softener))) return; // synchronized blocks are implemented with multiple monitor_exit instructions in the bytecode // (one for normal exit from the method, one for abnormal exit), we only want to tell the user // once we have advised the end of the sync block, even though under the covers we will have // woven both exit points if (shadow.getKind() == Shadow.SynchronizationUnlock) { if (advice.lastReportedMonitorExitJoinpointLocation == null) { // this is the first time through, let's continue... advice.lastReportedMonitorExitJoinpointLocation = shadow.getSourceLocation(); } else { if (areTheSame(shadow.getSourceLocation(), advice.lastReportedMonitorExitJoinpointLocation)) { // Don't report it again! advice.lastReportedMonitorExitJoinpointLocation = null; return; } // hmmm, this means some kind of nesting is going on, urgh advice.lastReportedMonitorExitJoinpointLocation = shadow.getSourceLocation(); } } String description = advice.getKind().toString(); String advisedType = shadow.getEnclosingType().getName(); String advisingType = advice.getConcreteAspect().getName(); Message msg = null; if (advice.getKind().equals(AdviceKind.Softener)) { msg = WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_SOFTENS, new String[] { advisedType, beautifyLocation(shadow.getSourceLocation()), advisingType, beautifyLocation(munger.getSourceLocation()) }, advisedType, advisingType); } else { boolean runtimeTest = advice.hasDynamicTests(); String joinPointDescription = shadow.toString(); msg = WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ADVISES, new String[] { joinPointDescription, advisedType, beautifyLocation(shadow.getSourceLocation()), description, advisingType, beautifyLocation(munger.getSourceLocation()), (runtimeTest ? " [with runtime test]" : "") }, advisedType, advisingType); // Boolean.toString(runtimeTest)}); } getMessageHandler().handleMessage(msg); } private boolean areTheSame(ISourceLocation locA, ISourceLocation locB) { if (locA == null) return locB == null; if (locB == null) return false; if (locA.getLine() != locB.getLine()) return false; File fA = locA.getSourceFile(); File fB = locA.getSourceFile(); if (fA == null) return fB == null; if (fB == null) return false; return fA.getName().equals(fB.getName()); } /* * Ensure we report a nice source location - particular in the case where the source info is missing (binary weave). */ private String beautifyLocation(ISourceLocation isl) { StringBuffer nice = new StringBuffer(); if (isl == null || isl.getSourceFile() == null || isl.getSourceFile().getName().indexOf("no debug info available") != -1) { nice.append("no debug info available"); } else { // can't use File.getName() as this fails when a Linux box encounters a path created on Windows and vice-versa int takeFrom = isl.getSourceFile().getPath().lastIndexOf('/'); if (takeFrom == -1) { takeFrom = isl.getSourceFile().getPath().lastIndexOf('\\'); } int binary = isl.getSourceFile().getPath().lastIndexOf('!'); if (binary != -1 && binary < takeFrom) { // we have been woven by a binary aspect String pathToBinaryLoc = isl.getSourceFile().getPath().substring(0, binary + 1); if (pathToBinaryLoc.indexOf(".jar") != -1) { // only want to add the extra info if we're from a jar file int lastSlash = pathToBinaryLoc.lastIndexOf('/'); if (lastSlash == -1) { lastSlash = pathToBinaryLoc.lastIndexOf('\\'); } nice.append(pathToBinaryLoc.substring(lastSlash + 1)); } } nice.append(isl.getSourceFile().getPath().substring(takeFrom + 1)); if (isl.getLine() != 0) nice.append(":").append(isl.getLine()); // if it's a binary file then also want to give the file name if (isl.getSourceFileName() != null) nice.append("(from " + isl.getSourceFileName() + ")"); } return nice.toString(); } private static List<String> makeDefaultClasspath(String cp) { List<String> classPath = new ArrayList<String>(); classPath.addAll(getPathEntries(cp)); classPath.addAll(getPathEntries(ClassPath.getClassPath())); return classPath; } private static List<String> getPathEntries(String s) { List<String> ret = new ArrayList<String>(); StringTokenizer tok = new StringTokenizer(s, File.pathSeparator); while (tok.hasMoreTokens()) { ret.add(tok.nextToken()); } return ret; } public BcelWorld(List classPath, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { // this.aspectPath = new ClassPathManager(aspectPath, handler); this.classPath = new ClassPathManager(classPath, handler); setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes delegate = this; } public BcelWorld(ClassPathManager cpm, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { classPath = cpm; setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes delegate = this; } /** * Build a World from a ClassLoader, for LTW support * * @param loader * @param handler * @param xrefHandler */ public BcelWorld(ClassLoader loader, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { classPath = null; loaderRef = new BcelWeakClassLoaderReference(loader); setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes // delegate = getClassLoaderRepositoryFor(loader); } public void ensureRepositorySetup() { if (delegate == null) { delegate = getClassLoaderRepositoryFor(loaderRef); } } public Repository getClassLoaderRepositoryFor(ClassLoaderReference loader) { if (bcelRepositoryCaching) { return new ClassLoaderRepository(loader); } else { return new NonCachingClassLoaderRepository(loader); } } public void addPath(String name) { classPath.addPath(name, this.getMessageHandler()); } // ---- various interactions with bcel public static Type makeBcelType(UnresolvedType type) { return Type.getType(type.getErasureSignature()); } static Type[] makeBcelTypes(UnresolvedType[] types) { Type[] ret = new Type[types.length]; for (int i = 0, len = types.length; i < len; i++) { ret[i] = makeBcelType(types[i]); } return ret; } static String[] makeBcelTypesAsClassNames(UnresolvedType[] types) { String[] ret = new String[types.length]; for (int i = 0, len = types.length; i < len; i++) { ret[i] = types[i].getName(); } return ret; } public static UnresolvedType fromBcel(Type t) { return UnresolvedType.forSignature(t.getSignature()); } static UnresolvedType[] fromBcel(Type[] ts) { UnresolvedType[] ret = new UnresolvedType[ts.length]; for (int i = 0, len = ts.length; i < len; i++) { ret[i] = fromBcel(ts[i]); } return ret; } public ResolvedType resolve(Type t) { return resolve(fromBcel(t)); } @Override protected ReferenceTypeDelegate resolveDelegate(ReferenceType ty) { String name = ty.getName(); ensureAdvancedConfigurationProcessed(); JavaClass jc = lookupJavaClass(classPath, name); if (jc == null) { return null; } else { return buildBcelDelegate(ty, jc, false); } } public BcelObjectType buildBcelDelegate(ReferenceType resolvedTypeX, JavaClass jc, boolean exposedToWeaver) { BcelObjectType ret = new BcelObjectType(resolvedTypeX, jc, exposedToWeaver); return ret; } private JavaClass lookupJavaClass(ClassPathManager classPath, String name) { if (classPath == null) { try { ensureRepositorySetup(); JavaClass jc = delegate.loadClass(name); if (trace.isTraceEnabled()) trace.event("lookupJavaClass", this, new Object[] { name, jc }); return jc; } catch (ClassNotFoundException e) { if (trace.isTraceEnabled()) trace.error("Unable to find class '" + name + "' in repository", e); return null; } } try { ClassPathManager.ClassFile file = classPath.find(UnresolvedType.forName(name)); if (file == null) return null; ClassParser parser = new ClassParser(file.getInputStream(), file.getPath()); JavaClass jc = parser.parse(); file.close(); return jc; } catch (IOException ioe) { return null; } } public BcelObjectType addSourceObjectType(JavaClass jc) { BcelObjectType ret = null; String signature = UnresolvedType.forName(jc.getClassName()).getSignature(); Object fromTheMap = typeMap.get(signature); if (fromTheMap != null && !(fromTheMap instanceof ReferenceType)) { // what on earth is it then? See pr 112243 StringBuffer exceptionText = new StringBuffer(); exceptionText.append("Found invalid (not a ReferenceType) entry in the type map. "); exceptionText.append("Signature=[" + signature + "] Found=[" + fromTheMap + "] Class=[" + fromTheMap.getClass() + "]"); throw new BCException(exceptionText.toString()); } ReferenceType nameTypeX = (ReferenceType) fromTheMap; if (nameTypeX == null) { if (jc.isGeneric() && isInJava5Mode()) { nameTypeX = ReferenceType.fromTypeX(UnresolvedType.forRawTypeName(jc.getClassName()), this); ret = buildBcelDelegate(nameTypeX, jc, true); ReferenceType genericRefType = new ReferenceType(UnresolvedType.forGenericTypeSignature(signature, ret .getDeclaredGenericSignature()), this); nameTypeX.setDelegate(ret); genericRefType.setDelegate(ret); nameTypeX.setGenericType(genericRefType); typeMap.put(signature, nameTypeX); } else { nameTypeX = new ReferenceType(signature, this); ret = buildBcelDelegate(nameTypeX, jc, true); typeMap.put(signature, nameTypeX); } } else { ret = buildBcelDelegate(nameTypeX, jc, true); } return ret; } void deleteSourceObjectType(UnresolvedType ty) { typeMap.remove(ty.getSignature()); } public static Member makeFieldJoinPointSignature(LazyClassGen cg, FieldInstruction fi) { ConstantPool cpg = cg.getConstantPool(); return MemberImpl.field(fi.getClassName(cpg), (fi.opcode == Constants.GETSTATIC || fi.opcode == Constants.PUTSTATIC) ? Modifier.STATIC : 0, fi.getName(cpg), fi .getSignature(cpg)); } public Member makeJoinPointSignatureFromMethod(LazyMethodGen mg, MemberKind kind) { Member ret = mg.getMemberView(); if (ret == null) { int mods = mg.getAccessFlags(); if (mg.getEnclosingClass().isInterface()) { mods |= Modifier.INTERFACE; } return new ResolvedMemberImpl(kind, UnresolvedType.forName(mg.getClassName()), mods, fromBcel(mg.getReturnType()), mg .getName(), fromBcel(mg.getArgumentTypes())); } else { return ret; } } public Member makeJoinPointSignatureForMonitorEnter(LazyClassGen cg, InstructionHandle h) { return MemberImpl.monitorEnter(); } public Member makeJoinPointSignatureForMonitorExit(LazyClassGen cg, InstructionHandle h) { return MemberImpl.monitorExit(); } public Member makeJoinPointSignatureForArrayConstruction(LazyClassGen cg, InstructionHandle handle) { Instruction i = handle.getInstruction(); ConstantPool cpg = cg.getConstantPool(); Member retval = null; if (i.opcode == Constants.ANEWARRAY) { // ANEWARRAY arrayInstruction = (ANEWARRAY)i; Type ot = i.getType(cpg); UnresolvedType ut = fromBcel(ot); ut = UnresolvedType.makeArray(ut, 1); retval = MemberImpl.method(ut, Modifier.PUBLIC, ResolvedType.VOID, "<init>", new ResolvedType[] { ResolvedType.INT }); } else if (i instanceof MULTIANEWARRAY) { MULTIANEWARRAY arrayInstruction = (MULTIANEWARRAY) i; UnresolvedType ut = null; short dimensions = arrayInstruction.getDimensions(); ObjectType ot = arrayInstruction.getLoadClassType(cpg); if (ot != null) { ut = fromBcel(ot); ut = UnresolvedType.makeArray(ut, dimensions); } else { Type t = arrayInstruction.getType(cpg); ut = fromBcel(t); } ResolvedType[] parms = new ResolvedType[dimensions]; for (int ii = 0; ii < dimensions; ii++) parms[ii] = ResolvedType.INT; retval = MemberImpl.method(ut, Modifier.PUBLIC, ResolvedType.VOID, "<init>", parms); } else if (i.opcode == Constants.NEWARRAY) { // NEWARRAY arrayInstruction = (NEWARRAY)i; Type ot = i.getType(); UnresolvedType ut = fromBcel(ot); retval = MemberImpl.method(ut, Modifier.PUBLIC, ResolvedType.VOID, "<init>", new ResolvedType[] { ResolvedType.INT }); } else { throw new BCException("Cannot create array construction signature for this non-array instruction:" + i); } return retval; } public Member makeJoinPointSignatureForMethodInvocation(LazyClassGen cg, InvokeInstruction ii) { ConstantPool cpg = cg.getConstantPool(); String name = ii.getName(cpg); String declaring = ii.getClassName(cpg); UnresolvedType declaringType = null; String signature = ii.getSignature(cpg); int modifier = (ii instanceof INVOKEINTERFACE) ? Modifier.INTERFACE : (ii.opcode == Constants.INVOKESTATIC) ? Modifier.STATIC : (ii.opcode == Constants.INVOKESPECIAL && !name .equals("<init>")) ? Modifier.PRIVATE : 0; // in Java 1.4 and after, static method call of super class within // subclass method appears // as declared by the subclass in the bytecode - but they are not // see #104212 if (ii.opcode == Constants.INVOKESTATIC) { ResolvedType appearsDeclaredBy = resolve(declaring); // look for the method there for (Iterator iterator = appearsDeclaredBy.getMethods(); iterator.hasNext();) { ResolvedMember method = (ResolvedMember) iterator.next(); if (method.isStatic()) { if (name.equals(method.getName()) && signature.equals(method.getSignature())) { // we found it declaringType = method.getDeclaringType(); break; } } } } if (declaringType == null) { if (declaring.charAt(0) == '[') declaringType = UnresolvedType.forSignature(declaring); else declaringType = UnresolvedType.forName(declaring); } return MemberImpl.method(declaringType, modifier, name, signature); } @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append("BcelWorld("); // buf.append(shadowMungerMap); buf.append(")"); return buf.toString(); } /** * Retrieve a bcel delegate for an aspect - this will return NULL if the delegate is an EclipseSourceType and not a * BcelObjectType - this happens quite often when incrementally compiling. */ public static BcelObjectType getBcelObjectType(ResolvedType concreteAspect) { if (concreteAspect == null) { return null; } if (!(concreteAspect instanceof ReferenceType)) { // Might be Missing return null; } ReferenceTypeDelegate rtDelegate = ((ReferenceType) concreteAspect).getDelegate(); if (rtDelegate instanceof BcelObjectType) { return (BcelObjectType) rtDelegate; } else { return null; } } public void tidyUp() { // At end of compile, close any open files so deletion of those archives // is possible classPath.closeArchives(); typeMap.report(); ResolvedType.resetPrimitives(); } // / The repository interface methods public JavaClass findClass(String className) { return lookupJavaClass(classPath, className); } public JavaClass loadClass(String className) throws ClassNotFoundException { return lookupJavaClass(classPath, className); } public void storeClass(JavaClass clazz) { // doesn't need to do anything } public void removeClass(JavaClass clazz) { throw new RuntimeException("Not implemented"); } public JavaClass loadClass(Class clazz) throws ClassNotFoundException { throw new RuntimeException("Not implemented"); } public void clear() { delegate.clear(); // throw new RuntimeException("Not implemented"); } /** * The aim of this method is to make sure a particular type is 'ok'. Some operations on the delegate for a type modify it and * this method is intended to undo that... see pr85132 */ @Override public void validateType(UnresolvedType type) { ResolvedType result = typeMap.get(type.getSignature()); if (result == null) return; // We haven't heard of it yet if (!result.isExposedToWeaver()) return; // cant need resetting result.ensureConsistent(); // If we want to rebuild it 'from scratch' then: // ClassParser cp = new ClassParser(new // ByteArrayInputStream(newbytes),new String(cs)); // try { // rt.setDelegate(makeBcelObjectType(rt,cp.parse(),true)); // } catch (ClassFormatException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } } /** * Apply a single declare parents - return true if we change the type */ private boolean applyDeclareParents(DeclareParents p, ResolvedType onType) { boolean didSomething = false; List newParents = p.findMatchingNewParents(onType, true); if (!newParents.isEmpty()) { didSomething = true; BcelObjectType classType = BcelWorld.getBcelObjectType(onType); // System.err.println("need to do declare parents for: " + onType); for (Iterator j = newParents.iterator(); j.hasNext();) { ResolvedType newParent = (ResolvedType) j.next(); // We set it here so that the imminent matching for ITDs can // succeed - we // still haven't done the necessary changes to the class file // itself // (like transform super calls) - that is done in // BcelTypeMunger.mungeNewParent() // classType.addParent(newParent); onType.addParent(newParent); ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent); newParentMunger.setSourceLocation(p.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, getCrosscuttingMembersSet() .findAspectDeclaringParents(p))); } } return didSomething; } /** * Apply a declare @type - return true if we change the type */ private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedType onType, boolean reportProblems) { boolean didSomething = false; if (decA.matches(onType)) { if (onType.hasAnnotation(decA.getAnnotation().getType())) { // already has it return false; } AnnotationAJ annoX = decA.getAnnotation(); // check the annotation is suitable for the target boolean isOK = checkTargetOK(decA, onType, annoX); if (isOK) { didSomething = true; ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX); newAnnotationTM.setSourceLocation(decA.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM, decA.getAspect().resolve(this))); decA.copyAnnotationTo(onType); } } return didSomething; } /** * Checks for an @target() on the annotation and if found ensures it allows the annotation to be attached to the target type * that matched. */ private boolean checkTargetOK(DeclareAnnotation decA, ResolvedType onType, AnnotationAJ annoX) { if (annoX.specifiesTarget()) { if ((onType.isAnnotation() && !annoX.allowedOnAnnotationType()) || (!annoX.allowedOnRegularType())) { return false; } } return true; } // Hmmm - very similar to the code in BcelWeaver.weaveParentTypeMungers - // this code // doesn't need to produce errors/warnings though as it won't really be // weaving. protected void weaveInterTypeDeclarations(ResolvedType onType) { List<DeclareParents> declareParentsList = getCrosscuttingMembersSet().getDeclareParents(); if (onType.isRawType()) { onType = onType.getGenericType(); } onType.clearInterTypeMungers(); List<DeclareParents> decpToRepeat = new ArrayList<DeclareParents>(); boolean aParentChangeOccurred = false; boolean anAnnotationChangeOccurred = false; // First pass - apply all decp mungers for (Iterator<DeclareParents> i = declareParentsList.iterator(); i.hasNext();) { DeclareParents decp = i.next(); boolean typeChanged = applyDeclareParents(decp, onType); if (typeChanged) { aParentChangeOccurred = true; } else { // Perhaps it would have matched if a 'dec @type' had // modified the type if (!decp.getChild().isStarAnnotation()) decpToRepeat.add(decp); } } // Still first pass - apply all dec @type mungers for (Iterator i = getCrosscuttingMembersSet().getDeclareAnnotationOnTypes().iterator(); i.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation) i.next(); boolean typeChanged = applyDeclareAtType(decA, onType, true); if (typeChanged) { anAnnotationChangeOccurred = true; } } while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) { anAnnotationChangeOccurred = aParentChangeOccurred = false; List<DeclareParents> decpToRepeatNextTime = new ArrayList<DeclareParents>(); for (Iterator<DeclareParents> iter = decpToRepeat.iterator(); iter.hasNext();) { DeclareParents decp = iter.next(); boolean typeChanged = applyDeclareParents(decp, onType); if (typeChanged) { aParentChangeOccurred = true; } else { decpToRepeatNextTime.add(decp); } } for (Iterator iter = getCrosscuttingMembersSet().getDeclareAnnotationOnTypes().iterator(); iter.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation) iter.next(); boolean typeChanged = applyDeclareAtType(decA, onType, false); if (typeChanged) { anAnnotationChangeOccurred = true; } } decpToRepeat = decpToRepeatNextTime; } } @Override public IWeavingSupport getWeavingSupport() { return bcelWeavingSupport; } @Override public void reportCheckerMatch(Checker checker, Shadow shadow) { IMessage iMessage = new Message(checker.getMessage(), shadow.toString(), checker.isError() ? IMessage.ERROR : IMessage.WARNING, shadow.getSourceLocation(), null, new ISourceLocation[] { checker.getSourceLocation() }, true, 0, -1, -1); getMessageHandler().handleMessage(iMessage); if (getCrossReferenceHandler() != null) { getCrossReferenceHandler() .addCrossReference( checker.getSourceLocation(), shadow.getSourceLocation(), (checker.isError() ? IRelationship.Kind.DECLARE_ERROR.getName() : IRelationship.Kind.DECLARE_WARNING .getName()), false); } if (getModel() != null) { AsmRelationshipProvider.addDeclareErrorOrWarningRelationship(getModelAsAsmManager(), shadow, checker); } } public AsmManager getModelAsAsmManager() { return (AsmManager) getModel(); // For now... always an AsmManager in a bcel environment } void raiseError(String message) { getMessageHandler().handleMessage(MessageUtil.error(message)); } /** * These are aop.xml files that can be used to alter the aspects that actually apply from those passed in - and also their scope * of application to other files in the system. * * @param xmlFiles list of File objects representing any aop.xml files passed in to configure the build process */ public void setXmlFiles(List<File> xmlFiles) { if (!isXmlConfiguredWorld && !xmlFiles.isEmpty()) { raiseError("xml configuration files only supported by the compiler when -xmlConfigured option specified"); return; } if (!xmlFiles.isEmpty()) { xmlConfiguration = new WeavingXmlConfig(this); } for (File xmlfile : xmlFiles) { try { Definition d = DocumentParser.parse(xmlfile.toURI().toURL()); xmlConfiguration.add(d); } catch (MalformedURLException e) { raiseError("Unexpected problem processing XML config file '" + xmlfile.getName() + "' :" + e.getMessage()); } catch (Exception e) { raiseError("Unexpected problem processing XML config file '" + xmlfile.getName() + "' :" + e.getMessage()); } } } public void setXmlConfigured(boolean b) { this.isXmlConfiguredWorld = b; } @Override public boolean isXmlConfigured() { return isXmlConfiguredWorld && xmlConfiguration != null; } public WeavingXmlConfig getXmlConfiguration() { return xmlConfiguration; } @Override public boolean isAspectIncluded(ResolvedType aspectType) { if (!isXmlConfigured()) { return true; } return xmlConfiguration.specifiesInclusionOfAspect(aspectType.getName()); } @Override public TypePattern getAspectScope(ResolvedType declaringType) { return xmlConfiguration.getScopeFor(declaringType.getName()); } /** * A WeavingXmlConfig is initially a collection of definitions from XML files - once the world is ready and weaving is running * it will initialize and transform those definitions into an optimized set of values (eg. resolve type patterns and string * names to real entities). It can then answer questions quickly: (1) is this aspect included in the weaving? (2) Is there a * scope specified for this aspect and does it include type X? * */ static class WeavingXmlConfig { private boolean initialized = false; // Lazily done private List<Definition> definitions = new ArrayList<Definition>(); private List<String> resolvedIncludedAspects = new ArrayList<String>(); private Map<String, TypePattern> scopes = new HashMap<String, TypePattern>(); private List<String> includedFastMatchPatterns = Collections.emptyList(); private List<TypePattern> includedPatterns = Collections.emptyList(); private List<String> excludedFastMatchPatterns = Collections.emptyList(); private List<TypePattern> excludedPatterns = Collections.emptyList(); private BcelWorld world; public WeavingXmlConfig(BcelWorld bcelWorld) { this.world = bcelWorld; } public void add(Definition d) { definitions.add(d); } public void ensureInitialized() { if (!initialized) { try { resolvedIncludedAspects = new ArrayList<String>(); // Process the definitions into something more optimal for (Definition definition : definitions) { List<String> aspectNames = definition.getAspectClassNames(); for (String name : aspectNames) { resolvedIncludedAspects.add(name); // TODO check for existence? // ResolvedType resolvedAspect = resolve(UnresolvedType.forName(name)); // if (resolvedAspect.isMissing()) { // // ERROR // } else { // resolvedIncludedAspects.add(resolvedAspect); // } String scope = definition.getScopeForAspect(name); if (scope != null) { // Resolve the type pattern try { TypePattern scopePattern = new PatternParser(scope).parseTypePattern(); scopePattern.resolve(world); scopes.put(name, scopePattern); if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) { world.getMessageHandler().handleMessage( MessageUtil.info("Aspect '" + name + "' is scoped to apply against types matching pattern '" + scopePattern.toString() + "'")); } } catch (Exception e) { // TODO definitions should remember which file they came from, for inclusion in this message world.getMessageHandler().handleMessage( MessageUtil.error("Unable to parse scope as type pattern. Scope was '" + scope + "': " + e.getMessage())); } } } try { List<String> includePatterns = definition.getIncludePatterns(); if (includePatterns.size() > 0) { includedPatterns = new ArrayList<TypePattern>(); includedFastMatchPatterns = new ArrayList<String>(); } for (String includePattern : includePatterns) { if (includePattern.endsWith("..*")) { // from 'blah.blah.blah..*' leave the 'blah.blah.blah.' includedFastMatchPatterns.add(includePattern .substring(0, includePattern.length() - 2)); } else { TypePattern includedPattern = new PatternParser(includePattern).parseTypePattern(); includedPatterns.add(includedPattern); } } List<String> excludePatterns = definition.getExcludePatterns(); if (excludePatterns.size() > 0) { excludedPatterns = new ArrayList<TypePattern>(); excludedFastMatchPatterns = new ArrayList<String>(); } for (String excludePattern : excludePatterns) { if (excludePattern.endsWith("..*")) { // from 'blah.blah.blah..*' leave the 'blah.blah.blah.' excludedFastMatchPatterns.add(excludePattern .substring(0, excludePattern.length() - 2)); } else { TypePattern excludedPattern = new PatternParser(excludePattern).parseTypePattern(); excludedPatterns.add(excludedPattern); } } } catch (ParserException pe) { // TODO definitions should remember which file they came from, for inclusion in this message world.getMessageHandler().handleMessage( MessageUtil.error("Unable to parse type pattern: " + pe.getMessage())); } } } finally { initialized = true; } } } public boolean specifiesInclusionOfAspect(String name) { ensureInitialized(); return resolvedIncludedAspects.contains(name); } public TypePattern getScopeFor(String name) { return scopes.get(name); } // Can't quite follow the same rules for exclusion as used for loadtime weaving: // "The set of types to be woven are those types matched by at least one weaver include element and not matched by any // weaver // exclude element. If there are no weaver include statements then all non-excluded types are included." // Since if the weaver is seeing it during this kind of build, the type is implicitly included. So all we should check // for is exclusion public boolean excludesType(ResolvedType type) { String typename = type.getName(); boolean excluded = false; for (String excludedPattern : excludedFastMatchPatterns) { if (typename.startsWith(excludedPattern)) { excluded = true; break; } } if (!excluded) { for (TypePattern excludedPattern : excludedPatterns) { if (excludedPattern.matchesStatically(type)) { excluded = true; break; } } } return excluded; } } }
289,818
Bug 289818 Unclosed stream in org.aspectj.weaver.bcel.ExtensibleURLClassLoader
null
resolved fixed
4d200d1
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-09-18T23:07:29Z"
"2009-09-18T07:46:40Z"
weaver/src/org/aspectj/weaver/bcel/ExtensibleURLClassLoader.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Matthew Webster, Adrian Colyer, * Martin Lippert initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.security.CodeSource; import org.aspectj.util.FileUtil; import org.aspectj.weaver.UnresolvedType; public abstract class ExtensibleURLClassLoader extends URLClassLoader { private ClassPathManager classPath; public ExtensibleURLClassLoader (URL[] urls, ClassLoader parent) { super(urls,parent); // System.err.println("? ExtensibleURLClassLoader.<init>() path=" + WeavingAdaptor.makeClasspath(urls)); try { classPath = new ClassPathManager(FileUtil.makeClasspath(urls),null); } catch (ExceptionInInitializerError ex) { ex.printStackTrace(System.out); throw ex; } } protected void addURL(URL url) { super.addURL(url); // amc - this call was missing and is needed in // WeavingURLClassLoader chains classPath.addPath(url.getPath(),null); } protected Class findClass(String name) throws ClassNotFoundException { // System.err.println("? ExtensibleURLClassLoader.findClass(" + name + ")"); try { byte[] bytes = getBytes(name); if (bytes != null) { return defineClass(name,bytes); } else { throw new ClassNotFoundException(name); } } catch (IOException ex) { throw new ClassNotFoundException(name); } } protected Class defineClass(String name, byte[] b, CodeSource cs) throws IOException { // System.err.println("? ExtensibleURLClassLoader.defineClass(" + name + ",[" + b.length + "])"); return defineClass(name, b, 0, b.length, cs); } protected byte[] getBytes (String name) throws IOException { byte[] b = null; ClassPathManager.ClassFile classFile = classPath.find(UnresolvedType.forName(name)); if (classFile != null) { b = FileUtil.readAsByteArray(classFile.getInputStream()); } return b; } private Class defineClass(String name, byte[] bytes /*ClassPathManager.ClassFile classFile*/) throws IOException { String packageName = getPackageName(name); if (packageName != null) { Package pakkage = getPackage(packageName); if (pakkage == null) { definePackage(packageName,null,null,null,null,null,null,null); } } return defineClass(name, bytes, null); } private String getPackageName (String className) { int offset = className.lastIndexOf('.'); return (offset == -1)? null : className.substring(0,offset); } }
279,298
Bug 279298 AspectJ LTW with Cobertura
null
resolved fixed
35a9649
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-10-22T23:26:14Z"
"2009-06-05T19:26:40Z"
weaver/src/org/aspectj/weaver/bcel/AtAjAttributes.java
/******************************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * initial implementation Alexandre Vasseur *******************************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.Constant; import org.aspectj.apache.bcel.classfile.ConstantUtf8; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.LocalVariable; import org.aspectj.apache.bcel.classfile.LocalVariableTable; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen; import org.aspectj.apache.bcel.classfile.annotation.ArrayElementValue; import org.aspectj.apache.bcel.classfile.annotation.ClassElementValue; import org.aspectj.apache.bcel.classfile.annotation.ElementValue; import org.aspectj.apache.bcel.classfile.annotation.NameValuePair; import org.aspectj.apache.bcel.classfile.annotation.RuntimeAnnos; import org.aspectj.apache.bcel.classfile.annotation.RuntimeVisAnnos; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.BindingScope; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.MethodDelegateTypeMunger; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; import org.aspectj.weaver.patterns.Bindings; import org.aspectj.weaver.patterns.DeclareErrorOrWarning; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.DeclareParentsMixin; import org.aspectj.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.FormalBinding; import org.aspectj.weaver.patterns.IScope; import org.aspectj.weaver.patterns.ParserException; import org.aspectj.weaver.patterns.PatternParser; import org.aspectj.weaver.patterns.PerCflow; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.PerFromSuper; import org.aspectj.weaver.patterns.PerObject; import org.aspectj.weaver.patterns.PerSingleton; import org.aspectj.weaver.patterns.PerTypeWithin; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.TypePattern; /** * Annotation defined aspect reader. Reads the Java 5 annotations and turns them into AjAttributes * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public class AtAjAttributes { private final static List<AjAttribute> NO_ATTRIBUTES = Collections.emptyList(); private final static String[] EMPTY_STRINGS = new String[0]; private final static String VALUE = "value"; private final static String ARGNAMES = "argNames"; private final static String POINTCUT = "pointcut"; private final static String THROWING = "throwing"; private final static String RETURNING = "returning"; private final static String STRING_DESC = "Ljava/lang/String;"; /** * A struct that allows to add extra arguments without always breaking the API */ private static class AjAttributeStruct { /** * The list of AjAttribute.XXX that we are populating from the @AJ read */ List<AjAttribute> ajAttributes = new ArrayList<AjAttribute>(); /** * The resolved type (class) for which we are reading @AJ for (be it class, method, field annotations) */ final ResolvedType enclosingType; final ISourceContext context; final IMessageHandler handler; public AjAttributeStruct(ResolvedType type, ISourceContext sourceContext, IMessageHandler messageHandler) { enclosingType = type; context = sourceContext; handler = messageHandler; } } /** * A struct when we read @AJ on method * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ private static class AjAttributeMethodStruct extends AjAttributeStruct { // argument names used for formal binding private String[] m_argumentNamesLazy = null; public String unparsedArgumentNames = null; // Set only if discovered as // argNames attribute of // annotation final Method method; final BcelMethod bMethod; public AjAttributeMethodStruct(Method method, BcelMethod bMethod, ResolvedType type, ISourceContext sourceContext, IMessageHandler messageHandler) { super(type, sourceContext, messageHandler); this.method = method; this.bMethod = bMethod; } public String[] getArgumentNames() { if (m_argumentNamesLazy == null) { m_argumentNamesLazy = getMethodArgumentNames(method, unparsedArgumentNames, this); } return m_argumentNamesLazy; } } /** * A struct when we read @AJ on field */ private static class AjAttributeFieldStruct extends AjAttributeStruct { final Field field; final BcelField bField; public AjAttributeFieldStruct(Field field, BcelField bField, ResolvedType type, ISourceContext sourceContext, IMessageHandler messageHandler) { super(type, sourceContext, messageHandler); this.field = field; this.bField = bField; } } /** * Annotations are RuntimeVisible only. This allow us to not visit RuntimeInvisible ones. * * @param attribute * @return true if runtime visible annotation */ public static boolean acceptAttribute(Attribute attribute) { return (attribute instanceof RuntimeVisAnnos); } /** * Extract class level annotations and turn them into AjAttributes. * * @param javaClass * @param type * @param context * @param msgHandler * @return list of AjAttributes */ public static List readAj5ClassAttributes(AsmManager model, JavaClass javaClass, ReferenceType type, ISourceContext context, IMessageHandler msgHandler, boolean isCodeStyleAspect) { boolean ignoreThisClass = javaClass.getClassName().charAt(0) == 'o' && javaClass.getClassName().startsWith("org.aspectj.lang.annotation"); if (ignoreThisClass) { return NO_ATTRIBUTES; } boolean containsPointcut = false; boolean containsAnnotationClassReference = false; Constant[] cpool = javaClass.getConstantPool().getConstantPool(); for (int i = 0; i < cpool.length; i++) { Constant constant = cpool[i]; if (constant != null && constant.getTag() == Constants.CONSTANT_Utf8) { String constantValue = ((ConstantUtf8) constant).getValue(); if (constantValue.length() > 28 && constantValue.charAt(1) == 'o') { if (constantValue.startsWith("Lorg/aspectj/lang/annotation")) { containsAnnotationClassReference = true; if ("Lorg/aspectj/lang/annotation/DeclareAnnotation;".equals(constantValue)) { msgHandler.handleMessage(new Message( "Found @DeclareAnnotation while current release does not support it (see '" + type.getName() + "')", IMessage.WARNING, null, type.getSourceLocation())); } if ("Lorg/aspectj/lang/annotation/Pointcut;".equals(constantValue)) { containsPointcut = true; } } } } } if (!containsAnnotationClassReference) { return NO_ATTRIBUTES; } AjAttributeStruct struct = new AjAttributeStruct(type, context, msgHandler); Attribute[] attributes = javaClass.getAttributes(); boolean hasAtAspectAnnotation = false; boolean hasAtPrecedenceAnnotation = false; for (int i = 0; i < attributes.length; i++) { Attribute attribute = attributes[i]; if (acceptAttribute(attribute)) { RuntimeAnnos rvs = (RuntimeAnnos) attribute; // we don't need to look for several attribute occurrences since // it cannot happen as per JSR175 if (!isCodeStyleAspect && !javaClass.isInterface()) { hasAtAspectAnnotation = handleAspectAnnotation(rvs, struct); // TODO AV - if put outside the if isCodeStyleAspect then we // would enable mix style hasAtPrecedenceAnnotation = handlePrecedenceAnnotation(rvs, struct); } // there can only be one RuntimeVisible bytecode attribute break; } } // basic semantic check if (hasAtPrecedenceAnnotation && !hasAtAspectAnnotation) { msgHandler.handleMessage(new Message("Found @DeclarePrecedence on a non @Aspect type '" + type.getName() + "'", IMessage.WARNING, null, type.getSourceLocation())); // bypass what we have read return NO_ATTRIBUTES; } // the following block will not detect @Pointcut in non @Aspect types // for optimization purpose if (!(hasAtAspectAnnotation || isCodeStyleAspect) && !containsPointcut) { return NO_ATTRIBUTES; } // FIXME AV - turn on when ajcMightHaveAspect // if (hasAtAspectAnnotation && type.isInterface()) { // msgHandler.handleMessage( // new Message( // "Found @Aspect on an interface type '" + type.getName() + "'", // IMessage.WARNING, // null, // type.getSourceLocation() // ) // ); // // bypass what we have read // return EMPTY_LIST; // } // semantic check: @Aspect must be public // FIXME AV - do we really want to enforce that? // if (hasAtAspectAnnotation && !javaClass.isPublic()) { // msgHandler.handleMessage( // new Message( // "Found @Aspect annotation on a non public class '" + // javaClass.getClassName() + "'", // IMessage.ERROR, // null, // type.getSourceLocation() // ) // ); // return EMPTY_LIST; // } // code style pointcuts are class attributes // we need to gather the @AJ pointcut right now and not at method level // annotation extraction time // in order to be able to resolve the pointcut references later on // we don't need to look in super class, the pointcut reference in the // grammar will do it for (int i = 0; i < javaClass.getMethods().length; i++) { Method method = javaClass.getMethods()[i]; if (method.getName().startsWith(NameMangler.PREFIX)) { continue; // already dealt with by ajc... } // FIXME alex optimize, this method struct will gets recreated for // advice extraction AjAttributeMethodStruct mstruct = null; boolean processedPointcut = false; Attribute[] mattributes = method.getAttributes(); for (int j = 0; j < mattributes.length; j++) { Attribute mattribute = mattributes[j]; if (acceptAttribute(mattribute)) { // TODO speed all this nonsense up rather than looking // through all the annotations every time // same for fields mstruct = new AjAttributeMethodStruct(method, null, type, context, msgHandler); processedPointcut = handlePointcutAnnotation((RuntimeAnnos) mattribute, mstruct); if (!processedPointcut) { processedPointcut = handleDeclareMixinAnnotation((RuntimeAnnos) mattribute, mstruct); } // there can only be one RuntimeVisible bytecode attribute break; } } if (processedPointcut) { // FIXME asc should check we aren't adding multiple versions... // will do once I get the tests passing again... struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo()); struct.ajAttributes.addAll(mstruct.ajAttributes); } } // code style declare error / warning / implements / parents are field // attributes Field[] fs = javaClass.getFields(); for (int i = 0; i < fs.length; i++) { Field field = fs[i]; if (field.getName().startsWith(NameMangler.PREFIX)) { continue; // already dealt with by ajc... } // FIXME alex optimize, this method struct will gets recreated for // advice extraction AjAttributeFieldStruct fstruct = new AjAttributeFieldStruct(field, null, type, context, msgHandler); Attribute[] fattributes = field.getAttributes(); for (int j = 0; j < fattributes.length; j++) { Attribute fattribute = fattributes[j]; if (acceptAttribute(fattribute)) { RuntimeAnnos frvs = (RuntimeAnnos) fattribute; if (handleDeclareErrorOrWarningAnnotation(model, frvs, fstruct) || handleDeclareParentsAnnotation(frvs, fstruct)) { // semantic check - must be in an @Aspect [remove if // previous block bypassed in advance] if (!type.isAnnotationStyleAspect() && !isCodeStyleAspect) { msgHandler.handleMessage(new Message("Found @AspectJ annotations in a non @Aspect type '" + type.getName() + "'", IMessage.WARNING, null, type.getSourceLocation())); // go ahead } } // there can only be one RuntimeVisible bytecode attribute break; } } struct.ajAttributes.addAll(fstruct.ajAttributes); } return struct.ajAttributes; } /** * Extract method level annotations and turn them into AjAttributes. * * @param method * @param type * @param context * @param msgHandler * @return list of AjAttributes */ public static List<AjAttribute> readAj5MethodAttributes(Method method, BcelMethod bMethod, ResolvedType type, ResolvedPointcutDefinition preResolvedPointcut, ISourceContext context, IMessageHandler msgHandler) { if (method.getName().startsWith(NameMangler.PREFIX)) { return Collections.emptyList(); // already dealt with by ajc... } AjAttributeMethodStruct struct = new AjAttributeMethodStruct(method, bMethod, type, context, msgHandler); Attribute[] attributes = method.getAttributes(); // we remember if we found one @AJ annotation for minimal semantic error // reporting // the real reporting beeing done thru AJDT and the compiler mapping @AJ // to AjAtttribute // or thru APT // // Note: we could actually skip the whole thing if type is not itself an // @Aspect // but then we would not see any warning. We do bypass for pointcut but // not for advice since it would // be too silent. boolean hasAtAspectJAnnotation = false; boolean hasAtAspectJAnnotationMustReturnVoid = false; for (int i = 0; i < attributes.length; i++) { Attribute attribute = attributes[i]; try { if (acceptAttribute(attribute)) { RuntimeAnnos rvs = (RuntimeAnnos) attribute; hasAtAspectJAnnotationMustReturnVoid = hasAtAspectJAnnotationMustReturnVoid || handleBeforeAnnotation(rvs, struct, preResolvedPointcut); hasAtAspectJAnnotationMustReturnVoid = hasAtAspectJAnnotationMustReturnVoid || handleAfterAnnotation(rvs, struct, preResolvedPointcut); hasAtAspectJAnnotationMustReturnVoid = hasAtAspectJAnnotationMustReturnVoid || handleAfterReturningAnnotation(rvs, struct, preResolvedPointcut, bMethod); hasAtAspectJAnnotationMustReturnVoid = hasAtAspectJAnnotationMustReturnVoid || handleAfterThrowingAnnotation(rvs, struct, preResolvedPointcut, bMethod); hasAtAspectJAnnotation = hasAtAspectJAnnotation || handleAroundAnnotation(rvs, struct, preResolvedPointcut); // there can only be one RuntimeVisible bytecode attribute break; } } catch (ReturningFormalNotDeclaredInAdviceSignatureException e) { msgHandler.handleMessage(new Message(WeaverMessages.format(WeaverMessages.RETURNING_FORMAL_NOT_DECLARED_IN_ADVICE, e.getFormalName()), IMessage.ERROR, null, bMethod.getSourceLocation())); } catch (ThrownFormalNotDeclaredInAdviceSignatureException e) { msgHandler.handleMessage(new Message(WeaverMessages.format(WeaverMessages.THROWN_FORMAL_NOT_DECLARED_IN_ADVICE, e .getFormalName()), IMessage.ERROR, null, bMethod.getSourceLocation())); } } hasAtAspectJAnnotation = hasAtAspectJAnnotation || hasAtAspectJAnnotationMustReturnVoid; // semantic check - must be in an @Aspect [remove if previous block // bypassed in advance] if (hasAtAspectJAnnotation && !type.isAspect()) { // isAnnotationStyleAspect()) // { msgHandler.handleMessage(new Message("Found @AspectJ annotations in a non @Aspect type '" + type.getName() + "'", IMessage.WARNING, null, type.getSourceLocation())); // go ahead } // semantic check - advice must be public if (hasAtAspectJAnnotation && !struct.method.isPublic()) { msgHandler.handleMessage(new Message("Found @AspectJ annotation on a non public advice '" + methodToString(struct.method) + "'", IMessage.ERROR, null, type.getSourceLocation())); // go ahead } // semantic check - advice must not be static if (hasAtAspectJAnnotation && struct.method.isStatic()) { msgHandler.handleMessage(MessageUtil.error("Advice cannot be declared static '" + methodToString(struct.method) + "'", type.getSourceLocation())); // new Message( // "Advice cannot be declared static '" + // methodToString(struct.method) + "'", // IMessage.ERROR, // null, // type.getSourceLocation() // ) // ); // go ahead } // semantic check for non around advice must return void if (hasAtAspectJAnnotationMustReturnVoid && !Type.VOID.equals(struct.method.getReturnType())) { msgHandler.handleMessage(new Message("Found @AspectJ annotation on a non around advice not returning void '" + methodToString(struct.method) + "'", IMessage.ERROR, null, type.getSourceLocation())); // go ahead } return struct.ajAttributes; } /** * Extract field level annotations and turn them into AjAttributes. * * @param field * @param type * @param context * @param msgHandler * @return list of AjAttributes, always empty for now */ public static List readAj5FieldAttributes(Field field, BcelField bField, ResolvedType type, ISourceContext context, IMessageHandler msgHandler) { // Note: field annotation are for ITD and DEOW - processed at class // level directly return Collections.EMPTY_LIST; } /** * Read @Aspect * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleAspectAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeStruct struct) { AnnotationGen aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.ASPECT_ANNOTATION); if (aspect != null) { // semantic check for inheritance (only one level up) boolean extendsAspect = false; if (!"java.lang.Object".equals(struct.enclosingType.getSuperclass().getName())) { if (!struct.enclosingType.getSuperclass().isAbstract() && struct.enclosingType.getSuperclass().isAspect()) { reportError("cannot extend a concrete aspect", struct); return false; } extendsAspect = struct.enclosingType.getSuperclass().isAspect(); } NameValuePair aspectPerClause = getAnnotationElement(aspect, VALUE); final PerClause perClause; if (aspectPerClause == null) { // empty value means singleton unless inherited if (!extendsAspect) { perClause = new PerSingleton(); } else { perClause = new PerFromSuper(struct.enclosingType.getSuperclass().getPerClause().getKind()); } } else { String perX = aspectPerClause.getValue().stringifyValue(); if (perX == null || perX.length() <= 0) { perClause = new PerSingleton(); } else { perClause = parsePerClausePointcut(perX, struct); } } if (perClause == null) { // could not parse it, ignore the aspect return false; } else { perClause.setLocation(struct.context, -1, -1);// struct.context.getOffset(), // struct.context.getOffset()+1);//FIXME // AVASM // FIXME asc see related comment way about about the version... struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo()); AjAttribute.Aspect aspectAttribute = new AjAttribute.Aspect(perClause); struct.ajAttributes.add(aspectAttribute); FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; final IScope binding; binding = new BindingScope(struct.enclosingType, struct.context, bindings); // // we can't resolve here since the perclause typically refers // to pointcuts // // defined in the aspect that we haven't told the // BcelObjectType about yet. // // perClause.resolve(binding); // so we prepare to do it later... aspectAttribute.setResolutionScope(binding); return true; } } return false; } /** * Read a perClause, returns null on failure and issue messages * * @param perClauseString like "pertarget(.....)" * @param struct for which we are parsing the per clause * @return a PerClause instance */ private static PerClause parsePerClausePointcut(String perClauseString, AjAttributeStruct struct) { final String pointcutString; Pointcut pointcut = null; TypePattern typePattern = null; final PerClause perClause; if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERCFLOW.getName())) { pointcutString = PerClause.KindAnnotationPrefix.PERCFLOW.extractPointcut(perClauseString); pointcut = parsePointcut(pointcutString, struct, false); perClause = new PerCflow(pointcut, false); } else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERCFLOWBELOW.getName())) { pointcutString = PerClause.KindAnnotationPrefix.PERCFLOWBELOW.extractPointcut(perClauseString); pointcut = parsePointcut(pointcutString, struct, false); perClause = new PerCflow(pointcut, true); } else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERTARGET.getName())) { pointcutString = PerClause.KindAnnotationPrefix.PERTARGET.extractPointcut(perClauseString); pointcut = parsePointcut(pointcutString, struct, false); perClause = new PerObject(pointcut, false); } else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERTHIS.getName())) { pointcutString = PerClause.KindAnnotationPrefix.PERTHIS.extractPointcut(perClauseString); pointcut = parsePointcut(pointcutString, struct, false); perClause = new PerObject(pointcut, true); } else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERTYPEWITHIN.getName())) { pointcutString = PerClause.KindAnnotationPrefix.PERTYPEWITHIN.extractPointcut(perClauseString); typePattern = parseTypePattern(pointcutString, struct); perClause = new PerTypeWithin(typePattern); } else if (perClauseString.equalsIgnoreCase(PerClause.SINGLETON.getName() + "()")) { perClause = new PerSingleton(); } else { // could not parse the @AJ perclause - fallback to singleton and // issue an error reportError("@Aspect per clause cannot be read '" + perClauseString + "'", struct); return null; } if (!PerClause.SINGLETON.equals(perClause.getKind()) && !PerClause.PERTYPEWITHIN.equals(perClause.getKind()) && pointcut == null) { // we could not parse the pointcut return null; } if (PerClause.PERTYPEWITHIN.equals(perClause.getKind()) && typePattern == null) { // we could not parse the type pattern return null; } return perClause; } /** * Read @DeclarePrecedence * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handlePrecedenceAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeStruct struct) { AnnotationGen aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREPRECEDENCE_ANNOTATION); if (aspect != null) { NameValuePair precedence = getAnnotationElement(aspect, VALUE); if (precedence != null) { String precedencePattern = precedence.getValue().stringifyValue(); PatternParser parser = new PatternParser(precedencePattern); DeclarePrecedence ajPrecedence = parser.parseDominates(); struct.ajAttributes.add(new AjAttribute.DeclareAttribute(ajPrecedence)); return true; } } return false; } // /** // * Read @DeclareImplements // * // * @param runtimeAnnotations // * @param struct // * @return true if found // */ // private static boolean // handleDeclareImplementsAnnotation(RuntimeAnnotations runtimeAnnotations, // AjAttributeFieldStruct // struct) {//, ResolvedPointcutDefinition preResolvedPointcut) { // Annotation deci = getAnnotation(runtimeAnnotations, // AjcMemberMaker.DECLAREIMPLEMENTS_ANNOTATION); // if (deci != null) { // ElementNameValuePairGen deciPatternNVP = getAnnotationElement(deci, // VALUE); // String deciPattern = deciPatternNVP.getValue().stringifyValue(); // if (deciPattern != null) { // TypePattern typePattern = parseTypePattern(deciPattern, struct); // ResolvedType fieldType = // UnresolvedType.forSignature(struct.field.getSignature()).resolve(struct.enclosingType.getWorld()); // if (fieldType.isPrimitiveType()) { // return false; // } else if (fieldType.isInterface()) { // TypePattern parent = new // ExactTypePattern(UnresolvedType.forSignature(struct.field.getSignature()), // false, false); // parent.resolve(struct.enclosingType.getWorld()); // List parents = new ArrayList(1); // parents.add(parent); // //TODO kick ISourceLocation sl = struct.bField.getSourceLocation(); ?? // struct.ajAttributes.add( // new AjAttribute.DeclareAttribute( // new DeclareParents( // typePattern, // parents, // false // ) // ) // ); // return true; // } else { // reportError("@DeclareImplements: can only be used on field whose type is an interface", // struct); // return false; // } // } // } // return false; // } /** * Read @DeclareParents * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleDeclareParentsAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeFieldStruct struct) {// , // ResolvedPointcutDefinition // preResolvedPointcut) // { AnnotationGen decp = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREPARENTS_ANNOTATION); if (decp != null) { NameValuePair decpPatternNVP = getAnnotationElement(decp, VALUE); String decpPattern = decpPatternNVP.getValue().stringifyValue(); if (decpPattern != null) { TypePattern typePattern = parseTypePattern(decpPattern, struct); ResolvedType fieldType = UnresolvedType.forSignature(struct.field.getSignature()).resolve( struct.enclosingType.getWorld()); if (fieldType.isInterface()) { TypePattern parent = parseTypePattern(fieldType.getName(), struct); FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings); // first add the declare implements like List parents = new ArrayList(1); parents.add(parent); DeclareParents dp = new DeclareParents(typePattern, parents, false); dp.resolve(binding); // resolves the parent and child parts // of the decp // resolve this so that we can use it for the // MethodDelegateMungers below. // eg. '@Coloured *' will change from a WildTypePattern to // an 'AnyWithAnnotationTypePattern' after this // resolution typePattern = typePattern.resolveBindings(binding, Bindings.NONE, false, false); // TODO kick ISourceLocation sl = // struct.bField.getSourceLocation(); ?? // dp.setLocation(dp.getDeclaringType().getSourceContext(), // dp.getDeclaringType().getSourceLocation().getOffset(), // dp.getDeclaringType().getSourceLocation().getOffset()); dp.setLocation(struct.context, -1, -1); // not ideal... struct.ajAttributes.add(new AjAttribute.DeclareAttribute(dp)); // do we have a defaultImpl=xxx.class (ie implementation) String defaultImplClassName = null; NameValuePair defaultImplNVP = getAnnotationElement(decp, "defaultImpl"); if (defaultImplNVP != null) { ClassElementValue defaultImpl = (ClassElementValue) defaultImplNVP.getValue(); defaultImplClassName = UnresolvedType.forSignature(defaultImpl.getClassString()).getName(); if (defaultImplClassName.equals("org.aspectj.lang.annotation.DeclareParents")) { defaultImplClassName = null; } else { // check public no arg ctor ResolvedType impl = struct.enclosingType.getWorld().resolve(defaultImplClassName, false); ResolvedMember[] mm = impl.getDeclaredMethods(); int implModifiers = impl.getModifiers(); boolean defaultVisibilityImpl = !(Modifier.isPrivate(implModifiers) || Modifier.isProtected(implModifiers) || Modifier.isPublic(implModifiers)); boolean hasNoCtorOrANoArgOne = true; ResolvedMember foundOneOfIncorrectVisibility = null; for (int i = 0; i < mm.length; i++) { ResolvedMember resolvedMember = mm[i]; if (resolvedMember.getName().equals("<init>")) { hasNoCtorOrANoArgOne = false; if (resolvedMember.getParameterTypes().length == 0) { if (defaultVisibilityImpl) { // default // visibility // implementation if (resolvedMember.isPublic() || resolvedMember.isDefault()) { hasNoCtorOrANoArgOne = true; } else { foundOneOfIncorrectVisibility = resolvedMember; } } else if (Modifier.isPublic(implModifiers)) { // public // implementation if (resolvedMember.isPublic()) { hasNoCtorOrANoArgOne = true; } else { foundOneOfIncorrectVisibility = resolvedMember; } } } } if (hasNoCtorOrANoArgOne) { break; } } if (!hasNoCtorOrANoArgOne) { if (foundOneOfIncorrectVisibility != null) { reportError( "@DeclareParents: defaultImpl=\"" + defaultImplClassName + "\" has a no argument constructor, but it is of incorrect visibility. It must be at least as visible as the type.", struct); } else { reportError("@DeclareParents: defaultImpl=\"" + defaultImplClassName + "\" has no public no-arg constructor", struct); } } if (!fieldType.isAssignableFrom(impl)) { reportError("@DeclareParents: defaultImpl=\"" + defaultImplClassName + "\" does not implement the interface '" + fieldType.toString() + "'", struct); } } } // then iterate on field interface hierarchy (not object) boolean hasAtLeastOneMethod = false; ResolvedMember[] methods = fieldType.getMethodsWithoutIterator(true, false).toArray(new ResolvedMember[0]); for (int i = 0; i < methods.length; i++) { ResolvedMember method = methods[i]; if (method.isAbstract()) { // moved to be detected at weave time if the target // doesnt implement the methods // if (defaultImplClassName == null) { // // non marker interface with no default impl // provided // reportError("@DeclareParents: used with a non marker interface and no defaultImpl=\"...\" provided", // struct); // return false; // } hasAtLeastOneMethod = true; // What we are saying here: // We have this method 'method' and we want to put a // forwarding method into a type that matches // typePattern that should delegate to the version // of the method in 'defaultImplClassName' // Now the method may be from a supertype but the // declaring type of the method we pass into the // type // munger is what is used to determine the type of // the field that hosts the delegate instance. // So here we create a modified method with an // alternative declaring type so that we lookup // the right field. See pr164016. MethodDelegateTypeMunger mdtm = new MethodDelegateTypeMunger(method, struct.enclosingType, defaultImplClassName, typePattern); mdtm.setFieldType(fieldType); mdtm.setSourceLocation(struct.enclosingType.getSourceLocation()); struct.ajAttributes.add(new AjAttribute.TypeMunger(mdtm)); } } // successfull so far, we thus need a bcel type munger to // have // a field hosting the mixin in the target type if (hasAtLeastOneMethod && defaultImplClassName != null) { ResolvedMember fieldHost = AjcMemberMaker.itdAtDeclareParentsField(null, fieldType, struct.enclosingType); struct.ajAttributes.add(new AjAttribute.TypeMunger(new MethodDelegateTypeMunger.FieldHostTypeMunger( fieldHost, struct.enclosingType, typePattern))); } return true; } else { reportError("@DeclareParents: can only be used on a field whose type is an interface", struct); return false; } } } return false; } /** * Return a nicely formatted method string, for example: int X.foo(java.lang.String) */ public static String getMethodForMessage(AjAttributeMethodStruct methodstructure) { StringBuffer sb = new StringBuffer(); sb.append("Method '"); sb.append(methodstructure.method.getReturnType().toString()); sb.append(" ").append(methodstructure.enclosingType).append(".").append(methodstructure.method.getName()); sb.append("("); Type[] args = methodstructure.method.getArgumentTypes(); if (args != null) { for (int t = 0; t < args.length; t++) { if (t > 0) { sb.append(","); } sb.append(args[t].toString()); } } sb.append(")'"); return sb.toString(); } /** * Process any @DeclareMixin annotation. * * Example Declaration <br> * * @DeclareMixin("Foo+") public I createImpl(Object o) { return new Impl(o); } * * <br> * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleDeclareMixinAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct) { AnnotationGen declareMixinAnnotation = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREMIXIN_ANNOTATION); if (declareMixinAnnotation == null) { // No annotation found return false; } Method annotatedMethod = struct.method; World world = struct.enclosingType.getWorld(); NameValuePair declareMixinPatternNameValuePair = getAnnotationElement(declareMixinAnnotation, VALUE); // declareMixinPattern could be of the form "Bar*" or "A || B" or "Foo+" String declareMixinPattern = declareMixinPatternNameValuePair.getValue().stringifyValue(); TypePattern targetTypePattern = parseTypePattern(declareMixinPattern, struct); // Return value of the annotated method is the interface or class that the mixin delegate should have ResolvedType methodReturnType = UnresolvedType.forSignature(annotatedMethod.getReturnType().getSignature()).resolve(world); if (methodReturnType.isPrimitiveType()) { reportError(getMethodForMessage(struct) + ": factory methods for a mixin cannot return void or a primitive type", struct); return false; } if (annotatedMethod.getArgumentTypes().length > 1) { reportError(getMethodForMessage(struct) + ": factory methods for a mixin can take a maximum of one parameter", struct); return false; } // The set of interfaces to be mixed in is either: // supplied as a list in the 'Class[] interfaces' value in the annotation value // supplied as just the interface return value of the annotated method // supplied as just the class return value of the annotated method NameValuePair interfaceListSpecified = getAnnotationElement(declareMixinAnnotation, "interfaces"); List<TypePattern> newParents = new ArrayList<TypePattern>(1); List<ResolvedType> newInterfaceTypes = new ArrayList<ResolvedType>(1); if (interfaceListSpecified != null) { ArrayElementValue arrayOfInterfaceTypes = (ArrayElementValue) interfaceListSpecified.getValue(); int numberOfTypes = arrayOfInterfaceTypes.getElementValuesArraySize(); ElementValue[] theTypes = arrayOfInterfaceTypes.getElementValuesArray(); for (int i = 0; i < numberOfTypes; i++) { ClassElementValue interfaceType = (ClassElementValue) theTypes[i]; // Check: needs to be resolvable // TODO crappy replace required ResolvedType ajInterfaceType = UnresolvedType.forSignature(interfaceType.getClassString().replace("/", ".")) .resolve(world); if (ajInterfaceType.isMissing() || !ajInterfaceType.isInterface()) { reportError( "Types listed in the 'interfaces' DeclareMixin annotation value must be valid interfaces. This is invalid: " + ajInterfaceType.getName(), struct); // TODO better error location, use the method position return false; } if (!ajInterfaceType.isAssignableFrom(methodReturnType)) { reportError(getMethodForMessage(struct) + ": factory method does not return something that implements '" + ajInterfaceType.getName() + "'", struct); return false; } newInterfaceTypes.add(ajInterfaceType); // Checking that it is a superinterface of the methods return value is done at weave time TypePattern newParent = parseTypePattern(ajInterfaceType.getName(), struct); newParents.add(newParent); } } else { if (methodReturnType.isClass()) { reportError( getMethodForMessage(struct) + ": factory methods for a mixin must either return an interface type or specify interfaces in the annotation and return a class", struct); return false; } // Use the method return type: this might be a class or an interface TypePattern newParent = parseTypePattern(methodReturnType.getName(), struct); newInterfaceTypes.add(methodReturnType); newParents.add(newParent); } if (newParents.size() == 0) { // Warning: did they foolishly put @DeclareMixin(value="Bar+",interfaces={}) // TODO output warning return false; } // Create the declare parents that will add the interfaces to matching targets FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings); // how do we mark this as a decp due to decmixin? DeclareParents dp = new DeclareParentsMixin(targetTypePattern, newParents); dp.resolve(binding); targetTypePattern = dp.getChild(); dp.setLocation(struct.context, -1, -1); // not ideal... struct.ajAttributes.add(new AjAttribute.DeclareAttribute(dp)); // The factory method for building the implementation is the // one attached to the annotation: Method implementationFactory = struct.method; boolean hasAtLeastOneMethod = false; for (Iterator iterator = newInterfaceTypes.iterator(); iterator.hasNext();) { ResolvedType typeForDelegation = (ResolvedType) iterator.next(); // TODO check for overlapping interfaces. Eg. A implements I, I extends J - if they specify interfaces={I,J} we dont // want to do any methods twice ResolvedMember[] methods = typeForDelegation.getMethodsWithoutIterator(true, false).toArray(new ResolvedMember[0]); for (int i = 0; i < methods.length; i++) { ResolvedMember method = methods[i]; if (method.isAbstract()) { hasAtLeastOneMethod = true; MethodDelegateTypeMunger mdtm = new MethodDelegateTypeMunger(method, struct.enclosingType, "", targetTypePattern, struct.method.getName(), struct.method.getSignature()); mdtm.setFieldType(methodReturnType); mdtm.setSourceLocation(struct.enclosingType.getSourceLocation()); struct.ajAttributes.add(new AjAttribute.TypeMunger(mdtm)); } } } // if any method delegate was created then a field to hold the delegate instance must also be added if (hasAtLeastOneMethod) { ResolvedMember fieldHost = AjcMemberMaker.itdAtDeclareParentsField(null, methodReturnType, struct.enclosingType); struct.ajAttributes.add(new AjAttribute.TypeMunger(new MethodDelegateTypeMunger.FieldHostTypeMunger(fieldHost, struct.enclosingType, targetTypePattern))); } return true; } /** * Read @Before * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleBeforeAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct, ResolvedPointcutDefinition preResolvedPointcut) { AnnotationGen before = getAnnotation(runtimeAnnotations, AjcMemberMaker.BEFORE_ANNOTATION); if (before != null) { NameValuePair beforeAdvice = getAnnotationElement(before, VALUE); if (beforeAdvice != null) { // this/target/args binding String argumentNames = getArgNamesValue(before); if (argumentNames != null) { struct.unparsedArgumentNames = argumentNames; } FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; try { bindings = extractBindings(struct); } catch (UnreadableDebugInfoException unreadableDebugInfoException) { return false; } IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings); // joinpoint, staticJoinpoint binding int extraArgument = extractExtraArgument(struct.method); Pointcut pc = null; if (preResolvedPointcut != null) { pc = preResolvedPointcut.getPointcut(); // pc.resolve(binding); } else { pc = parsePointcut(beforeAdvice.getValue().stringifyValue(), struct, false); if (pc == null) { return false;// parse error } pc = pc.resolve(binding); } setIgnoreUnboundBindingNames(pc, bindings); ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(), struct.bMethod .getDeclarationOffset()); struct.ajAttributes.add(new AjAttribute.AdviceAttribute(AdviceKind.Before, pc, extraArgument, sl.getOffset(), sl .getOffset() + 1,// FIXME AVASM struct.context)); return true; } } return false; } /** * Read @After * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleAfterAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct, ResolvedPointcutDefinition preResolvedPointcut) { AnnotationGen after = getAnnotation(runtimeAnnotations, AjcMemberMaker.AFTER_ANNOTATION); if (after != null) { NameValuePair afterAdvice = getAnnotationElement(after, VALUE); if (afterAdvice != null) { // this/target/args binding FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; String argumentNames = getArgNamesValue(after); if (argumentNames != null) { struct.unparsedArgumentNames = argumentNames; } try { bindings = extractBindings(struct); } catch (UnreadableDebugInfoException unreadableDebugInfoException) { return false; } IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings); // joinpoint, staticJoinpoint binding int extraArgument = extractExtraArgument(struct.method); Pointcut pc = null; if (preResolvedPointcut != null) { pc = preResolvedPointcut.getPointcut(); } else { pc = parsePointcut(afterAdvice.getValue().stringifyValue(), struct, false); if (pc == null) { return false;// parse error } pc.resolve(binding); } setIgnoreUnboundBindingNames(pc, bindings); ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(), struct.bMethod .getDeclarationOffset()); struct.ajAttributes.add(new AjAttribute.AdviceAttribute(AdviceKind.After, pc, extraArgument, sl.getOffset(), sl .getOffset() + 1,// FIXME AVASM struct.context)); return true; } } return false; } /** * Read @AfterReturning * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleAfterReturningAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct, ResolvedPointcutDefinition preResolvedPointcut, BcelMethod owningMethod) throws ReturningFormalNotDeclaredInAdviceSignatureException { AnnotationGen after = getAnnotation(runtimeAnnotations, AjcMemberMaker.AFTERRETURNING_ANNOTATION); if (after != null) { NameValuePair annValue = getAnnotationElement(after, VALUE); NameValuePair annPointcut = getAnnotationElement(after, POINTCUT); NameValuePair annReturned = getAnnotationElement(after, RETURNING); // extract the pointcut and returned type/binding - do some checks String pointcut = null; String returned = null; if ((annValue != null && annPointcut != null) || (annValue == null && annPointcut == null)) { reportError("@AfterReturning: either 'value' or 'poincut' must be provided, not both", struct); return false; } if (annValue != null) { pointcut = annValue.getValue().stringifyValue(); } else { pointcut = annPointcut.getValue().stringifyValue(); } if (isNullOrEmpty(pointcut)) { reportError("@AfterReturning: either 'value' or 'poincut' must be provided, not both", struct); return false; } if (annReturned != null) { returned = annReturned.getValue().stringifyValue(); if (isNullOrEmpty(returned)) { returned = null; } else { // check that thrownFormal exists as the last parameter in // the advice String[] pNames = owningMethod.getParameterNames(); if (pNames == null || pNames.length == 0 || !Arrays.asList(pNames).contains(returned)) { throw new ReturningFormalNotDeclaredInAdviceSignatureException(returned); } } } String argumentNames = getArgNamesValue(after); if (argumentNames != null) { struct.unparsedArgumentNames = argumentNames; } // this/target/args binding // exclude the return binding from the pointcut binding since it is // an extraArg binding FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; try { bindings = (returned == null ? extractBindings(struct) : extractBindings(struct, returned)); } catch (UnreadableDebugInfoException unreadableDebugInfoException) { return false; } IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings); // joinpoint, staticJoinpoint binding int extraArgument = extractExtraArgument(struct.method); // return binding if (returned != null) { extraArgument |= Advice.ExtraArgument; } Pointcut pc = null; if (preResolvedPointcut != null) { pc = preResolvedPointcut.getPointcut(); } else { pc = parsePointcut(pointcut, struct, false); if (pc == null) { return false;// parse error } pc.resolve(binding); } setIgnoreUnboundBindingNames(pc, bindings); ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(), struct.bMethod .getDeclarationOffset()); struct.ajAttributes.add(new AjAttribute.AdviceAttribute(AdviceKind.AfterReturning, pc, extraArgument, sl.getOffset(), sl.getOffset() + 1,// FIXME AVASM struct.context)); return true; } return false; } /** * Read @AfterThrowing * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleAfterThrowingAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct, ResolvedPointcutDefinition preResolvedPointcut, BcelMethod owningMethod) throws ThrownFormalNotDeclaredInAdviceSignatureException { AnnotationGen after = getAnnotation(runtimeAnnotations, AjcMemberMaker.AFTERTHROWING_ANNOTATION); if (after != null) { NameValuePair annValue = getAnnotationElement(after, VALUE); NameValuePair annPointcut = getAnnotationElement(after, POINTCUT); NameValuePair annThrown = getAnnotationElement(after, THROWING); // extract the pointcut and throwned type/binding - do some checks String pointcut = null; String thrownFormal = null; if ((annValue != null && annPointcut != null) || (annValue == null && annPointcut == null)) { reportError("@AfterThrowing: either 'value' or 'poincut' must be provided, not both", struct); return false; } if (annValue != null) { pointcut = annValue.getValue().stringifyValue(); } else { pointcut = annPointcut.getValue().stringifyValue(); } if (isNullOrEmpty(pointcut)) { reportError("@AfterThrowing: either 'value' or 'poincut' must be provided, not both", struct); return false; } if (annThrown != null) { thrownFormal = annThrown.getValue().stringifyValue(); if (isNullOrEmpty(thrownFormal)) { thrownFormal = null; } else { // check that thrownFormal exists as the last parameter in // the advice String[] pNames = owningMethod.getParameterNames(); if (pNames == null || pNames.length == 0 || !Arrays.asList(pNames).contains(thrownFormal)) { throw new ThrownFormalNotDeclaredInAdviceSignatureException(thrownFormal); } } } String argumentNames = getArgNamesValue(after); if (argumentNames != null) { struct.unparsedArgumentNames = argumentNames; } // this/target/args binding // exclude the throwned binding from the pointcut binding since it // is an extraArg binding FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; try { bindings = (thrownFormal == null ? extractBindings(struct) : extractBindings(struct, thrownFormal)); } catch (UnreadableDebugInfoException unreadableDebugInfoException) { return false; } IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings); // joinpoint, staticJoinpoint binding int extraArgument = extractExtraArgument(struct.method); // return binding if (thrownFormal != null) { extraArgument |= Advice.ExtraArgument; } Pointcut pc = null; if (preResolvedPointcut != null) { pc = preResolvedPointcut.getPointcut(); } else { pc = parsePointcut(pointcut, struct, false); if (pc == null) { return false;// parse error } pc.resolve(binding); } setIgnoreUnboundBindingNames(pc, bindings); ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(), struct.bMethod .getDeclarationOffset()); struct.ajAttributes.add(new AjAttribute.AdviceAttribute(AdviceKind.AfterThrowing, pc, extraArgument, sl.getOffset(), sl .getOffset() + 1, struct.context)); return true; } return false; } /** * Read @Around * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleAroundAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct, ResolvedPointcutDefinition preResolvedPointcut) { AnnotationGen around = getAnnotation(runtimeAnnotations, AjcMemberMaker.AROUND_ANNOTATION); if (around != null) { NameValuePair aroundAdvice = getAnnotationElement(around, VALUE); if (aroundAdvice != null) { // this/target/args binding String argumentNames = getArgNamesValue(around); if (argumentNames != null) { struct.unparsedArgumentNames = argumentNames; } FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; try { bindings = extractBindings(struct); } catch (UnreadableDebugInfoException unreadableDebugInfoException) { return false; } IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings); // joinpoint, staticJoinpoint binding int extraArgument = extractExtraArgument(struct.method); Pointcut pc = null; if (preResolvedPointcut != null) { pc = preResolvedPointcut.getPointcut(); } else { pc = parsePointcut(aroundAdvice.getValue().stringifyValue(), struct, false); if (pc == null) { return false;// parse error } pc.resolve(binding); } setIgnoreUnboundBindingNames(pc, bindings); ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(), struct.bMethod .getDeclarationOffset()); struct.ajAttributes.add(new AjAttribute.AdviceAttribute(AdviceKind.Around, pc, extraArgument, sl.getOffset(), sl .getOffset() + 1,// FIXME AVASM struct.context)); return true; } } return false; } /** * Read @Pointcut and handle the resolving in a lazy way to deal with pointcut references * * @param runtimeAnnotations * @param struct * @return true if a pointcut was handled */ private static boolean handlePointcutAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct) { AnnotationGen pointcut = getAnnotation(runtimeAnnotations, AjcMemberMaker.POINTCUT_ANNOTATION); if (pointcut == null) { return false; } NameValuePair pointcutExpr = getAnnotationElement(pointcut, VALUE); // semantic check: the method must return void, or be // "public static boolean" for if() support if (!(Type.VOID.equals(struct.method.getReturnType()) || (Type.BOOLEAN.equals(struct.method.getReturnType()) && struct.method.isStatic() && struct.method.isPublic()))) { reportWarning("Found @Pointcut on a method not returning 'void' or not 'public static boolean'", struct); // no need to stop } // semantic check: the method must not throw anything if (struct.method.getExceptionTable() != null) { reportWarning("Found @Pointcut on a method throwing exception", struct); // no need to stop } String argumentNames = getArgNamesValue(pointcut); if (argumentNames != null) { struct.unparsedArgumentNames = argumentNames; } // this/target/args binding final IScope binding; try { if (struct.method.isAbstract()) { binding = null; } else { binding = new BindingScope(struct.enclosingType, struct.context, extractBindings(struct)); } } catch (UnreadableDebugInfoException e) { return false; } UnresolvedType[] argumentTypes = new UnresolvedType[struct.method.getArgumentTypes().length]; for (int i = 0; i < argumentTypes.length; i++) { argumentTypes[i] = UnresolvedType.forSignature(struct.method.getArgumentTypes()[i].getSignature()); } Pointcut pc = null; if (struct.method.isAbstract()) { if ((pointcutExpr != null && isNullOrEmpty(pointcutExpr.getValue().stringifyValue())) || pointcutExpr == null) { // abstract pointcut // leave pc = null } else { reportError("Found defined @Pointcut on an abstract method", struct); return false;// stop } } else { if (pointcutExpr == null || isNullOrEmpty(pointcutExpr.getValue().stringifyValue())) { // the matches nothing pointcut (125475/125480) - perhaps not as // cleanly supported as it could be. } else { // if (pointcutExpr != null) { // use a LazyResolvedPointcutDefinition so that the pointcut is // resolved lazily // since for it to be resolved, we will need other pointcuts to // be registered as well pc = parsePointcut(pointcutExpr.getValue().stringifyValue(), struct, true); if (pc == null) { return false;// parse error } pc.setLocation(struct.context, -1, -1);// FIXME AVASM !! bMethod // is null here.. // } else { // reportError("Found undefined @Pointcut on a non-abstract method", // struct); // return false; // } } } // do not resolve binding now but lazily struct.ajAttributes.add(new AjAttribute.PointcutDeclarationAttribute(new LazyResolvedPointcutDefinition( struct.enclosingType, struct.method.getModifiers(), struct.method.getName(), argumentTypes, UnresolvedType .forSignature(struct.method.getReturnType().getSignature()), pc,// can // be // null // for // abstract // pointcut binding // can be null for abstract pointcut ))); return true; } /** * Read @DeclareError, @DeclareWarning * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleDeclareErrorOrWarningAnnotation(AsmManager model, RuntimeAnnos runtimeAnnotations, AjAttributeFieldStruct struct) { AnnotationGen error = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREERROR_ANNOTATION); boolean hasError = false; if (error != null) { NameValuePair declareError = getAnnotationElement(error, VALUE); if (declareError != null) { if (!STRING_DESC.equals(struct.field.getSignature()) || struct.field.getConstantValue() == null) { reportError("@DeclareError used on a non String constant field", struct); return false; } Pointcut pc = parsePointcut(declareError.getValue().stringifyValue(), struct, false); if (pc == null) { hasError = false;// cannot parse pointcut } else { DeclareErrorOrWarning deow = new DeclareErrorOrWarning(true, pc, struct.field.getConstantValue().toString()); setDeclareErrorOrWarningLocation(model, deow, struct); struct.ajAttributes.add(new AjAttribute.DeclareAttribute(deow)); hasError = true; } } } AnnotationGen warning = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREWARNING_ANNOTATION); boolean hasWarning = false; if (warning != null) { NameValuePair declareWarning = getAnnotationElement(warning, VALUE); if (declareWarning != null) { if (!STRING_DESC.equals(struct.field.getSignature()) || struct.field.getConstantValue() == null) { reportError("@DeclareWarning used on a non String constant field", struct); return false; } Pointcut pc = parsePointcut(declareWarning.getValue().stringifyValue(), struct, false); if (pc == null) { hasWarning = false;// cannot parse pointcut } else { DeclareErrorOrWarning deow = new DeclareErrorOrWarning(false, pc, struct.field.getConstantValue().toString()); setDeclareErrorOrWarningLocation(model, deow, struct); struct.ajAttributes.add(new AjAttribute.DeclareAttribute(deow)); return hasWarning = true; } } } return hasError || hasWarning; } /** * Sets the location for the declare error / warning using the corresponding IProgramElement in the structure model. This will * only fix bug 120356 if compiled with -emacssym, however, it does mean that the cross references view in AJDT will show the * correct information. * * Other possibilities for fix: 1. using the information in ajcDeclareSoft (if this is set correctly) which will fix the problem * if compiled with ajc but not if compiled with javac. 2. creating an AjAttribute called FieldDeclarationLineNumberAttribute * (much like MethodDeclarationLineNumberAttribute) which we can ask for the offset. This will again only fix bug 120356 when * compiled with ajc. * * @param deow * @param struct */ private static void setDeclareErrorOrWarningLocation(AsmManager model, DeclareErrorOrWarning deow, AjAttributeFieldStruct struct) { IHierarchy top = (model == null ? null : model.getHierarchy()); if (top != null && top.getRoot() != null) { IProgramElement ipe = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.FIELD, struct.field.getName()); if (ipe != null && ipe.getSourceLocation() != null) { ISourceLocation sourceLocation = ipe.getSourceLocation(); int start = sourceLocation.getOffset(); int end = start + struct.field.getName().length(); deow.setLocation(struct.context, start, end); return; } } deow.setLocation(struct.context, -1, -1); } /** * Returns a readable representation of a method. Method.toString() is not suitable. * * @param method * @return a readable representation of a method */ private static String methodToString(Method method) { StringBuffer sb = new StringBuffer(); sb.append(method.getName()); sb.append(method.getSignature()); return sb.toString(); } /** * Build the bindings for a given method (pointcut / advice) * * @param struct * @return null if no debug info is available */ private static FormalBinding[] extractBindings(AjAttributeMethodStruct struct) throws UnreadableDebugInfoException { Method method = struct.method; String[] argumentNames = struct.getArgumentNames(); // assert debug info was here if (argumentNames.length != method.getArgumentTypes().length) { reportError( "Cannot read debug info for @Aspect to handle formal binding in pointcuts (please compile with 'javac -g' or '<javac debug='true'.../>' in Ant)", struct); throw new UnreadableDebugInfoException(); } List<FormalBinding> bindings = new ArrayList<FormalBinding>(); for (int i = 0; i < argumentNames.length; i++) { String argumentName = argumentNames[i]; UnresolvedType argumentType = UnresolvedType.forSignature(method.getArgumentTypes()[i].getSignature()); // do not bind JoinPoint / StaticJoinPoint / // EnclosingStaticJoinPoint // TODO solve me : this means that the JP/SJP/ESJP cannot appear as // binding // f.e. when applying advice on advice etc if ((AjcMemberMaker.TYPEX_JOINPOINT.equals(argumentType) || AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.equals(argumentType) || AjcMemberMaker.TYPEX_STATICJOINPOINT.equals(argumentType) || AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.equals(argumentType) || AjcMemberMaker.AROUND_CLOSURE_TYPE .equals(argumentType))) { // continue;// skip bindings.add(new FormalBinding.ImplicitFormalBinding(argumentType, argumentName, i)); } else { bindings.add(new FormalBinding(argumentType, argumentName, i)); } } return bindings.toArray(new FormalBinding[] {}); } // FIXME alex deal with exclude index private static FormalBinding[] extractBindings(AjAttributeMethodStruct struct, String excludeFormal) throws UnreadableDebugInfoException { FormalBinding[] bindings = extractBindings(struct); // int excludeIndex = -1; for (int i = 0; i < bindings.length; i++) { FormalBinding binding = bindings[i]; if (binding.getName().equals(excludeFormal)) { // excludeIndex = i; bindings[i] = new FormalBinding.ImplicitFormalBinding(binding.getType(), binding.getName(), binding.getIndex()); break; } } return bindings; // // if (excludeIndex >= 0) { // FormalBinding[] bindingsFiltered = new // FormalBinding[bindings.length-1]; // int k = 0; // for (int i = 0; i < bindings.length; i++) { // if (i == excludeIndex) { // ; // } else { // bindingsFiltered[k] = new FormalBinding(bindings[i].getType(), // bindings[i].getName(), k); // k++; // } // } // return bindingsFiltered; // } else { // return bindings; // } } /** * Compute the flag for the xxxJoinPoint extra argument * * @param method * @return extra arg flag */ private static int extractExtraArgument(Method method) { Type[] methodArgs = method.getArgumentTypes(); String[] sigs = new String[methodArgs.length]; for (int i = 0; i < methodArgs.length; i++) { sigs[i] = methodArgs[i].getSignature(); } return extractExtraArgument(sigs); } /** * Compute the flag for the xxxJoinPoint extra argument * * @param argumentSignatures * @return extra arg flag */ public static int extractExtraArgument(String[] argumentSignatures) { int extraArgument = 0; for (int i = 0; i < argumentSignatures.length; i++) { if (AjcMemberMaker.TYPEX_JOINPOINT.getSignature().equals(argumentSignatures[i])) { extraArgument |= Advice.ThisJoinPoint; } else if (AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.getSignature().equals(argumentSignatures[i])) { extraArgument |= Advice.ThisJoinPoint; } else if (AjcMemberMaker.TYPEX_STATICJOINPOINT.getSignature().equals(argumentSignatures[i])) { extraArgument |= Advice.ThisJoinPointStaticPart; } else if (AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.getSignature().equals(argumentSignatures[i])) { extraArgument |= Advice.ThisEnclosingJoinPointStaticPart; } } return extraArgument; } /** * Returns the runtime (RV/RIV) annotation of type annotationType or null if no such annotation * * @param rvs * @param annotationType * @return annotation */ private static AnnotationGen getAnnotation(RuntimeAnnos rvs, UnresolvedType annotationType) { final String annotationTypeName = annotationType.getName(); for (Iterator iterator = rvs.getAnnotations().iterator(); iterator.hasNext();) { AnnotationGen rv = (AnnotationGen) iterator.next(); if (annotationTypeName.equals(rv.getTypeName())) { return rv; } } return null; } /** * Returns the value of a given element of an annotation or null if not found Caution: Does not handles default value. * * @param annotation * @param elementName * @return annotation NVP */ private static NameValuePair getAnnotationElement(AnnotationGen annotation, String elementName) { for (Iterator iterator1 = annotation.getValues().iterator(); iterator1.hasNext();) { NameValuePair element = (NameValuePair) iterator1.next(); if (elementName.equals(element.getNameString())) { return element; } } return null; } /** * Return the argNames set for an annotation or null if it is not specified. */ private static String getArgNamesValue(AnnotationGen anno) { List<NameValuePair> elements = anno.getValues(); for (NameValuePair element : elements) { if (ARGNAMES.equals(element.getNameString())) { return element.getValue().stringifyValue(); } } return null; } private static String lastbit(String fqname) { int i = fqname.lastIndexOf("."); if (i == -1) { return fqname; } else { return fqname.substring(i + 1); } } /** * Extract the method argument names. First we try the debug info attached to the method (the LocalVariableTable) - if we cannot * find that we look to use the argNames value that may have been supplied on the associated annotation. If that fails we just * don't know and return an empty string. * * @param method * @param argNamesFromAnnotation * @param methodStruct * @return method argument names */ private static String[] getMethodArgumentNames(Method method, String argNamesFromAnnotation, AjAttributeMethodStruct methodStruct) { if (method.getArgumentTypes().length == 0) { return EMPTY_STRINGS; } final int startAtStackIndex = method.isStatic() ? 0 : 1; final List<MethodArgument> arguments = new ArrayList<MethodArgument>(); LocalVariableTable lt = method.getLocalVariableTable(); if (lt != null) { for (int j = 0; j < lt.getLocalVariableTable().length; j++) { LocalVariable localVariable = lt.getLocalVariableTable()[j]; if (localVariable.getStartPC() == 0) { if (localVariable.getIndex() >= startAtStackIndex) { arguments.add(new MethodArgument(localVariable.getName(), localVariable.getIndex())); } } } } else { // No debug info, do we have an annotation value we can rely on? if (argNamesFromAnnotation != null) { StringTokenizer st = new StringTokenizer(argNamesFromAnnotation, " ,"); List<String> args = new ArrayList<String>(); while (st.hasMoreTokens()) { args.add(st.nextToken()); } if (args.size() != method.getArgumentTypes().length) { StringBuffer shortString = new StringBuffer().append(lastbit(method.getReturnType().toString())).append(" ") .append(method.getName()); if (method.getArgumentTypes().length > 0) { shortString.append("("); for (int i = 0; i < method.getArgumentTypes().length; i++) { shortString.append(lastbit(method.getArgumentTypes()[i].toString())); if ((i + 1) < method.getArgumentTypes().length) { shortString.append(","); } } shortString.append(")"); } reportError("argNames annotation value does not specify the right number of argument names for the method '" + shortString.toString() + "'", methodStruct); return EMPTY_STRINGS; } return args.toArray(new String[] {}); } } if (arguments.size() != method.getArgumentTypes().length) { return EMPTY_STRINGS; } // sort by index Collections.sort(arguments, new Comparator() { public int compare(Object o, Object o1) { MethodArgument mo = (MethodArgument) o; MethodArgument mo1 = (MethodArgument) o1; if (mo.indexOnStack == mo1.indexOnStack) { return 0; } else if (mo.indexOnStack > mo1.indexOnStack) { return 1; } else { return -1; } } }); String[] argumentNames = new String[arguments.size()]; int i = 0; for (MethodArgument methodArgument : arguments) { argumentNames[i++] = methodArgument.name; } return argumentNames; } /** * A method argument, used for sorting by indexOnStack (ie order in signature) * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ private static class MethodArgument { String name; int indexOnStack; public MethodArgument(String name, int indexOnStack) { this.name = name; this.indexOnStack = indexOnStack; } } /** * LazyResolvedPointcutDefinition lazyly resolve the pointcut so that we have time to register all pointcut referenced before * pointcut resolution happens * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public static class LazyResolvedPointcutDefinition extends ResolvedPointcutDefinition { private final Pointcut m_pointcutUnresolved; // null for abstract // pointcut private final IScope m_binding; private Pointcut m_lazyPointcut = null; public LazyResolvedPointcutDefinition(UnresolvedType declaringType, int modifiers, String name, UnresolvedType[] parameterTypes, UnresolvedType returnType, Pointcut pointcut, IScope binding) { super(declaringType, modifiers, name, parameterTypes, returnType, null); m_pointcutUnresolved = pointcut; m_binding = binding; } @Override public Pointcut getPointcut() { if (m_lazyPointcut == null && m_pointcutUnresolved == null) { m_lazyPointcut = Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } if (m_lazyPointcut == null && m_pointcutUnresolved != null) { m_lazyPointcut = m_pointcutUnresolved.resolve(m_binding); m_lazyPointcut.copyLocationFrom(m_pointcutUnresolved); } return m_lazyPointcut; } } /** * Helper to test empty strings * * @param s * @return true if empty or null */ private static boolean isNullOrEmpty(String s) { return (s == null || s.length() <= 0); } /** * Set the pointcut bindings for which to ignore unbound issues, so that we can implicitly bind xxxJoinPoint for @AJ advices * * @param pointcut * @param bindings */ private static void setIgnoreUnboundBindingNames(Pointcut pointcut, FormalBinding[] bindings) { // register ImplicitBindings as to be ignored since unbound // TODO is it likely to fail in a bad way if f.e. this(jp) etc ? List ignores = new ArrayList(); for (int i = 0; i < bindings.length; i++) { FormalBinding formalBinding = bindings[i]; if (formalBinding instanceof FormalBinding.ImplicitFormalBinding) { ignores.add(formalBinding.getName()); } } pointcut.m_ignoreUnboundBindingForNames = (String[]) ignores.toArray(new String[ignores.size()]); } /** * A check exception when we cannot read debug info (needed for formal binding) */ private static class UnreadableDebugInfoException extends Exception { } /** * Report an error * * @param message * @param location */ private static void reportError(String message, AjAttributeStruct location) { if (!location.handler.isIgnoring(IMessage.ERROR)) { location.handler.handleMessage(new Message(message, location.enclosingType.getSourceLocation(), true)); } } // private static void reportError(String message, IMessageHandler handler, ISourceLocation sourceLocation) { // if (!handler.isIgnoring(IMessage.ERROR)) { // handler.handleMessage(new Message(message, sourceLocation, true)); // } // } /** * Report a warning * * @param message * @param location */ private static void reportWarning(String message, AjAttributeStruct location) { if (!location.handler.isIgnoring(IMessage.WARNING)) { location.handler.handleMessage(new Message(message, location.enclosingType.getSourceLocation(), false)); } } /** * Parse the given pointcut, return null on failure and issue an error * * @param pointcutString * @param struct * @param allowIf * @return pointcut, unresolved */ private static Pointcut parsePointcut(String pointcutString, AjAttributeStruct struct, boolean allowIf) { try { PatternParser parser = new PatternParser(pointcutString, struct.context); Pointcut pointcut = parser.parsePointcut(); parser.checkEof(); pointcut.check(null, struct.enclosingType.getWorld()); if (!allowIf && pointcutString.indexOf("if()") >= 0 && hasIf(pointcut)) { reportError("if() pointcut is not allowed at this pointcut location '" + pointcutString + "'", struct); return null; } pointcut.setLocation(struct.context, -1, -1);// FIXME -1,-1 is not // good enough return pointcut; } catch (ParserException e) { reportError("Invalid pointcut '" + pointcutString + "': " + e.toString() + (e.getLocation() == null ? "" : " at position " + e.getLocation().getStart()), struct); return null; } } private static boolean hasIf(Pointcut pointcut) { IfFinder visitor = new IfFinder(); pointcut.accept(visitor, null); return visitor.hasIf; } /** * Parse the given type pattern, return null on failure and issue an error * * @param patternString * @param location * @return type pattern */ private static TypePattern parseTypePattern(String patternString, AjAttributeStruct location) { try { TypePattern typePattern = new PatternParser(patternString).parseTypePattern(); typePattern.setLocation(location.context, -1, -1);// FIXME -1,-1 is // not good // enough return typePattern; } catch (ParserException e) { reportError("Invalid type pattern'" + patternString + "' : " + e.getLocation(), location); return null; } } static class ThrownFormalNotDeclaredInAdviceSignatureException extends Exception { private final String formalName; public ThrownFormalNotDeclaredInAdviceSignatureException(String formalName) { this.formalName = formalName; } public String getFormalName() { return formalName; } } static class ReturningFormalNotDeclaredInAdviceSignatureException extends Exception { private final String formalName; public ReturningFormalNotDeclaredInAdviceSignatureException(String formalName) { this.formalName = formalName; } public String getFormalName() { return formalName; } } }
293,351
Bug 293351 RuntimeException weaving roo app with advice based on execution pointcut
java.lang.RuntimeException at org.aspectj.weaver.ResolvedType.getAnnotations(ResolvedType.java:718) at org.aspectj.weaver.AbstractAnnotationAJ.retrieveAnnotationOnAnnotation(AbstractAnnotationAJ.java:123) at org.aspectj.weaver.AbstractAnnotationAJ.ensureAtTargetInitialized(AbstractAnnotationAJ.java:85) at org.aspectj.weaver.AbstractAnnotationAJ.specifiesTarget(AbstractAnnotationAJ.java:115) at org.aspectj.weaver.bcel.BcelWeaver.verifyTa ... .eclipse.core.internal.jobs.Worker.run(Worker.java:55) Compile error: RuntimeException thrown: ResolvedType.getAnnotations() should never be called
resolved fixed
a23c7e4
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-10-27T14:04:12Z"
"2009-10-26T18:00:00Z"
org.aspectj.matcher/src/org/aspectj/weaver/MissingResolvedTypeWithKnownSignature.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.util.Collections; import java.util.List; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.context.CompilationAndWeavingContext; /** * When we try to resolve a type in the world that we require to be present, and then fail to find it, we return an instance of this * class. This class defers the production of the "can't find type error" until the first time that someone asks a question that * can't be answered solely from the signature. This enables the weaver to be more tolerant of missing types. * */ public class MissingResolvedTypeWithKnownSignature extends ResolvedType { private static ResolvedMember[] NO_MEMBERS = new ResolvedMember[0]; private static ResolvedType[] NO_TYPES = new ResolvedType[0]; private boolean issuedCantFindTypeError = false; private boolean issuedJoinPointWarning = false; private boolean issuedMissingInterfaceWarning = false; /** * @param signature * @param world */ public MissingResolvedTypeWithKnownSignature(String signature, World world) { super(signature, world); } public boolean isMissing() { return true; } /** * @param signature * @param signatureErasure * @param world */ public MissingResolvedTypeWithKnownSignature(String signature, String signatureErasure, World world) { super(signature, signatureErasure, world); } /* * (non-Javadoc) * * @see org.aspectj.weaver.ResolvedType#getDeclaredFields() */ public ResolvedMember[] getDeclaredFields() { raiseCantFindType(WeaverMessages.CANT_FIND_TYPE_FIELDS); return NO_MEMBERS; } /* * (non-Javadoc) * * @see org.aspectj.weaver.ResolvedType#getDeclaredMethods() */ public ResolvedMember[] getDeclaredMethods() { raiseCantFindType(WeaverMessages.CANT_FIND_TYPE_METHODS); return NO_MEMBERS; } /* * (non-Javadoc) * * @see org.aspectj.weaver.ResolvedType#getDeclaredInterfaces() */ public ResolvedType[] getDeclaredInterfaces() { raiseCantFindType(WeaverMessages.CANT_FIND_TYPE_INTERFACES); return NO_TYPES; } /* * (non-Javadoc) * * @see org.aspectj.weaver.ResolvedType#getDeclaredPointcuts() */ public ResolvedMember[] getDeclaredPointcuts() { raiseCantFindType(WeaverMessages.CANT_FIND_TYPE_POINTCUTS); return NO_MEMBERS; } /* * (non-Javadoc) * * @see org.aspectj.weaver.ResolvedType#getSuperclass() */ public ResolvedType getSuperclass() { raiseCantFindType(WeaverMessages.CANT_FIND_TYPE_SUPERCLASS); return ResolvedType.MISSING; } /* * (non-Javadoc) * * @see org.aspectj.weaver.ResolvedType#getModifiers() */ public int getModifiers() { raiseCantFindType(WeaverMessages.CANT_FIND_TYPE_MODIFIERS); return 0; } /* * (non-Javadoc) * * @see org.aspectj.weaver.ResolvedType#getSourceContext() */ public ISourceContext getSourceContext() { return new ISourceContext() { public ISourceLocation makeSourceLocation(IHasPosition position) { return null; } public ISourceLocation makeSourceLocation(int line, int offset) { return null; } public int getOffset() { return 0; } public void tidy() { } }; } /* * (non-Javadoc) * * @see org.aspectj.weaver.ResolvedType#isAssignableFrom(org.aspectj.weaver.ResolvedType) */ public boolean isAssignableFrom(ResolvedType other) { raiseCantFindType(WeaverMessages.CANT_FIND_TYPE_ASSIGNABLE, other.getName()); return false; } public boolean isAssignableFrom(ResolvedType other, boolean allowMissing) { if (allowMissing) return false; else return isAssignableFrom(other); } /* * (non-Javadoc) * * @see org.aspectj.weaver.ResolvedType#isCoerceableFrom(org.aspectj.weaver.ResolvedType) */ public boolean isCoerceableFrom(ResolvedType other) { raiseCantFindType(WeaverMessages.CANT_FIND_TYPE_COERCEABLE, other.getName()); return false; } /* * (non-Javadoc) * * @see org.aspectj.weaver.AnnotatedElement#hasAnnotation(org.aspectj.weaver.UnresolvedType) */ public boolean hasAnnotation(UnresolvedType ofType) { raiseCantFindType(WeaverMessages.CANT_FIND_TYPE_ANNOTATION); return false; } public List getInterTypeMungers() { return Collections.EMPTY_LIST; } public List getInterTypeMungersIncludingSupers() { return Collections.EMPTY_LIST; } public List getInterTypeParentMungers() { return Collections.EMPTY_LIST; } public List getInterTypeParentMungersIncludingSupers() { return Collections.EMPTY_LIST; } protected void collectInterTypeMungers(List collector) { return; } public void raiseWarningOnJoinPointSignature(String signature) { if (issuedJoinPointWarning) return; String message = WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_JOINPOINT, getName(), signature); message += "\n" + CompilationAndWeavingContext.getCurrentContext(); world.getLint().cantFindTypeAffectingJoinPointMatch.signal(message, null); // MessageUtil.warn(world.getMessageHandler(),message); issuedJoinPointWarning = true; } public void raiseWarningOnMissingInterfaceWhilstFindingMethods() { if (issuedMissingInterfaceWarning) return; String message = WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_INTERFACE_METHODS, getName(), signature); message += "\n" + CompilationAndWeavingContext.getCurrentContext(); world.getLint().cantFindTypeAffectingJoinPointMatch.signal(message, null); // MessageUtil.warn(world.getMessageHandler(),message); issuedMissingInterfaceWarning = true; } private void raiseCantFindType(String key) { if (issuedCantFindTypeError) return; String message = WeaverMessages.format(key, getName()); message += "\n" + CompilationAndWeavingContext.getCurrentContext(); world.getLint().cantFindType.signal(message, null); // MessageUtil.error(world.getMessageHandler(),message); issuedCantFindTypeError = true; } private void raiseCantFindType(String key, String insert) { if (issuedCantFindTypeError) return; String message = WeaverMessages.format(key, getName(), insert); message += "\n" + CompilationAndWeavingContext.getCurrentContext(); world.getLint().cantFindType.signal(message, null); // MessageUtil.error(world.getMessageHandler(),message); issuedCantFindTypeError = true; } }
293,457
Bug 293457 NPE on multiple declare @methods
null
resolved fixed
dc53b77
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-11-19T17:01:09Z"
"2009-10-27T16:13:20Z"
tests/bugs167/pr293457/org/springmodules/cache/annotations/Cacheable.java
293,457
Bug 293457 NPE on multiple declare @methods
null
resolved fixed
dc53b77
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-11-19T17:01:09Z"
"2009-10-27T16:13:20Z"
tests/src/org/aspectj/systemtest/ajc167/Ajc167Tests.java
/******************************************************************************* * Copyright (c) 2008 Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc167; import java.io.File; import junit.framework.Test; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc167Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testTimers_1() { runTest("timers - 1"); } // Test harness parse of -Xset:a=b,c=d will see c=d as a second option // public void testTimers_2() { // runTest("timers - 2"); // } public void testAnnoMatching_pr293203() { runTest("anno matching"); } public void testScalaOuterClassNames_pr288064() { runTest("outer class names - scala"); } public void testScalaOuterClassNames_pr288064_ltw() { runTest("outer class names - scala - ltw"); } // --- public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc167Tests.class); } @Override protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc167/ajc167.xml"); } }
293,457
Bug 293457 NPE on multiple declare @methods
null
resolved fixed
dc53b77
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-11-19T17:01:09Z"
"2009-10-27T16:13:20Z"
tests/src/org/aspectj/systemtest/ajc167/IntertypeTests.java
120,375
Bug 120375 Support Load-Time Weaving and HotSwap
null
resolved fixed
19355dd
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-11-19T18:33:01Z"
"2005-12-12T15:06:40Z"
loadtime5/java5-src/org/aspectj/weaver/loadtime/ClassPreProcessorAgentAdapter.java
/******************************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Alexandre Vasseur initial implementation *******************************************************************************/ package org.aspectj.weaver.loadtime; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; /** * Java 1.5 adapter for class pre processor * * @author <a href="mailto:alex@gnilux.com">Alexandre Vasseur</a> */ public class ClassPreProcessorAgentAdapter implements ClassFileTransformer { /** * Concrete preprocessor. */ private static ClassPreProcessor s_preProcessor; static { try { s_preProcessor = new Aj(); s_preProcessor.initialize(); } catch (Exception e) { throw new ExceptionInInitializerError("could not initialize JSR163 preprocessor due to: " + e.toString()); } } /** * Weaving delegation * * @param loader the defining class loader * @param className the name of class beeing loaded * @param classBeingRedefined when hotswap is called * @param protectionDomain * @param bytes the bytecode before weaving * @return the weaved bytecode */ public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] bytes) throws IllegalClassFormatException { if (classBeingRedefined == null) { return s_preProcessor.preProcess(className, bytes, loader); } else { // FIXME av for now we skip hotswap. We should think more about that new Exception("AspectJ5 does not weave hotswapped class (" + className + ")").printStackTrace(); return bytes; } } }
297,013
Bug 297013 Unclosed stream in AjAttribute
null
resolved fixed
28fb861
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2009-12-16T18:10:04Z"
"2009-12-06T09:00:00Z"
org.aspectj.matcher/src/org/aspectj/weaver/AjAttribute.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.Version; import org.aspectj.util.FileUtil; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.IScope; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.Pointcut; /** * These attributes are written to and read from .class files (see the JVM spec). * * <p> * Each member or type can have a number of AjAttributes. Each such attribute is in 1-1 correspondence with an Unknown bcel * attribute. Creating one of these does NOTHING to the underlying thing, so if you really want to add an attribute to a particular * thing, well, you'd better actually do that. * * @author Erik Hilsdale * @author Jim Hugunin */ public abstract class AjAttribute { public static final String AttributePrefix = "org.aspectj.weaver"; protected abstract void write(DataOutputStream s) throws IOException; public abstract String getNameString(); public char[] getNameChars() { return getNameString().toCharArray(); } /** * Just writes the contents */ public byte[] getBytes() { try { ByteArrayOutputStream b0 = new ByteArrayOutputStream(); DataOutputStream s0 = new DataOutputStream(b0); write(s0); return b0.toByteArray(); } catch (IOException e) { // shouldn't happen with ByteArrayOutputStreams throw new RuntimeException("sanity check"); } } /** * Writes the full attribute, i.e. name_index, length, and contents */ public byte[] getAllBytes(short nameIndex) { try { byte[] bytes = getBytes(); ByteArrayOutputStream b0 = new ByteArrayOutputStream(); DataOutputStream s0 = new DataOutputStream(b0); s0.writeShort(nameIndex); s0.writeInt(bytes.length); s0.write(bytes); return b0.toByteArray(); } catch (IOException e) { // shouldn't happen with ByteArrayOutputStreams throw new RuntimeException("sanity check"); } } public static AjAttribute read(AjAttribute.WeaverVersionInfo v, String name, byte[] bytes, ISourceContext context, World w) { try { if (bytes == null) { bytes = new byte[0]; } VersionedDataInputStream s = new VersionedDataInputStream(new ByteArrayInputStream(bytes)); s.setVersion(v); if (name.equals(Aspect.AttributeName)) { return new Aspect(PerClause.readPerClause(s, context)); } else if (name.equals(MethodDeclarationLineNumberAttribute.AttributeName)) { return MethodDeclarationLineNumberAttribute.read(s); } else if (name.equals(WeaverState.AttributeName)) { return new WeaverState(WeaverStateInfo.read(s, context)); } else if (name.equals(WeaverVersionInfo.AttributeName)) { return WeaverVersionInfo.read(s); } else if (name.equals(AdviceAttribute.AttributeName)) { AdviceAttribute aa = AdviceAttribute.read(s, context); aa.getPointcut().check(context, w); return aa; } else if (name.equals(PointcutDeclarationAttribute.AttributeName)) { PointcutDeclarationAttribute pda = new PointcutDeclarationAttribute(ResolvedPointcutDefinition.read(s, context)); pda.pointcutDef.getPointcut().check(context, w); return pda; } else if (name.equals(TypeMunger.AttributeName)) { return new TypeMunger(ResolvedTypeMunger.read(s, context)); } else if (name.equals(AjSynthetic.AttributeName)) { return new AjSynthetic(); } else if (name.equals(DeclareAttribute.AttributeName)) { return new DeclareAttribute(Declare.read(s, context)); } else if (name.equals(PrivilegedAttribute.AttributeName)) { return PrivilegedAttribute.read(s, context); } else if (name.equals(SourceContextAttribute.AttributeName)) { return SourceContextAttribute.read(s); } else if (name.equals(EffectiveSignatureAttribute.AttributeName)) { return EffectiveSignatureAttribute.read(s, context); } else { // We have to tell the user about this... if (w == null || w.getMessageHandler() == null) { throw new BCException("unknown attribute" + name); } w.getMessageHandler().handleMessage(MessageUtil.warn("unknown attribute encountered " + name)); return null; } } catch (BCException e) { throw new BCException("malformed " + name + " attribute (length:" + bytes.length + ")" + e); } catch (IOException e) { throw new BCException("malformed " + name + " attribute (length:" + bytes.length + ")" + e); } } // ---- /** * Synthetic members should have NO advice put on them or on their contents. This attribute is currently unused as we consider * all members starting with NameMangler.PREFIX to automatically be synthetic. As we use this we might find that we want * multiple kinds of synthetic. In particular, if we want to treat the call to a synthetic getter (say, of an introduced field) * as a field reference itself, then a method might want a particular kind of AjSynthetic attribute that also includes a * signature of what it stands for. */ public static class AjSynthetic extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.AjSynthetic"; @Override public String getNameString() { return AttributeName; } // private ResolvedTypeMunger munger; public AjSynthetic() { } @Override public void write(DataOutputStream s) throws IOException { } } public static class TypeMunger extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.TypeMunger"; @Override public String getNameString() { return AttributeName; } private final ResolvedTypeMunger munger; public TypeMunger(ResolvedTypeMunger munger) { this.munger = munger; } @Override public void write(DataOutputStream s) throws IOException { munger.write(s); } public ConcreteTypeMunger reify(World world, ResolvedType aspectType) { return world.getWeavingSupport().concreteTypeMunger(munger, aspectType); } } public static class WeaverState extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.WeaverState"; @Override public String getNameString() { return AttributeName; } private final WeaverStateInfo kind; public WeaverState(WeaverStateInfo kind) { this.kind = kind; } @Override public void write(DataOutputStream s) throws IOException { kind.write(s); } public WeaverStateInfo reify() { return kind; } } public static class WeaverVersionInfo extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.WeaverVersion"; // If you change the format of an AspectJ class file, you have two // options: // - changing the minor version means you have not added anything that // prevents // previous versions of the weaver from operating (e.g. // MethodDeclarationLineNumber attribute) // - changing the major version means you have added something that // prevents previous // versions of the weaver from operating correctly. // // The user will get a warning for any org.aspectj.weaver attributes the // weaver does // not recognize. // When we don't know ... (i.e. pre 1.2.1) public final static short WEAVER_VERSION_MAJOR_UNKNOWN = 0; public final static short WEAVER_VERSION_MINOR_UNKNOWN = 0; // These are the weaver major/minor numbers for AspectJ 1.2.1 public final static short WEAVER_VERSION_MAJOR_AJ121 = 1; public final static short WEAVER_VERSION_MINOR_AJ121 = 0; // These are the weaver major/minor numbers for AspectJ 1.5.0 public final static short WEAVER_VERSION_MAJOR_AJ150M4 = 3; public final static short WEAVER_VERSION_MAJOR_AJ150 = 2; public final static short WEAVER_VERSION_MINOR_AJ150 = 0; // These are the weaver major/minor numbers for AspectJ 1.6.0 public final static short WEAVER_VERSION_MAJOR_AJ160M2 = 5; public final static short WEAVER_VERSION_MAJOR_AJ160 = 4; public final static short WEAVER_VERSION_MINOR_AJ160 = 0; // These are the weaver major/minor numbers for AspectJ 1.6.1 public final static short WEAVER_VERSION_MAJOR_AJ161 = 6; // annotation // value // binding public final static short WEAVER_VERSION_MINOR_AJ161 = 0; // These are the weaver major/minor versions for *this* weaver private final static short CURRENT_VERSION_MAJOR = WEAVER_VERSION_MAJOR_AJ161; private final static short CURRENT_VERSION_MINOR = WEAVER_VERSION_MINOR_AJ161; public final static WeaverVersionInfo UNKNOWN = new WeaverVersionInfo(WEAVER_VERSION_MAJOR_UNKNOWN, WEAVER_VERSION_MINOR_UNKNOWN); public final static WeaverVersionInfo CURRENT = new WeaverVersionInfo(CURRENT_VERSION_MAJOR, CURRENT_VERSION_MINOR); // These are the versions read in from a particular class file. private final short major_version; private final short minor_version; private long buildstamp = Version.NOTIME; @Override public String getNameString() { return AttributeName; } // Default ctor uses the current version numbers public WeaverVersionInfo() { major_version = CURRENT_VERSION_MAJOR; minor_version = CURRENT_VERSION_MINOR; } public WeaverVersionInfo(short major, short minor) { major_version = major; minor_version = minor; } @Override public void write(DataOutputStream s) throws IOException { s.writeShort(CURRENT_VERSION_MAJOR); s.writeShort(CURRENT_VERSION_MINOR); s.writeLong(Version.getTime()); // build used to construct the // class... } public static WeaverVersionInfo read(VersionedDataInputStream s) throws IOException { short major = s.readShort(); short minor = s.readShort(); WeaverVersionInfo wvi = new WeaverVersionInfo(major, minor); if (s.getMajorVersion() >= WEAVER_VERSION_MAJOR_AJ150M4) { long stamp = 0; try { stamp = s.readLong(); wvi.setBuildstamp(stamp); } catch (EOFException eof) { // didnt find that build stamp - its not the end of the // world } } return wvi; } public short getMajorVersion() { return major_version; } public short getMinorVersion() { return minor_version; } public static short getCurrentWeaverMajorVersion() { return CURRENT_VERSION_MAJOR; } public static short getCurrentWeaverMinorVersion() { return CURRENT_VERSION_MINOR; } public void setBuildstamp(long stamp) { buildstamp = stamp; } public long getBuildstamp() { return buildstamp; } @Override public String toString() { return major_version + "." + minor_version; } public static String toCurrentVersionString() { return CURRENT_VERSION_MAJOR + "." + CURRENT_VERSION_MINOR; } } public static class SourceContextAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.SourceContext"; @Override public String getNameString() { return AttributeName; } private final String sourceFileName; private final int[] lineBreaks; public SourceContextAttribute(String sourceFileName, int[] lineBreaks) { this.sourceFileName = sourceFileName; this.lineBreaks = lineBreaks; } @Override public void write(DataOutputStream s) throws IOException { s.writeUTF(sourceFileName); FileUtil.writeIntArray(lineBreaks, s); } public static SourceContextAttribute read(VersionedDataInputStream s) throws IOException { return new SourceContextAttribute(s.readUTF(), FileUtil.readIntArray(s)); } public int[] getLineBreaks() { return lineBreaks; } public String getSourceFileName() { return sourceFileName; } } public static class MethodDeclarationLineNumberAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.MethodDeclarationLineNumber"; @Override public String getNameString() { return AttributeName; } private final int lineNumber; // AV: added in 1.5 M3 thus handling cases where we don't have that // information private final int offset; public MethodDeclarationLineNumberAttribute(int line, int offset) { lineNumber = line; this.offset = offset; } public int getLineNumber() { return lineNumber; } public int getOffset() { return offset; } @Override public void write(DataOutputStream s) throws IOException { s.writeInt(lineNumber); s.writeInt(offset); } public static MethodDeclarationLineNumberAttribute read(VersionedDataInputStream s) throws IOException { int line = s.readInt(); int offset = 0; if (s.available() > 0) { offset = s.readInt(); } return new MethodDeclarationLineNumberAttribute(line, offset); } @Override public String toString() { return AttributeName + ": " + lineNumber + ":" + offset; } } public static class PointcutDeclarationAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.PointcutDeclaration"; @Override public String getNameString() { return AttributeName; } private final ResolvedPointcutDefinition pointcutDef; public PointcutDeclarationAttribute(ResolvedPointcutDefinition pointcutDef) { this.pointcutDef = pointcutDef; } @Override public void write(DataOutputStream s) throws IOException { pointcutDef.write(s); } public ResolvedPointcutDefinition reify() { return pointcutDef; } } public static class DeclareAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.Declare"; @Override public String getNameString() { return AttributeName; } private final Declare declare; public DeclareAttribute(Declare declare) { this.declare = declare; } @Override public void write(DataOutputStream s) throws IOException { declare.write(s); } public Declare getDeclare() { return declare; } } public static class AdviceAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.Advice"; @Override public String getNameString() { return AttributeName; } private final AdviceKind kind; private final Pointcut pointcut; private final int extraParameterFlags; private final int start; private final int end; private final ISourceContext sourceContext; // these are only used by around advice private boolean proceedInInners; private ResolvedMember[] proceedCallSignatures; // size == # of proceed // calls in body private boolean[] formalsUnchangedToProceed; // size == formals.size private UnresolvedType[] declaredExceptions; /** * @param lexicalPosition must be greater than the lexicalPosition of any advice declared before this one in an aspect, * otherwise, it can be any value. */ public AdviceAttribute(AdviceKind kind, Pointcut pointcut, int extraArgumentFlags, int start, int end, ISourceContext sourceContext) { this.kind = kind; this.pointcut = pointcut; extraParameterFlags = extraArgumentFlags; this.start = start; this.end = end; this.sourceContext = sourceContext; // XXX put this back when testing works better (or fails better) // if (kind == AdviceKind.Around) throw new // IllegalArgumentException("not for around"); } public AdviceAttribute(AdviceKind kind, Pointcut pointcut, int extraArgumentFlags, int start, int end, ISourceContext sourceContext, boolean proceedInInners, ResolvedMember[] proceedCallSignatures, boolean[] formalsUnchangedToProceed, UnresolvedType[] declaredExceptions) { this.kind = kind; this.pointcut = pointcut; extraParameterFlags = extraArgumentFlags; this.start = start; this.end = end; this.sourceContext = sourceContext; if (kind != AdviceKind.Around) { throw new IllegalArgumentException("only for around"); } this.proceedInInners = proceedInInners; this.proceedCallSignatures = proceedCallSignatures; this.formalsUnchangedToProceed = formalsUnchangedToProceed; this.declaredExceptions = declaredExceptions; } public static AdviceAttribute read(VersionedDataInputStream s, ISourceContext context) throws IOException { AdviceKind kind = AdviceKind.read(s); if (kind == AdviceKind.Around) { return new AdviceAttribute(kind, Pointcut.read(s, context), s.readByte(), s.readInt(), s.readInt(), context, s .readBoolean(), ResolvedMemberImpl.readResolvedMemberArray(s, context), FileUtil.readBooleanArray(s), UnresolvedType.readArray(s)); } else { return new AdviceAttribute(kind, Pointcut.read(s, context), s.readByte(), s.readInt(), s.readInt(), context); } } @Override public void write(DataOutputStream s) throws IOException { kind.write(s); pointcut.write(s); s.writeByte(extraParameterFlags); s.writeInt(start); s.writeInt(end); if (kind == AdviceKind.Around) { s.writeBoolean(proceedInInners); ResolvedMemberImpl.writeArray(proceedCallSignatures, s); FileUtil.writeBooleanArray(formalsUnchangedToProceed, s); UnresolvedType.writeArray(declaredExceptions, s); } } public Advice reify(Member signature, World world, ResolvedType concreteAspect) { return world.getWeavingSupport().createAdviceMunger(this, pointcut, signature, concreteAspect); } @Override public String toString() { return "AdviceAttribute(" + kind + ", " + pointcut + ", " + extraParameterFlags + ", " + start + ")"; } public int getExtraParameterFlags() { return extraParameterFlags; } public AdviceKind getKind() { return kind; } public Pointcut getPointcut() { return pointcut; } public UnresolvedType[] getDeclaredExceptions() { return declaredExceptions; } public boolean[] getFormalsUnchangedToProceed() { return formalsUnchangedToProceed; } public ResolvedMember[] getProceedCallSignatures() { return proceedCallSignatures; } public boolean isProceedInInners() { return proceedInInners; } public int getEnd() { return end; } public ISourceContext getSourceContext() { return sourceContext; } public int getStart() { return start; } } public static class Aspect extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.Aspect"; @Override public String getNameString() { return AttributeName; } private final PerClause perClause; private IScope resolutionScope; public Aspect(PerClause perClause) { this.perClause = perClause; } public PerClause reify(ResolvedType inAspect) { // XXXperClause.concretize(inAspect); return perClause; } public PerClause reifyFromAtAspectJ(ResolvedType inAspect) { perClause.resolve(resolutionScope); return perClause; } @Override public void write(DataOutputStream s) throws IOException { perClause.write(s); } public void setResolutionScope(IScope binding) { resolutionScope = binding; } } public static class PrivilegedAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.Privileged"; @Override public String getNameString() { return AttributeName; } private final ResolvedMember[] accessedMembers; public PrivilegedAttribute(ResolvedMember[] accessedMembers) { this.accessedMembers = accessedMembers; } @Override public void write(DataOutputStream s) throws IOException { ResolvedMemberImpl.writeArray(accessedMembers, s); } public ResolvedMember[] getAccessedMembers() { return accessedMembers; } public static PrivilegedAttribute read(VersionedDataInputStream s, ISourceContext context) throws IOException { return new PrivilegedAttribute(ResolvedMemberImpl.readResolvedMemberArray(s, context)); } } public static class EffectiveSignatureAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.EffectiveSignature"; @Override public String getNameString() { return AttributeName; } private final ResolvedMember effectiveSignature; private final Shadow.Kind shadowKind; private final boolean weaveBody; public EffectiveSignatureAttribute(ResolvedMember effectiveSignature, Shadow.Kind shadowKind, boolean weaveBody) { this.effectiveSignature = effectiveSignature; this.shadowKind = shadowKind; this.weaveBody = weaveBody; } @Override public void write(DataOutputStream s) throws IOException { effectiveSignature.write(s); shadowKind.write(s); s.writeBoolean(weaveBody); } public static EffectiveSignatureAttribute read(VersionedDataInputStream s, ISourceContext context) throws IOException { return new EffectiveSignatureAttribute(ResolvedMemberImpl.readResolvedMember(s, context), Shadow.Kind.read(s), s .readBoolean()); } public ResolvedMember getEffectiveSignature() { return effectiveSignature; } @Override public String toString() { return "EffectiveSignatureAttribute(" + effectiveSignature + ", " + shadowKind + ")"; } public Shadow.Kind getShadowKind() { return shadowKind; } public boolean isWeaveBody() { return weaveBody; } } }
298,786
Bug 298786 suspected problem with handling of multiple aop.xml files
null
resolved fixed
a968890
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-01-05T00:44:36Z"
"2010-01-04T18:33:20Z"
loadtime/src/org/aspectj/weaver/loadtime/ClassLoaderWeavingAdaptor.java
/******************************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Alexandre Vasseur initial implementation * David Knibb weaving context enhancments *******************************************************************************/ package org.aspectj.weaver.loadtime; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.Constants; import org.aspectj.util.LangUtil; import org.aspectj.weaver.Lint; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.Lint.Kind; import org.aspectj.weaver.bcel.BcelWeakClassLoaderReference; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.Utility; import org.aspectj.weaver.loadtime.definition.Definition; import org.aspectj.weaver.loadtime.definition.DocumentParser; import org.aspectj.weaver.ltw.LTWWorld; import org.aspectj.weaver.patterns.PatternParser; import org.aspectj.weaver.patterns.TypePattern; import org.aspectj.weaver.tools.GeneratedClassHandler; import org.aspectj.weaver.tools.Trace; import org.aspectj.weaver.tools.TraceFactory; import org.aspectj.weaver.tools.WeavingAdaptor; /** * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public class ClassLoaderWeavingAdaptor extends WeavingAdaptor { private final static String AOP_XML = Constants.AOP_USER_XML + ";" + Constants.AOP_AJC_XML + ";" + Constants.AOP_OSGI_XML; private boolean initialized; private List m_dumpTypePattern = new ArrayList(); private boolean m_dumpBefore = false; private boolean dumpDirPerClassloader = false; private boolean hasExcludes = false; private List<TypePattern> excludeTypePattern = new ArrayList<TypePattern>(); // anything private List<String> excludeStartsWith = new ArrayList<String>(); // com.foo..* private List<String> excludeStarDotDotStar = new ArrayList<String>(); // *..*CGLIB* private List<String> excludeExactName = new ArrayList<String>(); // com.foo.Bar private List<String> excludeEndsWith = new ArrayList<String>(); // com.foo.Bar private List<String[]> excludeSpecial = new ArrayList<String[]>(); private boolean hasIncludes = false; private List<TypePattern> includeTypePattern = new ArrayList<TypePattern>(); private List<String> m_includeStartsWith = new ArrayList<String>(); private List<String> includeExactName = new ArrayList<String>(); private boolean includeStar = false; private List m_aspectExcludeTypePattern = new ArrayList(); private List m_aspectExcludeStartsWith = new ArrayList(); private List m_aspectIncludeTypePattern = new ArrayList(); private List m_aspectIncludeStartsWith = new ArrayList(); private StringBuffer namespace; private IWeavingContext weavingContext; private List concreteAspects = new ArrayList(); private static Trace trace = TraceFactory.getTraceFactory().getTrace(ClassLoaderWeavingAdaptor.class); public ClassLoaderWeavingAdaptor() { super(); if (trace.isTraceEnabled()) { trace.enter("<init>", this); } if (trace.isTraceEnabled()) { trace.exit("<init>"); } } /** * We don't need a reference to the class loader and using it during construction can cause problems with recursion. It also * makes sense to supply the weaving context during initialization to. * * @deprecated */ public ClassLoaderWeavingAdaptor(final ClassLoader deprecatedLoader, final IWeavingContext deprecatedContext) { super(); if (trace.isTraceEnabled()) { trace.enter("<init>", this, new Object[] { deprecatedLoader, deprecatedContext }); } if (trace.isTraceEnabled()) { trace.exit("<init>"); } } class SimpleGeneratedClassHandler implements GeneratedClassHandler { private BcelWeakClassLoaderReference loaderRef; SimpleGeneratedClassHandler(ClassLoader loader) { loaderRef = new BcelWeakClassLoaderReference(loader); } /** * Callback when we need to define a Closure in the JVM * */ public void acceptClass(String name, byte[] bytes) { try { if (shouldDump(name.replace('/', '.'), false)) { dump(name, bytes, false); } } catch (Throwable throwable) { throwable.printStackTrace(); } defineClass(loaderRef.getClassLoader(), name, bytes); // could be done lazily using the hook } } public void initialize(final ClassLoader classLoader, IWeavingContext context) { if (initialized) { return; } boolean success = true; this.weavingContext = context; if (weavingContext == null) { weavingContext = new DefaultWeavingContext(classLoader); } createMessageHandler(); this.generatedClassHandler = new SimpleGeneratedClassHandler(classLoader); List definitions = weavingContext.getDefinitions(classLoader, this); if (definitions.isEmpty()) { disable(); // TODO maw Needed to ensure messages are flushed if (trace.isTraceEnabled()) { trace.exit("initialize", definitions); } return; } // TODO when the world works in terms of the context, we can remove the loader bcelWorld = new LTWWorld(classLoader, weavingContext, getMessageHandler(), null); weaver = new BcelWeaver(bcelWorld); // register the definitions success = registerDefinitions(weaver, classLoader, definitions); if (success) { // after adding aspects weaver.prepareForWeave(); enable(); // TODO maw Needed to ensure messages are flushed success = weaveAndDefineConceteAspects(); } if (success) { enable(); } else { disable(); bcelWorld = null; weaver = null; } initialized = true; if (trace.isTraceEnabled()) { trace.exit("initialize", isEnabled()); } } /** * Load and cache the aop.xml/properties according to the classloader visibility rules * * @param weaver * @param loader */ List parseDefinitions(final ClassLoader loader) { if (trace.isTraceEnabled()) { trace.enter("parseDefinitions", this); } List definitions = new ArrayList(); try { info("register classloader " + getClassLoaderName(loader)); // TODO av underoptimized: we will parse each XML once per CL that see it // TODO av dev mode needed ? TBD -Daj5.def=... if (loader.equals(ClassLoader.getSystemClassLoader())) { String file = System.getProperty("aj5.def", null); if (file != null) { info("using (-Daj5.def) " + file); definitions.add(DocumentParser.parse((new File(file)).toURL())); } } String resourcePath = System.getProperty("org.aspectj.weaver.loadtime.configuration", AOP_XML); if (trace.isTraceEnabled()) { trace.event("parseDefinitions", this, resourcePath); } StringTokenizer st = new StringTokenizer(resourcePath, ";"); while (st.hasMoreTokens()) { String nextDefinition = st.nextToken(); if (nextDefinition.startsWith("file:")) { try { String fpath = new URL(nextDefinition).getFile(); File configFile = new File(fpath); if (!configFile.exists()) { warn("configuration does not exist: " + nextDefinition); } else { definitions.add(DocumentParser.parse(configFile.toURL())); } } catch (MalformedURLException mue) { error("malformed definition url: " + nextDefinition); } } else { Enumeration xmls = weavingContext.getResources(nextDefinition); // System.out.println("? registerDefinitions: found-aop.xml=" + xmls.hasMoreElements() + ", loader=" + loader); Set seenBefore = new HashSet(); while (xmls.hasMoreElements()) { URL xml = (URL) xmls.nextElement(); if (trace.isTraceEnabled()) { trace.event("parseDefinitions", this, xml); } if (!seenBefore.contains(xml)) { info("using configuration " + weavingContext.getFile(xml)); definitions.add(DocumentParser.parse(xml)); seenBefore.add(xml); } else { warn("ignoring duplicate definition: " + xml); } } } } if (definitions.isEmpty()) { info("no configuration found. Disabling weaver for class loader " + getClassLoaderName(loader)); } } catch (Exception e) { definitions.clear(); warn("parse definitions failed", e); } if (trace.isTraceEnabled()) { trace.exit("parseDefinitions", definitions); } return definitions; } private boolean registerDefinitions(final BcelWeaver weaver, final ClassLoader loader, List definitions) { if (trace.isTraceEnabled()) { trace.enter("registerDefinitions", this, definitions); } boolean success = true; try { registerOptions(weaver, loader, definitions); registerAspectExclude(weaver, loader, definitions); registerAspectInclude(weaver, loader, definitions); success = registerAspects(weaver, loader, definitions); registerIncludeExclude(weaver, loader, definitions); registerDump(weaver, loader, definitions); } catch (Exception ex) { trace.error("register definition failed", ex); success = false; warn("register definition failed", (ex instanceof AbortException) ? null : ex); } if (trace.isTraceEnabled()) { trace.exit("registerDefinitions", success); } return success; } private String getClassLoaderName(ClassLoader loader) { return weavingContext.getClassLoaderName(); } /** * Configure the weaver according to the option directives TODO av - don't know if it is that good to reuse, since we only allow * a small subset of options in LTW * * @param weaver * @param loader * @param definitions */ private void registerOptions(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { StringBuffer allOptions = new StringBuffer(); for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); allOptions.append(definition.getWeaverOptions()).append(' '); } Options.WeaverOption weaverOption = Options.parse(allOptions.toString(), loader, getMessageHandler()); // configure the weaver and world // AV - code duplicates AspectJBuilder.initWorldAndWeaver() World world = weaver.getWorld(); setMessageHandler(weaverOption.messageHandler); world.setXlazyTjp(weaverOption.lazyTjp); world.setXHasMemberSupportEnabled(weaverOption.hasMember); world.setTiming(weaverOption.timers, true); world.setOptionalJoinpoints(weaverOption.optionalJoinpoints); world.setPinpointMode(weaverOption.pinpoint); weaver.setReweavableMode(weaverOption.notReWeavable); world.performExtraConfiguration(weaverOption.xSet); world.setXnoInline(weaverOption.noInline); // AMC - autodetect as per line below, needed for AtAjLTWTests.testLTWUnweavable world.setBehaveInJava5Way(LangUtil.is15VMOrGreater()); world.setAddSerialVerUID(weaverOption.addSerialVersionUID); /* First load defaults */ bcelWorld.getLint().loadDefaultProperties(); /* Second overlay LTW defaults */ bcelWorld.getLint().adviceDidNotMatch.setKind(null); /* Third load user file using -Xlintfile so that -Xlint wins */ if (weaverOption.lintFile != null) { InputStream resource = null; try { resource = loader.getResourceAsStream(weaverOption.lintFile); Exception failure = null; if (resource != null) { try { Properties properties = new Properties(); properties.load(resource); world.getLint().setFromProperties(properties); } catch (IOException e) { failure = e; } } if (failure != null || resource == null) { warn("Cannot access resource for -Xlintfile:" + weaverOption.lintFile, failure); // world.getMessageHandler().handleMessage(new Message( // "Cannot access resource for -Xlintfile:"+weaverOption.lintFile, // IMessage.WARNING, // failure, // null)); } } finally { try { resource.close(); } catch (Throwable t) { } } } /* Fourth override with -Xlint */ if (weaverOption.lint != null) { if (weaverOption.lint.equals("default")) {// FIXME should be AjBuildConfig.AJLINT_DEFAULT but yetanother deps.. bcelWorld.getLint().loadDefaultProperties(); } else { bcelWorld.getLint().setAll(weaverOption.lint); if (weaverOption.lint.equals("ignore")) { bcelWorld.setAllLintIgnored(); } } } // TODO proceedOnError option } private void registerAspectExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { String fastMatchInfo = null; for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); for (Iterator iterator1 = definition.getAspectExcludePatterns().iterator(); iterator1.hasNext();) { String exclude = (String) iterator1.next(); TypePattern excludePattern = new PatternParser(exclude).parseTypePattern(); m_aspectExcludeTypePattern.add(excludePattern); fastMatchInfo = looksLikeStartsWith(exclude); if (fastMatchInfo != null) { m_aspectExcludeStartsWith.add(fastMatchInfo); } } } } private void registerAspectInclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { String fastMatchInfo = null; for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); for (Iterator iterator1 = definition.getAspectIncludePatterns().iterator(); iterator1.hasNext();) { String include = (String) iterator1.next(); TypePattern includePattern = new PatternParser(include).parseTypePattern(); m_aspectIncludeTypePattern.add(includePattern); fastMatchInfo = looksLikeStartsWith(include); if (fastMatchInfo != null) { m_aspectIncludeStartsWith.add(fastMatchInfo); } } } } protected void lint(String name, String[] infos) { Lint lint = bcelWorld.getLint(); Kind kind = lint.getLintKind(name); kind.signal(infos, null, null); } @Override public String getContextId() { return weavingContext.getId(); } /** * Register the aspect, following include / exclude rules * * @param weaver * @param loader * @param definitions */ private boolean registerAspects(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { if (trace.isTraceEnabled()) { trace.enter("registerAspects", this, new Object[] { weaver, loader, definitions }); } boolean success = true; // TODO: the exclude aspect allow to exclude aspect defined upper in the CL hierarchy - is it what we want ?? // if not, review the getResource so that we track which resource is defined by which CL // iterate aspectClassNames // exclude if in any of the exclude list for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); for (Iterator aspects = definition.getAspectClassNames().iterator(); aspects.hasNext();) { String aspectClassName = (String) aspects.next(); if (acceptAspect(aspectClassName)) { info("register aspect " + aspectClassName); // System.err.println("? ClassLoaderWeavingAdaptor.registerAspects() aspectName=" + aspectClassName + // ", loader=" + loader + ", bundle=" + weavingContext.getClassLoaderName()); /* ResolvedType aspect = */weaver.addLibraryAspect(aspectClassName); // generate key for SC if (namespace == null) { namespace = new StringBuffer(aspectClassName); } else { namespace = namespace.append(";" + aspectClassName); } } else { // warn("aspect excluded: " + aspectClassName); lint("aspectExcludedByConfiguration", new String[] { aspectClassName, getClassLoaderName(loader) }); } } } // iterate concreteAspects // exclude if in any of the exclude list - note that the user defined name matters for that to happen for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); for (Definition.ConcreteAspect concreteAspect : definition.getConcreteAspects()) { if (acceptAspect(concreteAspect.name)) { info("define aspect " + concreteAspect.name); ConcreteAspectCodeGen gen = new ConcreteAspectCodeGen(concreteAspect, weaver.getWorld()); if (!gen.validate()) { error("Concrete-aspect '" + concreteAspect.name + "' could not be registered"); success = false; break; } ((BcelWorld) weaver.getWorld()).addSourceObjectType(Utility.makeJavaClass(concreteAspect.name, gen.getBytes()), true); concreteAspects.add(gen); weaver.addLibraryAspect(concreteAspect.name); // generate key for SC if (namespace == null) { namespace = new StringBuffer(concreteAspect.name); } else { namespace = namespace.append(";" + concreteAspect.name); } } } } /* We couldn't register one or more aspects so disable the adaptor */ if (!success) { warn("failure(s) registering aspects. Disabling weaver for class loader " + getClassLoaderName(loader)); } /* We didn't register any aspects so disable the adaptor */ else if (namespace == null) { success = false; info("no aspects registered. Disabling weaver for class loader " + getClassLoaderName(loader)); } if (trace.isTraceEnabled()) { trace.exit("registerAspects", success); } return success; } private boolean weaveAndDefineConceteAspects() { if (trace.isTraceEnabled()) { trace.enter("weaveAndDefineConceteAspects", this, concreteAspects); } boolean success = true; for (Iterator iterator = concreteAspects.iterator(); iterator.hasNext();) { ConcreteAspectCodeGen gen = (ConcreteAspectCodeGen) iterator.next(); String name = gen.getClassName(); byte[] bytes = gen.getBytes(); try { byte[] newBytes = weaveClass(name, bytes, true); this.generatedClassHandler.acceptClass(name, newBytes); } catch (IOException ex) { trace.error("weaveAndDefineConceteAspects", ex); error("exception weaving aspect '" + name + "'", ex); } } if (trace.isTraceEnabled()) { trace.exit("weaveAndDefineConceteAspects", success); } return success; } /** * Register the include / exclude filters. We duplicate simple patterns in startWith filters that will allow faster matching * without ResolvedType * * @param weaver * @param loader * @param definitions */ private void registerIncludeExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { String fastMatchInfo = null; for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); for (Iterator iterator1 = definition.getIncludePatterns().iterator(); iterator1.hasNext();) { hasIncludes = true; String include = (String) iterator1.next(); fastMatchInfo = looksLikeStartsWith(include); if (fastMatchInfo != null) { m_includeStartsWith.add(fastMatchInfo); } else if (include.equals("*")) { includeStar = true; } else if ((fastMatchInfo = looksLikeExactName(include)) != null) { includeExactName.add(fastMatchInfo); } else { TypePattern includePattern = new PatternParser(include).parseTypePattern(); includeTypePattern.add(includePattern); } } for (Iterator iterator1 = definition.getExcludePatterns().iterator(); iterator1.hasNext();) { hasExcludes = true; String exclude = (String) iterator1.next(); fastMatchInfo = looksLikeStartsWith(exclude); if (fastMatchInfo != null) { excludeStartsWith.add(fastMatchInfo); } else if ((fastMatchInfo = looksLikeStarDotDotStarExclude(exclude)) != null) { excludeStarDotDotStar.add(fastMatchInfo); } else if ((fastMatchInfo = looksLikeExactName(exclude)) != null) { excludeExactName.add(exclude); } else if ((fastMatchInfo = looksLikeEndsWith(exclude)) != null) { excludeEndsWith.add(fastMatchInfo); } else if (exclude .equals("org.codehaus.groovy..* && !org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController*")) { // TODO need a more sophisticated analysis here, to allow for similar situations excludeSpecial.add(new String[] { "org.codehaus.groovy.", "org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController" }); // for the related test: // } else if (exclude.equals("testdata..* && !testdata.sub.Oran*")) { // excludeSpecial.add(new String[] { "testdata.", "testdata.sub.Oran" }); } else { TypePattern excludePattern = new PatternParser(exclude).parseTypePattern(); excludeTypePattern.add(excludePattern); } } } } /** * Checks if the pattern looks like "*..*XXXX*" and if so returns XXXX. This will enable fast name matching of CGLIB exclusion * */ private String looksLikeStarDotDotStarExclude(String typePattern) { if (!typePattern.startsWith("*..*")) { return null; } if (!typePattern.endsWith("*")) { return null; } String subPattern = typePattern.substring(4, typePattern.length() - 1); if (hasStarDot(subPattern, 0)) { return null; } return subPattern.replace('$', '.'); } /** * Checks if the pattern looks like "com.foo.Bar" - an exact name */ private String looksLikeExactName(String typePattern) { if (hasSpaceAnnotationPlus(typePattern, 0) || typePattern.indexOf("*") != -1) { return null; } return typePattern.replace('$', '.'); } /** * Checks if the pattern looks like "*Exception" */ private String looksLikeEndsWith(String typePattern) { if (typePattern.charAt(0) != '*') { return null; } if (hasSpaceAnnotationPlus(typePattern, 1) || hasStarDot(typePattern, 1)) { return null; } return typePattern.substring(1).replace('$', '.'); } /** * Determine if something in the string is going to affect our ability to optimize. Checks for: ' ' '@' '+' */ private boolean hasSpaceAnnotationPlus(String string, int pos) { for (int i = pos, max = string.length(); i < max; i++) { char ch = string.charAt(i); if (ch == ' ' || ch == '@' || ch == '+') { return true; } } return false; } /** * Determine if something in the string is going to affect our ability to optimize. Checks for: '*' '.' */ private boolean hasStarDot(String string, int pos) { for (int i = pos, max = string.length(); i < max; i++) { char ch = string.charAt(i); if (ch == '*' || ch == '.') { return true; } } return false; } /** * Checks if the type pattern looks like "com.foo..*" */ private String looksLikeStartsWith(String typePattern) { if (hasSpaceAnnotationPlus(typePattern, 0) || typePattern.charAt(typePattern.length() - 1) != '*') { return null; } // now must looks like with "charsss..*" or "cha.rss..*" etc // note that "*" and "*..*" won't be fast matched // and that "charsss.*" will not neither int length = typePattern.length(); if (typePattern.endsWith("..*") && length > 3) { if (typePattern.indexOf("..") == length - 3 // no ".." before last sequence && typePattern.indexOf('*') == length - 1) { // no earlier '*' return typePattern.substring(0, length - 2).replace('$', '.'); // "charsss." or "char.rss." etc } } return null; } /** * Register the dump filter * * @param weaver * @param loader * @param definitions */ private void registerDump(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); for (Iterator iterator1 = definition.getDumpPatterns().iterator(); iterator1.hasNext();) { String dump = (String) iterator1.next(); TypePattern pattern = new PatternParser(dump).parseTypePattern(); m_dumpTypePattern.add(pattern); } if (definition.shouldDumpBefore()) { m_dumpBefore = true; } if (definition.createDumpDirPerClassloader()) { dumpDirPerClassloader = true; } } } /** * Determine whether a type should be accepted for weaving, by checking it against any includes/excludes. * * @param className the name of the type to possibly accept * @param bytes the bytecode for the type (in case we need to look inside, eg. annotations) * @return true if it should be accepted for weaving */ @Override protected boolean accept(String className, byte[] bytes) { if (!hasExcludes && !hasIncludes) { return true; } // still try to avoid ResolvedType if we have simple patterns String fastClassName = className.replace('/', '.').replace('$', '.'); for (String excludeStartsWithString : excludeStartsWith) { if (fastClassName.startsWith(excludeStartsWithString)) { return false; } } // Fast exclusion of patterns like: "*..*CGLIB*" if (!excludeStarDotDotStar.isEmpty()) { for (String namePiece : excludeStarDotDotStar) { int index = fastClassName.lastIndexOf('.'); if (fastClassName.indexOf(namePiece, index + 1) != -1) { return false; } } } if (!excludeEndsWith.isEmpty()) { for (String lastPiece : excludeEndsWith) { if (fastClassName.endsWith(lastPiece)) { return false; } } } // Fast exclusion of exact names if (!excludeExactName.isEmpty()) { for (String name : excludeExactName) { if (fastClassName.equals(name)) { return false; } } } if (!excludeSpecial.isEmpty()) { for (String[] entry : excludeSpecial) { String excludeThese = entry[0]; String exceptThese = entry[1]; if (fastClassName.startsWith(excludeThese) && !fastClassName.startsWith(exceptThese)) { return false; } } } /* * Bug 120363 If we have an exclude pattern that cannot be matched using "starts with" then we cannot fast accept */ boolean didSomeIncludeMatching = false; if (excludeTypePattern.isEmpty()) { if (includeStar) { return true; } if (!includeExactName.isEmpty()) { didSomeIncludeMatching = true; for (String exactname : includeExactName) { if (fastClassName.equals(exactname)) { return true; } } } boolean fastAccept = false;// defaults to false if no fast include for (int i = 0; i < m_includeStartsWith.size(); i++) { didSomeIncludeMatching = true; fastAccept = fastClassName.startsWith(m_includeStartsWith.get(i)); if (fastAccept) { return true; } } // We may have processed all patterns now... check that and return if (includeTypePattern.isEmpty()) { return !didSomeIncludeMatching; } } boolean accept; try { ensureDelegateInitialized(className, bytes); ResolvedType classInfo = delegateForCurrentClass.getResolvedTypeX(); // exclude are "AND"ed for (TypePattern typePattern : excludeTypePattern) { if (typePattern.matchesStatically(classInfo)) { // exclude match - skip return false; } } // include are "OR"ed accept = !didSomeIncludeMatching; // only true if no includes at all for (TypePattern typePattern : includeTypePattern) { accept = typePattern.matchesStatically(classInfo); if (accept) { break; } // goes on if this include did not match ("OR"ed) } } finally { this.bcelWorld.demote(); } return accept; } // FIXME we don't use include/exclude of others aop.xml // this can be nice but very dangerous as well to change that private boolean acceptAspect(String aspectClassName) { // avoid ResolvedType if not needed if (m_aspectExcludeTypePattern.isEmpty() && m_aspectIncludeTypePattern.isEmpty()) { return true; } // still try to avoid ResolvedType if we have simple patterns // EXCLUDE: if one match then reject String fastClassName = aspectClassName.replace('/', '.').replace('.', '$'); for (int i = 0; i < m_aspectExcludeStartsWith.size(); i++) { if (fastClassName.startsWith((String) m_aspectExcludeStartsWith.get(i))) { return false; } } // INCLUDE: if one match then accept for (int i = 0; i < m_aspectIncludeStartsWith.size(); i++) { if (fastClassName.startsWith((String) m_aspectIncludeStartsWith.get(i))) { return true; } } // needs further analysis ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(aspectClassName), true); // exclude are "AND"ed for (Iterator iterator = m_aspectExcludeTypePattern.iterator(); iterator.hasNext();) { TypePattern typePattern = (TypePattern) iterator.next(); if (typePattern.matchesStatically(classInfo)) { // exclude match - skip return false; } } // include are "OR"ed boolean accept = true;// defaults to true if no include for (Iterator iterator = m_aspectIncludeTypePattern.iterator(); iterator.hasNext();) { TypePattern typePattern = (TypePattern) iterator.next(); accept = typePattern.matchesStatically(classInfo); if (accept) { break; } // goes on if this include did not match ("OR"ed) } return accept; } @Override protected boolean shouldDump(String className, boolean before) { // Don't dump before weaving unless asked to if (before && !m_dumpBefore) { return false; } // avoid ResolvedType if not needed if (m_dumpTypePattern.isEmpty()) { return false; } // TODO AV - optimize for className.startWith only ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(className), true); // dump for (Iterator iterator = m_dumpTypePattern.iterator(); iterator.hasNext();) { TypePattern typePattern = (TypePattern) iterator.next(); if (typePattern.matchesStatically(classInfo)) { // dump match return true; } } return false; } @Override protected String getDumpDir() { if (dumpDirPerClassloader) { StringBuffer dir = new StringBuffer(); dir.append("_ajdump").append(File.separator).append(weavingContext.getId()); return dir.toString(); } else { return super.getDumpDir(); } } /* * shared classes methods */ /** * @return Returns the key. */ public String getNamespace() { // System.out.println("ClassLoaderWeavingAdaptor.getNamespace() classloader=" + weavingContext.getClassLoaderName() + // ", namespace=" + namespace); if (namespace == null) { return ""; } else { return new String(namespace); } } /** * Check to see if any classes are stored in the generated classes cache. Then flush the cache if it is not empty * * @param className TODO * @return true if a class has been generated and is stored in the cache */ public boolean generatedClassesExistFor(String className) { // System.err.println("? ClassLoaderWeavingAdaptor.generatedClassesExist() classname=" + className + ", size=" + // generatedClasses); if (className == null) { return !generatedClasses.isEmpty(); } else { return generatedClasses.containsKey(className); } } /** * Flush the generated classes cache */ public void flushGeneratedClasses() { // System.err.println("? ClassLoaderWeavingAdaptor.flushGeneratedClasses() generatedClasses=" + generatedClasses); generatedClasses = new HashMap(); } private void defineClass(ClassLoader loader, String name, byte[] bytes) { if (trace.isTraceEnabled()) { trace.enter("defineClass", this, new Object[] { loader, name, bytes }); } Object clazz = null; debug("generating class '" + name + "'"); try { // TODO av protection domain, and optimize Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", new Class[] { String.class, bytes.getClass(), int.class, int.class }); defineClass.setAccessible(true); clazz = defineClass.invoke(loader, new Object[] { name, bytes, new Integer(0), new Integer(bytes.length) }); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof LinkageError) { warn("define generated class failed", e.getTargetException()); // is already defined (happens for X$ajcMightHaveAspect interfaces since aspects are reweaved) // TODO maw I don't think this is OK and } else { warn("define generated class failed", e.getTargetException()); } } catch (Exception e) { warn("define generated class failed", e); } if (trace.isTraceEnabled()) { trace.exit("defineClass", clazz); } } }
305,788
Bug 305788 Exception was thrown when I saved a file in Eclipse
Build Identifier: SpringSource STS 2.3.1 java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793) at java.util.HashMap$KeyIterator.next(HashMap.java:828) at org.aspectj.asm.internal.AspectJElementHierarchy.updateHandleMap(AspectJElementHierarchy.java:594) at org.aspectj.asm.AsmManager.removeStructureModelForFiles(AsmManager.java:564) at org.aspectj.asm.AsmManager.processDelta(AsmManager.java:639) at org.aspectj.ajdt.internal.core ... un(AutoBuildJob.java:238) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) Compile error: ConcurrentModificationException thrown: null Reproducible: Always Steps to Reproduce: 1.Generate an abstract class using Spring roo 2. Edit that file within Eclipse/STS to add JPA annotations 3.Click on the save icon to save the file - Exceptions box pops up
resolved fixed
749078d
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-03-23T14:26:02Z"
"2010-03-14T01:26:40Z"
asm/src/org/aspectj/asm/internal/AspectJElementHierarchy.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Mik Kersten initial implementation * Andy Clement Extensions for better IDE representation * ******************************************************************/ package org.aspectj.asm.internal; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; /** * @author Mik Kersten */ public class AspectJElementHierarchy implements IHierarchy { private static final long serialVersionUID = 6462734311117048620L; private transient AsmManager asm; protected IProgramElement root = null; protected String configFile = null; private Map fileMap = null; private Map handleMap = new HashMap(); private Map typeMap = null; public AspectJElementHierarchy(AsmManager asm) { this.asm = asm; } public IProgramElement getElement(String handle) { return findElementForHandleOrCreate(handle, false); } public void setAsmManager(AsmManager asm) { // used when deserializing this.asm = asm; } public IProgramElement getRoot() { return root; } public void setRoot(IProgramElement root) { this.root = root; handleMap = new HashMap(); typeMap = new HashMap(); } public void addToFileMap(Object key, Object value) { fileMap.put(key, value); } public boolean removeFromFileMap(Object key) { if (fileMap.containsKey(key)) { return (fileMap.remove(key) != null); } return true; } public void setFileMap(HashMap fileMap) { this.fileMap = fileMap; } public Object findInFileMap(Object key) { return fileMap.get(key); } public Set getFileMapEntrySet() { return fileMap.entrySet(); } public boolean isValid() { return root != null && fileMap != null; } /** * Returns the first match * * @param parent * @param kind not null * @return null if not found */ public IProgramElement findElementForSignature(IProgramElement parent, IProgramElement.Kind kind, String signature) { for (Iterator it = parent.getChildren().iterator(); it.hasNext();) { IProgramElement node = (IProgramElement) it.next(); if (node.getKind() == kind && signature.equals(node.toSignatureString())) { return node; } else { IProgramElement childSearch = findElementForSignature(node, kind, signature); if (childSearch != null) return childSearch; } } return null; } public IProgramElement findElementForLabel(IProgramElement parent, IProgramElement.Kind kind, String label) { for (Iterator it = parent.getChildren().iterator(); it.hasNext();) { IProgramElement node = (IProgramElement) it.next(); if (node.getKind() == kind && label.equals(node.toLabelString())) { return node; } else { IProgramElement childSearch = findElementForLabel(node, kind, label); if (childSearch != null) return childSearch; } } return null; } /** * Find the entry in the model that represents a particular type. * * @param packageName the package in which the type is declared or null for the default package * @param typeName the name of the type * @return the IProgramElement representing the type, or null if not found */ public IProgramElement findElementForType(String packageName, String typeName) { // Build a cache key and check the cache StringBuffer keyb = (packageName == null) ? new StringBuffer() : new StringBuffer(packageName); keyb.append(".").append(typeName); String key = keyb.toString(); IProgramElement cachedValue = (IProgramElement) typeMap.get(key); if (cachedValue != null) { return cachedValue; } List packageNodes = findMatchingPackages(packageName); for (Iterator iterator = packageNodes.iterator(); iterator.hasNext();) { IProgramElement pkg = (IProgramElement) iterator.next(); // this searches each file for a class for (Iterator it = pkg.getChildren().iterator(); it.hasNext();) { IProgramElement fileNode = (IProgramElement) it.next(); IProgramElement cNode = findClassInNodes(fileNode.getChildren(), typeName, typeName); if (cNode != null) { typeMap.put(key, cNode); return cNode; } } } return null; // IProgramElement packageNode = null; // if (packageName == null) { // packageNode = root; // } else { // if (root == null) // return null; // List kids = root.getChildren(); // if (kids == null) { // return null; // } // for (Iterator it = kids.iterator(); it.hasNext() && packageNode == null;) { // IProgramElement node = (IProgramElement) it.next(); // if (packageName.equals(node.getName())) { // packageNode = node; // } // } // if (packageNode == null) { // return null; // } // } // // this searches each file for a class // for (Iterator it = packageNode.getChildren().iterator(); it.hasNext();) { // IProgramElement fileNode = (IProgramElement) it.next(); // IProgramElement cNode = findClassInNodes(fileNode.getChildren(), typeName, typeName); // if (cNode != null) { // typeMap.put(key, cNode); // return cNode; // } // } // return null; } /** * Look for any package nodes matching the specified package name. There may be multiple in the case where the types within a * package are split across source folders. * * @param packagename the packagename being searched for * @return a list of package nodes that match that name */ public List/* IProgramElement */findMatchingPackages(String packagename) { List children = root.getChildren(); // The children might be source folders or packages if (children.size() == 0) { return Collections.EMPTY_LIST; } if (((IProgramElement) children.get(0)).getKind() == IProgramElement.Kind.SOURCE_FOLDER) { String searchPackageName = (packagename == null ? "" : packagename); // default package means match on "" // dealing with source folders List matchingPackageNodes = new ArrayList(); for (Iterator iterator = children.iterator(); iterator.hasNext();) { IProgramElement sourceFolder = (IProgramElement) iterator.next(); List possiblePackageNodes = sourceFolder.getChildren(); for (Iterator iterator2 = possiblePackageNodes.iterator(); iterator2.hasNext();) { IProgramElement possiblePackageNode = (IProgramElement) iterator2.next(); if (possiblePackageNode.getKind() == IProgramElement.Kind.PACKAGE) { if (possiblePackageNode.getName().equals(searchPackageName)) { matchingPackageNodes.add(possiblePackageNode); } } } } // 'binaries' will be checked automatically by the code above as it is represented as a SOURCE_FOLDER return matchingPackageNodes; } else { // dealing directly with packages below the root, no source folders. Therefore at most one // thing to return in the list if (packagename == null) { // default package List result = new ArrayList(); result.add(root); return result; } List result = new ArrayList(); for (Iterator iterator = children.iterator(); iterator.hasNext();) { IProgramElement possiblePackage = (IProgramElement) iterator.next(); if (possiblePackage.getKind() == IProgramElement.Kind.PACKAGE && possiblePackage.getName().equals(packagename)) { result.add(possiblePackage); } if (possiblePackage.getKind() == IProgramElement.Kind.SOURCE_FOLDER) { // might be 'binaries' if (possiblePackage.getName().equals("binaries")) { for (Iterator iter2 = possiblePackage.getChildren().iterator(); iter2.hasNext();) { IProgramElement possiblePackage2 = (IProgramElement) iter2.next(); if (possiblePackage2.getKind() == IProgramElement.Kind.PACKAGE && possiblePackage2.getName().equals(packagename)) { result.add(possiblePackage2); break; // ok to break here, can't be another entry under binaries } } } } } if (result.isEmpty()) { return Collections.EMPTY_LIST; } else { return result; } } } private IProgramElement findClassInNodes(Collection nodes, String name, String typeName) { String baseName; String innerName; int dollar = name.indexOf('$'); if (dollar == -1) { baseName = name; innerName = null; } else { baseName = name.substring(0, dollar); innerName = name.substring(dollar + 1); } for (Iterator j = nodes.iterator(); j.hasNext();) { IProgramElement classNode = (IProgramElement) j.next(); if (baseName.equals(classNode.getName())) { if (innerName == null) return classNode; else return findClassInNodes(classNode.getChildren(), innerName, typeName); } else if (name.equals(classNode.getName())) { return classNode; } else if (typeName.equals(classNode.getBytecodeSignature())) { return classNode; } else if (classNode.getChildren() != null && !classNode.getChildren().isEmpty()) { IProgramElement node = findClassInNodes(classNode.getChildren(), name, typeName); if (node != null) { return node; } } } return null; } /** * @param sourceFilePath modified to '/' delimited path for consistency * @return a new structure node for the file if it was not found in the model */ public IProgramElement findElementForSourceFile(String sourceFile) { try { if (!isValid() || sourceFile == null) { return IHierarchy.NO_STRUCTURE; } else { String correctedPath = asm.getCanonicalFilePath(new File(sourceFile)); // StructureNode node = (StructureNode)getFileMap().get(correctedPath);//findFileNode(filePath, model); IProgramElement node = (IProgramElement) findInFileMap(correctedPath);// findFileNode(filePath, model); if (node != null) { return node; } else { return createFileStructureNode(correctedPath); } } } catch (Exception e) { return IHierarchy.NO_STRUCTURE; } } /** * TODO: discriminate columns */ public IProgramElement findElementForSourceLine(ISourceLocation location) { try { return findElementForSourceLine(asm.getCanonicalFilePath(location.getSourceFile()), location.getLine()); } catch (Exception e) { return null; } } /** * Never returns null * * @param sourceFilePath canonicalized path for consistency * @param lineNumber if 0 or 1 the corresponding file node will be returned * @return a new structure node for the file if it was not found in the model */ public IProgramElement findElementForSourceLine(String sourceFilePath, int lineNumber) { String canonicalSFP = asm.getCanonicalFilePath(new File(sourceFilePath)); // Used to do this: // IProgramElement node2 = findNodeForSourceLineHelper(root, canonicalSFP, lineNumber, -1); // Find the relevant source file node first IProgramElement node = findNodeForSourceFile(root, canonicalSFP); if (node == null) { return createFileStructureNode(sourceFilePath); } // Check if there is a more accurate child node of that source file node: IProgramElement closernode = findCloserMatchForLineNumber(node, lineNumber); if (closernode == null) { return node; } else { return closernode; } } /** * Discover the node representing a particular source file. * * @param node where in the model to start looking (usually the root on the initial call) * @param sourcefilePath the source file being searched for * @return the node representing that source file or null if it cannot be found */ public IProgramElement findNodeForSourceFile(IProgramElement node, String sourcefilePath) { // 1. why is <root> a sourcefile node? // 2. should isSourceFile() return true for a FILE that is a .class file...? if ((node.getKind().isSourceFile() && !node.getName().equals("<root>")) || node.getKind().isFile()) { ISourceLocation nodeLoc = node.getSourceLocation(); if (nodeLoc != null && asm.getCanonicalFilePath(nodeLoc.getSourceFile()).equals(sourcefilePath)) { return node; } return null; // no need to search children of a source file node } else { // check the children for (Iterator iterator = node.getChildren().iterator(); iterator.hasNext();) { IProgramElement foundit = findNodeForSourceFile((IProgramElement) iterator.next(), sourcefilePath); if (foundit != null) { return foundit; } } return null; } } public IProgramElement findElementForOffSet(String sourceFilePath, int lineNumber, int offSet) { String canonicalSFP = asm.getCanonicalFilePath(new File(sourceFilePath)); IProgramElement node = findNodeForSourceLineHelper(root, canonicalSFP, lineNumber, offSet); if (node != null) { return node; } else { return createFileStructureNode(sourceFilePath); } } private IProgramElement createFileStructureNode(String sourceFilePath) { // SourceFilePath might have originated on windows on linux... int lastSlash = sourceFilePath.lastIndexOf('\\'); if (lastSlash == -1) { lastSlash = sourceFilePath.lastIndexOf('/'); } // '!' is used like in URLs "c:/blahblah/X.jar!a/b.class" int i = sourceFilePath.lastIndexOf('!'); int j = sourceFilePath.indexOf(".class"); if (i > lastSlash && i != -1 && j != -1) { // we are a binary aspect in the default package lastSlash = i; } String fileName = sourceFilePath.substring(lastSlash + 1); IProgramElement fileNode = new ProgramElement(asm, fileName, IProgramElement.Kind.FILE_JAVA, new SourceLocation(new File( sourceFilePath), 1, 1), 0, null, null); // fileNode.setSourceLocation(); fileNode.addChild(NO_STRUCTURE); return fileNode; } /** * For a specified node, check if any of the children more accurately represent the specified line. * * @param node where to start looking * @param lineno the line number * @return any closer match below 'node' or null if nothing is a more accurate match */ public IProgramElement findCloserMatchForLineNumber(IProgramElement node, int lineno) { if (node == null || node.getChildren() == null) { return null; } for (Iterator childrenIter = node.getChildren().iterator(); childrenIter.hasNext();) { IProgramElement child = (IProgramElement) childrenIter.next(); ISourceLocation childLoc = child.getSourceLocation(); if (childLoc != null) { if (childLoc.getLine() <= lineno && childLoc.getEndLine() >= lineno) { // This child is a better match for that line number IProgramElement evenCloserMatch = findCloserMatchForLineNumber(child, lineno); if (evenCloserMatch == null) { return child; } else { return evenCloserMatch; } } else if (child.getKind().isType()) { // types are a bit clueless about where they are... do other nodes have // similar problems?? IProgramElement evenCloserMatch = findCloserMatchForLineNumber(child, lineno); if (evenCloserMatch != null) { return evenCloserMatch; } } } } return null; } private IProgramElement findNodeForSourceLineHelper(IProgramElement node, String sourceFilePath, int lineno, int offset) { if (matches(node, sourceFilePath, lineno, offset) && !hasMoreSpecificChild(node, sourceFilePath, lineno, offset)) { return node; } if (node != null) { for (Iterator it = node.getChildren().iterator(); it.hasNext();) { IProgramElement foundNode = findNodeForSourceLineHelper((IProgramElement) it.next(), sourceFilePath, lineno, offset); if (foundNode != null) { return foundNode; } } } return null; } private boolean matches(IProgramElement node, String sourceFilePath, int lineNumber, int offSet) { // try { // if (node != null && node.getSourceLocation() != null) // System.err.println("====\n1: " + // sourceFilePath + "\n2: " + // node.getSourceLocation().getSourceFile().getCanonicalPath().equals(sourceFilePath) // ); ISourceLocation nodeSourceLocation = (node != null ? node.getSourceLocation() : null); return node != null && nodeSourceLocation != null && nodeSourceLocation.getSourceFile().getAbsolutePath().equals(sourceFilePath) && ((offSet != -1 && nodeSourceLocation.getOffset() == offSet) || offSet == -1) && ((nodeSourceLocation.getLine() <= lineNumber && nodeSourceLocation.getEndLine() >= lineNumber) || (lineNumber <= 1 && node .getKind().isSourceFile())); // } catch (IOException ioe) { // return false; // } } private boolean hasMoreSpecificChild(IProgramElement node, String sourceFilePath, int lineNumber, int offSet) { for (Iterator it = node.getChildren().iterator(); it.hasNext();) { IProgramElement child = (IProgramElement) it.next(); if (matches(child, sourceFilePath, lineNumber, offSet)) return true; } return false; } public String getConfigFile() { return configFile; } public void setConfigFile(String configFile) { this.configFile = configFile; } public IProgramElement findElementForHandle(String handle) { return findElementForHandleOrCreate(handle, true); } // TODO: optimize this lookup // only want to create a file node if can't find the IPE if called through // findElementForHandle() to mirror behaviour before pr141730 public IProgramElement findElementForHandleOrCreate(String handle, boolean create) { // try the cache first... IProgramElement ipe = (IProgramElement) handleMap.get(handle); if (ipe != null) { return ipe; } ipe = findElementForHandle(root, handle); if (ipe == null && create) { ipe = createFileStructureNode(getFilename(handle)); } if (ipe != null) { cache(handle, ipe); } return ipe; } private IProgramElement findElementForHandle(IProgramElement parent, String handle) { for (Iterator it = parent.getChildren().iterator(); it.hasNext();) { IProgramElement node = (IProgramElement) it.next(); String nodeHid = node.getHandleIdentifier(); if (handle.equals(nodeHid)) { return node; } else { if (handle.startsWith(nodeHid)) { // it must be down here if it is anywhere IProgramElement childSearch = findElementForHandle(node, handle); if (childSearch != null) return childSearch; } } } return null; } // // private IProgramElement findElementForBytecodeInfo( // IProgramElement node, // String parentName, // String name, // String signature) { // for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { // IProgramElement curr = (IProgramElement)it.next(); // if (parentName.equals(curr.getParent().getBytecodeName()) // && name.equals(curr.getBytecodeName()) // && signature.equals(curr.getBytecodeSignature())) { // return node; // } else { // IProgramElement childSearch = findElementForBytecodeInfo(curr, parentName, name, signature); // if (childSearch != null) return childSearch; // } // } // return null; // } protected void cache(String handle, IProgramElement pe) { if (!AsmManager.isCompletingTypeBindings()) { handleMap.put(handle, pe); } } public void flushTypeMap() { typeMap.clear(); } public void flushHandleMap() { handleMap.clear(); } public void flushFileMap() { fileMap.clear(); } // TODO rename this method ... it does more than just the handle map public void updateHandleMap(Set deletedFiles) { // Only delete the entries we need to from the handle map - for performance reasons List forRemoval = new ArrayList(); Set k = handleMap.keySet(); for (Iterator iter = k.iterator(); iter.hasNext();) { String handle = (String) iter.next(); IProgramElement ipe = (IProgramElement) handleMap.get(handle); if (deletedFiles.contains(getCanonicalFilePath(ipe))) forRemoval.add(handle); } for (Iterator iter = forRemoval.iterator(); iter.hasNext();) { String handle = (String) iter.next(); handleMap.remove(handle); } forRemoval.clear(); k = typeMap.keySet(); for (Iterator iter = k.iterator(); iter.hasNext();) { String typeName = (String) iter.next(); IProgramElement ipe = (IProgramElement) typeMap.get(typeName); if (deletedFiles.contains(getCanonicalFilePath(ipe))) forRemoval.add(typeName); } for (Iterator iter = forRemoval.iterator(); iter.hasNext();) { String typeName = (String) iter.next(); typeMap.remove(typeName); } forRemoval.clear(); k = fileMap.keySet(); for (Iterator iter = k.iterator(); iter.hasNext();) { String filePath = (String) iter.next(); IProgramElement ipe = (IProgramElement) fileMap.get(filePath); if (deletedFiles.contains(getCanonicalFilePath(ipe))) forRemoval.add(filePath); } for (Iterator iter = forRemoval.iterator(); iter.hasNext();) { String filePath = (String) iter.next(); fileMap.remove(filePath); } } private String getFilename(String hid) { return asm.getHandleProvider().getFileForHandle(hid); } private String getCanonicalFilePath(IProgramElement ipe) { if (ipe.getSourceLocation() != null) { return asm.getCanonicalFilePath(ipe.getSourceLocation().getSourceFile()); } return ""; } }
308,093
Bug 308093 incremental build problem when mixing up ITDs and declare parents
reported by Rod Johnson. He had a sophisticated aspect doing a mix of ITDs and declare parents. On doing an incremental build he was receiving errors that looked like the declare parents hadn't applied on the secondary build. What was actually happening is that when a class file was brought in as a BinaryTypeBinding, the existing World representation wasn't being cleaned up properly. Without the cleanup the declare parents thought it was still in effect, but it was not. With proper cleanup the declare parents applies on the secondary build and all is well. Change is in AjLookupEnviroment.weaveInterTypeDeclarations where the onType.clearInterTypeMungers() must be paired with an onType.ensureConsistent() call.
resolved fixed
4b43dc6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-04-05T18:25:10Z"
"2010-04-05T17:53:20Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/AjLookupEnvironment.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.lookup; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration; import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration; import org.aspectj.asm.AsmManager; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.NormalAnnotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.env.AccessRestriction; import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryType; import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ITypeRequestor; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.PackageBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelAnnotation; import org.aspectj.weaver.bcel.BcelObjectType; import org.aspectj.weaver.bcel.FakeAnnotation; import org.aspectj.weaver.bcel.LazyClassGen; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; /** * Overrides the default eclipse LookupEnvironment for two purposes. * * 1. To provide some additional phases to <code>completeTypeBindings</code> that weave declare parents and inter-type declarations * at the correct time. * * 2. To intercept the loading of new binary types to ensure the they will have declare parents and inter-type declarations woven * when appropriate. * * @author Jim Hugunin */ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousClassCreationListener { public EclipseFactory factory = null; // private boolean builtInterTypesAndPerClauses = false; private final List pendingTypesToWeave = new ArrayList(); // Q: What are dangerousInterfaces? // A: An interface is considered dangerous if an ITD has been made upon it // and that ITD // requires the top most implementors of the interface to be woven *and yet* // the aspect // responsible for the ITD is not in the 'world'. // Q: Err, how can that happen? // A: When a type is on the inpath, it is 'processed' when completing type // bindings. At this // point we look at any type mungers it was affected by previously (stored // in the weaver // state info attribute). Effectively we are working with a type munger and // yet may not have its // originating aspect in the world. This is a problem if, for example, the // aspect supplied // a 'body' for a method targetting an interface - since the top most // implementors should // be woven by the munger from the aspect. When this happens we store the // interface name here // in the map - if we later process a type that is the topMostImplementor of // a dangerous // interface then we put out an error message. /** * interfaces targetted by ITDs that have to be implemented by accessing the topMostImplementor of the interface, yet the aspect * where the ITD originated is not in the world */ private final Map dangerousInterfaces = new HashMap(); public AjLookupEnvironment(ITypeRequestor typeRequestor, CompilerOptions options, ProblemReporter problemReporter, INameEnvironment nameEnvironment) { super(typeRequestor, options, problemReporter, nameEnvironment); } // ??? duplicates some of super's code public void completeTypeBindings() { AsmManager.setCompletingTypeBindings(true); ContextToken completeTypeBindingsToken = CompilationAndWeavingContext.enteringPhase( CompilationAndWeavingContext.COMPLETING_TYPE_BINDINGS, ""); // builtInterTypesAndPerClauses = false; // pendingTypesToWeave = new ArrayList(); stepCompleted = BUILD_TYPE_HIERARCHY; for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.CHECK_AND_SET_IMPORTS, units[i].compilationResult.fileName); units[i].scope.checkAndSetImports(); CompilationAndWeavingContext.leavingPhase(tok); } stepCompleted = CHECK_AND_SET_IMPORTS; for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.CONNECTING_TYPE_HIERARCHY, units[i].compilationResult.fileName); units[i].scope.connectTypeHierarchy(); CompilationAndWeavingContext.leavingPhase(tok); } stepCompleted = CONNECT_TYPE_HIERARCHY; for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.BUILDING_FIELDS_AND_METHODS, units[i].compilationResult.fileName); // units[i].scope.checkParameterizedTypes(); do this check a little // later, after ITDs applied to stbs units[i].scope.buildFieldsAndMethods(); CompilationAndWeavingContext.leavingPhase(tok); } // would like to gather up all TypeDeclarations at this point and put // them in the factory for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { SourceTypeBinding[] b = units[i].scope.topLevelTypes; for (int j = 0; j < b.length; j++) { factory.addSourceTypeBinding(b[j], units[i]); } } // We won't find out about anonymous types until later though, so // register to be // told about them when they turn up. AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(this); // need to build inter-type declarations for all AspectDeclarations at // this point // this MUST be done in order from super-types to subtypes List typesToProcess = new ArrayList(); for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { CompilationUnitScope cus = units[i].scope; SourceTypeBinding[] stbs = cus.topLevelTypes; for (int j = 0; j < stbs.length; j++) { SourceTypeBinding stb = stbs[j]; typesToProcess.add(stb); } } factory.getWorld().getCrosscuttingMembersSet().reset(); while (typesToProcess.size() > 0) { // removes types from the list as they are processed... collectAllITDsAndDeclares((SourceTypeBinding) typesToProcess.get(0), typesToProcess); } factory.finishTypeMungers(); // now do weaving Collection typeMungers = factory.getTypeMungers(); Collection declareParents = factory.getDeclareParents(); Collection declareAnnotationOnTypes = factory.getDeclareAnnotationOnTypes(); doPendingWeaves(); // We now have some list of types to process, and we are about to apply // the type mungers. // There can be situations where the order of types passed to the // compiler causes the // output from the compiler to vary - THIS IS BAD. For example, if we // have class A // and class B extends A. Also, an aspect that 'declare parents: A+ // implements Serializable' // then depending on whether we see A first, we may or may not make B // serializable. // The fix is to process them in the right order, ensuring that for a // type we process its // supertypes and superinterfaces first. This algorithm may have // problems with: // - partial hierarchies (e.g. suppose types A,B,C are in a hierarchy // and A and C are to be woven but not B) // - weaving that brings new types in for processing (see // pendingTypesToWeave.add() calls) after we thought // we had the full list. // // but these aren't common cases (he bravely said...) boolean typeProcessingOrderIsImportant = declareParents.size() > 0 || declareAnnotationOnTypes.size() > 0; // DECAT if (typeProcessingOrderIsImportant) { typesToProcess = new ArrayList(); for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { CompilationUnitScope cus = units[i].scope; SourceTypeBinding[] stbs = cus.topLevelTypes; for (int j = 0; j < stbs.length; j++) { SourceTypeBinding stb = stbs[j]; typesToProcess.add(stb); } } while (typesToProcess.size() > 0) { // A side effect of weaveIntertypes() is that the processed type // is removed from the collection weaveIntertypes(typesToProcess, (SourceTypeBinding) typesToProcess.get(0), typeMungers, declareParents, declareAnnotationOnTypes); } } else { // Order isn't important for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { // System.err.println("Working on "+new // String(units[i].getFileName())); weaveInterTypeDeclarations(units[i].scope, typeMungers, declareParents, declareAnnotationOnTypes); } } for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { units[i].scope.checkParameterizedTypes(); } for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { SourceTypeBinding[] b = units[i].scope.topLevelTypes; for (int j = 0; j < b.length; j++) { ContextToken tok = CompilationAndWeavingContext.enteringPhase( CompilationAndWeavingContext.RESOLVING_POINTCUT_DECLARATIONS, b[j].sourceName); resolvePointcutDeclarations(b[j].scope); CompilationAndWeavingContext.leavingPhase(tok); } } for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { SourceTypeBinding[] b = units[i].scope.topLevelTypes; for (int j = 0; j < b.length; j++) { ContextToken tok = CompilationAndWeavingContext.enteringPhase( CompilationAndWeavingContext.ADDING_DECLARE_WARNINGS_AND_ERRORS, b[j].sourceName); addAdviceLikeDeclares(b[j].scope); CompilationAndWeavingContext.leavingPhase(tok); } } for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { units[i] = null; // release unnecessary reference to the parsed unit } stepCompleted = BUILD_FIELDS_AND_METHODS; lastCompletedUnitIndex = lastUnitIndex; AsmManager.setCompletingTypeBindings(false); factory.getWorld().getCrosscuttingMembersSet().verify(); CompilationAndWeavingContext.leavingPhase(completeTypeBindingsToken); } // /** // * For any given sourcetypebinding, this method checks that if it is a // parameterized aspect that // * the type parameters specified for any supertypes meet the bounds for // the generic type // * variables. // */ // private void verifyAnyTypeParametersMeetBounds(SourceTypeBinding // sourceType) { // ResolvedType onType = factory.fromEclipse(sourceType); // if (onType.isAspect()) { // ResolvedType superType = factory.fromEclipse(sourceType.superclass); // // Don't need to check if it was used in its RAW form or isnt generic // if (superType.isGenericType() || superType.isParameterizedType()) { // TypeVariable[] typeVariables = superType.getTypeVariables(); // UnresolvedType[] typeParams = superType.getTypeParameters(); // if (typeVariables!=null && typeParams!=null) { // for (int i = 0; i < typeVariables.length; i++) { // boolean ok = // typeVariables[i].canBeBoundTo(typeParams[i].resolve(factory.getWorld())); // if (!ok) { // the supplied parameter violates the bounds // // Type {0} does not meet the specification for type parameter {1} ({2}) // in generic type {3} // String msg = // WeaverMessages.format( // WeaverMessages.VIOLATES_TYPE_VARIABLE_BOUNDS, // typeParams[i], // new Integer(i+1), // typeVariables[i].getDisplayName(), // superType.getGenericType().getName()); // factory.getWorld().getMessageHandler().handleMessage(MessageUtil.error(msg // ,onType.getSourceLocation())); // } // } // } // } // } // } public void doSupertypesFirst(ReferenceBinding rb, Collection yetToProcess) { if (rb instanceof SourceTypeBinding) { if (yetToProcess.contains(rb)) { collectAllITDsAndDeclares((SourceTypeBinding) rb, yetToProcess); } } else if (rb instanceof ParameterizedTypeBinding) { // If its a PTB we need to pull the SourceTypeBinding out of it. ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) rb; if (ptb.type instanceof SourceTypeBinding && yetToProcess.contains(ptb.type)) { collectAllITDsAndDeclares((SourceTypeBinding) ptb.type, yetToProcess); } } } /** * Find all the ITDs and Declares, but it is important we do this from the supertypes down to the subtypes. * * @param sourceType * @param yetToProcess */ private void collectAllITDsAndDeclares(SourceTypeBinding sourceType, Collection yetToProcess) { // Look at the supertype first ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.COLLECTING_ITDS_AND_DECLARES, sourceType.sourceName); yetToProcess.remove(sourceType); // look out our direct supertype doSupertypesFirst(sourceType.superclass(), yetToProcess); // now check our membertypes (pr119570) ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { SourceTypeBinding rb = (SourceTypeBinding) memberTypes[i]; if (!rb.superclass().equals(sourceType)) { doSupertypesFirst(rb.superclass(), yetToProcess); } } buildInterTypeAndPerClause(sourceType.scope); addCrosscuttingStructures(sourceType.scope); CompilationAndWeavingContext.leavingPhase(tok); } /** * Weave the parents and intertype decls into a given type. This method looks at the supertype and superinterfaces for the * specified type and recurses to weave those first if they are in the full list of types we are going to process during this * compile... it stops recursing the first time it hits a type we aren't going to process during this compile. This could cause * problems if you supply 'pieces' of a hierarchy, i.e. the bottom and the top, but not the middle - but what the hell are you * doing if you do that? */ private void weaveIntertypes(List typesToProcess, SourceTypeBinding typeToWeave, Collection typeMungers, Collection declareParents, Collection declareAnnotationOnTypes) { // Look at the supertype first ReferenceBinding superType = typeToWeave.superclass(); if (typesToProcess.contains(superType) && superType instanceof SourceTypeBinding) { // System.err.println("Recursing to supertype "+new // String(superType.getFileName())); weaveIntertypes(typesToProcess, (SourceTypeBinding) superType, typeMungers, declareParents, declareAnnotationOnTypes); } // Then look at the superinterface list ReferenceBinding[] interfaceTypes = typeToWeave.superInterfaces(); for (int i = 0; i < interfaceTypes.length; i++) { ReferenceBinding binding = interfaceTypes[i]; if (typesToProcess.contains(binding) && binding instanceof SourceTypeBinding) { // System.err.println("Recursing to superinterface "+new // String(binding.getFileName())); weaveIntertypes(typesToProcess, (SourceTypeBinding) binding, typeMungers, declareParents, declareAnnotationOnTypes); } } weaveInterTypeDeclarations(typeToWeave, typeMungers, declareParents, declareAnnotationOnTypes, false); typesToProcess.remove(typeToWeave); } private void doPendingWeaves() { for (Iterator i = pendingTypesToWeave.iterator(); i.hasNext();) { SourceTypeBinding t = (SourceTypeBinding) i.next(); ContextToken tok = CompilationAndWeavingContext.enteringPhase( CompilationAndWeavingContext.WEAVING_INTERTYPE_DECLARATIONS, t.sourceName); weaveInterTypeDeclarations(t); CompilationAndWeavingContext.leavingPhase(tok); } pendingTypesToWeave.clear(); } private void addAdviceLikeDeclares(ClassScope s) { TypeDeclaration dec = s.referenceContext; if (dec instanceof AspectDeclaration) { ResolvedType typeX = factory.fromEclipse(dec.binding); factory.getWorld().getCrosscuttingMembersSet().addAdviceLikeDeclares(typeX); } SourceTypeBinding sourceType = s.referenceContext.binding; ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { addAdviceLikeDeclares(((SourceTypeBinding) memberTypes[i]).scope); } } private void addCrosscuttingStructures(ClassScope s) { TypeDeclaration dec = s.referenceContext; if (dec instanceof AspectDeclaration) { ResolvedType typeX = factory.fromEclipse(dec.binding); factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX, false); if (typeX.getSuperclass().isAspect() && !typeX.getSuperclass().isExposedToWeaver()) { factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX.getSuperclass(), false); } } SourceTypeBinding sourceType = s.referenceContext.binding; ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { addCrosscuttingStructures(((SourceTypeBinding) memberTypes[i]).scope); } } private void resolvePointcutDeclarations(ClassScope s) { TypeDeclaration dec = s.referenceContext; SourceTypeBinding sourceType = s.referenceContext.binding; boolean hasPointcuts = false; AbstractMethodDeclaration[] methods = dec.methods; boolean initializedMethods = false; if (methods != null) { for (int i = 0; i < methods.length; i++) { if (methods[i] instanceof PointcutDeclaration) { hasPointcuts = true; if (!initializedMethods) { sourceType.methods(); // force initialization initializedMethods = true; } ((PointcutDeclaration) methods[i]).resolvePointcut(s); } } } if (hasPointcuts || dec instanceof AspectDeclaration || couldBeAnnotationStyleAspectDeclaration(dec)) { ReferenceType name = (ReferenceType) factory.fromEclipse(sourceType); EclipseSourceType eclipseSourceType = (EclipseSourceType) name.getDelegate(); eclipseSourceType.checkPointcutDeclarations(); } ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { resolvePointcutDeclarations(((SourceTypeBinding) memberTypes[i]).scope); } } /** * Return true if the declaration has @Aspect annotation. Called 'couldBe' rather than 'is' because someone else may have * defined an annotation called Aspect - we can't verify the full name (including package name) because it may not have been * resolved just yet and rather going through expensive resolution when we dont have to, this gives us a cheap check that tells * us whether to bother. */ private boolean couldBeAnnotationStyleAspectDeclaration(TypeDeclaration dec) { Annotation[] annotations = dec.annotations; boolean couldBeAtAspect = false; if (annotations != null) { for (int i = 0; i < annotations.length && !couldBeAtAspect; i++) { if (annotations[i].toString().equals("@Aspect")) { couldBeAtAspect = true; } } } return couldBeAtAspect; } private void buildInterTypeAndPerClause(ClassScope s) { TypeDeclaration dec = s.referenceContext; if (dec instanceof AspectDeclaration) { ((AspectDeclaration) dec).buildInterTypeAndPerClause(s); } SourceTypeBinding sourceType = s.referenceContext.binding; // test classes don't extend aspects if (sourceType.superclass != null) { ResolvedType parent = factory.fromEclipse(sourceType.superclass); if (parent.isAspect() && !isAspect(dec)) { factory.showMessage(IMessage.ERROR, "class \'" + new String(sourceType.sourceName) + "\' can not extend aspect \'" + parent.getName() + "\'", factory.fromEclipse(sourceType).getSourceLocation(), null); } } ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { buildInterTypeAndPerClause(((SourceTypeBinding) memberTypes[i]).scope); } } private boolean isAspect(TypeDeclaration decl) { if ((decl instanceof AspectDeclaration)) { return true; } else if (decl.annotations == null) { return false; } else { for (int i = 0; i < decl.annotations.length; i++) { Annotation ann = decl.annotations[i]; if (ann.type instanceof SingleTypeReference) { if (CharOperation.equals("Aspect".toCharArray(), ((SingleTypeReference) ann.type).token)) { return true; } } else if (ann.type instanceof QualifiedTypeReference) { QualifiedTypeReference qtr = (QualifiedTypeReference) ann.type; if (qtr.tokens.length != 5) { return false; } if (!CharOperation.equals("org".toCharArray(), qtr.tokens[0])) { return false; } if (!CharOperation.equals("aspectj".toCharArray(), qtr.tokens[1])) { return false; } if (!CharOperation.equals("lang".toCharArray(), qtr.tokens[2])) { return false; } if (!CharOperation.equals("annotation".toCharArray(), qtr.tokens[3])) { return false; } if (!CharOperation.equals("Aspect".toCharArray(), qtr.tokens[4])) { return false; } return true; } } } return false; } private void weaveInterTypeDeclarations(CompilationUnitScope unit, Collection typeMungers, Collection declareParents, Collection declareAnnotationOnTypes) { for (int i = 0, length = unit.topLevelTypes.length; i < length; i++) { weaveInterTypeDeclarations(unit.topLevelTypes[i], typeMungers, declareParents, declareAnnotationOnTypes, false); } } private void weaveInterTypeDeclarations(SourceTypeBinding sourceType) { if (!factory.areTypeMungersFinished()) { if (!pendingTypesToWeave.contains(sourceType)) { pendingTypesToWeave.add(sourceType); } } else { weaveInterTypeDeclarations(sourceType, factory.getTypeMungers(), factory.getDeclareParents(), factory .getDeclareAnnotationOnTypes(), true); } } private void weaveInterTypeDeclarations(SourceTypeBinding sourceType, Collection typeMungers, Collection declareParents, Collection declareAnnotationOnTypes, boolean skipInners) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_INTERTYPE_DECLARATIONS, sourceType.sourceName); ResolvedType onType = factory.fromEclipse(sourceType); // AMC we shouldn't need this when generic sigs are fixed?? if (onType.isRawType()) { onType = onType.getGenericType(); } WeaverStateInfo info = onType.getWeaverState(); // this test isnt quite right - there will be a case where we fail to // flag a problem // with a 'dangerous interface' because the type is reweavable when we // should have // because the type wasn't going to be rewoven... if that happens, we // should perhaps // move this test and dangerous interface processing to the end of this // method and // make it conditional on whether any of the typeMungers passed into // here actually // matched this type. if (info != null && !info.isOldStyle() && !info.isReweavable()) { processTypeMungersFromExistingWeaverState(sourceType, onType); CompilationAndWeavingContext.leavingPhase(tok); return; } // Check if the type we are looking at is the topMostImplementor of a // dangerous interface - // report a problem if it is. for (Iterator i = dangerousInterfaces.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); ResolvedType interfaceType = (ResolvedType) entry.getKey(); if (onType.isTopmostImplementor(interfaceType)) { factory.showMessage(IMessage.ERROR, onType + ": " + entry.getValue(), onType.getSourceLocation(), null); } } boolean needOldStyleWarning = (info != null && info.isOldStyle()); onType.clearInterTypeMungers(); // FIXME asc perf Could optimize here, after processing the expected set // of types we may bring // binary types that are not exposed to the weaver, there is no need to // attempt declare parents // or declare annotation really - unless we want to report the // not-exposed to weaver // messages... List decpToRepeat = new ArrayList(); List decaToRepeat = new ArrayList(); boolean anyNewParents = false; boolean anyNewAnnotations = false; // first pass // try and apply all decps - if they match, then great. If they don't // then // check if they are starred-annotation patterns. If they are not // starred // annotation patterns then they might match later...remember that... for (Iterator i = declareParents.iterator(); i.hasNext();) { DeclareParents decp = (DeclareParents) i.next(); if (!decp.isMixin()) { boolean didSomething = doDeclareParents(decp, sourceType); if (didSomething) { anyNewParents = true; } else { if (!decp.getChild().isStarAnnotation()) { decpToRepeat.add(decp); } } } } for (Iterator i = declareAnnotationOnTypes.iterator(); i.hasNext();) { DeclareAnnotation deca = (DeclareAnnotation) i.next(); boolean didSomething = doDeclareAnnotations(deca, sourceType, true); if (didSomething) { anyNewAnnotations = true; } else { if (!deca.getTypePattern().isStar()) { decaToRepeat.add(deca); } } } // now lets loop over and over until we have done all we can while ((anyNewAnnotations || anyNewParents) && (!decpToRepeat.isEmpty() || !decaToRepeat.isEmpty())) { anyNewParents = anyNewAnnotations = false; List forRemoval = new ArrayList(); for (Iterator i = decpToRepeat.iterator(); i.hasNext();) { DeclareParents decp = (DeclareParents) i.next(); boolean didSomething = doDeclareParents(decp, sourceType); if (didSomething) { anyNewParents = true; forRemoval.add(decp); } } decpToRepeat.removeAll(forRemoval); forRemoval.clear(); for (Iterator i = declareAnnotationOnTypes.iterator(); i.hasNext();) { DeclareAnnotation deca = (DeclareAnnotation) i.next(); boolean didSomething = doDeclareAnnotations(deca, sourceType, false); if (didSomething) { anyNewAnnotations = true; forRemoval.add(deca); } } decaToRepeat.removeAll(forRemoval); } for (Iterator i = typeMungers.iterator(); i.hasNext();) { EclipseTypeMunger munger = (EclipseTypeMunger) i.next(); if (munger.matches(onType)) { if (needOldStyleWarning) { factory.showMessage(IMessage.WARNING, "The class for " + onType + " should be recompiled with ajc-1.1.1 for best results", onType.getSourceLocation(), null); needOldStyleWarning = false; } onType.addInterTypeMunger(munger, true); } } onType.checkInterTypeMungers(); for (Iterator i = onType.getInterTypeMungers().iterator(); i.hasNext();) { EclipseTypeMunger munger = (EclipseTypeMunger) i.next(); munger.munge(sourceType, onType); } // Call if you would like to do source weaving of declare // @method/@constructor // at source time... no need to do this as it can't impact anything, but // left here for // future generations to enjoy. Method source is commented out at the // end of this module // doDeclareAnnotationOnMethods(); // Call if you would like to do source weaving of declare @field // at source time... no need to do this as it can't impact anything, but // left here for // future generations to enjoy. Method source is commented out at the // end of this module // doDeclareAnnotationOnFields(); if (skipInners) { CompilationAndWeavingContext.leavingPhase(tok); return; } ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { if (memberTypes[i] instanceof SourceTypeBinding) { weaveInterTypeDeclarations((SourceTypeBinding) memberTypes[i], typeMungers, declareParents, declareAnnotationOnTypes, false); } } CompilationAndWeavingContext.leavingPhase(tok); } /** * Called when we discover we are weaving intertype declarations on some type that has an existing 'WeaverStateInfo' object - * this is typically some previously woven type that has been passed on the inpath. * * sourceType and onType are the 'same type' - the former is the 'Eclipse' version and the latter is the 'Weaver' version. */ private void processTypeMungersFromExistingWeaverState(SourceTypeBinding sourceType, ResolvedType onType) { Collection previouslyAppliedMungers = onType.getWeaverState().getTypeMungers(onType); for (Iterator i = previouslyAppliedMungers.iterator(); i.hasNext();) { ConcreteTypeMunger m = (ConcreteTypeMunger) i.next(); EclipseTypeMunger munger = factory.makeEclipseTypeMunger(m); if (munger.munge(sourceType, onType)) { if (onType.isInterface() && munger.getMunger().needsAccessToTopmostImplementor()) { if (!onType.getWorld().getCrosscuttingMembersSet().containsAspect(munger.getAspectType())) { dangerousInterfaces .put(onType, "implementors of " + onType + " must be woven by " + munger.getAspectType()); } } } } } private boolean doDeclareParents(DeclareParents declareParents, SourceTypeBinding sourceType) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS, sourceType.sourceName); ResolvedType resolvedSourceType = factory.fromEclipse(sourceType); List newParents = declareParents.findMatchingNewParents(resolvedSourceType, false); if (!newParents.isEmpty()) { for (Iterator i = newParents.iterator(); i.hasNext();) { ResolvedType parent = (ResolvedType) i.next(); if (dangerousInterfaces.containsKey(parent)) { ResolvedType onType = factory.fromEclipse(sourceType); factory.showMessage(IMessage.ERROR, onType + ": " + dangerousInterfaces.get(parent), onType.getSourceLocation(), null); } if (Modifier.isFinal(parent.getModifiers())) { factory.showMessage(IMessage.ERROR, "cannot extend final class " + parent.getClassName(), declareParents .getSourceLocation(), null); } else { // do not actually do it if the type isn't exposed - this // will correctly reported as a problem elsewhere if (!resolvedSourceType.isExposedToWeaver()) { return false; } // AsmRelationshipProvider.getDefault(). // addDeclareParentsRelationship // (declareParents.getSourceLocation(), // factory.fromEclipse(sourceType), newParents); addParent(sourceType, parent); } } CompilationAndWeavingContext.leavingPhase(tok); return true; } CompilationAndWeavingContext.leavingPhase(tok); return false; } private String stringifyTargets(long bits) { if ((bits & TagBits.AnnotationTargetMASK) == 0) { return ""; } Set s = new HashSet(); if ((bits & TagBits.AnnotationForAnnotationType) != 0) { s.add("ANNOTATION_TYPE"); } if ((bits & TagBits.AnnotationForConstructor) != 0) { s.add("CONSTRUCTOR"); } if ((bits & TagBits.AnnotationForField) != 0) { s.add("FIELD"); } if ((bits & TagBits.AnnotationForLocalVariable) != 0) { s.add("LOCAL_VARIABLE"); } if ((bits & TagBits.AnnotationForMethod) != 0) { s.add("METHOD"); } if ((bits & TagBits.AnnotationForPackage) != 0) { s.add("PACKAGE"); } if ((bits & TagBits.AnnotationForParameter) != 0) { s.add("PARAMETER"); } if ((bits & TagBits.AnnotationForType) != 0) { s.add("TYPE"); } StringBuffer sb = new StringBuffer(); sb.append("{"); for (Iterator iter = s.iterator(); iter.hasNext();) { String element = (String) iter.next(); sb.append(element); if (iter.hasNext()) { sb.append(","); } } sb.append("}"); return sb.toString(); } private boolean doDeclareAnnotations(DeclareAnnotation decA, SourceTypeBinding sourceType, boolean reportProblems) { ResolvedType rtx = factory.fromEclipse(sourceType); if (!decA.matches(rtx)) { return false; } if (!rtx.isExposedToWeaver()) { return false; } ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_ANNOTATIONS, sourceType.sourceName); // Get the annotation specified in the declare UnresolvedType aspectType = decA.getAspect(); if (aspectType instanceof ReferenceType) { ReferenceType rt = (ReferenceType) aspectType; if (rt.isParameterizedType() || rt.isRawType()) { aspectType = rt.getGenericType(); } } TypeBinding tb = factory.makeTypeBinding(aspectType); // Hideousness follows: // There are multiple situations to consider here and they relate to the // combinations of // where the annotation is coming from and where the annotation is going // to be put: // // 1. Straight full build, all from source - the annotation is from a // dec@type and // is being put on some type. Both types are real SourceTypeBindings. // WORKS // 2. Incremental build, changing the affected type - the annotation is // from a // dec@type in a BinaryTypeBinding (so has to be accessed via bcel) and // the // affected type is a real SourceTypeBinding. Mostly works (pr128665) // 3. ? SourceTypeBinding stb = (SourceTypeBinding) tb; Annotation[] toAdd = null; long abits = 0; // Might have to retrieve the annotation through BCEL and construct an // eclipse one for it. if (stb instanceof BinaryTypeBinding) { ReferenceType rt = (ReferenceType) factory.fromEclipse(stb); ResolvedMember[] methods = rt.getDeclaredMethods(); ResolvedMember decaMethod = null; String nameToLookFor = decA.getAnnotationMethod(); for (int i = 0; i < methods.length; i++) { if (methods[i].getName().equals(nameToLookFor)) { decaMethod = methods[i]; break; } } if (decaMethod != null) { // could assert this ... AnnotationAJ[] axs = decaMethod.getAnnotations(); if (axs != null) { // another error has occurred, dont crash here because of it toAdd = new Annotation[1]; toAdd[0] = createAnnotationFromBcelAnnotation(axs[0], decaMethod.getSourceLocation().getOffset(), factory); // BUG BUG BUG - We dont test these abits are correct, in fact // we'll be very lucky if they are. // What does that mean? It means on an incremental compile you // might get away with an // annotation that isn't allowed on a type being put on a type. if (toAdd[0].resolvedType != null) { abits = toAdd[0].resolvedType.getAnnotationTagBits(); } } } } else if (stb != null) { // much nicer, its a real SourceTypeBinding so we can stay in // eclipse land // if (decA.getAnnotationMethod() != null) { MethodBinding[] mbs = stb.getMethods(decA.getAnnotationMethod().toCharArray()); abits = mbs[0].getAnnotationTagBits(); // ensure resolved TypeDeclaration typeDecl = ((SourceTypeBinding) mbs[0].declaringClass).scope.referenceContext; AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(mbs[0]); toAdd = methodDecl.annotations; // this is what to add toAdd[0] = createAnnotationCopy(toAdd[0]); if (toAdd[0].resolvedType != null) { abits = toAdd[0].resolvedType.getAnnotationTagBits(); // } } } // This happens if there is another error in the code - that should be reported separately if (toAdd == null || toAdd[0] == null || toAdd[0].type == null) { CompilationAndWeavingContext.leavingPhase(tok); return false; } if (sourceType instanceof BinaryTypeBinding) { // In this case we can't access the source type binding to add a new // annotation, so let's put something // on the weaver type temporarily ResolvedType theTargetType = factory.fromEclipse(sourceType); TypeBinding theAnnotationType = toAdd[0].resolvedType; // The annotation type may be null if it could not be resolved (eg. the relevant import has not been added yet) // In this case an error will be put out about the annotation but not if we crash here if (theAnnotationType == null) { return false; } String sig = new String(theAnnotationType.signature()); UnresolvedType bcelAnnotationType = UnresolvedType.forSignature(sig); String name = bcelAnnotationType.getName(); if (theTargetType.hasAnnotation(bcelAnnotationType)) { CompilationAndWeavingContext.leavingPhase(tok); return false; } // FIXME asc tidy up this code that duplicates whats below! // Simple checks on the bits boolean giveupnow = false; if (((abits & TagBits.AnnotationTargetMASK) != 0)) { if (isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(abits)) { // error will have been already reported giveupnow = true; } else if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0) || (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) { if (reportProblems) { if (decA.isExactPattern()) { factory.showMessage(IMessage.ERROR, WeaverMessages.format( WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, rtx.getName(), toAdd[0].type, stringifyTargets(abits)), decA.getSourceLocation(), null); } // dont put out the lint - the weaving process will do // that // else { // if (factory.getWorld().getLint(). // invalidTargetForAnnotation.isEnabled()) { // factory.getWorld().getLint().invalidTargetForAnnotation // .signal(new // String[]{rtx.getName(),toAdd[0].type.toString(), // stringifyTargets // (abits)},decA.getSourceLocation(),null); // } // } } giveupnow = true; } } if (giveupnow) { CompilationAndWeavingContext.leavingPhase(tok); return false; } theTargetType.addAnnotation(new BcelAnnotation(new FakeAnnotation(name, sig, (abits & TagBits.AnnotationRuntimeRetention) != 0), factory.getWorld())); CompilationAndWeavingContext.leavingPhase(tok); return true; } Annotation currentAnnotations[] = sourceType.scope.referenceContext.annotations; if (currentAnnotations != null) { for (int i = 0; i < currentAnnotations.length; i++) { Annotation annotation = currentAnnotations[i]; String a = CharOperation.toString(annotation.type.getTypeName()); String b = CharOperation.toString(toAdd[0].type.getTypeName()); // FIXME asc we have a lint for attempting to add an annotation // twice to a method, // we could put it out here *if* we can resolve the problem of // errors coming out // multiple times if we have cause to loop through here if (a.equals(b)) { CompilationAndWeavingContext.leavingPhase(tok); return false; } } } if (((abits & TagBits.AnnotationTargetMASK) != 0)) { if ((abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType)) == 0) { // this means it specifies something other than annotation or // normal type - error will have been already reported, // just resolution process above CompilationAndWeavingContext.leavingPhase(tok); return false; } if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0) || (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) { if (reportProblems) { if (decA.isExactPattern()) { factory.showMessage(IMessage.ERROR, WeaverMessages.format( WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, rtx.getName(), toAdd[0].type, stringifyTargets(abits)), decA.getSourceLocation(), null); } // dont put out the lint - the weaving process will do that // else { // if // (factory.getWorld().getLint().invalidTargetForAnnotation // .isEnabled()) { // factory.getWorld().getLint().invalidTargetForAnnotation. // signal(new // String[]{rtx.getName(),toAdd[0].type.toString(), // stringifyTargets(abits)},decA.getSourceLocation(),null); // } // } } CompilationAndWeavingContext.leavingPhase(tok); return false; } } // Build a new array of annotations // remember the current set (rememberAnnotations only does something the // first time it is called for a type) sourceType.scope.referenceContext.rememberAnnotations(); // AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship( // decA.getSourceLocation(), rtx.getSourceLocation()); Annotation abefore[] = sourceType.scope.referenceContext.annotations; Annotation[] newset = new Annotation[toAdd.length + (abefore == null ? 0 : abefore.length)]; System.arraycopy(toAdd, 0, newset, 0, toAdd.length); if (abefore != null) { System.arraycopy(abefore, 0, newset, toAdd.length, abefore.length); } sourceType.scope.referenceContext.annotations = newset; CompilationAndWeavingContext.leavingPhase(tok); return true; } /** * Transform an annotation from its AJ form to an eclipse form. We *DONT* care about the values of the annotation. that is * because it is only being stuck on a type during type completion to allow for other constructs (decps, decas) that might be * looking for it - when the class actually gets to disk it wont have this new annotation on it and during weave time we will do * the right thing copying across values too. */ private static Annotation createAnnotationFromBcelAnnotation(AnnotationAJ annX, int pos, EclipseFactory factory) { String name = annX.getTypeName(); TypeBinding tb = factory.makeTypeBinding(annX.getType()); // String theName = annX.getSignature().getBaseName(); char[][] typeName = CharOperation.splitOn('.', name.replace('$', '.').toCharArray()); // pr149293 - not bulletproof... long[] positions = new long[typeName.length]; for (int i = 0; i < positions.length; i++) { positions[i] = pos; } TypeReference annType = new QualifiedTypeReference(typeName, positions); NormalAnnotation ann = new NormalAnnotation(annType, pos); ann.resolvedType = tb; // yuck - is this OK in all cases? // We don't need membervalues... // Expression pcExpr = new // StringLiteral(pointcutExpression.toCharArray(),pos,pos); // MemberValuePair[] mvps = new MemberValuePair[2]; // mvps[0] = new MemberValuePair("value".toCharArray(),pos,pos,pcExpr); // Expression argNamesExpr = new // StringLiteral(argNames.toCharArray(),pos,pos); // mvps[1] = new // MemberValuePair("argNames".toCharArray(),pos,pos,argNamesExpr); // ann.memberValuePairs = mvps; return ann; } /** * Create a copy of an annotation, not deep but deep enough so we don't copy across fields that will get us into trouble like * 'recipient' */ private static Annotation createAnnotationCopy(Annotation ann) { NormalAnnotation ann2 = new NormalAnnotation(ann.type, ann.sourceStart); ann2.memberValuePairs = ann.memberValuePairs(); ann2.resolvedType = ann.resolvedType; ann2.bits = ann.bits; return ann2; // String name = annX.getTypeName(); // TypeBinding tb = factory.makeTypeBinding(annX.getSignature()); // String theName = annX.getSignature().getBaseName(); // char[][] typeName = // CharOperation.splitOn('.',name.replace('$','.').toCharArray()); // //pr149293 - not bulletproof... // long[] positions = new long[typeName.length]; // for (int i = 0; i < positions.length; i++) positions[i]=pos; // TypeReference annType = new // QualifiedTypeReference(typeName,positions); // NormalAnnotation ann = new NormalAnnotation(annType,pos); // ann.resolvedType=tb; // yuck - is this OK in all cases? // // We don't need membervalues... // // Expression pcExpr = new // StringLiteral(pointcutExpression.toCharArray(),pos,pos); // // MemberValuePair[] mvps = new MemberValuePair[2]; // // mvps[0] = new // MemberValuePair("value".toCharArray(),pos,pos,pcExpr); // // Expression argNamesExpr = new // StringLiteral(argNames.toCharArray(),pos,pos); // // mvps[1] = new // MemberValuePair("argNames".toCharArray(),pos,pos,argNamesExpr); // // ann.memberValuePairs = mvps; // return ann; } private boolean isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(long abits) { return (abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType)) == 0; } private void reportDeclareParentsMessage(WeaveMessage.WeaveMessageKind wmk, SourceTypeBinding sourceType, ResolvedType parent) { if (!factory.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { String filename = new String(sourceType.getFileName()); int takefrom = filename.lastIndexOf('/'); if (takefrom == -1) { takefrom = filename.lastIndexOf('\\'); } filename = filename.substring(takefrom + 1); factory.getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(wmk, new String[] { CharOperation.toString(sourceType.compoundName), filename, parent.getClassName(), getShortname(parent.getSourceLocation().getSourceFile().getPath()) })); } } private String getShortname(String path) { int takefrom = path.lastIndexOf('/'); if (takefrom == -1) { takefrom = path.lastIndexOf('\\'); } return path.substring(takefrom + 1); } private void addParent(SourceTypeBinding sourceType, ResolvedType parent) { ReferenceBinding parentBinding = (ReferenceBinding) factory.makeTypeBinding(parent); if (parentBinding == null) { return; // The parent is missing, it will be reported elsewhere. } sourceType.rememberTypeHierarchy(); if (parentBinding.isClass()) { sourceType.superclass = parentBinding; // this used to be true, but I think I've fixed it now, decp is done // at weave time! // TAG: WeavingMessage DECLARE PARENTS: EXTENDS // Compiler restriction: Can't do EXTENDS at weave time // So, only see this message if doing a source compilation // reportDeclareParentsMessage(WeaveMessage. // WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent); } else { ReferenceBinding[] oldI = sourceType.superInterfaces; ReferenceBinding[] newI; if (oldI == null) { newI = new ReferenceBinding[1]; newI[0] = parentBinding; } else { int n = oldI.length; newI = new ReferenceBinding[n + 1]; System.arraycopy(oldI, 0, newI, 0, n); newI[n] = parentBinding; } sourceType.superInterfaces = newI; // warnOnAddedInterface(factory.fromEclipse(sourceType),parent); // // now reported at weave time... // this used to be true, but I think I've fixed it now, decp is done // at weave time! // TAG: WeavingMessage DECLARE PARENTS: IMPLEMENTS // This message will come out of BcelTypeMunger.munge if doing a // binary weave // reportDeclareParentsMessage(WeaveMessage. // WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS,sourceType,parent); } // also add it to the bcel delegate if there is one if (sourceType instanceof BinaryTypeBinding) { ResolvedType onType = factory.fromEclipse(sourceType); ReferenceType rt = (ReferenceType) onType; ReferenceTypeDelegate rtd = rt.getDelegate(); if (rtd instanceof BcelObjectType) { rt.addParent(parent); // ((BcelObjectType) rtd).addParent(parent); } } } public void warnOnAddedInterface(ResolvedType type, ResolvedType parent) { World world = factory.getWorld(); ResolvedType serializable = world.getCoreType(UnresolvedType.SERIALIZABLE); if (serializable.isAssignableFrom(type) && !serializable.isAssignableFrom(parent) && !LazyClassGen.hasSerialVersionUIDField(type)) { world.getLint().needsSerialVersionUIDField.signal(new String[] { type.getName().toString(), "added interface " + parent.getName().toString() }, null, null); } } private final List pendingTypesToFinish = new ArrayList(); boolean inBinaryTypeCreationAndWeaving = false; boolean processingTheQueue = false; public BinaryTypeBinding createBinaryTypeFrom(IBinaryType binaryType, PackageBinding packageBinding, boolean needFieldsAndMethods, AccessRestriction accessRestriction) { if (inBinaryTypeCreationAndWeaving) { BinaryTypeBinding ret = super.createBinaryTypeFrom(binaryType, packageBinding, needFieldsAndMethods, accessRestriction); pendingTypesToFinish.add(ret); return ret; } inBinaryTypeCreationAndWeaving = true; try { BinaryTypeBinding ret = super.createBinaryTypeFrom(binaryType, packageBinding, needFieldsAndMethods, accessRestriction); factory.getWorld().validateType(factory.fromBinding(ret)); // if you need the bytes to pass to validate, here they // are:((ClassFileReader)binaryType).getReferenceBytes() weaveInterTypeDeclarations(ret); return ret; } finally { inBinaryTypeCreationAndWeaving = false; // Start processing the list... if (pendingTypesToFinish.size() > 0) { processingTheQueue = true; while (!pendingTypesToFinish.isEmpty()) { BinaryTypeBinding nextVictim = (BinaryTypeBinding) pendingTypesToFinish.remove(0); // During this call we may recurse into this method and add // more entries to the pendingTypesToFinish list. weaveInterTypeDeclarations(nextVictim); } processingTheQueue = false; } } } /** * Callback driven when the compiler detects an anonymous type during block resolution. We need to add it to the weaver so that * we don't trip up later. * * @param aBinding */ public void anonymousTypeBindingCreated(LocalTypeBinding aBinding) { factory.addSourceTypeBinding(aBinding, null); } } // commented out, supplied as info on how to manipulate annotations in an // eclipse world // // public void doDeclareAnnotationOnMethods() { // Do the declare annotation on fields/methods/ctors // Collection daoms = factory.getDeclareAnnotationOnMethods(); // if (daoms!=null && daoms.size()>0 && !(sourceType instanceof // BinaryTypeBinding)) { // System.err.println("Going through the methods on "+sourceType.debugName()+ // " looking for DECA matches"); // // We better take a look through them... // for (Iterator iter = daoms.iterator(); iter.hasNext();) { // DeclareAnnotation element = (DeclareAnnotation) iter.next(); // System.err.println("Looking for anything that might match "+element+" on "+ // sourceType.debugName()+" "+getType(sourceType. // compoundName).debugName()+" "+(sourceType instanceof BinaryTypeBinding)); // // ReferenceBinding rbb = getType(sourceType.compoundName); // // fix me if we ever uncomment this code... should iterate the other way // round, over the methods then over the decas // sourceType.methods(); // MethodBinding sourceMbs[] = sourceType.methods; // for (int i = 0; i < sourceMbs.length; i++) { // MethodBinding sourceMb = sourceMbs[i]; // MethodBinding mbbbb = // ((SourceTypeBinding)rbb).getExactMethod(sourceMb.selector // ,sourceMb.parameters); // boolean isCtor = sourceMb.selector[0]=='<'; // // if ((element.isDeclareAtConstuctor() ^ !isCtor)) { // System.err.println("Checking "+sourceMb+" ... declaringclass="+sourceMb. // declaringClass.debugName()+" rbb="+rbb.debugName()+" "+ // sourceMb.declaringClass.equals(rbb)); // // ResolvedMember rm = null; // rm = EclipseFactory.makeResolvedMember(mbbbb); // if (element.matches(rm,factory.getWorld())) { // System.err.println("MATCH"); // // // Determine the set of annotations that are currently on the method // ReferenceBinding rb = getType(sourceType.compoundName); // // TypeBinding tb = factory.makeTypeBinding(decA.getAspect()); // MethodBinding mb = // ((SourceTypeBinding)rb).getExactMethod(sourceMb.selector,sourceMb // .parameters); // //long abits = mbs[0].getAnnotationTagBits(); // ensure resolved // TypeDeclaration typeDecl = // ((SourceTypeBinding)sourceMb.declaringClass).scope.referenceContext; // AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(sourceMb); // Annotation[] currentlyHas = methodDecl.annotations; // this is what to add // //abits = toAdd[0].resolvedType.getAnnotationTagBits(); // // // Determine the annotations to add to that method // TypeBinding tb = factory.makeTypeBinding(element.getAspect()); // MethodBinding[] aspectMbs = // ((SourceTypeBinding)tb).getMethods(element.getAnnotationMethod // ().toCharArray()); // long abits = aspectMbs[0].getAnnotationTagBits(); // ensure resolved // TypeDeclaration typeDecl2 = // ((SourceTypeBinding)aspectMbs[0].declaringClass).scope.referenceContext; // AbstractMethodDeclaration methodDecl2 = // typeDecl2.declarationOf(aspectMbs[0]); // Annotation[] toAdd = methodDecl2.annotations; // this is what to add // // abits = toAdd[0].resolvedType.getAnnotationTagBits(); // System.err.println("Has: "+currentlyHas+" toAdd: "+toAdd); // // // fix me? should check if it already has the annotation // //Annotation abefore[] = sourceType.scope.referenceContext.annotations; // Annotation[] newset = new // Annotation[(currentlyHas==null?0:currentlyHas.length)+1]; // System.arraycopy(toAdd,0,newset,0,toAdd.length); // if (currentlyHas!=null) { // System.arraycopy(currentlyHas,0,newset,1,currentlyHas.length); // } // methodDecl.annotations = newset; // System.err.println("New set on "+CharOperation.charToString(sourceMb.selector) // +" is "+newset); // } else // System.err.println("NO MATCH"); // } // } // } // } // } // commented out, supplied as info on how to manipulate annotations in an // eclipse world // // public void doDeclareAnnotationOnFields() { // Collection daofs = factory.getDeclareAnnotationOnFields(); // if (daofs!=null && daofs.size()>0 && !(sourceType instanceof // BinaryTypeBinding)) { // System.err.println("Going through the fields on "+sourceType.debugName()+ // " looking for DECA matches"); // // We better take a look through them... // for (Iterator iter = daofs.iterator(); iter.hasNext();) { // DeclareAnnotation element = (DeclareAnnotation) iter.next(); // System.err.println("Processing deca "+element+" on "+sourceType.debugName()+ // " "+getType(sourceType.compoundName).debugName()+" " // +(sourceType instanceof BinaryTypeBinding)); // // ReferenceBinding rbb = getType(sourceType.compoundName); // // fix me? should iterate the other way round, over the methods then over the // decas // sourceType.fields(); // resolve the bloody things // FieldBinding sourceFbs[] = sourceType.fields; // for (int i = 0; i < sourceFbs.length; i++) { // FieldBinding sourceFb = sourceFbs[i]; // //FieldBinding fbbbb = // ((SourceTypeBinding)rbb).getgetExactMethod(sourceMb.selector // ,sourceMb.parameters); // // System.err.println("Checking "+sourceFb+" ... declaringclass="+sourceFb. // declaringClass.debugName()+" rbb="+rbb.debugName()); // // ResolvedMember rm = null; // rm = EclipseFactory.makeResolvedMember(sourceFb); // if (element.matches(rm,factory.getWorld())) { // System.err.println("MATCH"); // // // Determine the set of annotations that are currently on the field // ReferenceBinding rb = getType(sourceType.compoundName); // // TypeBinding tb = factory.makeTypeBinding(decA.getAspect()); // FieldBinding fb = ((SourceTypeBinding)rb).getField(sourceFb.name,true); // //long abits = mbs[0].getAnnotationTagBits(); // ensure resolved // TypeDeclaration typeDecl = // ((SourceTypeBinding)sourceFb.declaringClass).scope.referenceContext; // FieldDeclaration fd = typeDecl.declarationOf(sourceFb); // //AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(sourceMb); // Annotation[] currentlyHas = fd.annotations; // this is what to add // //abits = toAdd[0].resolvedType.getAnnotationTagBits(); // // // Determine the annotations to add to that method // TypeBinding tb = factory.makeTypeBinding(element.getAspect()); // MethodBinding[] aspectMbs = // ((SourceTypeBinding)tb).getMethods(element.getAnnotationMethod // ().toCharArray()); // long abits = aspectMbs[0].getAnnotationTagBits(); // ensure resolved // TypeDeclaration typeDecl2 = // ((SourceTypeBinding)aspectMbs[0].declaringClass).scope.referenceContext; // AbstractMethodDeclaration methodDecl2 = // typeDecl2.declarationOf(aspectMbs[0]); // Annotation[] toAdd = methodDecl2.annotations; // this is what to add // // abits = toAdd[0].resolvedType.getAnnotationTagBits(); // System.err.println("Has: "+currentlyHas+" toAdd: "+toAdd); // // // fix me? check if it already has the annotation // // // //Annotation abefore[] = sourceType.scope.referenceContext.annotations; // Annotation[] newset = new // Annotation[(currentlyHas==null?0:currentlyHas.length)+1]; // System.arraycopy(toAdd,0,newset,0,toAdd.length); // if (currentlyHas!=null) { // System.arraycopy(currentlyHas,0,newset,1,currentlyHas.length); // } // fd.annotations = newset; // System.err.println("New set on "+CharOperation.charToString(sourceFb.name)+ // " is "+newset); // } else // System.err.println("NO MATCH"); // } // // } // }
291,206
Bug 291206 Allow declare error & declare warning to support type expressions
null
resolved fixed
9241e2e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-04-05T23:38:16Z"
"2009-10-02T16:13:20Z"
tests/bugs169/pr291206/One.java
291,206
Bug 291206 Allow declare error & declare warning to support type expressions
null
resolved fixed
9241e2e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-04-05T23:38:16Z"
"2009-10-02T16:13:20Z"
tests/bugs169/pr291206/Three.java
291,206
Bug 291206 Allow declare error & declare warning to support type expressions
null
resolved fixed
9241e2e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-04-05T23:38:16Z"
"2009-10-02T16:13:20Z"
tests/bugs169/pr291206/Two.java
308,386
Bug 308386 NPE when hasfield evaluating with annotations and there is an unresolved import
hasfield/hasmethod can cause early matching - before the weaving process kicks in properly. For a 'normal' compile error, like an unresolvable import, the error is put out before the weaving process kicks off. However hasfield/hasmethod happening early causes an NPE to occur before the error is put out. A guard for the NPE (which occurs in EclipseResolvedMember.getAnnotationTypes()) addresses this problem and allows the real error to come out.
resolved fixed
94d0a4e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-04-07T19:24:04Z"
"2010-04-07T19:53:20Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseResolvedMember.java
/* ******************************************************************* * Copyright (c) 2006 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.lookup; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AnnotationMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.FalseLiteral; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.IntLiteral; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TrueLiteral; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.IntConstant; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Binding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.BCException; import org.aspectj.weaver.MemberKind; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; /** * In the pipeline world, we can be weaving before all types have come through from compilation. In some cases this means the weaver * will want to ask questions of eclipse types and this subtype of ResolvedMemberImpl is here to answer some of those questions - it * is backed by the real eclipse MethodBinding object and can translate from Eclipse -> Weaver information. */ public class EclipseResolvedMember extends ResolvedMemberImpl { private static String[] NO_ARGS = new String[] {}; private Binding realBinding; private String[] argumentNames; private World w; private ResolvedType[] cachedAnnotationTypes; private EclipseFactory eclipseFactory; public EclipseResolvedMember(MethodBinding binding, MemberKind memberKind, ResolvedType realDeclaringType, int modifiers, UnresolvedType rettype, String name, UnresolvedType[] paramtypes, UnresolvedType[] extypes, EclipseFactory eclipseFactory) { super(memberKind, realDeclaringType, modifiers, rettype, name, paramtypes, extypes); this.realBinding = binding; this.eclipseFactory = eclipseFactory; this.w = realDeclaringType.getWorld(); } public EclipseResolvedMember(FieldBinding binding, MemberKind field, ResolvedType realDeclaringType, int modifiers, ResolvedType type, String string, UnresolvedType[] none) { super(field, realDeclaringType, modifiers, type, string, none); this.realBinding = binding; this.w = realDeclaringType.getWorld(); } public boolean hasAnnotation(UnresolvedType ofType) { ResolvedType[] annotationTypes = getAnnotationTypes(); if (annotationTypes == null) return false; for (int i = 0; i < annotationTypes.length; i++) { ResolvedType type = annotationTypes[i]; if (type.equals(ofType)) return true; } return false; } public AnnotationAJ[] getAnnotations() { // long abits = realBinding.getAnnotationTagBits(); // ensure resolved Annotation[] annos = getEclipseAnnotations(); if (annos == null) { return null; } AnnotationAJ[] annoAJs = new AnnotationAJ[annos.length]; for (int i = 0; i < annos.length; i++) { annoAJs[i] = EclipseAnnotationConvertor.convertEclipseAnnotation(annos[i], w, eclipseFactory); } return annoAJs; } public AnnotationAJ getAnnotationOfType(UnresolvedType ofType) { // long abits = realBinding.getAnnotationTagBits(); // ensure resolved Annotation[] annos = getEclipseAnnotations(); if (annos == null) return null; for (int i = 0; i < annos.length; i++) { Annotation anno = annos[i]; UnresolvedType ut = UnresolvedType.forSignature(new String(anno.resolvedType.signature())); if (w.resolve(ut).equals(ofType)) { // Found the one return EclipseAnnotationConvertor.convertEclipseAnnotation(anno, w, eclipseFactory); } } return null; } public String getAnnotationDefaultValue() { if (realBinding instanceof MethodBinding) { AbstractMethodDeclaration methodDecl = getTypeDeclaration().declarationOf((MethodBinding) realBinding); if (methodDecl instanceof AnnotationMethodDeclaration) { AnnotationMethodDeclaration annoMethodDecl = (AnnotationMethodDeclaration) methodDecl; Expression e = annoMethodDecl.defaultValue; if (e.resolvedType == null) e.resolve(methodDecl.scope); // TODO does not cope with many cases... if (e instanceof QualifiedNameReference) { QualifiedNameReference qnr = (QualifiedNameReference) e; if (qnr.binding instanceof FieldBinding) { FieldBinding fb = (FieldBinding) qnr.binding; StringBuffer sb = new StringBuffer(); sb.append(fb.declaringClass.signature()); sb.append(fb.name); return sb.toString(); } } else if (e instanceof TrueLiteral) { return "true"; } else if (e instanceof FalseLiteral) { return "false"; } else if (e instanceof StringLiteral) { return new String(((StringLiteral) e).source()); } else if (e instanceof IntLiteral) { return Integer.toString(((IntConstant) e.constant).intValue()); } else { throw new BCException("EclipseResolvedMember.getAnnotationDefaultValue() not implemented for value of type '" + e.getClass() + "' - raise an AspectJ bug !"); } } } return null; } public ResolvedType[] getAnnotationTypes() { if (cachedAnnotationTypes == null) { // long abits = realBinding.getAnnotationTagBits(); // ensure resolved Annotation[] annos = getEclipseAnnotations(); if (annos == null) { cachedAnnotationTypes = ResolvedType.EMPTY_RESOLVED_TYPE_ARRAY; } else { cachedAnnotationTypes = new ResolvedType[annos.length]; for (int i = 0; i < annos.length; i++) { Annotation type = annos[i]; cachedAnnotationTypes[i] = w.resolve(UnresolvedType.forSignature(new String(type.resolvedType.signature()))); } } } return cachedAnnotationTypes; } public String[] getParameterNames() { if (argumentNames != null) return argumentNames; if (realBinding instanceof FieldBinding) { argumentNames = NO_ARGS; } else { TypeDeclaration typeDecl = getTypeDeclaration(); AbstractMethodDeclaration methodDecl = (typeDecl == null ? null : typeDecl.declarationOf((MethodBinding) realBinding)); Argument[] args = (methodDecl == null ? null : methodDecl.arguments); // dont // like // this // - // why // isnt // the // method // found // sometimes? is it because other errors are // being reported? if (args == null) { argumentNames = NO_ARGS; } else { argumentNames = new String[args.length]; for (int i = 0; i < argumentNames.length; i++) { argumentNames[i] = new String(methodDecl.arguments[i].name); } } } return argumentNames; } private Annotation[] getEclipseAnnotations() { TypeDeclaration tDecl = getTypeDeclaration(); if (tDecl != null) {// if the code is broken then tDecl may be null if (realBinding instanceof MethodBinding) { MethodBinding methodBinding = (MethodBinding) realBinding; AbstractMethodDeclaration methodDecl = tDecl.declarationOf(methodBinding); if (methodDecl == null) { // pr284862 // bindings may have been trashed by InterTypeMemberFinder.addInterTypeMethod() - and so we need to take // a better look. Really this EclipseResolvedMember is broken... // Grab the set of bindings with matching selector MethodBinding[] mb = ((MethodBinding) realBinding).declaringClass.getMethods(methodBinding.selector); if (mb!=null) { for (int m = 0, max = mb.length; m < max; m++) { MethodBinding candidate = mb[m]; if (candidate instanceof InterTypeMethodBinding) { if (InterTypeMemberFinder.matches(mb[m], methodBinding)) { InterTypeMethodBinding intertypeMethodBinding = (InterTypeMethodBinding) candidate; Annotation[] annos = intertypeMethodBinding.sourceMethod.annotations; return annos; } } } } return null; // give up! kind of assuming here that the code has other problems (and they will be reported) } return methodDecl.annotations; } else if (realBinding instanceof FieldBinding) { FieldDeclaration fieldDecl = tDecl.declarationOf((FieldBinding) realBinding); return fieldDecl.annotations; } } return null; } private TypeDeclaration getTypeDeclaration() { if (realBinding instanceof MethodBinding) { MethodBinding mb = (MethodBinding) realBinding; if (mb != null) { SourceTypeBinding stb = (SourceTypeBinding) mb.declaringClass; if (stb != null) { ClassScope cScope = stb.scope; if (cScope != null) return cScope.referenceContext; } } } else if (realBinding instanceof FieldBinding) { FieldBinding fb = (FieldBinding) realBinding; if (fb != null) { SourceTypeBinding stb = (SourceTypeBinding) fb.declaringClass; if (stb != null) { ClassScope cScope = stb.scope; if (cScope != null) return cScope.referenceContext; } } } return null; } /** * Return true if this is the default constructor. The default constructor is the one generated if there isn't one in the * source. Eclipse helpfully uses a bit to indicate the default constructor. * * @return true if this is the default constructor. */ public boolean isDefaultConstructor() { if (!(realBinding instanceof MethodBinding)) { return false; } MethodBinding mb = (MethodBinding) realBinding; return mb.isConstructor() && ((mb.modifiers & ExtraCompilerModifiers.AccIsDefaultConstructor) != 0); } }
309,402
Bug 309402 Changes to Main.java
In order to get the AJDT ant integration working, we need a small change to Main.java. We need to be able to pass in a custom org.aspectj.bridge.ICommand object. Currently, the ICommand object is created via reflection. Here is my suggestion: 1. augment the ICommand local variable to being a field 2. add a setter for this field 3. change this: ICommand command = ReflectionFactory.makeCommand(commandName, holder); to this: if (command != null) command = ReflectionFactory.makeCommand(commandName, holder);
verified fixed
b21eb05
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-04-16T15:18:11Z"
"2010-04-15T22:20:00Z"
org.aspectj.ajdt.core/src/org/aspectj/tools/ajc/Main.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.tools.ajc; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.Arrays; import java.util.Date; import java.util.List; import org.aspectj.ajdt.internal.core.builder.AjBuildManager; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.ICommand; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IMessageHolder; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageHandler; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.ReflectionFactory; import org.aspectj.bridge.Version; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.util.FileUtil; import org.aspectj.util.LangUtil; import org.aspectj.weaver.Dump; /** * Programmatic and command-line interface to AspectJ compiler. The compiler is an ICommand obtained by reflection. Not thread-safe. * By default, messages are printed as they are emitted; info messages go to the output stream, and warnings and errors go to the * error stream. * <p> * Clients can handle all messages by registering a holder: * * <pre> * Main main = new Main(); * IMessageHolder holder = new MessageHandler(); * main.setHolder(holder); * </pre> * * Clients can get control after each command completes by installing a Runnable: * * <pre> * main.setCompletionRunner(new Runnable() {..}); * </pre> * */ public class Main { /** Header used when rendering exceptions for users */ public static final String THROWN_PREFIX = "Exception thrown from AspectJ " + Version.text + LangUtil.EOL + "" + LangUtil.EOL + "This might be logged as a bug already -- find current bugs at" + LangUtil.EOL + " http://bugs.eclipse.org/bugs/buglist.cgi?product=AspectJ&component=Compiler" + LangUtil.EOL + "" + LangUtil.EOL + "Bugs for exceptions thrown have titles File:line from the top stack, " + LangUtil.EOL + "e.g., \"SomeFile.java:243\"" + LangUtil.EOL + "" + LangUtil.EOL + "If you don't find the exception below in a bug, please add a new bug" + LangUtil.EOL + "at http://bugs.eclipse.org/bugs/enter_bug.cgi?product=AspectJ" + LangUtil.EOL + "To make the bug a priority, please include a test program" + LangUtil.EOL + "that can reproduce this exception." + LangUtil.EOL; private static final String OUT_OF_MEMORY_MSG = "AspectJ " + Version.text + " ran out of memory during compilation:" + LangUtil.EOL + LangUtil.EOL + "Please increase the memory available to ajc by editing the ajc script " + LangUtil.EOL + "found in your AspectJ installation directory. The -Xmx parameter value" + LangUtil.EOL + "should be increased from 64M (default) to 128M or even 256M." + LangUtil.EOL + LangUtil.EOL + "See the AspectJ FAQ available from the documentation link" + LangUtil.EOL + "on the AspectJ home page at http://www.eclipse.org/aspectj"; private static final String MESSAGE_HOLDER_OPTION = "-messageHolder"; /** @param args the String[] of command-line arguments */ public static void main(String[] args) throws IOException { new Main().runMain(args, true); } /** * Convenience method to run ajc and collect String lists of messages. This can be reflectively invoked with the List collecting * parameters supplied by a parent class loader. The String messages take the same form as command-line messages. * * @param args the String[] args to pass to the compiler * @param useSystemExit if true and errors, return System.exit(errs) * @param fails the List sink, if any, for String failure (or worse) messages * @param errors the List sink, if any, for String error messages * @param warnings the List sink, if any, for String warning messages * @param info the List sink, if any, for String info messages * @return number of messages reported with level ERROR or above * @throws any unchecked exceptions the compiler does */ public static int bareMain(String[] args, boolean useSystemExit, List fails, List errors, List warnings, List infos) { Main main = new Main(); MessageHandler holder = new MessageHandler(); main.setHolder(holder); try { main.runMain(args, useSystemExit); } finally { readMessages(holder, IMessage.FAIL, true, fails); readMessages(holder, IMessage.ERROR, false, errors); readMessages(holder, IMessage.WARNING, false, warnings); readMessages(holder, IMessage.INFO, false, infos); } return holder.numMessages(IMessage.ERROR, true); } /** Read messages of a given kind into a List as String */ private static void readMessages(IMessageHolder holder, IMessage.Kind kind, boolean orGreater, List sink) { if ((null == sink) || (null == holder)) { return; } IMessage[] messages = holder.getMessages(kind, orGreater); if (!LangUtil.isEmpty(messages)) { for (int i = 0; i < messages.length; i++) { sink.add(MessagePrinter.render(messages[i])); } } } /** * @return String rendering throwable as compiler error for user/console, including information on how to report as a bug. * @throws NullPointerException if thrown is null */ public static String renderExceptionForUser(Throwable thrown) { String m = thrown.getMessage(); return THROWN_PREFIX + (null != m ? m + "\n" : "") + "\n" + CompilationAndWeavingContext.getCurrentContext() + LangUtil.renderException(thrown, true); } private static String parmInArgs(String flag, String[] args) { int loc = 1 + (null == args ? -1 : Arrays.asList(args).indexOf(flag)); return ((0 == loc) || (args.length <= loc) ? null : args[loc]); } private static boolean flagInArgs(String flag, String[] args) { return ((null != args) && (Arrays.asList(args).indexOf(flag) != -1)); } /** * append nothing if numItems is 0, numItems + label + (numItems > 1? "s" : "") otherwise, prefixing with " " if sink has * content */ private static void appendNLabel(StringBuffer sink, String label, int numItems) { if (0 == numItems) { return; } if (0 < sink.length()) { sink.append(", "); } sink.append(numItems + " "); if (!LangUtil.isEmpty(label)) { sink.append(label); } if (1 < numItems) { sink.append("s"); } } /** control iteration/continuation for command (compiler) */ protected CommandController controller; /** ReflectionFactory identifier for command (compiler) */ protected String commandName; /** client-set message sink */ private IMessageHolder clientHolder; /** internally-set message sink */ protected final MessageHandler ourHandler; private int lastFails; private int lastErrors; /** if not null, run this synchronously after each compile completes */ private Runnable completionRunner; public Main() { controller = new CommandController(); commandName = ReflectionFactory.ECLIPSE; CompilationAndWeavingContext.setMultiThreaded(false); ourHandler = new MessageHandler(true); } public MessageHandler getMessageHandler() { return ourHandler; } // for unit testing... void setController(CommandController controller) { this.controller = controller; } /** * Run without throwing exceptions but optionally using System.exit(..). This sets up a message handler which emits messages * immediately, so report(boolean, IMessageHandler) only reports total number of errors or warnings. * * @param args the String[] command line for the compiler * @param useSystemExit if true, use System.exit(int) to complete unless one of the args is -noExit. and signal result (0 no * exceptions/error, <0 exceptions, >0 compiler errors). */ public void runMain(String[] args, boolean useSystemExit) { // Urk - default no check for AJDT, enabled here for Ant, command-line AjBuildManager.enableRuntimeVersionCheck(this); final boolean verbose = flagInArgs("-verbose", args); final boolean timers = flagInArgs("-timers", args); if (null == this.clientHolder) { this.clientHolder = checkForCustomMessageHolder(args); } IMessageHolder holder = clientHolder; if (null == holder) { holder = ourHandler; if (verbose) { ourHandler.setInterceptor(MessagePrinter.VERBOSE); } else { ourHandler.ignore(IMessage.INFO); ourHandler.setInterceptor(MessagePrinter.TERSE); } } // make sure we handle out of memory gracefully... try { // byte[] b = new byte[100000000]; for testing OoME only! long stime = System.currentTimeMillis(); // uncomment next line to pause before startup (attach jconsole) // try {Thread.sleep(5000); }catch(Exception e) {} run(args, holder); long etime = System.currentTimeMillis(); if (timers) { System.out.println("Compiler took " + (etime - stime) + "ms"); } holder.handleMessage(MessageUtil.info("Compiler took " + (etime - stime) + "ms")); // uncomment next line to pause at end (keeps jconsole alive!) // try { System.in.read(); } catch (Exception e) {} } catch (OutOfMemoryError outOfMemory) { IMessage outOfMemoryMessage = new Message(OUT_OF_MEMORY_MSG, null, true); holder.handleMessage(outOfMemoryMessage); systemExit(holder); // we can't reasonably continue from this point. } finally { CompilationAndWeavingContext.reset(); Dump.reset(); } boolean skipExit = false; if (useSystemExit && !LangUtil.isEmpty(args)) { // sigh - pluck -noExit for (int i = 0; i < args.length; i++) { if ("-noExit".equals(args[i])) { skipExit = true; break; } } } if (useSystemExit && !skipExit) { systemExit(holder); } } // put calls around run() call above to allowing connecting jconsole // private void pause(int ms) { // try { // System.err.println("Pausing for "+ms+"ms"); // System.gc(); // Thread.sleep(ms); // System.gc(); // System.err.println("Continuing"); // } catch (Exception e) {} // } /** * @param args */ private IMessageHolder checkForCustomMessageHolder(String[] args) { IMessageHolder holder = null; final String customMessageHolder = parmInArgs(MESSAGE_HOLDER_OPTION, args); if (customMessageHolder != null) { try { holder = (IMessageHolder) Class.forName(customMessageHolder).newInstance(); } catch (Exception ex) { holder = ourHandler; throw new AbortException("Failed to create custom message holder of class '" + customMessageHolder + "' : " + ex); } } return holder; } /** * Run without using System.exit(..), putting all messages in holder: * <ul> * <li>ERROR: compiler error</li> * <li>WARNING: compiler warning</li> * <li>FAIL: command error (bad arguments, exception thrown)</li> * </ul> * This handles incremental behavior: * <ul> * <li>If args include "-incremental", repeat for every input char until 'q' is entered. * <li> * <li>If args include "-incrementalTagFile {file}", repeat every time we detect that {file} modification time has changed.</li> * <li>Either way, list files recompiled each time if args includes "-verbose".</li> * <li>Exit when the commmand/compiler throws any Throwable.</li> * </ul> * When complete, this contains all the messages of the final run of the command and/or any FAIL messages produced in running * the command, including any Throwable thrown by the command itself. * * @param args the String[] command line for the compiler * @param holder the MessageHandler sink for messages. */ public void run(String[] args, IMessageHolder holder) { PrintStream logStream = null; FileOutputStream fos = null; String logFileName = parmInArgs("-log", args); if (null != logFileName) { File logFile = new File(logFileName); try { logFile.createNewFile(); fos = new FileOutputStream(logFileName, true); logStream = new PrintStream(fos, true); } catch (Exception e) { fail(holder, "Couldn't open log file: " + logFileName, e); } Date now = new Date(); logStream.println(now.toString()); if (flagInArgs("-verbose", args)) { ourHandler.setInterceptor(new LogModeMessagePrinter(true, logStream)); } else { ourHandler.ignore(IMessage.INFO); ourHandler.setInterceptor(new LogModeMessagePrinter(false, logStream)); } holder = ourHandler; } if (LangUtil.isEmpty(args)) { args = new String[] { "-?" }; } else if (controller.running()) { fail(holder, "already running with controller: " + controller, null); return; } args = controller.init(args, holder); if (0 < holder.numMessages(IMessage.ERROR, true)) { return; } ICommand command = ReflectionFactory.makeCommand(commandName, holder); if (0 < holder.numMessages(IMessage.ERROR, true)) { return; } try { outer: while (true) { boolean passed = command.runCommand(args, holder); if (report(passed, holder) && controller.incremental()) { while (controller.doRepeatCommand(command)) { holder.clearMessages(); if (controller.buildFresh()) { continue outer; } else { passed = command.repeatCommand(holder); } if (!report(passed, holder)) { break; } } } break; } } catch (AbortException ae) { if (ae.isSilent()) { quit(); } else { IMessage message = ae.getIMessage(); Throwable thrown = ae.getThrown(); if (null == thrown) { // toss AbortException wrapper if (null != message) { holder.handleMessage(message); } else { fail(holder, "abort without message", ae); } } else if (null == message) { fail(holder, "aborted", thrown); } else { String mssg = MessageUtil.MESSAGE_MOST.renderToString(message); fail(holder, mssg, thrown); } } } catch (Throwable t) { fail(holder, "unexpected exception", t); } finally { if (logStream != null) { logStream.close(); logStream = null; } if (fos != null) { try { fos.close(); } catch (IOException e) { fail(holder, "unexpected exception", e); } fos = null; } } } /** call this to stop after the next iteration of incremental compile */ public void quit() { controller.quit(); } /** * Set holder to be passed all messages. When holder is set, messages will not be printed by default. * * @param holder the IMessageHolder sink for all messages (use null to restore default behavior) */ public void setHolder(IMessageHolder holder) { clientHolder = holder; } public IMessageHolder getHolder() { return clientHolder; } /** * Install a Runnable to be invoked synchronously after each compile completes. * * @param runner the Runnable to invoke - null to disable */ public void setCompletionRunner(Runnable runner) { this.completionRunner = runner; } /** * Call System.exit(int) with values derived from the number of failures/aborts or errors in messages. * * @param messages the IMessageHolder to interrogate. * @param messages */ protected void systemExit(IMessageHolder messages) { int num = lastFails; // messages.numMessages(IMessage.FAIL, true); if (0 < num) { System.exit(-num); } num = lastErrors; // messages.numMessages(IMessage.ERROR, false); if (0 < num) { System.exit(num); } System.exit(0); } /** Messages to the user */ protected void outMessage(String message) { // XXX coordinate with MessagePrinter System.out.print(message); System.out.flush(); } /** * Report results from a (possibly-incremental) compile run. This delegates to any reportHandler or otherwise prints summary * counts of errors/warnings to System.err (if any errors) or System.out (if only warnings). WARNING: this silently ignores * other messages like FAIL, but clears the handler of all messages when returning true. XXX false * * This implementation ignores the pass parameter but clears the holder after reporting on the assumption messages were * handled/printed already. (ignoring UnsupportedOperationException from holder.clearMessages()). * * @param pass true result of the command * @param holder IMessageHolder with messages from the command * @see reportCommandResults(IMessageHolder) * @return false if the process should abort */ protected boolean report(boolean pass, IMessageHolder holder) { lastFails = holder.numMessages(IMessage.FAIL, true); boolean result = (0 == lastFails); final Runnable runner = completionRunner; if (null != runner) { runner.run(); } if (holder == ourHandler) { lastErrors = holder.numMessages(IMessage.ERROR, false); int warnings = holder.numMessages(IMessage.WARNING, false); StringBuffer sb = new StringBuffer(); appendNLabel(sb, "fail|abort", lastFails); appendNLabel(sb, "error", lastErrors); appendNLabel(sb, "warning", warnings); if (0 < sb.length()) { PrintStream out = (0 < (lastErrors + lastFails) ? System.err : System.out); out.println(""); // XXX "wrote class file" messages no eol? out.println(sb.toString()); } } return result; } /** convenience API to make fail messages (without MessageUtils's fail prefix) */ protected static void fail(IMessageHandler handler, String message, Throwable thrown) { handler.handleMessage(new Message(message, IMessage.FAIL, thrown, null)); } /** * interceptor IMessageHandler to print as we go. This formats all messages to the user. */ public static class MessagePrinter implements IMessageHandler { public static final IMessageHandler VERBOSE = new MessagePrinter(true); public static final IMessageHandler TERSE = new MessagePrinter(false); final boolean verbose; protected MessagePrinter(boolean verbose) { this.verbose = verbose; } /** * Print errors and warnings to System.err, and optionally info to System.out, rendering message String only. * * @return false always */ public boolean handleMessage(IMessage message) { if (null != message) { PrintStream out = getStreamFor(message.getKind()); if (null != out) { out.println(render(message)); } } return false; } /** * Render message differently. If abort, then prefix stack trace with feedback request. If the actual message is empty, then * use toString on the whole. Prefix message part with file:line; If it has context, suffix message with context. * * @param message the IMessage to render * @return String rendering IMessage (never null) */ public static String render(IMessage message) { // IMessage.Kind kind = message.getKind(); StringBuffer sb = new StringBuffer(); String text = message.getMessage(); if (text.equals(AbortException.NO_MESSAGE_TEXT)) { text = null; } boolean toString = (LangUtil.isEmpty(text)); if (toString) { text = message.toString(); } ISourceLocation loc = message.getSourceLocation(); String context = null; if (null != loc) { File file = loc.getSourceFile(); if (null != file) { String name = file.getName(); if (!toString || (-1 == text.indexOf(name))) { sb.append(FileUtil.getBestPath(file)); if (loc.getLine() > 0) { sb.append(":" + loc.getLine()); } int col = loc.getColumn(); if (0 < col) { sb.append(":" + col); } sb.append(" "); } } context = loc.getContext(); } // per Wes' suggestion on dev... if (message.getKind() == IMessage.ERROR) { sb.append("[error] "); } else if (message.getKind() == IMessage.WARNING) { sb.append("[warning] "); } sb.append(text); if (null != context) { sb.append(LangUtil.EOL); sb.append(context); } String details = message.getDetails(); if (details != null) { sb.append(LangUtil.EOL); sb.append('\t'); sb.append(details); } Throwable thrown = message.getThrown(); if (null != thrown) { sb.append(LangUtil.EOL); sb.append(Main.renderExceptionForUser(thrown)); } if (message.getExtraSourceLocations().isEmpty()) { return sb.toString(); } else { return MessageUtil.addExtraSourceLocations(message, sb.toString()); } } public boolean isIgnoring(IMessage.Kind kind) { return (null != getStreamFor(kind)); } /** * No-op * * @see org.aspectj.bridge.IMessageHandler#isIgnoring(org.aspectj.bridge.IMessage.Kind) * @param kind */ public void dontIgnore(IMessage.Kind kind) { } /** * @return System.err for FAIL, ABORT, ERROR, and WARNING, System.out for INFO if -verbose and WEAVEINFO if -showWeaveInfo. */ protected PrintStream getStreamFor(IMessage.Kind kind) { if (IMessage.WARNING.isSameOrLessThan(kind)) { return System.err; } else if (verbose && IMessage.INFO.equals(kind)) { return System.out; } else if (IMessage.WEAVEINFO.equals(kind)) { return System.out; } else { return null; } } /** * No-op * * @see org.aspectj.bridge.IMessageHandler#ignore(org.aspectj.bridge.IMessage.Kind) * @param kind */ public void ignore(Kind kind) { } } public static class LogModeMessagePrinter extends MessagePrinter { protected final PrintStream logStream; public LogModeMessagePrinter(boolean verbose, PrintStream logStream) { super(verbose); this.logStream = logStream; } protected PrintStream getStreamFor(IMessage.Kind kind) { if (IMessage.WARNING.isSameOrLessThan(kind)) { return logStream; } else if (verbose && IMessage.INFO.equals(kind)) { return logStream; } else if (IMessage.WEAVEINFO.equals(kind)) { return logStream; } else { return null; } } } /** controller for repeatable command delays until input or file changed or removed */ public static class CommandController { public static String TAG_FILE_OPTION = "-XincrementalFile"; public static String INCREMENTAL_OPTION = "-incremental"; /** maximum 10-minute delay between filesystem checks */ public static long MAX_DELAY = 1000 * 600; /** default 5-second delay between filesystem checks */ public static long DEFAULT_DELAY = 1000 * 5; /** @see init(String[]) */ private static String[][] OPTIONS = new String[][] { new String[] { INCREMENTAL_OPTION }, new String[] { TAG_FILE_OPTION, null } }; /** true between init(String[]) and doRepeatCommand() that returns false */ private boolean running; /** true after quit() called */ private boolean quit; /** true if incremental mode, waiting for input other than 'q' */ private boolean incremental; /** true if incremental mode, waiting for file to change (repeat) or disappear (quit) */ private File tagFile; /** last modification time for tagFile as of last command - 0 to start */ private long fileModTime; /** delay between filesystem checks for tagFile modification time */ private long delay; /** true just after user types 'r' for rebuild */ private boolean buildFresh; public CommandController() { delay = DEFAULT_DELAY; } /** * @param argList read and strip incremental args from this * @param sink IMessageHandler for error messages * @return String[] remainder of args */ public String[] init(String[] args, IMessageHandler sink) { running = true; // String[] unused; if (!LangUtil.isEmpty(args)) { String[][] options = LangUtil.copyStrings(OPTIONS); /* unused = */LangUtil.extractOptions(args, options); incremental = (null != options[0][0]); if (null != options[1][0]) { File file = new File(options[1][1]); if (!file.exists()) { MessageUtil.abort(sink, "tag file does not exist: " + file); } else { tagFile = file; fileModTime = tagFile.lastModified(); } } } return args; } /** * @return true if init(String[]) called but doRepeatCommand has not returned false */ public boolean running() { return running; } /** @param delay milliseconds between filesystem checks */ public void setDelay(long delay) { if ((delay > -1) && (delay < MAX_DELAY)) { this.delay = delay; } } /** @return true if INCREMENTAL_OPTION or TAG_FILE_OPTION was in args */ public boolean incremental() { return (incremental || (null != tagFile)); } /** @return true if INCREMENTAL_OPTION was in args */ public boolean commandLineIncremental() { return incremental; } public void quit() { if (!quit) { quit = true; } } /** @return true just after user typed 'r' */ boolean buildFresh() { return buildFresh; } /** @return false if we should quit, true to do another command */ boolean doRepeatCommand(ICommand command) { if (!running) { return false; } boolean result = false; if (quit) { result = false; } else if (incremental) { try { if (buildFresh) { // reset before input request buildFresh = false; } System.out.println(" press enter to recompile, r to rebuild, q to quit: "); System.out.flush(); // boolean doMore = false; // seek for one q or a series of [\n\r]... do { int input = System.in.read(); if ('q' == input) { break; // result = false; } else if ('r' == input) { buildFresh = true; result = true; } else if (('\n' == input) || ('\r' == input)) { result = true; } // else eat anything else } while (!result); System.in.skip(Integer.MAX_VALUE); } catch (IOException e) { // XXX silence for error? result = false; } } else if (null != tagFile) { long curModTime; while (true) { if (!tagFile.exists()) { result = false; break; } else if (fileModTime == (curModTime = tagFile.lastModified())) { fileCheckDelay(); } else { fileModTime = curModTime; result = true; break; } } } // else, not incremental - false if (!result && running) { running = false; } return result; } /** delay between filesystem checks, returning if quit is set */ protected void fileCheckDelay() { // final Thread thread = Thread.currentThread(); long targetTime = System.currentTimeMillis() + delay; // long curTime; while (targetTime > System.currentTimeMillis()) { if (quit) { return; } try { Thread.sleep(300); } // 1/3-second delta for quit check catch (InterruptedException e) { } } } } }
310,704
Bug 310704 Bug in ProgramElement.getCorrespondingType()
Here is the code for the method: public String getCorrespondingType(boolean getFullyQualifiedType) { String returnType = (String) kvpairs.get("returnType"); if (returnType == null) returnType = ""; if (getFullyQualifiedType) { return returnType; } int index = returnType.lastIndexOf("."); if (index != -1) { return returnType.substring(index); } return returnType; } the line: return returnType.substring(index); should be using 'index+1'
resolved fixed
a502da8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-04-28T01:05:35Z"
"2010-04-27T20:26:40Z"
asm/src/org/aspectj/asm/internal/ProgramElement.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Mik Kersten initial implementation * Andy Clement Extensions for better IDE representation * ******************************************************************/ package org.aspectj.asm.internal; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.asm.AsmManager; import org.aspectj.asm.HierarchyWalker; import org.aspectj.asm.IProgramElement; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; /** * @author Mik Kersten */ public class ProgramElement implements IProgramElement { public transient AsmManager asm; // which structure model is this node part of private static final long serialVersionUID = 171673495267384449L; public static boolean shortITDNames = true; private final static String UNDEFINED = "<undefined>"; private final static int AccPublic = 0x0001; private final static int AccPrivate = 0x0002; private final static int AccProtected = 0x0004; private final static int AccPrivileged = 0x0006; // XXX is this right? private final static int AccStatic = 0x0008; private final static int AccFinal = 0x0010; private final static int AccSynchronized = 0x0020; private final static int AccVolatile = 0x0040; private final static int AccTransient = 0x0080; private final static int AccNative = 0x0100; private final static int AccInterface = 0x0200; private final static int AccAbstract = 0x0400; private final static int AccStrictfp = 0x0800; protected String name; private Kind kind; protected IProgramElement parent = null; protected List children = Collections.EMPTY_LIST; public Map kvpairs = Collections.EMPTY_MAP; protected ISourceLocation sourceLocation = null; public int modifiers; private String handle = null; // --- ctors public AsmManager getModel() { return asm; } /** Used during de-externalization */ public ProgramElement() { int stop = 1; } /** Use to create program element nodes that do not correspond to source locations */ public ProgramElement(AsmManager asm, String name, Kind kind, List children) { this.asm = asm; if (asm == null && !name.equals("<build to view structure>")) { throw new RuntimeException(); } this.name = name; this.kind = kind; if (children != null) setChildren(children); } public ProgramElement(AsmManager asm, String name, IProgramElement.Kind kind, ISourceLocation sourceLocation, int modifiers, String comment, List children) { this(asm, name, kind, children); this.sourceLocation = sourceLocation; setFormalComment(comment); // if (comment!=null && comment.length()>0) formalComment = comment; this.modifiers = modifiers; } // /** // * Use to create program element nodes that correspond to source locations. // */ // public ProgramElement( // String name, // Kind kind, // int modifiers, // //Accessibility accessibility, // String declaringType, // String packageName, // String comment, // ISourceLocation sourceLocation, // List relations, // List children, // boolean member) { // // this(name, kind, children); // this.sourceLocation = sourceLocation; // this.kind = kind; // this.modifiers = modifiers; // setDeclaringType(declaringType);//this.declaringType = declaringType; // //this.packageName = packageName; // setFormalComment(comment); // // if (comment!=null && comment.length()>0) formalComment = comment; // if (relations!=null && relations.size()!=0) setRelations(relations); // // this.relations = relations; // } public int getRawModifiers() { return this.modifiers; } public List getModifiers() { return genModifiers(this.modifiers); } public Accessibility getAccessibility() { return genAccessibility(this.modifiers); } public void setDeclaringType(String t) { if (t != null && t.length() > 0) { if (kvpairs == Collections.EMPTY_MAP) kvpairs = new HashMap(); kvpairs.put("declaringType", t); } } public String getDeclaringType() { String dt = (String) kvpairs.get("declaringType"); if (dt == null) return ""; // assumption that not having one means "" is at HtmlDecorator line 111 return dt; } public String getPackageName() { if (kind == Kind.PACKAGE) return getName(); if (getParent() == null) { return ""; } return getParent().getPackageName(); } public Kind getKind() { return kind; } public boolean isCode() { return kind.equals(Kind.CODE); } public ISourceLocation getSourceLocation() { return sourceLocation; } // not really sure why we have this setter ... how can we be in the situation where we didn't // know the location when we built the node but we learned it later on? public void setSourceLocation(ISourceLocation sourceLocation) { // this.sourceLocation = sourceLocation; } public IMessage getMessage() { return (IMessage) kvpairs.get("message"); // return message; } public void setMessage(IMessage message) { if (kvpairs == Collections.EMPTY_MAP) kvpairs = new HashMap(); kvpairs.put("message", message); // this.message = message; } public IProgramElement getParent() { return parent; } public void setParent(IProgramElement parent) { this.parent = parent; } public boolean isMemberKind() { return kind.isMember(); } public void setRunnable(boolean value) { if (kvpairs == Collections.EMPTY_MAP) kvpairs = new HashMap(); if (value) kvpairs.put("isRunnable", "true"); else kvpairs.remove("isRunnable"); // this.runnable = value; } public boolean isRunnable() { return kvpairs.get("isRunnable") != null; // return runnable; } public boolean isImplementor() { return kvpairs.get("isImplementor") != null; // return implementor; } public void setImplementor(boolean value) { if (kvpairs == Collections.EMPTY_MAP) kvpairs = new HashMap(); if (value) kvpairs.put("isImplementor", "true"); else kvpairs.remove("isImplementor"); // this.implementor = value; } public boolean isOverrider() { return kvpairs.get("isOverrider") != null; // return overrider; } public void setOverrider(boolean value) { if (kvpairs == Collections.EMPTY_MAP) kvpairs = new HashMap(); if (value) kvpairs.put("isOverrider", "true"); else kvpairs.remove("isOverrider"); // this.overrider = value; } public List getRelations() { return (List) kvpairs.get("relations"); // return relations; } public void setRelations(List relations) { if (relations.size() > 0) { if (kvpairs == Collections.EMPTY_MAP) kvpairs = new HashMap(); kvpairs.put("relations", relations); // this.relations = relations; } } public String getFormalComment() { return (String) kvpairs.get("formalComment"); // return formalComment; } public String toString() { return toLabelString(); } private static List genModifiers(int modifiers) { List modifiersList = new ArrayList(); if ((modifiers & AccStatic) != 0) modifiersList.add(IProgramElement.Modifiers.STATIC); if ((modifiers & AccFinal) != 0) modifiersList.add(IProgramElement.Modifiers.FINAL); if ((modifiers & AccSynchronized) != 0) modifiersList.add(IProgramElement.Modifiers.SYNCHRONIZED); if ((modifiers & AccVolatile) != 0) modifiersList.add(IProgramElement.Modifiers.VOLATILE); if ((modifiers & AccTransient) != 0) modifiersList.add(IProgramElement.Modifiers.TRANSIENT); if ((modifiers & AccNative) != 0) modifiersList.add(IProgramElement.Modifiers.NATIVE); if ((modifiers & AccAbstract) != 0) modifiersList.add(IProgramElement.Modifiers.ABSTRACT); return modifiersList; } public static IProgramElement.Accessibility genAccessibility(int modifiers) { if ((modifiers & AccPublic) != 0) return IProgramElement.Accessibility.PUBLIC; if ((modifiers & AccPrivate) != 0) return IProgramElement.Accessibility.PRIVATE; if ((modifiers & AccProtected) != 0) return IProgramElement.Accessibility.PROTECTED; if ((modifiers & AccPrivileged) != 0) return IProgramElement.Accessibility.PRIVILEGED; else return IProgramElement.Accessibility.PACKAGE; } public String getBytecodeName() { String s = (String) kvpairs.get("bytecodeName"); if (s == null) { return UNDEFINED; } return s; } public void setBytecodeName(String s) { if (kvpairs == Collections.EMPTY_MAP) kvpairs = new HashMap(); kvpairs.put("bytecodeName", s); } public void setBytecodeSignature(String s) { initMap(); // Different kinds of format here. The one worth compressing starts with a '(': // (La/b/c/D;Le/f/g/G;)Ljava/lang/String; // maybe want to avoid generics initially. // boolean worthCompressing = s.charAt(0) == '(' && s.indexOf('<') == -1 && s.indexOf('P') == -1; // starts parentheses and // no // // generics // if (worthCompressing) { // kvpairs.put("bytecodeSignatureCompressed", asm.compress(s)); // } else { kvpairs.put("bytecodeSignature", s); // } } public String getBytecodeSignature() { String s = (String) kvpairs.get("bytecodeSignature"); // if (s == null) { // List compressed = (List) kvpairs.get("bytecodeSignatureCompressed"); // if (compressed != null) { // return asm.decompress(compressed, '/'); // } // } // if (s==null) return UNDEFINED; return s; } private void initMap() { if (kvpairs == Collections.EMPTY_MAP) { kvpairs = new HashMap(); } } public String getSourceSignature() { return (String) kvpairs.get("sourceSignature"); } public void setSourceSignature(String string) { if (kvpairs == Collections.EMPTY_MAP) kvpairs = new HashMap(); // System.err.println(name+" SourceSig=>"+string); kvpairs.put("sourceSignature", string); // sourceSignature = string; } public void setKind(Kind kind) { this.kind = kind; } public void setCorrespondingType(String s) { if (kvpairs == Collections.EMPTY_MAP) kvpairs = new HashMap(); kvpairs.put("returnType", s); // this.returnType = s; } public void setParentTypes(List ps) { if (kvpairs == Collections.EMPTY_MAP) kvpairs = new HashMap(); kvpairs.put("parentTypes", ps); } public List getParentTypes() { return (List) (kvpairs == null ? null : kvpairs.get("parentTypes")); } /** * {@inheritDoc} */ public void setAnnotationType(String fullyQualifiedAnnotationType) { if (kvpairs == Collections.EMPTY_MAP) { kvpairs = new HashMap(); } kvpairs.put("annotationType", fullyQualifiedAnnotationType); } /** * {@inheritDoc} */ public String getAnnotationType() { return (String) (kvpairs == null ? null : kvpairs.get("annotationType")); } public String getCorrespondingType() { return getCorrespondingType(false); } public String getCorrespondingType(boolean getFullyQualifiedType) { String returnType = (String) kvpairs.get("returnType"); if (returnType == null) returnType = ""; if (getFullyQualifiedType) { return returnType; } int index = returnType.lastIndexOf("."); if (index != -1) { return returnType.substring(index); } return returnType; } public String getName() { return name; } public List getChildren() { return children; } public void setChildren(List children) { this.children = children; if (children == null) return; for (Iterator it = children.iterator(); it.hasNext();) { ((IProgramElement) it.next()).setParent(this); } } public void addChild(IProgramElement child) { if (children == null || children == Collections.EMPTY_LIST) children = new ArrayList(); children.add(child); child.setParent(this); } public void addChild(int position, IProgramElement child) { if (children == null || children == Collections.EMPTY_LIST) children = new ArrayList(); children.add(position, child); child.setParent(this); } public boolean removeChild(IProgramElement child) { child.setParent(null); return children.remove(child); } public void setName(String string) { name = string; } public IProgramElement walk(HierarchyWalker walker) { if (children != null) { for (Iterator it = children.iterator(); it.hasNext();) { IProgramElement child = (IProgramElement) it.next(); walker.process(child); } } return this; } public String toLongString() { final StringBuffer buffer = new StringBuffer(); HierarchyWalker walker = new HierarchyWalker() { private int depth = 0; public void preProcess(IProgramElement node) { for (int i = 0; i < depth; i++) buffer.append(' '); buffer.append(node.toString()); buffer.append('\n'); depth += 2; } public void postProcess(IProgramElement node) { depth -= 2; } }; walker.process(this); return buffer.toString(); } public void setModifiers(int i) { this.modifiers = i; } /** * Convenience mechanism for setting new modifiers which do not require knowledge of the private internal representation * * @param newModifier */ public void addModifiers(IProgramElement.Modifiers newModifier) { modifiers |= newModifier.getBit(); } public String toSignatureString() { return toSignatureString(true); } public String toSignatureString(boolean getFullyQualifiedArgTypes) { StringBuffer sb = new StringBuffer(); sb.append(name); List ptypes = getParameterTypes(); if (ptypes != null && (!ptypes.isEmpty() || this.kind.equals(IProgramElement.Kind.METHOD)) || this.kind.equals(IProgramElement.Kind.CONSTRUCTOR) || this.kind.equals(IProgramElement.Kind.ADVICE) || this.kind.equals(IProgramElement.Kind.POINTCUT) || this.kind.equals(IProgramElement.Kind.INTER_TYPE_METHOD) || this.kind.equals(IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR)) { sb.append('('); for (Iterator it = ptypes.iterator(); it.hasNext();) { char[] arg = (char[]) it.next(); if (getFullyQualifiedArgTypes) { sb.append(arg); } else { int index = CharOperation.lastIndexOf('.', arg); if (index != -1) { sb.append(CharOperation.subarray(arg, index + 1, arg.length)); } else { sb.append(arg); } } if (it.hasNext()) sb.append(","); } sb.append(')'); } return sb.toString(); } /** * TODO: move the "parent != null"==>injar heuristic to more explicit */ public String toLinkLabelString() { return toLinkLabelString(true); } public String toLinkLabelString(boolean getFullyQualifiedArgTypes) { String label; if (kind == Kind.CODE || kind == Kind.INITIALIZER) { label = parent.getParent().getName() + ": "; } else if (kind.isInterTypeMember()) { if (shortITDNames) { // if (name.indexOf('.')!=-1) return toLabelString().substring(name.indexOf('.')+1); label = ""; } else { int dotIndex = name.indexOf('.'); if (dotIndex != -1) { return parent.getName() + ": " + toLabelString().substring(dotIndex + 1); } else { label = parent.getName() + '.'; } } } else if (kind == Kind.CLASS || kind == Kind.ASPECT || kind == Kind.INTERFACE) { label = ""; } else if (kind.equals(Kind.DECLARE_PARENTS)) { label = ""; } else { if (parent != null) { label = parent.getName() + '.'; } else { label = "injar aspect: "; } } label += toLabelString(getFullyQualifiedArgTypes); return label; } public String toLabelString() { return toLabelString(true); } public String toLabelString(boolean getFullyQualifiedArgTypes) { String label = toSignatureString(getFullyQualifiedArgTypes); String details = getDetails(); if (details != null) { label += ": " + details; } return label; } public String getHandleIdentifier() { return getHandleIdentifier(true); } public String getHandleIdentifier(boolean create) { String h = handle; if (null == handle && create) { if (asm == null && name.equals("<build to view structure>")) { h = "<build to view structure>"; } else { try { h = asm.getHandleProvider().createHandleIdentifier(this); } catch (ArrayIndexOutOfBoundsException aioobe) { throw new RuntimeException("AIOOBE whilst building handle for " + this, aioobe); } } } setHandleIdentifier(h); return h; } public void setHandleIdentifier(String handle) { this.handle = handle; } public List getParameterNames() { List parameterNames = (List) kvpairs.get("parameterNames"); return parameterNames; } public void setParameterNames(List list) { if (list == null || list.size() == 0) return; if (kvpairs == Collections.EMPTY_MAP) kvpairs = new HashMap(); kvpairs.put("parameterNames", list); // parameterNames = list; } public List getParameterTypes() { List l = getParameterSignatures(); if (l == null || l.isEmpty()) { return Collections.EMPTY_LIST; } List params = new ArrayList(); for (Iterator iter = l.iterator(); iter.hasNext();) { char[] param = (char[]) iter.next(); params.add(NameConvertor.convertFromSignature(param)); } return params; } public List getParameterSignatures() { List parameters = (List) kvpairs.get("parameterSigs"); return parameters; } public List getParameterSignaturesSourceRefs() { List parameters = (List) kvpairs.get("parameterSigsSourceRefs"); return parameters; } /** * Set the parameter signatures for this method/constructor. The bit flags tell us if any were not singletypereferences in the * the source. A singletypereference would be 'String' - whilst a qualifiedtypereference would be 'java.lang.String' - this has * an effect on the handles. */ public void setParameterSignatures(List list, List sourceRefs) { if (kvpairs == Collections.EMPTY_MAP) { kvpairs = new HashMap(); } if (list == null || list.size() == 0) { kvpairs.put("parameterSigs", Collections.EMPTY_LIST); } else { kvpairs.put("parameterSigs", list); } if (sourceRefs != null && sourceRefs.size() != 0) { kvpairs.put("parameterSigsSourceRefs", sourceRefs); } } public String getDetails() { String details = (String) kvpairs.get("details"); return details; } public void setDetails(String string) { if (kvpairs == Collections.EMPTY_MAP) kvpairs = new HashMap(); kvpairs.put("details", string); } public void setFormalComment(String txt) { if (txt != null && txt.length() > 0) { if (kvpairs == Collections.EMPTY_MAP) kvpairs = new HashMap(); kvpairs.put("formalComment", txt); } } public void setExtraInfo(ExtraInformation info) { if (kvpairs == Collections.EMPTY_MAP) kvpairs = new HashMap(); kvpairs.put("ExtraInformation", info); } public ExtraInformation getExtraInfo() { return (ExtraInformation) kvpairs.get("ExtraInformation"); } public boolean isAnnotationStyleDeclaration() { return kvpairs.get("annotationStyleDeclaration") != null; } public void setAnnotationStyleDeclaration(boolean b) { if (b) { if (kvpairs == Collections.EMPTY_MAP) { kvpairs = new HashMap(); } kvpairs.put("annotationStyleDeclaration", "true"); } } }
310,144
Bug 310144 java.lang.RuntimeException at AsmManager.java:1143
Build Identifier: Eclipse AspectJ Development Tools Version: 2.0.3.e35x-20100419-1200 AspectJ version: 1.6.9.20100416110000 java.lang.RuntimeException at org.aspectj.asm.AsmManager.removeSingleNode(AsmManager.java:1143) at org.aspectj.asm.AsmManager.removeRelationshipsTargettingThisType(AsmManager.java:798) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1173) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.weaveQueuedEntries(AjPipeliningCompilerAdapter.java:455) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter. ... for handle =xstm/stm<com.argilsoft.xstm.core{TKeyed.java[TKeyed[Visitor?field-set(java.util.ArrayList com.argilsoft.xstm.core.Visitor._continueStack) Reproducible: Sometimes Steps to Reproduce: Random exception popup in Eclipse
resolved fixed
728ecb8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-04-29T19:54:09Z"
"2010-04-22T15:26:40Z"
asm/src/org/aspectj/asm/AsmManager.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Mik Kersten initial implementation * Andy Clement incremental support and switch on/off state * ******************************************************************/ package org.aspectj.asm; import java.io.BufferedWriter; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.aspectj.asm.internal.AspectJElementHierarchy; import org.aspectj.asm.internal.HandleProviderDelimiter; import org.aspectj.asm.internal.JDTLikeHandleProvider; import org.aspectj.asm.internal.RelationshipMap; import org.aspectj.bridge.ISourceLocation; import org.aspectj.util.IStructureModel; /** * The Abstract Structure Model (ASM) represents the containment hierarchy and crosscutting structure map for AspectJ programs. It * is used by IDE views such as the document outline, and by other tools such as ajdoc to show both AspectJ declarations and * crosscutting links, such as which advice affects which join point shadows. * * @author Mik Kersten * @author Andy Clement */ public class AsmManager implements IStructureModel { // For testing ONLY public static boolean recordingLastActiveStructureModel = true; public static AsmManager lastActiveStructureModel; public static boolean forceSingletonBehaviour = false; // SECRETAPI asc pull the secret options together into a system API you lazy fool public static boolean attemptIncrementalModelRepairs = false; // Dumping the model is expensive public static boolean dumpModelPostBuild = false; // For offline debugging, you can now ask for the AsmManager to // dump the model - see the method setReporting() private static boolean dumpModel = false; private static boolean dumpRelationships = false; private static boolean dumpDeltaProcessing = false; private static IModelFilter modelFilter = null; private static String dumpFilename = ""; private static boolean reporting = false; private static boolean completingTypeBindings = false; private final List structureListeners = new ArrayList(); // The model is 'manipulated' by the AjBuildManager.setupModel() code which // trashes all the // fields when setting up a new model for a batch build. // Due to the requirements of incremental compilation we need to tie some of // the info // below to the AjState for a compilation and recover it if switching // between projects. protected IHierarchy hierarchy; /* * Map from String > String - it maps absolute paths for inpath dirs/jars to workspace relative paths suitable for handle * inclusion */ protected Map inpathMap; private IRelationshipMap mapper; private IElementHandleProvider handleProvider; private final CanonicalFilePathMap canonicalFilePathMap = new CanonicalFilePathMap(); // Record the Set<File> for which the model has been modified during the // last incremental build private final Set lastBuildChanges = new HashSet(); // Record the Set<File> of aspects that wove the files listed in lastBuildChanges final Set aspectsWeavingInLastBuild = new HashSet(); // static { // setReporting("c:/model.nfo",true,true,true,true); // } private AsmManager() { } public static AsmManager createNewStructureModel(Map inpathMap) { if (forceSingletonBehaviour && lastActiveStructureModel != null) { return lastActiveStructureModel; } AsmManager asm = new AsmManager(); asm.inpathMap = inpathMap; asm.hierarchy = new AspectJElementHierarchy(asm); asm.mapper = new RelationshipMap(asm.hierarchy); asm.handleProvider = new JDTLikeHandleProvider(asm); // call initialize on the handleProvider when we create a new ASM // to give handleProviders the chance to reset any state asm.handleProvider.initialize(); asm.resetDeltaProcessing(); setLastActiveStructureModel(asm); return asm; } public IHierarchy getHierarchy() { return hierarchy; } public IRelationshipMap getRelationshipMap() { return mapper; } public void fireModelUpdated() { notifyListeners(); if (dumpModelPostBuild && hierarchy.getConfigFile() != null) { writeStructureModel(hierarchy.getConfigFile()); } } /** * Constructs map each time it's called. */ public HashMap getInlineAnnotations(String sourceFile, boolean showSubMember, boolean showMemberAndType) { if (!hierarchy.isValid()) { return null; } HashMap annotations = new HashMap(); IProgramElement node = hierarchy.findElementForSourceFile(sourceFile); if (node == IHierarchy.NO_STRUCTURE) { return null; } else { IProgramElement fileNode = node; ArrayList peNodes = new ArrayList(); getAllStructureChildren(fileNode, peNodes, showSubMember, showMemberAndType); for (Iterator it = peNodes.iterator(); it.hasNext();) { IProgramElement peNode = (IProgramElement) it.next(); List entries = new ArrayList(); entries.add(peNode); ISourceLocation sourceLoc = peNode.getSourceLocation(); if (null != sourceLoc) { Integer hash = new Integer(sourceLoc.getLine()); List existingEntry = (List) annotations.get(hash); if (existingEntry != null) { entries.addAll(existingEntry); } annotations.put(hash, entries); } } return annotations; } } private void getAllStructureChildren(IProgramElement node, List result, boolean showSubMember, boolean showMemberAndType) { List children = node.getChildren(); if (node.getChildren() == null) { return; } for (Iterator it = children.iterator(); it.hasNext();) { IProgramElement next = (IProgramElement) it.next(); List rels = mapper.get(next); if (next != null && ((next.getKind() == IProgramElement.Kind.CODE && showSubMember) || (next.getKind() != IProgramElement.Kind.CODE && showMemberAndType)) && rels != null && rels.size() > 0) { result.add(next); } getAllStructureChildren(next, result, showSubMember, showMemberAndType); } } public void addListener(IHierarchyListener listener) { structureListeners.add(listener); } public void removeStructureListener(IHierarchyListener listener) { structureListeners.remove(listener); } // this shouldn't be needed - but none of the people that add listeners // in the test suite ever remove them. AMC added this to be called in // setup() so that the test cases would cease leaking listeners and go // back to executing at a reasonable speed. public void removeAllListeners() { structureListeners.clear(); } private void notifyListeners() { for (Iterator it = structureListeners.iterator(); it.hasNext();) { ((IHierarchyListener) it.next()).elementsUpdated(hierarchy); } } public IElementHandleProvider getHandleProvider() { return handleProvider; } public void setHandleProvider(IElementHandleProvider handleProvider) { this.handleProvider = handleProvider; } public void writeStructureModel(String configFilePath) { try { String filePath = genExternFilePath(configFilePath); FileOutputStream fos = new FileOutputStream(filePath); ObjectOutputStream s = new ObjectOutputStream(fos); s.writeObject(hierarchy); // Store the program element tree s.writeObject(mapper); // Store the relationships s.flush(); fos.flush(); fos.close(); s.close(); } catch (IOException e) { // System.err.println("AsmManager: Unable to write structure model: " // +configFilePath+" because of:"); // e.printStackTrace(); } } /** * @param configFilePath path to an ".lst" file */ public void readStructureModel(String configFilePath) { boolean hierarchyReadOK = false; try { if (configFilePath == null) { hierarchy.setRoot(IHierarchy.NO_STRUCTURE); } else { String filePath = genExternFilePath(configFilePath); FileInputStream in = new FileInputStream(filePath); ObjectInputStream s = new ObjectInputStream(in); hierarchy = (AspectJElementHierarchy) s.readObject(); ((AspectJElementHierarchy) hierarchy).setAsmManager(this); hierarchyReadOK = true; mapper = (RelationshipMap) s.readObject(); ((RelationshipMap) mapper).setHierarchy(hierarchy); } } catch (FileNotFoundException fnfe) { // That is OK hierarchy.setRoot(IHierarchy.NO_STRUCTURE); } catch (EOFException eofe) { // Might be an old format sym file that is missing its relationships if (!hierarchyReadOK) { System.err.println("AsmManager: Unable to read structure model: " + configFilePath + " because of:"); eofe.printStackTrace(); hierarchy.setRoot(IHierarchy.NO_STRUCTURE); } } catch (Exception e) { // System.err.println("AsmManager: Unable to read structure model: "+ // configFilePath+" because of:"); // e.printStackTrace(); hierarchy.setRoot(IHierarchy.NO_STRUCTURE); } finally { notifyListeners(); } } private String genExternFilePath(String configFilePath) { // sometimes don't have ".lst" if (configFilePath.lastIndexOf(".lst") != -1) { configFilePath = configFilePath.substring(0, configFilePath.lastIndexOf(".lst")); } return configFilePath + ".ajsym"; } public String getCanonicalFilePath(File f) { return canonicalFilePathMap.get(f); } private static class CanonicalFilePathMap { private static final int MAX_SIZE = 4000; private final Map pathMap = new HashMap(20); // // guards to ensure correctness and liveness // private boolean cacheInUse = false; // private boolean stopRequested = false; // // private synchronized boolean isCacheInUse() { // return cacheInUse; // } // // private synchronized void setCacheInUse(boolean val) { // cacheInUse = val; // if (val) { // notifyAll(); // } // } // // private synchronized boolean isStopRequested() { // return stopRequested; // } // // private synchronized void requestStop() { // stopRequested = true; // } // // /** // * Begin prepopulating the map by adding an entry from // * file.getPath -> file.getCanonicalPath for each file in // * the list. Do this on a background thread. // * @param files // */ // public void prepopulate(final List files) { // stopRequested = false; // setCacheInUse(false); // if (pathMap.size() > MAX_SIZE) { // pathMap.clear(); // } // new Thread() { // public void run() { // System.out.println("Starting cache population: " + // System.currentTimeMillis()); // Iterator it = files.iterator(); // while (!isStopRequested() && it.hasNext()) { // File f = (File)it.next(); // if (pathMap.get(f.getPath()) == null) { // // may reuse cache across compiles from ides... // try { // pathMap.put(f.getPath(),f.getCanonicalPath()); // } catch (IOException ex) { // pathMap.put(f.getPath(),f.getPath()); // } // } // } // System.out.println("Cached " + files.size()); // setCacheInUse(true); // System.out.println("Cache populated: " + System.currentTimeMillis()); // } // }.start(); // } // // /** // * Stop pre-populating the cache - our customers are ready to use it. // * If there are any cache misses from this point on, we'll populate // the // * cache as we go. // * The handover is done this way to ensure that only one thread is // ever // * accessing the cache, and that we minimize synchronization. // */ // public synchronized void handover() { // if (!isCacheInUse()) { // requestStop(); // try { // while (!isCacheInUse()) wait(); // } catch (InterruptedException intEx) { } // just continue // } // } public String get(File f) { // if (!cacheInUse) { // unsynchronized test - should never be // parallel // // threads at this point // throw new IllegalStateException( // "Must take ownership of cache before using by calling " + // "handover()"); // } String ret = (String) pathMap.get(f.getPath()); if (ret == null) { try { ret = f.getCanonicalPath(); } catch (IOException ioEx) { ret = f.getPath(); } pathMap.put(f.getPath(), ret); if (pathMap.size() > MAX_SIZE) { pathMap.clear(); } } return ret; } } // SECRETAPI public static void setReporting(String filename, boolean dModel, boolean dRels, boolean dDeltaProcessing, boolean deletefile) { reporting = true; dumpModel = dModel; dumpRelationships = dRels; dumpDeltaProcessing = dDeltaProcessing; if (deletefile) { new File(filename).delete(); } dumpFilename = filename; } public static void setReporting(String filename, boolean dModel, boolean dRels, boolean dDeltaProcessing, boolean deletefile, IModelFilter aFilter) { setReporting(filename, dModel, dRels, dDeltaProcessing, deletefile); modelFilter = aFilter; } public static boolean isReporting() { return reporting; } public static void setDontReport() { reporting = false; dumpDeltaProcessing = false; dumpModel = false; dumpRelationships = false; } // NB. If the format of this report changes then the model tests // (@see org.aspectj.systemtest.model.ModelTestCase) will fail in // their comparison. The tests are assuming that both the model // and relationship map are reported and as a consequence single // testcases test that both the model and relationship map are correct. public void reportModelInfo(String reasonForReport) { if (!dumpModel && !dumpRelationships) { return; } try { FileWriter fw = new FileWriter(dumpFilename, true); BufferedWriter bw = new BufferedWriter(fw); if (dumpModel) { bw.write("=== MODEL STATUS REPORT ========= " + reasonForReport + "\n"); dumptree(bw, hierarchy.getRoot(), 0); bw.write("=== END OF MODEL REPORT =========\n"); } if (dumpRelationships) { bw.write("=== RELATIONSHIPS REPORT ========= " + reasonForReport + "\n"); dumprels(bw); bw.write("=== END OF RELATIONSHIPS REPORT ==\n"); } Properties p = summarizeModel().getProperties(); Enumeration pkeyenum = p.keys(); bw.write("=== Properties of the model and relationships map =====\n"); while (pkeyenum.hasMoreElements()) { String pkey = (String) pkeyenum.nextElement(); bw.write(pkey + "=" + p.getProperty(pkey) + "\n"); } bw.flush(); fw.close(); } catch (IOException e) { System.err.println("InternalError: Unable to report model information:"); e.printStackTrace(); } } public static void dumptree(Writer w, IProgramElement node, int indent) throws IOException { for (int i = 0; i < indent; i++) { w.write(" "); } String loc = ""; if (node != null) { if (node.getSourceLocation() != null) { loc = node.getSourceLocation().toString(); if (modelFilter != null) { loc = modelFilter.processFilelocation(loc); } } } w.write(node + " [" + (node == null ? "null" : node.getKind().toString()) + "] " + loc + "\n"); if (node != null) { for (Iterator i = node.getChildren().iterator(); i.hasNext();) { dumptree(w, (IProgramElement) i.next(), indent + 2); } } } public static void dumptree(IProgramElement node, int indent) throws IOException { for (int i = 0; i < indent; i++) { System.out.print(" "); } String loc = ""; if (node != null) { if (node.getSourceLocation() != null) { loc = node.getSourceLocation().toString(); } } System.out.println(node + " [" + (node == null ? "null" : node.getKind().toString()) + "] " + loc); if (node != null) { for (Iterator i = node.getChildren().iterator(); i.hasNext();) { dumptree((IProgramElement) i.next(), indent + 2); } } } public void dumprels(Writer w) throws IOException { int ctr = 1; Set entries = mapper.getEntries(); for (Iterator iter = entries.iterator(); iter.hasNext();) { String hid = (String) iter.next(); List rels = mapper.get(hid); for (Iterator iterator = rels.iterator(); iterator.hasNext();) { IRelationship ir = (IRelationship) iterator.next(); List targets = ir.getTargets(); for (Iterator iterator2 = targets.iterator(); iterator2.hasNext();) { String thid = (String) iterator2.next(); StringBuffer sb = new StringBuffer(); if (modelFilter == null || modelFilter.wantsHandleIds()) { sb.append("Hid:" + (ctr++) + ":"); } sb.append("(targets=" + targets.size() + ") " + hid + " (" + ir.getName() + ") " + thid + "\n"); w.write(sb.toString()); } } } } private void dumprelsStderr(String key) { System.err.println("Relationships dump follows: " + key); int ctr = 1; Set entries = mapper.getEntries(); for (Iterator iter = entries.iterator(); iter.hasNext();) { String hid = (String) iter.next(); List rels = mapper.get(hid); for (Iterator iterator = rels.iterator(); iterator.hasNext();) { IRelationship ir = (IRelationship) iterator.next(); List targets = ir.getTargets(); for (Iterator iterator2 = targets.iterator(); iterator2.hasNext();) { String thid = (String) iterator2.next(); System.err.println("Hid:" + (ctr++) + ":(targets=" + targets.size() + ") " + hid + " (" + ir.getName() + ") " + thid); } } } System.err.println("End of relationships dump for: " + key); } // ===================== DELTA PROCESSING CODE ============== start // ==========// /** * Removes the hierarchy structure for the specified files from the structure model. Returns true if it deleted anything */ public boolean removeStructureModelForFiles(Writer fw, Collection files) throws IOException { boolean modelModified = false; Set deletedNodes = new HashSet(); for (Iterator iter = files.iterator(); iter.hasNext();) { File fileForCompilation = (File) iter.next(); String correctedPath = getCanonicalFilePath(fileForCompilation); IProgramElement progElem = (IProgramElement) hierarchy.findInFileMap(correctedPath); if (progElem != null) { // Found it, let's remove it if (dumpDeltaProcessing) { fw.write("Deleting " + progElem + " node for file " + fileForCompilation + "\n"); } removeNode(progElem); lastBuildChanges.add(fileForCompilation); deletedNodes.add(getCanonicalFilePath(progElem.getSourceLocation().getSourceFile())); if (!hierarchy.removeFromFileMap(correctedPath)) { throw new RuntimeException("Whilst repairing model, couldn't remove entry for file: " + correctedPath + " from the filemap"); } modelModified = true; } } if (modelModified) { hierarchy.updateHandleMap(deletedNodes); } return modelModified; } // This code is *SLOW* but it isnt worth fixing until we address the // bugs in binary weaving. public void fixupStructureModel(Writer fw, List filesToBeCompiled, Set files_added, Set files_deleted) throws IOException { // Three kinds of things to worry about: // 1. New files have been added since the last compile // 2. Files have been deleted since the last compile // 3. Files have 'changed' since the last compile (really just those in // config.getFiles()) // List files = config.getFiles(); boolean modelModified = false; // Files to delete are: those to be compiled + those that have been // deleted Set filesToRemoveFromStructureModel = new HashSet(filesToBeCompiled); filesToRemoveFromStructureModel.addAll(files_deleted); Set deletedNodes = new HashSet(); for (Iterator iter = filesToRemoveFromStructureModel.iterator(); iter.hasNext();) { File fileForCompilation = (File) iter.next(); String correctedPath = getCanonicalFilePath(fileForCompilation); IProgramElement progElem = (IProgramElement) hierarchy.findInFileMap(correctedPath); if (progElem != null) { // Found it, let's remove it if (dumpDeltaProcessing) { fw.write("Deleting " + progElem + " node for file " + fileForCompilation + "\n"); } removeNode(progElem); deletedNodes.add(getCanonicalFilePath(progElem.getSourceLocation().getSourceFile())); if (!hierarchy.removeFromFileMap(correctedPath)) { throw new RuntimeException("Whilst repairing model, couldn't remove entry for file: " + correctedPath + " from the filemap"); } modelModified = true; } } if (modelModified) { hierarchy.flushTypeMap(); hierarchy.updateHandleMap(deletedNodes); } } public void processDelta(Collection files_tobecompiled, Set files_added, Set files_deleted) { try { Writer fw = null; // Are we recording this ? if (dumpDeltaProcessing) { FileWriter filew = new FileWriter(dumpFilename, true); fw = new BufferedWriter(filew); fw.write("=== Processing delta changes for the model ===\n"); fw.write("Files for compilation:#" + files_tobecompiled.size() + ":" + files_tobecompiled + "\n"); fw.write("Files added :#" + files_added.size() + ":" + files_added + "\n"); fw.write("Files deleted :#" + files_deleted.size() + ":" + files_deleted + "\n"); } long stime = System.currentTimeMillis(); // fixupStructureModel(fw,filesToBeCompiled,files_added,files_deleted // ); // Let's remove all the files that are deleted on this compile removeStructureModelForFiles(fw, files_deleted); long etime1 = System.currentTimeMillis(); // etime1-stime = time to // fix up the model repairRelationships(fw); long etime2 = System.currentTimeMillis(); // etime2-stime = time to // repair the // relationship map removeStructureModelForFiles(fw, files_tobecompiled); if (dumpDeltaProcessing) { fw.write("===== Delta Processing timing ==========\n"); fw.write("Hierarchy=" + (etime1 - stime) + "ms Relationshipmap=" + (etime2 - etime1) + "ms\n"); fw.write("===== Traversal ========================\n"); // fw.write("Source handles processed="+srchandlecounter+"\n"); // fw.write("Target handles processed="+tgthandlecounter+"\n"); fw.write("========================================\n"); fw.flush(); fw.close(); } reportModelInfo("After delta processing"); } catch (IOException e) { e.printStackTrace(); } } private String getTypeNameFromHandle(String handle, Map cache) { String typename = (String) cache.get(handle); if (typename != null) { return typename; } // inpath handle - but for which type? // let's do it the slow way, we can optimize this with a cache perhaps int hasPackage = handle.indexOf('<'); int typeLocation = handle.indexOf('['); if (typeLocation == -1) { typeLocation = handle.indexOf('}'); } if (typeLocation == -1) { // unexpected - time to give up return ""; } StringBuffer qualifiedTypeNameFromHandle = new StringBuffer(); if (hasPackage != -1) { qualifiedTypeNameFromHandle.append(handle.substring(hasPackage + 1, handle.indexOf('(', hasPackage))); qualifiedTypeNameFromHandle.append('.'); } qualifiedTypeNameFromHandle.append(handle.substring(typeLocation + 1)); typename = qualifiedTypeNameFromHandle.toString(); cache.put(handle, typename); return typename; } /** * two kinds of relationships * * A affects B B affectedBy A * * Both of these relationships are added when 'B' is modified. Concrete examples are 'advises/advisedby' or * 'annotates/annotatedby'. * * What we need to do is when 'B' is going to be woven, remove all relationships that may reoccur when it is woven. So - remove * 'affects' relationships where the target is 'B', remove all 'affectedBy' relationships where the source is 'B'. * */ public void removeRelationshipsTargettingThisType(String typename) { boolean debug = false; if (debug) { System.err.println(">>removeRelationshipsTargettingThisType " + typename); } String pkg = null; String type = typename; int lastSep = typename.lastIndexOf('.'); if (lastSep != -1) { pkg = typename.substring(0, lastSep); type = typename.substring(lastSep + 1); } boolean didsomething = false; IProgramElement typeNode = hierarchy.findElementForType(pkg, type); // Reasons for that being null: // 1. the file has fundamental errors and so doesn't exist in the model // (-proceedOnError probably forced us to weave) if (typeNode == null) { return; } Set sourcesToRemove = new HashSet(); Map handleToTypenameCache = new HashMap(); // Iterate over the source handles in the relationships map, the aim // here is to remove any 'affected by' // relationships where the source of the relationship is the specified // type (since it will be readded // when the type is woven) Set sourcehandlesSet = mapper.getEntries(); List relationshipsToRemove = new ArrayList(); for (Iterator keyiter = sourcehandlesSet.iterator(); keyiter.hasNext();) { String hid = (String) keyiter.next(); if (isPhantomHandle(hid)) { // inpath handle - but for which type? // TODO promote cache for reuse during one whole model update if (!getTypeNameFromHandle(hid, handleToTypenameCache).equals(typename)) { continue; } } IProgramElement sourceElement = hierarchy.getElement(hid); if (sourceElement == null || sameType(hid, sourceElement, typeNode)) { // worth continuing as there may be a relationship to remove relationshipsToRemove.clear(); List relationships = mapper.get(hid); for (Iterator reliter = relationships.iterator(); reliter.hasNext();) { IRelationship rel = (IRelationship) reliter.next(); if (rel.getKind() == IRelationship.Kind.USES_POINTCUT) { continue; // these relationships are added at compile } // time, argh if (rel.isAffects()) { continue; // we want 'affected by' relationships - (e.g. } // advised by) relationshipsToRemove.add(rel); // all the relationships can // be removed, regardless of // the target(s) } // Now, were any relationships emptied during that processing // and so need removing for this source handle if (relationshipsToRemove.size() > 0) { didsomething = true; if (relationshipsToRemove.size() == relationships.size()) { sourcesToRemove.add(hid); } else { for (int i = 0; i < relationshipsToRemove.size(); i++) { relationships.remove(relationshipsToRemove.get(i)); } } } } } // Remove sources that have no valid relationships any more for (Iterator srciter = sourcesToRemove.iterator(); srciter.hasNext();) { String hid = (String) srciter.next(); // System.err.println( // " source handle: all relationships have gone for "+hid); mapper.removeAll(hid); IProgramElement ipe = hierarchy.getElement(hid); if (ipe != null) { // If the relationship was hanging off a 'code' node, delete it. if (ipe.getKind().equals(IProgramElement.Kind.CODE)) { if (debug) { System.err.println(" source handle: it was code node, removing that as well... code=" + ipe + " parent=" + ipe.getParent()); } removeSingleNode(ipe); } } } if (debug) { dumprelsStderr("after processing 'affectedby'"); } if (didsomething) { // did we do anything? sourcesToRemove.clear(); // removing 'affects' relationships if (debug) { dumprelsStderr("before processing 'affects'"); } // Iterate over the source handles in the relationships map sourcehandlesSet = mapper.getEntries(); for (Iterator keyiter = sourcehandlesSet.iterator(); keyiter.hasNext();) { String hid = (String) keyiter.next(); relationshipsToRemove.clear(); List relationships = mapper.get(hid); for (Iterator reliter = relationships.iterator(); reliter.hasNext();) { IRelationship rel = (IRelationship) reliter.next(); if (rel.getKind() == IRelationship.Kind.USES_POINTCUT) { continue; // these relationships are added at compile } // time, argh if (!rel.isAffects()) { continue; } List targets = rel.getTargets(); List targetsToRemove = new ArrayList(); // find targets that target the type we are interested in, // they need removing for (Iterator targetsIter = targets.iterator(); targetsIter.hasNext();) { String targethid = (String) targetsIter.next(); if (isPhantomHandle(hid) && !getTypeNameFromHandle(hid, handleToTypenameCache).equals(typename)) { continue; } // Does this point to the same type? IProgramElement existingTarget = hierarchy.getElement(targethid); if (existingTarget == null || sameType(targethid, existingTarget, typeNode)) { targetsToRemove.add(targethid); } } if (targetsToRemove.size() != 0) { if (targetsToRemove.size() == targets.size()) { relationshipsToRemove.add(rel); } else { // Remove all the targets that are no longer valid for (Iterator targsIter = targetsToRemove.iterator(); targsIter.hasNext();) { String togo = (String) targsIter.next(); targets.remove(togo); } } } } // Now, were any relationships emptied during that processing // and so need removing for this source handle if (relationshipsToRemove.size() > 0) { // Are we removing *all* of the relationships for this // source handle? if (relationshipsToRemove.size() == relationships.size()) { sourcesToRemove.add(hid); } else { for (int i = 0; i < relationshipsToRemove.size(); i++) { relationships.remove(relationshipsToRemove.get(i)); } } } } // Remove sources that have no valid relationships any more for (Iterator srciter = sourcesToRemove.iterator(); srciter.hasNext();) { String hid = (String) srciter.next(); // System.err.println( // " source handle: all relationships have gone for "+hid); mapper.removeAll(hid); IProgramElement ipe = hierarchy.getElement(hid); if (ipe != null) { // If the relationship was hanging off a 'code' node, delete // it. if (ipe.getKind().equals(IProgramElement.Kind.CODE)) { if (debug) { System.err.println(" source handle: it was code node, removing that as well... code=" + ipe + " parent=" + ipe.getParent()); } removeSingleNode(ipe); } } } if (debug) { dumprelsStderr("after processing 'affects'"); } } if (debug) { System.err.println("<<removeRelationshipsTargettingThisFile"); } } /** * Return true if the target element is in the type specified. */ private boolean sameType(String hid, IProgramElement target, IProgramElement type) { IProgramElement containingType = target; if (target == null) { throw new RuntimeException("target can't be null!"); } if (type == null) { throw new RuntimeException("type can't be null!"); } if (target.getKind().isSourceFile() || target.getKind().isFile()) { // isFile() covers pr263487 // @AJ aspect with broken relationship endpoint - we couldn't find // the real // endpoint (the declare parents or ITD or similar) so defaulted to // the // first line of the source file... // FRAGILE // Let's assume the worst, and that it is the same type if the // source files // are the same. This will break for multiple top level types in a // file... if (target.getSourceLocation() == null) { return false; // these four possibilities should really be FIXED } // so we don't have this situation if (type.getSourceLocation() == null) { return false; } if (target.getSourceLocation().getSourceFile() == null) { return false; } if (type.getSourceLocation().getSourceFile() == null) { return false; } return (target.getSourceLocation().getSourceFile().equals(type.getSourceLocation().getSourceFile())); } try { while (!containingType.getKind().isType()) { containingType = containingType.getParent(); } } catch (Throwable t) { // Example: // java.lang.RuntimeException: Exception whilst walking up from target X.class kind=(file) // hid=(=importProb/binaries<x(X.class) throw new RuntimeException("Exception whilst walking up from target " + target.toLabelString() + " kind=(" + target.getKind() + ") hid=(" + target.getHandleIdentifier() + ")", t); } return (type.equals(containingType)); } /** * @param handle a JDT like handle, following the form described in AsmRelationshipProvider.findOrFakeUpNode * @return true if the handle contains ';' - the char indicating that it is a phantom handle */ private boolean isPhantomHandle(String handle) { return handle.indexOf(HandleProviderDelimiter.PHANTOM.getDelimiter()) != -1; } /** * Go through all the relationships in the model, if any endpoints no longer exist (the node it points to has been deleted from * the model) then delete the relationship. */ private void repairRelationships(Writer fw) { try { // IHierarchy model = AsmManager.getDefault().getHierarchy(); // TODO Speed this code up by making this assumption: // the only piece of the handle that is interesting is the file // name. We are working at file granularity, if the // file does not exist (i.e. its not in the filemap) then any handle // inside that file cannot exist. if (dumpDeltaProcessing) { fw.write("Repairing relationships map:\n"); } // Now sort out the relationships map // IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap(); Set sourcesToRemove = new HashSet(); Set nonExistingHandles = new HashSet(); // Cache of handles that we // *know* are invalid int srchandlecounter = 0; int tgthandlecounter = 0; // Iterate over the source handles in the relationships map Set keyset = mapper.getEntries(); // These are source handles for (Iterator keyiter = keyset.iterator(); keyiter.hasNext();) { String hid = (String) keyiter.next(); srchandlecounter++; // Do we already know this handle points to nowhere? if (nonExistingHandles.contains(hid)) { sourcesToRemove.add(hid); } else if (!isPhantomHandle(hid)) { // We better check if it actually exists IProgramElement existingElement = hierarchy.getElement(hid); if (dumpDeltaProcessing) { fw.write("Looking for handle [" + hid + "] in model, found: " + existingElement + "\n"); } // Did we find it? if (existingElement == null) { // No, so delete this relationship sourcesToRemove.add(hid); nonExistingHandles.add(hid); // Speed up a bit you swine } else { // Ok, so the source is valid, what about the targets? List relationships = mapper.get(hid); List relationshipsToRemove = new ArrayList(); // Iterate through the relationships against this source // handle for (Iterator reliter = relationships.iterator(); reliter.hasNext();) { IRelationship rel = (IRelationship) reliter.next(); List targets = rel.getTargets(); List targetsToRemove = new ArrayList(); // Iterate through the targets for this relationship for (Iterator targetIter = targets.iterator(); targetIter.hasNext();) { String targethid = (String) targetIter.next(); tgthandlecounter++; // Do we already know it doesn't exist? if (nonExistingHandles.contains(targethid)) { if (dumpDeltaProcessing) { fw.write("Target handle [" + targethid + "] for srchid[" + hid + "]rel[" + rel.getName() + "] does not exist\n"); } targetsToRemove.add(targethid); } else if (!isPhantomHandle(targethid)) { // We better check IProgramElement existingTarget = hierarchy.getElement(targethid); if (existingTarget == null) { if (dumpDeltaProcessing) { fw.write("Target handle [" + targethid + "] for srchid[" + hid + "]rel[" + rel.getName() + "] does not exist\n"); } targetsToRemove.add(targethid); nonExistingHandles.add(targethid); } } } // Do we have some targets that need removing? if (targetsToRemove.size() != 0) { // Are we removing *all* of the targets for this // relationship (i.e. removing the relationship) if (targetsToRemove.size() == targets.size()) { if (dumpDeltaProcessing) { fw.write("No targets remain for srchid[" + hid + "] rel[" + rel.getName() + "]: removing it\n"); } relationshipsToRemove.add(rel); } else { // Remove all the targets that are no longer // valid for (Iterator targsIter = targetsToRemove.iterator(); targsIter.hasNext();) { String togo = (String) targsIter.next(); targets.remove(togo); } // Should have already been caught above, // but lets double check ... if (targets.size() == 0) { if (dumpDeltaProcessing) { fw.write("No targets remain for srchid[" + hid + "] rel[" + rel.getName() + "]: removing it\n"); } relationshipsToRemove.add(rel); // TODO // Should // only // remove // this // relationship // for // the // srchid // ? } } } } // Now, were any relationships emptied during that // processing and so need removing for this source // handle if (relationshipsToRemove.size() > 0) { // Are we removing *all* of the relationships for // this source handle? if (relationshipsToRemove.size() == relationships.size()) { // We know they are all going to go, so just // delete the source handle. sourcesToRemove.add(hid); } else { // MEMORY LEAK - we don't remove the // relationships !! for (int i = 0; i < relationshipsToRemove.size(); i++) { IRelationship irel = (IRelationship) relationshipsToRemove.get(i); verifyAssumption(mapper.remove(hid, irel), "Failed to remove relationship " + irel.getName() + " for shid " + hid); } List rels = mapper.get(hid); if (rels == null || rels.size() == 0) { sourcesToRemove.add(hid); } } } } } } // Remove sources that have no valid relationships any more for (Iterator srciter = sourcesToRemove.iterator(); srciter.hasNext();) { String hid = (String) srciter.next(); mapper.removeAll(hid); IProgramElement ipe = hierarchy.getElement(hid); if (ipe != null) { // If the relationship was hanging off a 'code' node, delete // it. if (ipe.getKind().equals(IProgramElement.Kind.CODE)) { // System.err.println("Deleting code node"); removeSingleNode(ipe); } } } } catch (IOException ioe) { System.err.println("Failed to repair relationships:"); ioe.printStackTrace(); } } /** * Removes a specified program element from the structure model. We go to the parent of the program element, ask for all its * children and remove the node we want to delete from the list of children. */ private void removeSingleNode(IProgramElement progElem) { if (progElem == null) { throw new IllegalStateException("AsmManager.removeNode(): programElement unexpectedly null"); } boolean deleteOK = false; IProgramElement parent = progElem.getParent(); List kids = parent.getChildren(); for (int i = 0; i < kids.size(); i++) { if (kids.get(i).equals(progElem)) { kids.remove(i); deleteOK = true; break; } } if (!deleteOK) { throw new RuntimeException("Unable to delete the node from the model. trying to delete node for handle " + progElem.getHandleIdentifier()); } } /** * Removes a specified program element from the structure model. Two processing stages: * <p> * First: We go to the parent of the program element, ask for all its children and remove the node we want to delete from the * list of children. * <p> * Second:We check if that parent has any other children. If it has no other children and it is either a CODE node or a PACKAGE * node, we delete it too. */ private void removeNode(IProgramElement progElem) { // StringBuffer flightrecorder = new StringBuffer(); try { // flightrecorder.append("In removeNode, about to chuck away: "+ // progElem+"\n"); if (progElem == null) { throw new IllegalStateException("AsmManager.removeNode(): programElement unexpectedly null"); } // boolean deleteOK = false; IProgramElement parent = progElem.getParent(); // flightrecorder.append("Parent of it is "+parent+"\n"); List kids = parent.getChildren(); // flightrecorder.append("Which has "+kids.size()+" kids\n"); for (int i = 0; i < kids.size(); i++) { // flightrecorder.append("Comparing with "+kids.get(i)+"\n"); if (kids.get(i).equals(progElem)) { kids.remove(i); // flightrecorder.append("Removing it\n"); // deleteOK=true; break; } } // verifyAssumption(deleteOK,flightrecorder.toString()); // Are there any kids left for this node? if (parent.getChildren().size() == 0 && parent.getParent() != null && (parent.getKind().equals(IProgramElement.Kind.CODE) || parent.getKind().equals(IProgramElement.Kind.PACKAGE))) { // This node is on its own, we should trim it too *as long as // its not a structural node* which we currently check by // making sure its a code node // We should trim if it // System.err.println("Deleting parent:"+parent); removeNode(parent); } } catch (NullPointerException npe) { // Occurred when commenting out other 2 ras classes in wsif?? // reproducable? // System.err.println(flightrecorder.toString()); npe.printStackTrace(); } } public static void verifyAssumption(boolean b, String info) { if (!b) { System.err.println("=========== ASSERTION IS NOT TRUE =========v"); System.err.println(info); Thread.dumpStack(); System.err.println("=========== ASSERTION IS NOT TRUE =========^"); throw new RuntimeException("Assertion is false"); } } public static void verifyAssumption(boolean b) { if (!b) { Thread.dumpStack(); throw new RuntimeException("Assertion is false"); } } // ===================== DELTA PROCESSING CODE ============== end // ==========// /** * A ModelInfo object captures basic information about the structure model. It is used for testing and producing debug info. */ public static class ModelInfo { private final Hashtable nodeTypeCount = new Hashtable(); private final Properties extraProperties = new Properties(); private ModelInfo(IHierarchy hierarchy, IRelationshipMap relationshipMap) { IProgramElement ipe = hierarchy.getRoot(); walkModel(ipe); recordStat("FileMapSize", new Integer(hierarchy.getFileMapEntrySet().size()).toString()); recordStat("RelationshipMapSize", new Integer(relationshipMap.getEntries().size()).toString()); } private void walkModel(IProgramElement ipe) { countNode(ipe); List kids = ipe.getChildren(); for (Iterator iter = kids.iterator(); iter.hasNext();) { IProgramElement nextElement = (IProgramElement) iter.next(); walkModel(nextElement); } } private void countNode(IProgramElement ipe) { String node = ipe.getKind().toString(); Integer ctr = (Integer) nodeTypeCount.get(node); if (ctr == null) { nodeTypeCount.put(node, new Integer(1)); } else { ctr = new Integer(ctr.intValue() + 1); nodeTypeCount.put(node, ctr); } } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("Model node summary:\n"); Enumeration nodeKeys = nodeTypeCount.keys(); while (nodeKeys.hasMoreElements()) { String key = (String) nodeKeys.nextElement(); Integer ct = (Integer) nodeTypeCount.get(key); sb.append(key + "=" + ct + "\n"); } sb.append("Model stats:\n"); Enumeration ks = extraProperties.keys(); while (ks.hasMoreElements()) { String k = (String) ks.nextElement(); String v = extraProperties.getProperty(k); sb.append(k + "=" + v + "\n"); } return sb.toString(); } public Properties getProperties() { Properties p = new Properties(); Enumeration nodeKeys = nodeTypeCount.keys(); while (nodeKeys.hasMoreElements()) { String key = (String) nodeKeys.nextElement(); Integer ct = (Integer) nodeTypeCount.get(key); p.setProperty(key, ct.toString()); } p.putAll(extraProperties); return p; } public void recordStat(String string, String string2) { extraProperties.setProperty(string, string2); } } public ModelInfo summarizeModel() { return new ModelInfo(getHierarchy(), getRelationshipMap()); } /** * Set to indicate whether we are currently building a structure model, should be set up front. */ // public static void setCreatingModel(boolean b) { // creatingModel = b; // } // // /** // * returns true if we are currently generating a structure model, enables guarding of expensive operations on an empty/null // * model. // */ // public static boolean isCreatingModel() { // return creatingModel; // } public static void setCompletingTypeBindings(boolean b) { completingTypeBindings = b; } public static boolean isCompletingTypeBindings() { return completingTypeBindings; } // public void setRelationshipMap(IRelationshipMap irm) { // mapper = irm; // } // // public void setHierarchy(IHierarchy ih) { // hierarchy = ih; // } public void resetDeltaProcessing() { lastBuildChanges.clear(); aspectsWeavingInLastBuild.clear(); } /** * @return the Set of files for which the structure model was modified (they may have been removed or otherwise rebuilt). Set is * empty for a full build. */ public Set getModelChangesOnLastBuild() { return lastBuildChanges; } /** * @return the Set of aspects that wove files on the last build (either incremental or full build) */ public Set getAspectsWeavingFilesOnLastBuild() { return aspectsWeavingInLastBuild; } public void addAspectInEffectThisBuild(File f) { aspectsWeavingInLastBuild.add(f); } public static void setLastActiveStructureModel(AsmManager structureModel) { if (recordingLastActiveStructureModel) { lastActiveStructureModel = structureModel; } } public String getHandleElementForInpath(String binaryPath) { return (String) inpathMap.get(new File(binaryPath)); } private List pieces = new ArrayList(); private Object intern(String substring) { int lastIdx = -1; if ((lastIdx = substring.lastIndexOf('/')) != -1) { String pkg = substring.substring(0, lastIdx); String type = substring.substring(lastIdx + 1); pkg = internOneThing(pkg); type = internOneThing(type); return new String[] { pkg, type }; } else { return internOneThing(substring); } } private String internOneThing(String substring) { // simple name for (int p = 0, max = pieces.size(); p < max; p++) { String s = (String) pieces.get(p); if (s.equals(substring)) { return s; } } pieces.add(substring); return substring; } /** * What we can rely on: <br> * - it is a method signature of the form (La/B;Lc/D;)LFoo;<br> * - there are no generics<br> * * What we must allow for: - may use primitive refs (single chars rather than L) */ /* * public List compress(String s) { int openParen = 0; int closeParen = s.indexOf(')'); int pos = 1; List compressed = new * ArrayList(); // do the parens while (pos < closeParen) { char ch = s.charAt(pos); if (ch == 'L') { int idx = s.indexOf(';', * pos); compressed.add(intern(s.substring(pos + 1, idx))); pos = idx + 1; } else if (ch == '[') { int x = pos; while * (s.charAt(++pos) == '[') ; // now pos will point at something not an array compressed.add(intern(s.substring(x, pos))); // * intern the [[[[[[ char ch2 = s.charAt(pos); if (ch2 == 'L') { int idx = s.indexOf(';', pos); * compressed.add(intern(s.substring(pos + 1, idx))); pos = idx + 1; } else if (ch2 == 'T') { int idx = s.indexOf(';'); * compressed.add(intern(s.substring(pos, idx + 1))); // should be TT; pos = idx + 1; } else { * compressed.add(toCharacter(s.charAt(pos))); pos++; } } else { // it is a primitive ref (SVBCZJ) * compressed.add(toCharacter(ch)); pos++; } } // do the return type pos++; char ch = s.charAt(pos); if (ch == 'L') { int idx = * s.indexOf(';', pos); compressed.add(intern(s.substring(pos, idx))); } else if (ch == '[') { int x = pos; while * (s.charAt(++pos) == '[') ; // now pos will point at something not an array compressed.add(intern(s.substring(x, pos))); // * intern the [[[[[[ char ch2 = s.charAt(pos); if (ch2 == 'L') { int idx = s.indexOf(';', pos); * compressed.add(intern(s.substring(pos + 1, idx))); pos = idx + 1; } else if (ch2 == 'T') { int idx = s.indexOf(';'); * compressed.add(intern(s.substring(pos, idx + 1))); // should be TT; pos = idx + 2; } else { * compressed.add(toCharacter(s.charAt(pos))); pos++; } } else { // it is a primitive ref (SVBCZJ) compressed.add(new * Character(ch)); } return compressed; * * // char delimiter = '/'; // int pos = -1; // List compressed = new ArrayList(); // int start = 0; // while ((pos = * s.indexOf(delimiter, start)) != -1) { // String part = s.substring(start, pos); // int alreadyRecorded = * pieces.indexOf(part); // if (alreadyRecorded != -1) { // compressed.add(new Integer(alreadyRecorded)); // } else { // * compressed.add(new Integer(pieces.size())); // pieces.add(part); // } // start = pos + 1; // } // // last piece // String * part = s.substring(start, s.length()); // int alreadyRecorded = pieces.indexOf(part); // if (alreadyRecorded != -1) { // * compressed.add(youkirtyounew Integer(alreadyRecorded)); // } else { // compressed.add(new Integer(pieces.size())); // * pieces.add(part); // } // return compressed; } * * static final Character charB = new Character('B'); static final Character charS = new Character('S'); static final Character * charI = new Character('I'); static final Character charF = new Character('F'); static final Character charD = new * Character('D'); static final Character charJ = new Character('J'); static final Character charC = new Character('C'); static * final Character charV = new Character('V'); static final Character charZ = new Character('Z'); * * private Character toCharacter(char ch) { switch (ch) { case 'B': return charB; case 'S': return charS; case 'I': return * charI; case 'F': return charF; case 'D': return charD; case 'J': return charJ; case 'C': return charC; case 'V': return * charV; case 'Z': return charZ; default: throw new IllegalStateException(new Character(ch).toString()); } } * * public String decompress(List refs, char delimiter) { StringBuilder result = new StringBuilder(); result.append("("); for * (int i = 0, max = refs.size() - 1; i < max; i++) { result.append(unintern(refs.get(i))); } result.append(")"); * result.append(unintern(refs.get(refs.size() - 1))); return result.toString(); } * * private String unintern(Object o) { if (o instanceof Character) { return ((Character) o).toString(); } else if (o instanceof * String[]) { String[] strings = (String[]) o; StringBuilder sb = new StringBuilder(); sb.append('L'); * sb.append(strings[0]).append('/').append(strings[1]); sb.append(';'); return sb.toString(); } else { // String String so = * (String) o; if (so.endsWith(";")) { // will be TT; return so; } else { StringBuilder sb = new StringBuilder(); * sb.append('L'); sb.append(so); sb.append(';'); return sb.toString(); } } } */ }
311,910
Bug 311910 AspectJ internal Compiler Error
Stack Trace: java.lang.NullPointerException at org.aspectj.weaver.model.AsmRelationshipProvider.createSourceLocation(AsmRelationshipProvider.java:303) at org.aspectj.weaver.model.AsmRelationshipProvider.addPointcuts(AsmRelationshipProvider.java:580) at org.aspectj.weaver.model.AsmRelationshipProvider.createHierarchyForBinaryAspect(AsmRelationshipProvider.java:562) at org.aspectj.weaver.model.AsmRelationshipProvider.addAdvisedRelationship(AsmRelations ... ARETURN end public Object run(Object[]) end public class com.cerner.isis.biz.services.asclepius.patient.PatientManagerImplTest$AjcClosure3 Happening when weaving a jar with a aspect jar.
resolved fixed
3be69a2
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-05-06T16:34:47Z"
"2010-05-06T15:33:20Z"
weaver/src/org/aspectj/weaver/model/AsmRelationshipProvider.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.model; import java.io.File; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.IRelationship; import org.aspectj.asm.IRelationshipMap; import org.aspectj.asm.internal.HandleProviderDelimiter; import org.aspectj.asm.internal.ProgramElement; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.Checker; import org.aspectj.weaver.Lint; import org.aspectj.weaver.Member; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.ResolvedTypeMunger.Kind; import org.aspectj.weaver.bcel.BcelShadow; import org.aspectj.weaver.bcel.BcelTypeMunger; import org.aspectj.weaver.patterns.DeclareErrorOrWarning; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.Pointcut; public class AsmRelationshipProvider { public static final String ADVISES = "advises"; public static final String ADVISED_BY = "advised by"; public static final String DECLARES_ON = "declares on"; public static final String DECLAREDY_BY = "declared by"; public static final String SOFTENS = "softens"; public static final String SOFTENED_BY = "softened by"; public static final String MATCHED_BY = "matched by"; public static final String MATCHES_DECLARE = "matches declare"; public static final String INTER_TYPE_DECLARES = "declared on"; public static final String INTER_TYPE_DECLARED_BY = "aspect declarations"; public static final String ANNOTATES = "annotates"; public static final String ANNOTATED_BY = "annotated by"; /** * Add a relationship for a declare error or declare warning */ public static void addDeclareErrorOrWarningRelationship(AsmManager model, Shadow affectedShadow, Checker deow) { if (model == null) { return; } if (affectedShadow.getSourceLocation() == null || deow.getSourceLocation() == null) { return; } if (World.createInjarHierarchy) { createHierarchyForBinaryAspect(model, deow); } IProgramElement targetNode = getNode(model, affectedShadow); if (targetNode == null) { return; } String targetHandle = targetNode.getHandleIdentifier(); if (targetHandle == null) { return; } IProgramElement sourceNode = model.getHierarchy().findElementForSourceLine(deow.getSourceLocation()); String sourceHandle = sourceNode.getHandleIdentifier(); if (sourceHandle == null) { return; } IRelationshipMap relmap = model.getRelationshipMap(); IRelationship foreward = relmap.get(sourceHandle, IRelationship.Kind.DECLARE, MATCHED_BY, false, true); foreward.addTarget(targetHandle); IRelationship back = relmap.get(targetHandle, IRelationship.Kind.DECLARE, MATCHES_DECLARE, false, true); if (back != null && back.getTargets() != null) { back.addTarget(sourceHandle); } if (sourceNode.getSourceLocation() != null) { model.addAspectInEffectThisBuild(sourceNode.getSourceLocation().getSourceFile()); } } private static boolean isMixinRelated(ResolvedTypeMunger typeTransformer) { Kind kind = typeTransformer.getKind(); return kind == ResolvedTypeMunger.MethodDelegate2 || kind == ResolvedTypeMunger.FieldHost || (kind == ResolvedTypeMunger.Parent && ((NewParentTypeMunger) typeTransformer).isMixin()); } /** * Add a relationship for a type transformation (declare parents, intertype method declaration, declare annotation on type). */ public static void addRelationship(AsmManager model, ResolvedType onType, ResolvedTypeMunger typeTransformer, ResolvedType originatingAspect) { if (model == null) { return; } if (World.createInjarHierarchy && isBinaryAspect(originatingAspect)) { createHierarchy(model, typeTransformer, originatingAspect); } if (originatingAspect.getSourceLocation() != null) { String sourceHandle = ""; IProgramElement sourceNode = null; if (typeTransformer.getSourceLocation() != null && typeTransformer.getSourceLocation().getOffset() != -1 && !isMixinRelated(typeTransformer)) { sourceNode = model.getHierarchy().findElementForType(originatingAspect.getPackageName(), originatingAspect.getClassName()); IProgramElement closer = model.getHierarchy().findCloserMatchForLineNumber(sourceNode, typeTransformer.getSourceLocation().getLine()); if (closer != null) { sourceNode = closer; } if (sourceNode == null) { // This can be caused by the aspect defining the type munger actually being on the classpath and not the // inpath or aspectpath. Rather than NPE at the next line, let's have another go at faulting it in. // This inner loop is a small duplicate of the outer loop that attempts to find something closer than // the type declaration if (World.createInjarHierarchy) { createHierarchy(model, typeTransformer, originatingAspect); if (typeTransformer.getSourceLocation() != null && typeTransformer.getSourceLocation().getOffset() != -1 && !isMixinRelated(typeTransformer)) { sourceNode = model.getHierarchy().findElementForType(originatingAspect.getPackageName(), originatingAspect.getClassName()); IProgramElement closer2 = model.getHierarchy().findCloserMatchForLineNumber(sourceNode, typeTransformer.getSourceLocation().getLine()); if (closer2 != null) { sourceNode = closer2; } } else { sourceNode = model.getHierarchy().findElementForType(originatingAspect.getPackageName(), originatingAspect.getClassName()); } } } sourceHandle = sourceNode.getHandleIdentifier(); } else { sourceNode = model.getHierarchy().findElementForType(originatingAspect.getPackageName(), originatingAspect.getClassName()); // sourceNode = // asm.getHierarchy().findElementForSourceLine(originatingAspect // .getSourceLocation()); sourceHandle = sourceNode.getHandleIdentifier(); } // sourceNode = // asm.getHierarchy().findElementForType(originatingAspect // .getPackageName(), // originatingAspect.getClassName()); // // sourceNode = // asm.getHierarchy().findElementForSourceLine(munger // .getSourceLocation()); // sourceHandle = // asm.getHandleProvider().createHandleIdentifier(sourceNode); if (sourceHandle == null) { return; } String targetHandle = findOrFakeUpNode(model, onType); if (targetHandle == null) { return; } IRelationshipMap mapper = model.getRelationshipMap(); IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARES, false, true); foreward.addTarget(targetHandle); IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARED_BY, false, true); back.addTarget(sourceHandle); if (sourceNode != null && sourceNode.getSourceLocation() != null) { // May have been a bug in the compiled aspect - so it didn't get put in the model model.addAspectInEffectThisBuild(sourceNode.getSourceLocation().getSourceFile()); } } } private static String findOrFakeUpNode(AsmManager model, ResolvedType onType) { IHierarchy hierarchy = model.getHierarchy(); ISourceLocation sourceLocation = onType.getSourceLocation(); String canonicalFilePath = model.getCanonicalFilePath(sourceLocation.getSourceFile()); int lineNumber = sourceLocation.getLine(); // Find the relevant source file node first IProgramElement node = hierarchy.findNodeForSourceFile(hierarchy.getRoot(), canonicalFilePath); if (node == null) { // Does not exist in the model - probably an inpath String bpath = onType.getBinaryPath(); if (bpath == null) { return model.getHandleProvider().createHandleIdentifier(createFileStructureNode(model, canonicalFilePath)); } else { IProgramElement programElement = model.getHierarchy().getRoot(); // =Foo/,<g(G.class[G StringBuffer phantomHandle = new StringBuffer(); // =Foo phantomHandle.append(programElement.getHandleIdentifier()); // /, - the comma is a 'well defined char' that means inpath phantomHandle.append(HandleProviderDelimiter.PACKAGEFRAGMENTROOT.getDelimiter()).append( HandleProviderDelimiter.PHANTOM.getDelimiter()); int pos = bpath.indexOf('!'); if (pos != -1) { // jar or dir String jarPath = bpath.substring(0, pos); String element = model.getHandleElementForInpath(jarPath); if (element != null) { phantomHandle.append(element); } } // <g String packageName = onType.getPackageName(); phantomHandle.append(HandleProviderDelimiter.PACKAGEFRAGMENT.getDelimiter()).append(packageName); // (G.class // could fix the binary path to only be blah.class bit int dotClassPosition = bpath.lastIndexOf(".class");// what to do if -1 if (dotClassPosition == -1) { phantomHandle.append(HandleProviderDelimiter.CLASSFILE.getDelimiter()).append("UNKNOWN.class"); } else { int startPosition = dotClassPosition; char ch; while (startPosition > 0 && ((ch = bpath.charAt(startPosition)) != '/' && ch != '\\' && ch != '!')) { startPosition--; } String classFile = bpath.substring(startPosition + 1, dotClassPosition + 6); phantomHandle.append(HandleProviderDelimiter.CLASSFILE.getDelimiter()).append(classFile); } // [G phantomHandle.append(HandleProviderDelimiter.TYPE.getDelimiter()).append(onType.getClassName()); return phantomHandle.toString(); } } else { // Check if there is a more accurate child node of that source file node: IProgramElement closernode = hierarchy.findCloserMatchForLineNumber(node, lineNumber); if (closernode == null) { return node.getHandleIdentifier(); } else { return closernode.getHandleIdentifier(); } } } public static IProgramElement createFileStructureNode(AsmManager asm, String sourceFilePath) { // SourceFilePath might have originated on windows on linux... int lastSlash = sourceFilePath.lastIndexOf('\\'); if (lastSlash == -1) { lastSlash = sourceFilePath.lastIndexOf('/'); } // '!' is used like in URLs "c:/blahblah/X.jar!a/b.class" int i = sourceFilePath.lastIndexOf('!'); int j = sourceFilePath.indexOf(".class"); if (i > lastSlash && i != -1 && j != -1) { // we are a binary aspect in the default package lastSlash = i; } String fileName = sourceFilePath.substring(lastSlash + 1); IProgramElement fileNode = new ProgramElement(asm, fileName, IProgramElement.Kind.FILE_JAVA, new SourceLocation(new File( sourceFilePath), 1, 1), 0, null, null); // fileNode.setSourceLocation(); fileNode.addChild(IHierarchy.NO_STRUCTURE); return fileNode; } private static boolean isBinaryAspect(ResolvedType aspect) { return aspect.getBinaryPath() != null; } /** * Returns the binarySourceLocation for the given sourcelocation. This isn't cached because it's used when faulting in the * binary nodes and is called with ISourceLocations for all advice, pointcuts and deows contained within the * resolvedDeclaringAspect. */ private static ISourceLocation getBinarySourceLocation(ResolvedType aspect, ISourceLocation sl) { if (sl == null) { return null; } String sourceFileName = null; if (aspect instanceof ReferenceType) { String s = ((ReferenceType) aspect).getDelegate().getSourcefilename(); int i = s.lastIndexOf('/'); if (i != -1) { sourceFileName = s.substring(i + 1); } else { sourceFileName = s; } } ISourceLocation sLoc = new SourceLocation(getBinaryFile(aspect), sl.getLine(), sl.getEndLine(), ((sl.getColumn() == 0) ? ISourceLocation.NO_COLUMN : sl.getColumn()), sl.getContext(), sourceFileName); return sLoc; } private static ISourceLocation createSourceLocation(String sourcefilename, ResolvedType aspect, ISourceLocation sl) { ISourceLocation sLoc = new SourceLocation(getBinaryFile(aspect), sl.getLine(), sl.getEndLine(), ((sl.getColumn() == 0) ? ISourceLocation.NO_COLUMN : sl.getColumn()), sl.getContext(), sourcefilename); return sLoc; } private static String getSourceFileName(ResolvedType aspect) { String sourceFileName = null; if (aspect instanceof ReferenceType) { String s = ((ReferenceType) aspect).getDelegate().getSourcefilename(); int i = s.lastIndexOf('/'); if (i != -1) { sourceFileName = s.substring(i + 1); } else { sourceFileName = s; } } return sourceFileName; } /** * Returns the File with pathname to the class file, for example either C:\temp * \ajcSandbox\workspace\ajcTest16957.tmp\simple.jar!pkg\BinaryAspect.class if the class file is in a jar file, or * C:\temp\ajcSandbox\workspace\ajcTest16957.tmp!pkg\BinaryAspect.class if the class file is in a directory */ private static File getBinaryFile(ResolvedType aspect) { String s = aspect.getBinaryPath(); File f = aspect.getSourceLocation().getSourceFile(); // Replace the source file suffix with .class int i = f.getPath().lastIndexOf('.'); String path = null; if (i != -1) { path = f.getPath().substring(0, i) + ".class"; } else { path = f.getPath() + ".class"; } return new File(s + "!" + path); } /** * Create a basic hierarchy to represent an aspect only available in binary (from the aspectpath). */ private static void createHierarchy(AsmManager model, ResolvedTypeMunger typeTransformer, ResolvedType aspect) { // assert aspect != null; // Check if already defined in the model // IProgramElement filenode = // model.getHierarchy().findElementForType(aspect.getPackageName(), // aspect.getClassName()); // SourceLine(typeTransformer.getSourceLocation()); IProgramElement filenode = model.getHierarchy().findElementForSourceLine(typeTransformer.getSourceLocation()); if (filenode == null) { if (typeTransformer.getKind() == ResolvedTypeMunger.MethodDelegate2 || typeTransformer.getKind() == ResolvedTypeMunger.FieldHost) { // not yet faulting these in return; } } // the call to findElementForSourceLine(ISourceLocation) returns a file // node // if it can't find a node in the hierarchy for the given // sourcelocation. // Therefore, if this is returned, we know we can't find one and have to // // continue to fault in the model. // if (filenode != null) { // if (!filenode.getKind().equals(IProgramElement.Kind.FILE_JAVA)) { return; } // create the class file node ISourceLocation binLocation = getBinarySourceLocation(aspect, aspect.getSourceLocation()); String f = getBinaryFile(aspect).getName(); IProgramElement classFileNode = new ProgramElement(model, f, IProgramElement.Kind.FILE, binLocation, 0, null, null); // create package ipe if one exists.... IProgramElement root = model.getHierarchy().getRoot(); IProgramElement binaries = model.getHierarchy().findElementForLabel(root, IProgramElement.Kind.SOURCE_FOLDER, "binaries"); if (binaries == null) { binaries = new ProgramElement(model, "binaries", IProgramElement.Kind.SOURCE_FOLDER, new ArrayList()); root.addChild(binaries); } // if (aspect.getPackageName() != null) { String packagename = aspect.getPackageName() == null ? "" : aspect.getPackageName(); // check that there doesn't already exist a node with this name IProgramElement pkgNode = model.getHierarchy().findElementForLabel(binaries, IProgramElement.Kind.PACKAGE, packagename); // note packages themselves have no source location if (pkgNode == null) { pkgNode = new ProgramElement(model, packagename, IProgramElement.Kind.PACKAGE, new ArrayList()); binaries.addChild(pkgNode); pkgNode.addChild(classFileNode); } else { // need to add it first otherwise the handle for classFileNode // may not be generated correctly if it uses information from // it's parent node pkgNode.addChild(classFileNode); for (Iterator iter = pkgNode.getChildren().iterator(); iter.hasNext();) { IProgramElement element = (IProgramElement) iter.next(); if (!element.equals(classFileNode) && element.getHandleIdentifier().equals(classFileNode.getHandleIdentifier())) { // already added the classfile so have already // added the structure for this aspect pkgNode.removeChild(classFileNode); return; } } } // } else { // // need to add it first otherwise the handle for classFileNode // // may not be generated correctly if it uses information from // // it's parent node // root.addChild(classFileNode); // for (Iterator iter = root.getChildren().iterator(); iter.hasNext();) // { // IProgramElement element = (IProgramElement) iter.next(); // if (!element.equals(classFileNode) && // element.getHandleIdentifier().equals // (classFileNode.getHandleIdentifier())) { // // already added the sourcefile so have already // // added the structure for this aspect // root.removeChild(classFileNode); // return; // } // } // } // add and create empty import declaration ipe // no import container for binary type - 265693 // classFileNode.addChild(new ProgramElement(model, "import declarations", IProgramElement.Kind.IMPORT_REFERENCE, null, 0, // null, null)); // add and create aspect ipe IProgramElement aspectNode = new ProgramElement(model, aspect.getSimpleName(), IProgramElement.Kind.ASPECT, getBinarySourceLocation(aspect, aspect.getSourceLocation()), aspect.getModifiers(), null, null); classFileNode.addChild(aspectNode); addChildNodes(model, aspect, aspectNode, aspect.getDeclaredPointcuts()); addChildNodes(model, aspect, aspectNode, aspect.getDeclaredAdvice()); addChildNodes(model, aspect, aspectNode, aspect.getDeclares()); addChildNodes(model, aspect, aspectNode, aspect.getTypeMungers()); } /** * Adds a declare annotation relationship, sometimes entities don't have source locs (methods/fields) so use other variants of * this method if that is the case as they will look the entities up in the structure model. */ public static void addDeclareAnnotationRelationship(AsmManager model, ISourceLocation declareAnnotationLocation, ISourceLocation annotatedLocation) { if (model == null) { return; } IProgramElement sourceNode = model.getHierarchy().findElementForSourceLine(declareAnnotationLocation); String sourceHandle = sourceNode.getHandleIdentifier(); if (sourceHandle == null) { return; } IProgramElement targetNode = model.getHierarchy().findElementForSourceLine(annotatedLocation); String targetHandle = targetNode.getHandleIdentifier(); if (targetHandle == null) { return; } IRelationshipMap mapper = model.getRelationshipMap(); IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATES, false, true); foreward.addTarget(targetHandle); IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATED_BY, false, true); back.addTarget(sourceHandle); if (sourceNode.getSourceLocation() != null) { model.addAspectInEffectThisBuild(sourceNode.getSourceLocation().getSourceFile()); } } /** * Creates the hierarchy for binary aspects */ public static void createHierarchyForBinaryAspect(AsmManager asm, ShadowMunger munger) { if (!munger.isBinary()) { return; } IProgramElement sourceFileNode = asm.getHierarchy().findElementForSourceLine(munger.getSourceLocation()); // the call to findElementForSourceLine(ISourceLocation) returns a file // node // if it can't find a node in the hierarchy for the given // sourcelocation. // Therefore, if this is returned, we know we can't find one and have to // continue to fault in the model. if (!sourceFileNode.getKind().equals(IProgramElement.Kind.FILE_JAVA)) { return; } ResolvedType aspect = munger.getDeclaringType(); // create the class file node IProgramElement classFileNode = new ProgramElement(asm, sourceFileNode.getName(), IProgramElement.Kind.FILE, munger .getBinarySourceLocation(aspect.getSourceLocation()), 0, null, null); // create package ipe if one exists.... IProgramElement root = asm.getHierarchy().getRoot(); IProgramElement binaries = asm.getHierarchy().findElementForLabel(root, IProgramElement.Kind.SOURCE_FOLDER, "binaries"); if (binaries == null) { binaries = new ProgramElement(asm, "binaries", IProgramElement.Kind.SOURCE_FOLDER, new ArrayList()); root.addChild(binaries); } // if (aspect.getPackageName() != null) { String packagename = aspect.getPackageName() == null ? "" : aspect.getPackageName(); // check that there doesn't already exist a node with this name IProgramElement pkgNode = asm.getHierarchy().findElementForLabel(binaries, IProgramElement.Kind.PACKAGE, packagename); // note packages themselves have no source location if (pkgNode == null) { pkgNode = new ProgramElement(asm, packagename, IProgramElement.Kind.PACKAGE, new ArrayList()); binaries.addChild(pkgNode); pkgNode.addChild(classFileNode); } else { // need to add it first otherwise the handle for classFileNode // may not be generated correctly if it uses information from // it's parent node pkgNode.addChild(classFileNode); for (Iterator iter = pkgNode.getChildren().iterator(); iter.hasNext();) { IProgramElement element = (IProgramElement) iter.next(); if (!element.equals(classFileNode) && element.getHandleIdentifier().equals(classFileNode.getHandleIdentifier())) { // already added the classfile so have already // added the structure for this aspect pkgNode.removeChild(classFileNode); return; } } } // } else { // // need to add it first otherwise the handle for classFileNode // // may not be generated correctly if it uses information from // // it's parent node // root.addChild(classFileNode); // for (Iterator iter = root.getChildren().iterator(); iter.hasNext();) // { // IProgramElement element = (IProgramElement) iter.next(); // if (!element.equals(classFileNode) && // element.getHandleIdentifier().equals // (classFileNode.getHandleIdentifier())) { // // already added the sourcefile so have already // // added the structure for this aspect // root.removeChild(classFileNode); // return; // } // } // } // add and create empty import declaration ipe // classFileNode.addChild(new ProgramElement(asm, "import declarations", IProgramElement.Kind.IMPORT_REFERENCE, null, 0, // null, // null)); // add and create aspect ipe IProgramElement aspectNode = new ProgramElement(asm, aspect.getSimpleName(), IProgramElement.Kind.ASPECT, munger .getBinarySourceLocation(aspect.getSourceLocation()), aspect.getModifiers(), null, null); classFileNode.addChild(aspectNode); String sourcefilename = getSourceFileName(aspect); addPointcuts(asm, sourcefilename, aspect, aspectNode, aspect.getDeclaredPointcuts()); addChildNodes(asm, aspect, aspectNode, aspect.getDeclaredAdvice()); addChildNodes(asm, aspect, aspectNode, aspect.getDeclares()); addChildNodes(asm, aspect, aspectNode, aspect.getTypeMungers()); } private static void addPointcuts(AsmManager model, String sourcefilename, ResolvedType aspect, IProgramElement containingAspect, ResolvedMember[] pointcuts) { for (int i = 0; i < pointcuts.length; i++) { ResolvedMember pointcut = pointcuts[i]; if (pointcut instanceof ResolvedPointcutDefinition) { ResolvedPointcutDefinition rpcd = (ResolvedPointcutDefinition) pointcut; Pointcut p = rpcd.getPointcut(); ISourceLocation sLoc = (p == null ? null : p.getSourceLocation()); if (sLoc == null) { sLoc = rpcd.getSourceLocation(); } ISourceLocation pointcutLocation = createSourceLocation(sourcefilename, aspect, sLoc); ProgramElement pointcutElement = new ProgramElement(model, pointcut.getName(), IProgramElement.Kind.POINTCUT, pointcutLocation, pointcut.getModifiers(), NO_COMMENT, Collections.EMPTY_LIST); containingAspect.addChild(pointcutElement); } } } private static final String NO_COMMENT = null; private static void addChildNodes(AsmManager asm, ResolvedType aspect, IProgramElement parent, ResolvedMember[] children) { for (int i = 0; i < children.length; i++) { ResolvedMember pcd = children[i]; if (pcd instanceof ResolvedPointcutDefinition) { ResolvedPointcutDefinition rpcd = (ResolvedPointcutDefinition) pcd; Pointcut p = rpcd.getPointcut(); ISourceLocation sLoc = (p == null ? null : p.getSourceLocation()); if (sLoc == null) { sLoc = rpcd.getSourceLocation(); } parent.addChild(new ProgramElement(asm, pcd.getName(), IProgramElement.Kind.POINTCUT, getBinarySourceLocation( aspect, sLoc), pcd.getModifiers(), null, Collections.EMPTY_LIST)); } } } private static void addChildNodes(AsmManager asm, ResolvedType aspect, IProgramElement parent, Collection children) { int deCtr = 1; int dwCtr = 1; for (Iterator iter = children.iterator(); iter.hasNext();) { Object element = iter.next(); if (element instanceof DeclareErrorOrWarning) { DeclareErrorOrWarning decl = (DeclareErrorOrWarning) element; int counter = 0; if (decl.isError()) { counter = deCtr++; } else { counter = dwCtr++; } parent.addChild(createDeclareErrorOrWarningChild(asm, aspect, decl, counter)); } else if (element instanceof Advice) { Advice advice = (Advice) element; parent.addChild(createAdviceChild(asm, advice)); } else if (element instanceof DeclareParents) { parent.addChild(createDeclareParentsChild(asm, (DeclareParents) element)); } else if (element instanceof BcelTypeMunger) { IProgramElement newChild = createIntertypeDeclaredChild(asm, aspect, (BcelTypeMunger) element); // newChild==null means it is something that could not be handled by createIntertypeDeclaredChild() if (newChild != null) { parent.addChild(newChild); } } } } // private static IProgramElement // createDeclareErrorOrWarningChild(AsmManager asm, ShadowMunger munger, // DeclareErrorOrWarning decl, int count) { // IProgramElement deowNode = new ProgramElement(asm, decl.getName(), // decl.isError() ? IProgramElement.Kind.DECLARE_ERROR // : IProgramElement.Kind.DECLARE_WARNING, // munger.getBinarySourceLocation(decl.getSourceLocation()), decl // .getDeclaringType().getModifiers(), null, null); // deowNode.setDetails("\"" + // AsmRelationshipUtils.genDeclareMessage(decl.getMessage()) + "\""); // if (count != -1) { // deowNode.setBytecodeName(decl.getName() + "_" + count); // } // return deowNode; // } private static IProgramElement createDeclareErrorOrWarningChild(AsmManager model, ResolvedType aspect, DeclareErrorOrWarning decl, int count) { IProgramElement deowNode = new ProgramElement(model, decl.getName(), decl.isError() ? IProgramElement.Kind.DECLARE_ERROR : IProgramElement.Kind.DECLARE_WARNING, getBinarySourceLocation(aspect, decl.getSourceLocation()), decl .getDeclaringType().getModifiers(), null, null); deowNode.setDetails("\"" + AsmRelationshipUtils.genDeclareMessage(decl.getMessage()) + "\""); if (count != -1) { deowNode.setBytecodeName(decl.getName() + "_" + count); } return deowNode; } private static IProgramElement createAdviceChild(AsmManager model, Advice advice) { IProgramElement adviceNode = new ProgramElement(model, advice.getKind().getName(), IProgramElement.Kind.ADVICE, advice .getBinarySourceLocation(advice.getSourceLocation()), advice.getSignature().getModifiers(), null, Collections.EMPTY_LIST); adviceNode.setDetails(AsmRelationshipUtils.genPointcutDetails(advice.getPointcut())); adviceNode.setBytecodeName(advice.getSignature().getName()); return adviceNode; } /** * Half baked implementation - will need completing if we go down this route rather than replacing it all for binary aspects. * Doesn't attempt to get parameter names correct - they may have been lost during (de)serialization of the munger, but the * member could still be located so they might be retrievable. */ private static IProgramElement createIntertypeDeclaredChild(AsmManager model, ResolvedType aspect, BcelTypeMunger itd) { ResolvedTypeMunger rtMunger = itd.getMunger(); ResolvedMember sig = rtMunger.getSignature(); Kind kind = rtMunger.getKind(); if (kind == ResolvedTypeMunger.Field) { // ITD FIELD // String name = rtMunger.getSignature().toString(); String name = sig.getDeclaringType().getClassName() + "." + sig.getName(); if (name.indexOf("$") != -1) { name = name.substring(name.indexOf("$") + 1); } IProgramElement pe = new ProgramElement(model, name, IProgramElement.Kind.INTER_TYPE_FIELD, getBinarySourceLocation( aspect, itd.getSourceLocation()), rtMunger.getSignature().getModifiers(), null, Collections.EMPTY_LIST); pe.setCorrespondingType(sig.getReturnType().getName()); return pe; } else if (kind == ResolvedTypeMunger.Method) { // ITD // METHOD String name = sig.getDeclaringType().getClassName() + "." + sig.getName(); if (name.indexOf("$") != -1) { name = name.substring(name.indexOf("$") + 1); } IProgramElement pe = new ProgramElement(model, name, IProgramElement.Kind.INTER_TYPE_METHOD, getBinarySourceLocation( aspect, itd.getSourceLocation()), rtMunger.getSignature().getModifiers(), null, Collections.EMPTY_LIST); setParams(pe, sig); return pe; } else if (kind == ResolvedTypeMunger.Constructor) { String name = sig.getDeclaringType().getClassName() + "." + sig.getDeclaringType().getClassName(); if (name.indexOf("$") != -1) { name = name.substring(name.indexOf("$") + 1); } IProgramElement pe = new ProgramElement(model, name, IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR, getBinarySourceLocation(aspect, itd.getSourceLocation()), rtMunger.getSignature().getModifiers(), null, Collections.EMPTY_LIST); setParams(pe, sig); return pe; // } else if (kind == ResolvedTypeMunger.MethodDelegate2) { // String name = sig.getDeclaringType().getClassName() + "." + sig.getName(); // if (name.indexOf("$") != -1) { // name = name.substring(name.indexOf("$") + 1); // } // IProgramElement pe = new ProgramElement(model, name, IProgramElement.Kind.INTER_TYPE_METHOD, getBinarySourceLocation( // aspect, itd.getSourceLocation()), rtMunger.getSignature().getModifiers(), null, Collections.EMPTY_LIST); // setParams(pe, sig); // return pe; } // other cases ignored for now return null; } private static void setParams(IProgramElement pe, ResolvedMember sig) { // do it for itds too UnresolvedType[] ts = sig.getParameterTypes(); pe.setParameterNames(Collections.EMPTY_LIST); // String[] pnames = sig.getParameterNames(); if (ts == null) { pe.setParameterSignatures(Collections.EMPTY_LIST, Collections.EMPTY_LIST); } else { List paramSigs = new ArrayList(); // List paramNames = new ArrayList(); for (int i = 0; i < ts.length; i++) { paramSigs.add(ts[i].getSignature().toCharArray()); // paramNames.add(pnames[i]); } pe.setParameterSignatures(paramSigs, Collections.EMPTY_LIST); // pe.setParameterNames(paramNames); } pe.setCorrespondingType(sig.getReturnType().getName()); } private static IProgramElement createDeclareParentsChild(AsmManager model, DeclareParents decp) { IProgramElement decpElement = new ProgramElement(model, "declare parents", IProgramElement.Kind.DECLARE_PARENTS, getBinarySourceLocation(decp.getDeclaringType(), decp.getSourceLocation()), Modifier.PUBLIC, null, Collections.EMPTY_LIST); return decpElement; } public static String getHandle(AsmManager asm, Advice advice) { if (null == advice.handle) { ISourceLocation sl = advice.getSourceLocation(); if (sl != null) { IProgramElement ipe = asm.getHierarchy().findElementForSourceLine(sl); advice.handle = ipe.getHandleIdentifier(); } } return advice.handle; } public static void addAdvisedRelationship(AsmManager model, Shadow matchedShadow, ShadowMunger munger) { if (model == null) { return; } if (munger instanceof Advice) { Advice advice = (Advice) munger; if (advice.getKind().isPerEntry() || advice.getKind().isCflow()) { // TODO: might want to show these in the future return; } if (World.createInjarHierarchy) { createHierarchyForBinaryAspect(model, advice); } IRelationshipMap mapper = model.getRelationshipMap(); IProgramElement targetNode = getNode(model, matchedShadow); if (targetNode == null) { return; } boolean runtimeTest = advice.hasDynamicTests(); IProgramElement.ExtraInformation extra = new IProgramElement.ExtraInformation(); String adviceHandle = getHandle(model, advice); if (adviceHandle == null) { return; } extra.setExtraAdviceInformation(advice.getKind().getName()); IProgramElement adviceElement = model.getHierarchy().findElementForHandle(adviceHandle); if (adviceElement != null) { adviceElement.setExtraInfo(extra); } String targetHandle = targetNode.getHandleIdentifier(); if (advice.getKind().equals(AdviceKind.Softener)) { IRelationship foreward = mapper.get(adviceHandle, IRelationship.Kind.DECLARE_SOFT, SOFTENS, runtimeTest, true); if (foreward != null) { foreward.addTarget(targetHandle); } IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE, SOFTENED_BY, runtimeTest, true); if (back != null) { back.addTarget(adviceHandle); } } else { IRelationship foreward = mapper.get(adviceHandle, IRelationship.Kind.ADVICE, ADVISES, runtimeTest, true); if (foreward != null) { foreward.addTarget(targetHandle); } IRelationship back = mapper.get(targetHandle, IRelationship.Kind.ADVICE, ADVISED_BY, runtimeTest, true); if (back != null) { back.addTarget(adviceHandle); } } if (adviceElement.getSourceLocation() != null) { model.addAspectInEffectThisBuild(adviceElement.getSourceLocation().getSourceFile()); } } } protected static IProgramElement getNode(AsmManager model, Shadow shadow) { Member enclosingMember = shadow.getEnclosingCodeSignature(); // This variant will not be tricked by ITDs that would report they are // in the target type already. // This enables us to discover the ITD declaration (in the aspect) and // advise it appropriately. // Have to be smart here, for a code node within an ITD we want to // lookup the declaration of the // ITD in the aspect in order to add the code node at the right place - // and not lookup the // ITD as it applies in some target type. Due to the use of // effectiveSignature we will find // that shadow.getEnclosingCodeSignature() will return a member // representing the ITD as it will // appear in the target type. So here, we do an extra bit of analysis to // make sure we // do the right thing in the ITD case. IProgramElement enclosingNode = null; if (shadow instanceof BcelShadow) { Member actualEnclosingMember = ((BcelShadow) shadow).getRealEnclosingCodeSignature(); if (actualEnclosingMember == null) { enclosingNode = lookupMember(model.getHierarchy(), shadow.getEnclosingType(), enclosingMember); } else { UnresolvedType type = enclosingMember.getDeclaringType(); UnresolvedType actualType = actualEnclosingMember.getDeclaringType(); // if these are not the same, it is an ITD and we need to use // the latter to lookup if (type.equals(actualType)) { enclosingNode = lookupMember(model.getHierarchy(), shadow.getEnclosingType(), enclosingMember); } else { enclosingNode = lookupMember(model.getHierarchy(), shadow.getEnclosingType(), actualEnclosingMember); } } } else { enclosingNode = lookupMember(model.getHierarchy(), shadow.getEnclosingType(), enclosingMember); } if (enclosingNode == null) { Lint.Kind err = shadow.getIWorld().getLint().shadowNotInStructure; if (err.isEnabled()) { err.signal(shadow.toString(), shadow.getSourceLocation()); } return null; } Member shadowSig = shadow.getSignature(); // pr235204 if (shadow.getKind() == Shadow.MethodCall || shadow.getKind() == Shadow.ConstructorCall || !shadowSig.equals(enclosingMember)) { IProgramElement bodyNode = findOrCreateCodeNode(model, enclosingNode, shadowSig, shadow); return bodyNode; } else { return enclosingNode; } } private static boolean sourceLinesMatch(ISourceLocation location1, ISourceLocation location2) { return (location1.getLine() == location2.getLine()); } /** * Finds or creates a code IProgramElement for the given shadow. * * The byteCodeName of the created node is set to 'shadowSig.getName() + "!" + counter', eg "println!3". The counter is the * occurence count of children within the enclosingNode which have the same name. So, for example, if a method contains two * System.out.println statements, the first one will have byteCodeName 'println!1' and the second will have byteCodeName * 'println!2'. This is to ensure the two nodes have unique handles when the handles do not depend on sourcelocations. * * Currently the shadows are examined in the sequence they appear in the source file. This means that the counters are * consistent over incremental builds. All aspects are compiled up front and any new aspect created will force a full build. * Moreover, if the body of the enclosingShadow is changed, then the model for this is rebuilt from scratch. */ private static IProgramElement findOrCreateCodeNode(AsmManager asm, IProgramElement enclosingNode, Member shadowSig, Shadow shadow) { for (Iterator it = enclosingNode.getChildren().iterator(); it.hasNext();) { IProgramElement node = (IProgramElement) it.next(); int excl = node.getBytecodeName().lastIndexOf('!'); if (((excl != -1 && shadowSig.getName().equals(node.getBytecodeName().substring(0, excl))) || shadowSig.getName() .equals(node.getBytecodeName())) && shadowSig.getSignature().equals(node.getBytecodeSignature()) && sourceLinesMatch(node.getSourceLocation(), shadow.getSourceLocation())) { return node; } } ISourceLocation sl = shadow.getSourceLocation(); // XXX why not use shadow file? new SourceLocation(sl.getSourceFile(), // sl.getLine()), SourceLocation peLoc = new SourceLocation(enclosingNode.getSourceLocation().getSourceFile(), sl.getLine()); peLoc.setOffset(sl.getOffset()); IProgramElement peNode = new ProgramElement(asm, shadow.toString(), IProgramElement.Kind.CODE, peLoc, 0, null, null); // check to see if the enclosing shadow already has children with the // same name. If so we want to add a counter to the byteCodeName // otherwise // we wont get unique handles int numberOfChildrenWithThisName = 0; for (Iterator it = enclosingNode.getChildren().iterator(); it.hasNext();) { IProgramElement child = (IProgramElement) it.next(); if (child.getName().equals(shadow.toString())) { numberOfChildrenWithThisName++; } } peNode.setBytecodeName(shadowSig.getName() + "!" + String.valueOf(numberOfChildrenWithThisName + 1)); peNode.setBytecodeSignature(shadowSig.getSignature()); enclosingNode.addChild(peNode); return peNode; } private static IProgramElement lookupMember(IHierarchy model, UnresolvedType declaringType, Member member) { IProgramElement typeElement = model.findElementForType(declaringType.getPackageName(), declaringType.getClassName()); if (typeElement == null) { return null; } for (Iterator it = typeElement.getChildren().iterator(); it.hasNext();) { IProgramElement element = (IProgramElement) it.next(); if (member.getName().equals(element.getBytecodeName()) && member.getSignature().equals(element.getBytecodeSignature())) { return element; } } // if we can't find the member, we'll just put it in the class return typeElement; } /** * Add a relationship for a matching declare annotation method or declare annotation constructor. Locating the method is a messy * (for messy read 'fragile') bit of code that could break at any moment but it's working for my simple testcase. */ public static void addDeclareAnnotationMethodRelationship(ISourceLocation sourceLocation, String affectedTypeName, ResolvedMember affectedMethod, AsmManager model) { if (model == null) { return; } String pkg = null; String type = affectedTypeName; int packageSeparator = affectedTypeName.lastIndexOf("."); if (packageSeparator != -1) { pkg = affectedTypeName.substring(0, packageSeparator); type = affectedTypeName.substring(packageSeparator + 1); } IHierarchy hierarchy = model.getHierarchy(); IProgramElement typeElem = hierarchy.findElementForType(pkg, type); if (typeElem == null) return; StringBuffer parmString = new StringBuffer("("); UnresolvedType[] args = affectedMethod.getParameterTypes(); // Type[] args = method.getArgumentTypes(); for (int i = 0; i < args.length; i++) { String s = args[i].getName();// Utility.signatureToString(args[i]. // getName()getSignature(), false); parmString.append(s); if ((i + 1) < args.length) parmString.append(","); } parmString.append(")"); IProgramElement methodElem = null; if (affectedMethod.getName().startsWith("<init>")) { // its a ctor methodElem = hierarchy.findElementForSignature(typeElem, IProgramElement.Kind.CONSTRUCTOR, type + parmString); if (methodElem == null && args.length == 0) methodElem = typeElem; // assume default ctor } else { // its a method methodElem = hierarchy.findElementForSignature(typeElem, IProgramElement.Kind.METHOD, affectedMethod.getName() + parmString); } if (methodElem == null) return; try { String targetHandle = methodElem.getHandleIdentifier(); if (targetHandle == null) return; IProgramElement sourceNode = hierarchy.findElementForSourceLine(sourceLocation); String sourceHandle = sourceNode.getHandleIdentifier(); if (sourceHandle == null) return; IRelationshipMap mapper = model.getRelationshipMap(); IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATES, false, true); foreward.addTarget(targetHandle); IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATED_BY, false, true); back.addTarget(sourceHandle); } catch (Throwable t) { // I'm worried about that code above, this will // make sure we don't explode if it plays up t.printStackTrace(); // I know I know .. but I don't want to lose // it! } } /** * Add a relationship for a matching declare ATfield. Locating the field is trickier than it might seem since we have no line * number info for it, we have to dig through the structure model under the fields' type in order to locate it. */ public static void addDeclareAnnotationFieldRelationship(AsmManager model, ISourceLocation declareLocation, String affectedTypeName, ResolvedMember affectedFieldName) { if (model == null) { return; } String pkg = null; String type = affectedTypeName; int packageSeparator = affectedTypeName.lastIndexOf("."); if (packageSeparator != -1) { pkg = affectedTypeName.substring(0, packageSeparator); type = affectedTypeName.substring(packageSeparator + 1); } IHierarchy hierarchy = model.getHierarchy(); IProgramElement typeElem = hierarchy.findElementForType(pkg, type); if (typeElem == null) { return; } IProgramElement fieldElem = hierarchy.findElementForSignature(typeElem, IProgramElement.Kind.FIELD, affectedFieldName .getName()); if (fieldElem == null) { return; } String targetHandle = fieldElem.getHandleIdentifier(); if (targetHandle == null) { return; } IProgramElement sourceNode = hierarchy.findElementForSourceLine(declareLocation); String sourceHandle = sourceNode.getHandleIdentifier(); if (sourceHandle == null) { return; } IRelationshipMap relmap = model.getRelationshipMap(); IRelationship foreward = relmap.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATES, false, true); foreward.addTarget(targetHandle); IRelationship back = relmap.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATED_BY, false, true); back.addTarget(sourceHandle); } }
314,365
Bug 314365 pointcut rewriter can have issues for large hashcode values
AJDT uses a pointcut like this: (persingleton(org.eclipse.ajdt.internal.ui.ras.UIFFDC) && ((handler(java.lang.Throwable+) && args(arg1)) && ((within(org.eclipse.ajdt..*) && (!within(org.eclipse.ajdt.internal.ui.lazystart..*) && (!within(org.eclipse.ajdt.internal.ui.dialogs.OpenTypeSelectionDialog2) && !(within(org.eclipse.ajdt.internal.ui.editor.AspectJBreakpointRulerAction) && handler(org.eclipse.jface.text.BadLocationException))))) && (!(within(org.eclipse.ajdt.core.ras.FFDC+) || handler(org.eclipse.core.runtime.OperationCanceledException)) && !this(java.lang.Object))))) After the pointcut rewriter has chewed on it, it is reduced to a normal form. This is meant to be a stable form such that further rewrites of it would not change it. This turned out not to be the case. The hashcodes for some of the components were quite large and manifested as negative integers. The arithmetic in the comparator for the elements would have a problem and give unhelpful responses. For example, if the elements were C,B,A it might rewrite them to A,B,C but on a subsequent rewrite it would realise that C was less than A, giving B,C,A. Whether it went wrong was dependent on the order in which the elements were collected by the rewriter. This is now fixed. It impacts incremental compilation sometimes as two pointcuts that should be identical look different because one has been through the rewritter more times than the other...
resolved fixed
1e28b92
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-05-25T23:03:13Z"
"2010-05-25T20:40:00Z"
org.aspectj.matcher/src/org/aspectj/weaver/patterns/PointcutEvaluationExpenseComparator.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.util.Comparator; import org.aspectj.weaver.Shadow; public class PointcutEvaluationExpenseComparator implements Comparator<Pointcut> { private static final int MATCHES_NOTHING = -1; private static final int WITHIN = 1; private static final int ATWITHIN = 2; private static final int STATICINIT = 3; private static final int ADVICEEXECUTION = 4; private static final int HANDLER = 5; private static final int GET_OR_SET = 6; private static final int WITHINCODE = 7; private static final int ATWITHINCODE = 8; private static final int EXE_INIT_PREINIT = 9; private static final int THIS_OR_TARGET = 10; private static final int CALL = 11; private static final int ANNOTATION = 12; private static final int AT_THIS_OR_TARGET = 13; private static final int ARGS = 14; private static final int AT_ARGS = 15; private static final int CFLOW = 16; private static final int IF = 17; private static final int OTHER = 20; /** * Compare 2 pointcuts based on an estimate of how expensive they may be to evaluate. * * within * * @within staticinitialization [make sure this has a fast match method] adviceexecution handler get, set withincode * @withincode execution, initialization, preinitialization call * @annotation this, target * @this, @target args * @args cflow, cflowbelow if */ public int compare(Pointcut p1, Pointcut p2) { // important property for a well-defined comparator if (p1.equals(p2)) { return 0; } int result = getScore(p1) - getScore(p2); if (result == 0) { // they have the same evaluation expense, but are not 'equal' // sort by hashCode result = p1.hashCode() - p2.hashCode(); if (result == 0) { /* not allowed if ne */return -1; } } return result; } // a higher score means a more expensive evaluation private int getScore(Pointcut p) { if (p.couldMatchKinds() == Shadow.NO_SHADOW_KINDS_BITS) { return MATCHES_NOTHING; } if (p instanceof WithinPointcut) { return WITHIN; } if (p instanceof WithinAnnotationPointcut) { return ATWITHIN; } if (p instanceof KindedPointcut) { KindedPointcut kp = (KindedPointcut) p; Shadow.Kind kind = kp.getKind(); if (kind == Shadow.AdviceExecution) { return ADVICEEXECUTION; } else if ((kind == Shadow.ConstructorCall) || (kind == Shadow.MethodCall)) { return CALL; } else if ((kind == Shadow.ConstructorExecution) || (kind == Shadow.MethodExecution) || (kind == Shadow.Initialization) || (kind == Shadow.PreInitialization)) { return EXE_INIT_PREINIT; } else if (kind == Shadow.ExceptionHandler) { return HANDLER; } else if ((kind == Shadow.FieldGet) || (kind == Shadow.FieldSet)) { return GET_OR_SET; } else if (kind == Shadow.StaticInitialization) { return STATICINIT; } else { return OTHER; } } if (p instanceof AnnotationPointcut) { return ANNOTATION; } if (p instanceof ArgsPointcut) { return ARGS; } if (p instanceof ArgsAnnotationPointcut) { return AT_ARGS; } if (p instanceof CflowPointcut) { return CFLOW; } if (p instanceof HandlerPointcut) { return HANDLER; } if (p instanceof IfPointcut) { return IF; } if (p instanceof ThisOrTargetPointcut) { return THIS_OR_TARGET; } if (p instanceof ThisOrTargetAnnotationPointcut) { return AT_THIS_OR_TARGET; } if (p instanceof WithincodePointcut) { return WITHINCODE; } if (p instanceof WithinCodeAnnotationPointcut) { return ATWITHINCODE; } if (p instanceof NotPointcut) { return getScore(((NotPointcut) p).getNegatedPointcut()); } if (p instanceof AndPointcut) { return getScore(((AndPointcut) p).getLeft()); } if (p instanceof OrPointcut) { return getScore(((OrPointcut) p).getLeft()); } return OTHER; } }
314,365
Bug 314365 pointcut rewriter can have issues for large hashcode values
AJDT uses a pointcut like this: (persingleton(org.eclipse.ajdt.internal.ui.ras.UIFFDC) && ((handler(java.lang.Throwable+) && args(arg1)) && ((within(org.eclipse.ajdt..*) && (!within(org.eclipse.ajdt.internal.ui.lazystart..*) && (!within(org.eclipse.ajdt.internal.ui.dialogs.OpenTypeSelectionDialog2) && !(within(org.eclipse.ajdt.internal.ui.editor.AspectJBreakpointRulerAction) && handler(org.eclipse.jface.text.BadLocationException))))) && (!(within(org.eclipse.ajdt.core.ras.FFDC+) || handler(org.eclipse.core.runtime.OperationCanceledException)) && !this(java.lang.Object))))) After the pointcut rewriter has chewed on it, it is reduced to a normal form. This is meant to be a stable form such that further rewrites of it would not change it. This turned out not to be the case. The hashcodes for some of the components were quite large and manifested as negative integers. The arithmetic in the comparator for the elements would have a problem and give unhelpful responses. For example, if the elements were C,B,A it might rewrite them to A,B,C but on a subsequent rewrite it would realise that C was less than A, giving B,C,A. Whether it went wrong was dependent on the order in which the elements were collected by the rewriter. This is now fixed. It impacts incremental compilation sometimes as two pointcuts that should be identical look different because one has been through the rewritter more times than the other...
resolved fixed
1e28b92
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-05-25T23:03:13Z"
"2010-05-25T20:40:00Z"
org.aspectj.matcher/testsrc/org/aspectj/weaver/patterns/PointcutRewriterTest.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.util.Iterator; import java.util.Set; import java.util.StringTokenizer; import junit.framework.TestCase; import org.aspectj.weaver.Shadow; /** * @author colyer * * TODO To change the template for this generated type comment go to Window - Preferences - Java - Code Style - Code * Templates */ public class PointcutRewriterTest extends TestCase { private PointcutRewriter prw; public void testDistributeNot() { Pointcut plain = getPointcut("this(Foo)"); assertEquals("Unchanged", plain, prw.rewrite(plain)); Pointcut not = getPointcut("!this(Foo)"); assertEquals("Unchanged", not, prw.rewrite(not)); Pointcut notNot = getPointcut("!!this(Foo)"); assertEquals("this(Foo)", prw.rewrite(notNot).toString()); Pointcut notNotNOT = getPointcut("!!!this(Foo)"); assertEquals("!this(Foo)", prw.rewrite(notNotNOT).toString()); Pointcut and = getPointcut("!(this(Foo) && this(Goo))"); assertEquals("(!this(Foo) || !this(Goo))", prw.rewrite(and, true).toString()); Pointcut or = getPointcut("!(this(Foo) || this(Goo))"); assertEquals("(!this(Foo) && !this(Goo))", prw.rewrite(or, true).toString()); Pointcut nestedNot = getPointcut("!(this(Foo) && !this(Goo))"); assertEquals("(!this(Foo) || this(Goo))", prw.rewrite(nestedNot, true).toString()); } public void testPullUpDisjunctions() { Pointcut aAndb = getPointcut("this(Foo) && this(Goo)"); assertEquals("Unchanged", aAndb, prw.rewrite(aAndb)); Pointcut aOrb = getPointcut("this(Foo) || this(Moo)"); assertEquals("Unchanged", aOrb, prw.rewrite(aOrb)); Pointcut leftOr = getPointcut("this(Foo) || (this(Goo) && this(Boo))"); assertEquals("or%anyorder%this(Foo)%and%anyorder%this(Boo)%this(Goo)", prw.rewrite(leftOr)); // assertEquals("(this(Foo) || (this(Boo) && this(Goo)))",prw.rewrite(leftOr).toString()); Pointcut rightOr = getPointcut("(this(Goo) && this(Boo)) || this(Foo)"); // assertEquals("(this(Foo) || (this(Boo) && this(Goo)))",prw.rewrite(rightOr).toString()); assertEquals("or%anyorder%this(Foo)%and%anyorder%this(Goo)%this(Boo)", prw.rewrite(rightOr)); Pointcut leftAnd = getPointcut("this(Foo) && (this(Goo) || this(Boo))"); // assertEquals("((this(Boo) && this(Foo)) || (this(Foo) && this(Goo)))",prw.rewrite(leftAnd).toString()); assertEquals("or%anyorder%and%anyorder%this(Boo)%this(Foo)%and%anyorder%this(Foo)%this(Goo)", prw.rewrite(leftAnd)); Pointcut rightAnd = getPointcut("(this(Goo) || this(Boo)) && this(Foo)"); // assertEquals("((this(Boo) && this(Foo)) || (this(Foo) && this(Goo)))",prw.rewrite(rightAnd).toString()); assertEquals("or%anyorder%and%anyorder%this(Boo)%this(Foo)%and%anyorder%this(Foo)%this(Goo)", prw.rewrite(rightAnd)); Pointcut nestedOrs = getPointcut("this(Foo) || this(Goo) || this(Boo)"); // assertEquals("((this(Boo) || this(Foo)) || this(Goo))",prw.rewrite(nestedOrs).toString()); assertEquals("or%anyorder%this(Goo)%or%anyorder%this(Boo)%this(Foo)", prw.rewrite(nestedOrs)); Pointcut nestedAnds = getPointcut("(this(Foo) && (this(Boo) && (this(Goo) || this(Moo))))"); // t(F) && (t(B) && (t(G) || t(M))) // ==> t(F) && ((t(B) && t(G)) || (t(B) && t(M))) // ==> (t(F) && (t(B) && t(G))) || (t(F) && (t(B) && t(M))) // assertEquals("(((this(Boo) && this(Foo)) && this(Goo)) || ((this(Boo) && this(Foo)) && this(Moo)))", // prw.rewrite(nestedAnds).toString()); assertEquals( "or%anyorder%and%anyorder%and%anyorder%this(Boo)%this(Foo)%this(Goo)%and%anyorder%and%anyorder%this(Boo)%this(Foo)%this(Moo)", prw.rewrite(nestedAnds)); } /** * spec is reverse polish notation with operators and, or , not, anyorder, delimiter is "%" (not whitespace). * * @param spec * @param pc */ private void assertEquals(String spec, Pointcut pc) { StringTokenizer strTok = new StringTokenizer(spec, "%"); String[] tokens = new String[strTok.countTokens()]; for (int i = 0; i < tokens.length; i++) { tokens[i] = strTok.nextToken(); } tokenIndex = 0; assertTrue(spec, equals(pc, tokens)); } private int tokenIndex = 0; private boolean equals(Pointcut pc, String[] tokens) { if (tokens[tokenIndex].equals("and")) { tokenIndex++; if (!(pc instanceof AndPointcut)) { return false; } AndPointcut apc = (AndPointcut) pc; Pointcut left = apc.getLeft(); Pointcut right = apc.getRight(); if (tokens[tokenIndex].equals("anyorder")) { tokenIndex++; int restorePoint = tokenIndex; boolean leftMatchFirst = equals(left, tokens) && equals(right, tokens); if (leftMatchFirst) { return true; } tokenIndex = restorePoint; boolean rightMatchFirst = equals(right, tokens) && equals(left, tokens); return rightMatchFirst; } else { return equals(left, tokens) && equals(right, tokens); } } else if (tokens[tokenIndex].equals("or")) { tokenIndex++; if (!(pc instanceof OrPointcut)) { return false; } OrPointcut opc = (OrPointcut) pc; Pointcut left = opc.getLeft(); Pointcut right = opc.getRight(); if (tokens[tokenIndex].equals("anyorder")) { tokenIndex++; int restorePoint = tokenIndex; boolean leftMatchFirst = equals(left, tokens) && equals(right, tokens); if (leftMatchFirst) { return true; } tokenIndex = restorePoint; boolean rightMatchFirst = equals(right, tokens) && equals(left, tokens); return rightMatchFirst; } else { return equals(left, tokens) && equals(right, tokens); } } else if (tokens[tokenIndex].equals("not")) { if (!(pc instanceof NotPointcut)) { return false; } tokenIndex++; NotPointcut np = (NotPointcut) pc; return equals(np.getNegatedPointcut(), tokens); } else { return tokens[tokenIndex++].equals(pc.toString()); } } // public void testSplitOutWithins() { // Pointcut simpleExecution = getPointcut("execution(* *.*(..))"); // assertEquals("Unchanged",simpleExecution,prw.rewrite(simpleExecution)); // Pointcut simpleWithinCode = getPointcut("withincode(* *.*(..))"); // assertEquals("Unchanged",simpleWithinCode,prw.rewrite(simpleWithinCode)); // Pointcut execution = getPointcut("execution(@Foo Foo (@Goo org.xyz..*).m*(Foo,Boo))"); // assertEquals("(within((@(Goo) org.xyz..*)) && execution(@(Foo) Foo m*(Foo, Boo)))", // prw.rewrite(execution).toString()); // Pointcut withincode = getPointcut("withincode(@Foo Foo (@Goo org.xyz..*).m*(Foo,Boo))"); // assertEquals("(within((@(Goo) org.xyz..*)) && withincode(@(Foo) Foo m*(Foo, Boo)))", // prw.rewrite(withincode).toString()); // Pointcut notExecution = getPointcut("!execution(Foo BankAccount+.*(..))"); // assertEquals("(!within(BankAccount+) || !execution(Foo *(..)))", // prw.rewrite(notExecution).toString()); // Pointcut andWithincode = getPointcut("withincode(Foo.new(..)) && this(Foo)"); // assertEquals("((within(Foo) && withincode(new(..))) && this(Foo))", // prw.rewrite(andWithincode).toString()); // Pointcut orExecution = getPointcut("this(Foo) || execution(Goo Foo.moo(Baa))"); // assertEquals("((within(Foo) && execution(Goo moo(Baa))) || this(Foo))", // prw.rewrite(orExecution).toString()); // } public void testRemoveDuplicatesInAnd() { Pointcut dupAnd = getPointcut("this(Foo) && this(Foo)"); assertEquals("this(Foo)", prw.rewrite(dupAnd).toString()); Pointcut splitdupAnd = getPointcut("(this(Foo) && target(Boo)) && this(Foo)"); assertEquals("(target(Boo) && this(Foo))", prw.rewrite(splitdupAnd).toString()); } public void testNotRemoveNearlyDuplicatesInAnd() { Pointcut toAndto = getPointcut("this(Object+) && this(Object)"); // Pointcut rewritten = prw.rewrite(toAndto); } public void testAAndNotAinAnd() { Pointcut aAndNota = getPointcut("this(Foo)&& !this(Foo)"); assertEquals("Matches nothing", "", prw.rewrite(aAndNota).toString()); Pointcut aAndBAndNota = getPointcut("this(Foo) && execution(* *.*(..)) && !this(Foo)"); assertEquals("Matches nothing", "", prw.rewrite(aAndBAndNota).toString()); } public void testIfFalseInAnd() { Pointcut ifFalse = IfPointcut.makeIfFalsePointcut(Pointcut.CONCRETE); Pointcut p = getPointcut("this(A)"); assertEquals("Matches nothing", "", prw.rewrite(new AndPointcut(ifFalse, p)).toString()); } public void testMatchesNothinginAnd() { Pointcut nothing = Pointcut.makeMatchesNothing(Pointcut.CONCRETE); Pointcut p = getPointcut("this(A)"); assertEquals("Matches nothing", "", prw.rewrite(new AndPointcut(nothing, p)).toString()); } public void testMixedKindsInAnd() { Pointcut mixedKinds = getPointcut("call(* *(..)) && execution(* *(..))"); assertEquals("Matches nothing", "", prw.rewrite(mixedKinds).toString()); Pointcut ok = getPointcut("this(Foo) && call(* *(..))"); assertEquals(ok, prw.rewrite(ok)); } public void testDetermineKindSetOfAnd() { Pointcut oneKind = getPointcut("execution(* foo(..)) && this(Boo)"); AndPointcut rewritten = (AndPointcut) prw.rewrite(oneKind); assertEquals("Only one kind", 1, Shadow.howMany(rewritten.couldMatchKinds())); assertTrue("It's Shadow.MethodExecution", Shadow.MethodExecution.isSet(rewritten.couldMatchKinds())); } public void testKindSetOfExecution() { Pointcut p = getPointcut("execution(* foo(..))"); assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); assertTrue("It's Shadow.MethodExecution", Shadow.MethodExecution.isSet(p.couldMatchKinds())); p = getPointcut("execution(new(..))"); assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); assertTrue("It's Shadow.ConstructorExecution", Shadow.ConstructorExecution.isSet(p.couldMatchKinds())); } public void testKindSetOfCall() { Pointcut p = getPointcut("call(* foo(..))"); assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); assertTrue("It's Shadow.MethodCall", Shadow.MethodCall.isSet(p.couldMatchKinds())); p = getPointcut("call(new(..))"); assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); assertTrue("It's Shadow.ConstructorCall", Shadow.ConstructorCall.isSet(p.couldMatchKinds())); } public void testKindSetOfAdviceExecution() { Pointcut p = getPointcut("adviceexecution()"); assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); assertTrue("It's Shadow.AdviceExecution", Shadow.AdviceExecution.isSet(p.couldMatchKinds())); } public void testKindSetOfGet() { Pointcut p = getPointcut("get(* *)"); assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); assertTrue("It's Shadow.FieldGet", Shadow.FieldGet.isSet(p.couldMatchKinds())); } public void testKindSetOfSet() { Pointcut p = getPointcut("set(* *)"); assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); assertTrue("It's Shadow.FieldSet", Shadow.FieldSet.isSet(p.couldMatchKinds())); } public void testKindSetOfHandler() { Pointcut p = getPointcut("handler(*)"); assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); assertTrue("It's Shadow.ExceptionHandler", Shadow.ExceptionHandler.isSet(p.couldMatchKinds())); } public void testKindSetOfInitialization() { Pointcut p = getPointcut("initialization(new (..))"); assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); assertTrue("It's Shadow.Initialization", Shadow.Initialization.isSet(p.couldMatchKinds())); } public void testKindSetOfPreInitialization() { Pointcut p = getPointcut("preinitialization(new (..))"); assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); assertTrue("It's Shadow.PreInitialization", Shadow.PreInitialization.isSet(p.couldMatchKinds())); } public void testKindSetOfStaticInitialization() { Pointcut p = getPointcut("staticinitialization(*)"); assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); assertTrue("It's Shadow.StaticInitialization", Shadow.StaticInitialization.isSet(p.couldMatchKinds())); } public void testKindSetOfThis() { Pointcut p = getPointcut("this(Foo)"); Set matches = Shadow.toSet(p.couldMatchKinds()); for (Iterator iter = matches.iterator(); iter.hasNext();) { Shadow.Kind kind = (Shadow.Kind) iter.next(); assertFalse("No kinds that don't have a this", kind.neverHasThis()); } for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { if (!Shadow.SHADOW_KINDS[i].neverHasThis()) { assertTrue("All kinds that do have this", matches.contains(Shadow.SHADOW_KINDS[i])); } } // + @ p = getPointcut("@this(Foo)"); matches = Shadow.toSet(p.couldMatchKinds()); for (Iterator iter = matches.iterator(); iter.hasNext();) { Shadow.Kind kind = (Shadow.Kind) iter.next(); assertFalse("No kinds that don't have a this", kind.neverHasThis()); } for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { if (!Shadow.SHADOW_KINDS[i].neverHasThis()) { assertTrue("All kinds that do have this", matches.contains(Shadow.SHADOW_KINDS[i])); } } } public void testKindSetOfTarget() { Pointcut p = getPointcut("target(Foo)"); Set matches = Shadow.toSet(p.couldMatchKinds()); for (Iterator iter = matches.iterator(); iter.hasNext();) { Shadow.Kind kind = (Shadow.Kind) iter.next(); assertFalse("No kinds that don't have a target", kind.neverHasTarget()); } for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { if (!Shadow.SHADOW_KINDS[i].neverHasTarget()) { assertTrue("All kinds that do have target", matches.contains(Shadow.SHADOW_KINDS[i])); } } // + @ p = getPointcut("@target(Foo)"); matches = Shadow.toSet(p.couldMatchKinds()); for (Iterator iter = matches.iterator(); iter.hasNext();) { Shadow.Kind kind = (Shadow.Kind) iter.next(); assertFalse("No kinds that don't have a target", kind.neverHasTarget()); } for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { if (!Shadow.SHADOW_KINDS[i].neverHasTarget()) { assertTrue("All kinds that do have target", matches.contains(Shadow.SHADOW_KINDS[i])); } } } public void testKindSetOfArgs() { Pointcut p = getPointcut("args(..)"); assertTrue("All kinds", p.couldMatchKinds() == Shadow.ALL_SHADOW_KINDS_BITS); // + @ p = getPointcut("@args(..)"); assertTrue("All kinds", p.couldMatchKinds() == Shadow.ALL_SHADOW_KINDS_BITS); } public void testKindSetOfAnnotation() { Pointcut p = getPointcut("@annotation(Foo)"); assertTrue("All kinds", p.couldMatchKinds() == Shadow.ALL_SHADOW_KINDS_BITS); } public void testKindSetOfWithin() { Pointcut p = getPointcut("within(*)"); assertTrue("All kinds", p.couldMatchKinds() == Shadow.ALL_SHADOW_KINDS_BITS); // + @ p = getPointcut("@within(Foo)"); assertTrue("All kinds", p.couldMatchKinds() == Shadow.ALL_SHADOW_KINDS_BITS); } public void testKindSetOfWithinCode() { Pointcut p = getPointcut("withincode(* foo(..))"); Set matches = Shadow.toSet(p.couldMatchKinds()); for (Iterator iter = matches.iterator(); iter.hasNext();) { Shadow.Kind kind = (Shadow.Kind) iter.next(); assertFalse("No kinds that are themselves enclosing", (kind.isEnclosingKind() && kind != Shadow.ConstructorExecution && kind != Shadow.Initialization)); } for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { if (!Shadow.SHADOW_KINDS[i].isEnclosingKind()) { assertTrue("All kinds that are not enclosing", matches.contains(Shadow.SHADOW_KINDS[i])); } } assertTrue("Need cons-exe for inlined field inits", matches.contains(Shadow.ConstructorExecution)); assertTrue("Need init for inlined field inits", matches.contains(Shadow.Initialization)); // + @ p = getPointcut("@withincode(Foo)"); matches = Shadow.toSet(p.couldMatchKinds()); for (Iterator iter = matches.iterator(); iter.hasNext();) { Shadow.Kind kind = (Shadow.Kind) iter.next(); assertFalse("No kinds that are themselves enclosing", kind.isEnclosingKind()); } for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { if (!Shadow.SHADOW_KINDS[i].isEnclosingKind()) { assertTrue("All kinds that are not enclosing", matches.contains(Shadow.SHADOW_KINDS[i])); } } } public void testKindSetOfIf() { Pointcut p = new IfPointcut(null, 0); assertTrue("All kinds", p.couldMatchKinds() == Shadow.ALL_SHADOW_KINDS_BITS); p = IfPointcut.makeIfTruePointcut(Pointcut.CONCRETE); assertTrue("All kinds", p.couldMatchKinds() == Shadow.ALL_SHADOW_KINDS_BITS); p = IfPointcut.makeIfFalsePointcut(Pointcut.CONCRETE); assertTrue("Nothing", p.couldMatchKinds() == Shadow.NO_SHADOW_KINDS_BITS); } public void testKindSetOfCflow() { Pointcut p = getPointcut("cflow(this(Foo))"); assertTrue("All kinds", p.couldMatchKinds() == Shadow.ALL_SHADOW_KINDS_BITS); // [below] p = getPointcut("cflowbelow(this(Foo))"); assertTrue("All kinds", p.couldMatchKinds() == Shadow.ALL_SHADOW_KINDS_BITS); } public void testKindSetInNegation() { Pointcut p = getPointcut("!execution(new(..))"); assertTrue("All kinds", p.couldMatchKinds() == Shadow.ALL_SHADOW_KINDS_BITS); } public void testKindSetOfOr() { Pointcut p = getPointcut("execution(new(..)) || get(* *)"); Set matches = Shadow.toSet(p.couldMatchKinds()); assertEquals("2 kinds", 2, matches.size()); assertTrue("ConstructorExecution", matches.contains(Shadow.ConstructorExecution)); assertTrue("FieldGet", matches.contains(Shadow.FieldGet)); } public void testOrderingInAnd() { Pointcut bigLongPC = getPointcut("cflow(this(Foo)) && @args(X) && args(X) && @this(Foo) && @target(Boo) && this(Moo) && target(Boo) && @annotation(Moo) && @withincode(Boo) && withincode(new(..)) && set(* *)&& @within(Foo) && within(Foo)"); Pointcut rewritten = prw.rewrite(bigLongPC); assertEquals( "((((((((((((within(Foo) && @within(Foo)) && set(* *)) && withincode(new(..))) && @withincode(Boo)) && target(Boo)) && this(Moo)) && @annotation(Moo)) && @target(Boo)) && @this(Foo)) && args(X)) && @args(X)) && cflow(this(Foo)))", rewritten.toString()); } public void testOrderingInSimpleOr() { OrPointcut opc = (OrPointcut) getPointcut("execution(new(..)) || get(* *)"); assertEquals("reordered", "(get(* *) || execution(new(..)))", prw.rewrite(opc).toString()); } public void testOrderingInNestedOrs() { OrPointcut opc = (OrPointcut) getPointcut("(execution(new(..)) || get(* *)) || within(abc)"); assertEquals("reordered", "((within(abc) || get(* *)) || execution(new(..)))", prw.rewrite(opc).toString()); } public void testOrderingInOrsWithNestedAnds() { OrPointcut opc = (OrPointcut) getPointcut("get(* *) || (execution(new(..)) && within(abc))"); assertEquals("reordered", "((within(abc) && execution(new(..))) || get(* *))", prw.rewrite(opc).toString()); } private Pointcut getPointcut(String s) { return new PatternParser(s).parsePointcut(); } /* * @see TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); prw = new PointcutRewriter(); } }
314,130
Bug 314130 [plan] [ltw] [hcr] LTW, Reweaving and Hot Code Replace changes reflected every two saves of files
null
resolved fixed
cf0ee0c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-05-26T22:31:02Z"
"2010-05-24T16:53:20Z"
weaver/src/org/aspectj/weaver/bcel/BcelObjectType.java
/* ******************************************************************* * Copyright (c) 2002 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * RonBodkin/AndyClement optimizations for memory consumption/speed * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.PrintStream; import java.lang.ref.WeakReference; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.AttributeUtils; import org.aspectj.apache.bcel.classfile.ConstantClass; import org.aspectj.apache.bcel.classfile.ConstantPool; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.InnerClass; import org.aspectj.apache.bcel.classfile.InnerClasses; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen; import org.aspectj.apache.bcel.classfile.annotation.EnumElementValue; import org.aspectj.apache.bcel.classfile.annotation.NameValuePair; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.GenericSignature; import org.aspectj.weaver.AbstractReferenceTypeDelegate; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.AnnotationTargetKind; import org.aspectj.weaver.BCException; import org.aspectj.weaver.BindingScope; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.SourceContextImpl; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelGenericSignatureToTypeXConverter.GenericSignatureFormatException; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.DeclareErrorOrWarning; import org.aspectj.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.FormalBinding; import org.aspectj.weaver.patterns.IScope; import org.aspectj.weaver.patterns.PerClause; public class BcelObjectType extends AbstractReferenceTypeDelegate { public JavaClass javaClass; private boolean artificial; // Was the BcelObject built from an artificial set of bytes? Or from the real ondisk stuff? private LazyClassGen lazyClassGen = null; // set lazily if it's an aspect private int modifiers; private String className; private String superclassSignature; private String superclassName; private String[] interfaceSignatures; private ResolvedMember[] fields = null; private ResolvedMember[] methods = null; private ResolvedType[] annotationTypes = null; private AnnotationAJ[] annotations = null; private TypeVariable[] typeVars = null; private String retentionPolicy; private AnnotationTargetKind[] annotationTargetKinds; // Aspect related stuff (pointcuts *could* be in a java class) private AjAttribute.WeaverVersionInfo wvInfo = AjAttribute.WeaverVersionInfo.UNKNOWN; private ResolvedPointcutDefinition[] pointcuts = null; private ResolvedMember[] privilegedAccess = null; private WeaverStateInfo weaverState = null; private PerClause perClause = null; private List<ConcreteTypeMunger> typeMungers = Collections.emptyList(); private List<Declare> declares = Collections.emptyList(); private GenericSignature.FormalTypeParameter[] formalsForResolution = null; private String declaredSignature = null; private boolean hasBeenWoven = false; private boolean isGenericType = false; private boolean isInterface; private boolean isEnum; private boolean isAnnotation; private boolean isAnonymous; private boolean isNested; private boolean isObject = false; // set upon construction private boolean isAnnotationStyleAspect = false;// set upon construction private boolean isCodeStyleAspect = false; // not redundant with field // above! private WeakReference<ResolvedType> superTypeReference = new WeakReference<ResolvedType>(null); private WeakReference<ResolvedType[]> superInterfaceReferences = new WeakReference<ResolvedType[]>(null); private int bitflag = 0x0000; // discovery bits private static final int DISCOVERED_ANNOTATION_RETENTION_POLICY = 0x0001; private static final int UNPACKED_GENERIC_SIGNATURE = 0x0002; private static final int UNPACKED_AJATTRIBUTES = 0x0004; // see note(1) // below private static final int DISCOVERED_ANNOTATION_TARGET_KINDS = 0x0008; private static final int DISCOVERED_DECLARED_SIGNATURE = 0x0010; private static final int DISCOVERED_WHETHER_ANNOTATION_STYLE = 0x0020; private static final int ANNOTATION_UNPACK_IN_PROGRESS = 0x0100; private static final String[] NO_INTERFACE_SIGS = new String[] {}; /* * Notes: note(1): in some cases (perclause inheritance) we encounter unpacked state when calling getPerClause * * note(2): A BcelObjectType is 'damaged' if it has been modified from what was original constructed from the bytecode. This * currently happens if the parents are modified or an annotation is added - ideally BcelObjectType should be immutable but * that's a bigger piece of work. XXX */ BcelObjectType(ReferenceType resolvedTypeX, JavaClass javaClass, boolean artificial, boolean exposedToWeaver) { super(resolvedTypeX, exposedToWeaver); this.javaClass = javaClass; this.artificial = artificial; initializeFromJavaclass(); // ATAJ: set the delegate right now for @AJ pointcut, else it is done // too late to lookup // @AJ pc refs annotation in class hierarchy resolvedTypeX.setDelegate(this); ISourceContext sourceContext = resolvedTypeX.getSourceContext(); if (sourceContext == SourceContextImpl.UNKNOWN_SOURCE_CONTEXT) { sourceContext = new SourceContextImpl(this); setSourceContext(sourceContext); } // this should only ever be java.lang.Object which is // the only class in Java-1.4 with no superclasses isObject = (javaClass.getSuperclassNameIndex() == 0); ensureAspectJAttributesUnpacked(); // if (sourceContext instanceof SourceContextImpl) { // ((SourceContextImpl)sourceContext).setSourceFileName(javaClass. // getSourceFileName()); // } setSourcefilename(javaClass.getSourceFileName()); } // repeat initialization public void setJavaClass(JavaClass newclass, boolean artificial) { this.javaClass = newclass; this.artificial = artificial; resetState(); initializeFromJavaclass(); } @Override public boolean isCacheable() { return true; } private void initializeFromJavaclass() { isInterface = javaClass.isInterface(); isEnum = javaClass.isEnum(); isAnnotation = javaClass.isAnnotation(); isAnonymous = javaClass.isAnonymous(); isNested = javaClass.isNested(); modifiers = javaClass.getModifiers(); superclassName = javaClass.getSuperclassName(); className = javaClass.getClassName(); cachedGenericClassTypeSignature = null; } // --- getters // Java related public boolean isInterface() { return isInterface; } public boolean isEnum() { return isEnum; } public boolean isAnnotation() { return isAnnotation; } public boolean isAnonymous() { return isAnonymous; } public boolean isNested() { return isNested; } public int getModifiers() { return modifiers; } /** * Must take into account generic signature */ public ResolvedType getSuperclass() { if (isObject) { return null; } ResolvedType supertype = superTypeReference.get(); if (supertype == null) { ensureGenericSignatureUnpacked(); if (superclassSignature == null) { if (superclassName == null) { superclassName = javaClass.getSuperclassName(); } superclassSignature = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(superclassName)).getSignature(); } World world = getResolvedTypeX().getWorld(); supertype = world.resolve(UnresolvedType.forSignature(superclassSignature)); superTypeReference = new WeakReference<ResolvedType>(supertype); } return supertype; } public World getWorld() { return getResolvedTypeX().getWorld(); } /** * Retrieves the declared interfaces - this allows for the generic signature on a type. If specified then the generic signature * is used to work out the types - this gets around the results of erasure when the class was originally compiled. */ public ResolvedType[] getDeclaredInterfaces() { ResolvedType[] cachedInterfaceTypes = superInterfaceReferences.get(); if (cachedInterfaceTypes == null) { ensureGenericSignatureUnpacked(); ResolvedType[] interfaceTypes = null; if (interfaceSignatures == null) { String[] names = javaClass.getInterfaceNames(); if (names.length == 0) { interfaceSignatures = NO_INTERFACE_SIGS; interfaceTypes = ResolvedType.NONE; } else { interfaceSignatures = new String[names.length]; interfaceTypes = new ResolvedType[names.length]; for (int i = 0, len = names.length; i < len; i++) { interfaceTypes[i] = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(names[i])); interfaceSignatures[i] = interfaceTypes[i].getSignature(); } } } else { interfaceTypes = new ResolvedType[interfaceSignatures.length]; for (int i = 0, len = interfaceSignatures.length; i < len; i++) { interfaceTypes[i] = getResolvedTypeX().getWorld().resolve(UnresolvedType.forSignature(interfaceSignatures[i])); } } superInterfaceReferences = new WeakReference<ResolvedType[]>(interfaceTypes); return interfaceTypes; } else { return cachedInterfaceTypes; } } public ResolvedMember[] getDeclaredMethods() { ensureGenericSignatureUnpacked(); if (methods == null) { Method[] ms = javaClass.getMethods(); methods = new ResolvedMember[ms.length]; for (int i = ms.length - 1; i >= 0; i--) { methods[i] = new BcelMethod(this, ms[i]); } } return methods; } public ResolvedMember[] getDeclaredFields() { ensureGenericSignatureUnpacked(); if (fields == null) { Field[] fs = javaClass.getFields(); fields = new ResolvedMember[fs.length]; for (int i = 0, len = fs.length; i < len; i++) { fields[i] = new BcelField(this, fs[i]); } } return fields; } public TypeVariable[] getTypeVariables() { if (!isGeneric()) { return TypeVariable.NONE; } if (typeVars == null) { GenericSignature.ClassSignature classSig = getGenericClassTypeSignature(); typeVars = new TypeVariable[classSig.formalTypeParameters.length]; for (int i = 0; i < typeVars.length; i++) { GenericSignature.FormalTypeParameter ftp = classSig.formalTypeParameters[i]; try { typeVars[i] = BcelGenericSignatureToTypeXConverter.formalTypeParameter2TypeVariable(ftp, classSig.formalTypeParameters, getResolvedTypeX().getWorld()); } catch (GenericSignatureFormatException e) { // this is a development bug, so fail fast with good info throw new IllegalStateException("While getting the type variables for type " + this.toString() + " with generic signature " + classSig + " the following error condition was detected: " + e.getMessage()); } } } return typeVars; } public Collection<ConcreteTypeMunger> getTypeMungers() { return typeMungers; } public Collection<Declare> getDeclares() { return declares; } public Collection<ResolvedMember> getPrivilegedAccesses() { if (privilegedAccess == null) { return Collections.emptyList(); } return Arrays.asList(privilegedAccess); } public ResolvedMember[] getDeclaredPointcuts() { return pointcuts; } public boolean isAspect() { return perClause != null; } /** * Check if the type is an @AJ aspect (no matter if used from an LTW point of view). Such aspects are annotated with @Aspect * * @return true for @AJ aspect */ public boolean isAnnotationStyleAspect() { if ((bitflag & DISCOVERED_WHETHER_ANNOTATION_STYLE) == 0) { bitflag |= DISCOVERED_WHETHER_ANNOTATION_STYLE; isAnnotationStyleAspect = !isCodeStyleAspect && hasAnnotation(AjcMemberMaker.ASPECT_ANNOTATION); } return isAnnotationStyleAspect; } /** * Process any org.aspectj.weaver attributes stored against the class. */ private void ensureAspectJAttributesUnpacked() { if ((bitflag & UNPACKED_AJATTRIBUTES) != 0) { return; } bitflag |= UNPACKED_AJATTRIBUTES; IMessageHandler msgHandler = getResolvedTypeX().getWorld().getMessageHandler(); // Pass in empty list that can store things for readAj5 to process List<AjAttribute> l = null; try { l = Utility.readAjAttributes(className, javaClass.getAttributes(), getResolvedTypeX().getSourceContext(), getResolvedTypeX().getWorld(), AjAttribute.WeaverVersionInfo.UNKNOWN, new BcelConstantPoolReader( javaClass.getConstantPool())); } catch (RuntimeException re) { throw new RuntimeException("Problem processing attributes in " + javaClass.getFileName(), re); } List pointcuts = new ArrayList(); typeMungers = new ArrayList(); declares = new ArrayList(); processAttributes(l, pointcuts, false); l = AtAjAttributes.readAj5ClassAttributes(((BcelWorld) getResolvedTypeX().getWorld()).getModelAsAsmManager(), javaClass, getResolvedTypeX(), getResolvedTypeX().getSourceContext(), msgHandler, isCodeStyleAspect); AjAttribute.Aspect deferredAspectAttribute = processAttributes(l, pointcuts, true); if (pointcuts.size() == 0) { this.pointcuts = ResolvedPointcutDefinition.NO_POINTCUTS; } else { this.pointcuts = (ResolvedPointcutDefinition[]) pointcuts.toArray(new ResolvedPointcutDefinition[pointcuts.size()]); } resolveAnnotationDeclares(l); if (deferredAspectAttribute != null) { // we can finally process the aspect and its associated perclause... perClause = deferredAspectAttribute.reifyFromAtAspectJ(this.getResolvedTypeX()); } if (isAspect() && !Modifier.isAbstract(getModifiers()) && isGeneric()) { msgHandler.handleMessage(MessageUtil.error("The generic aspect '" + getResolvedTypeX().getName() + "' must be declared abstract", getResolvedTypeX().getSourceLocation())); } } private AjAttribute.Aspect processAttributes(List<AjAttribute> attributeList, List<ResolvedPointcutDefinition> pointcuts, boolean fromAnnotations) { AjAttribute.Aspect deferredAspectAttribute = null; for (AjAttribute a : attributeList) { if (a instanceof AjAttribute.Aspect) { if (fromAnnotations) { deferredAspectAttribute = (AjAttribute.Aspect) a; } else { perClause = ((AjAttribute.Aspect) a).reify(this.getResolvedTypeX()); isCodeStyleAspect = true; } } else if (a instanceof AjAttribute.PointcutDeclarationAttribute) { pointcuts.add(((AjAttribute.PointcutDeclarationAttribute) a).reify()); } else if (a instanceof AjAttribute.WeaverState) { weaverState = ((AjAttribute.WeaverState) a).reify(); } else if (a instanceof AjAttribute.TypeMunger) { typeMungers.add(((AjAttribute.TypeMunger) a).reify(getResolvedTypeX().getWorld(), getResolvedTypeX())); } else if (a instanceof AjAttribute.DeclareAttribute) { declares.add(((AjAttribute.DeclareAttribute) a).getDeclare()); } else if (a instanceof AjAttribute.PrivilegedAttribute) { AjAttribute.PrivilegedAttribute privAttribute = (AjAttribute.PrivilegedAttribute) a; privilegedAccess = privAttribute.getAccessedMembers(); } else if (a instanceof AjAttribute.SourceContextAttribute) { if (getResolvedTypeX().getSourceContext() instanceof SourceContextImpl) { AjAttribute.SourceContextAttribute sca = (AjAttribute.SourceContextAttribute) a; ((SourceContextImpl) getResolvedTypeX().getSourceContext()).configureFromAttribute(sca.getSourceFileName(), sca .getLineBreaks()); setSourcefilename(sca.getSourceFileName()); } } else if (a instanceof AjAttribute.WeaverVersionInfo) { wvInfo = (AjAttribute.WeaverVersionInfo) a; // Set the weaver // version used to // build this type } else { throw new BCException("bad attribute " + a); } } return deferredAspectAttribute; } /** * Extra processing step needed because declares that come from annotations are not pre-resolved. We can't do the resolution * until *after* the pointcuts have been resolved. * * @param attributeList */ private void resolveAnnotationDeclares(List attributeList) { FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; IScope bindingScope = new BindingScope(getResolvedTypeX(), getResolvedTypeX().getSourceContext(), bindings); for (Iterator iter = attributeList.iterator(); iter.hasNext();) { AjAttribute a = (AjAttribute) iter.next(); if (a instanceof AjAttribute.DeclareAttribute) { Declare decl = (((AjAttribute.DeclareAttribute) a).getDeclare()); if (decl instanceof DeclareErrorOrWarning) { decl.resolve(bindingScope); } else if (decl instanceof DeclarePrecedence) { ((DeclarePrecedence) decl).setScopeForResolution(bindingScope); } } } } public PerClause getPerClause() { ensureAspectJAttributesUnpacked(); return perClause; } public JavaClass getJavaClass() { return javaClass; } public boolean isArtificial() { return artificial; } public void resetState() { if (javaClass == null) { // we might store the classname and allow reloading? // At this point we are relying on the world to not evict if it // might want to reweave multiple times throw new BCException("can't weave evicted type"); } bitflag = 0x0000; this.annotationTypes = null; this.annotations = null; this.interfaceSignatures = null; this.superclassSignature = null; this.superclassName = null; this.fields = null; this.methods = null; this.pointcuts = null; this.perClause = null; this.weaverState = null; this.lazyClassGen = null; hasBeenWoven = false; isObject = (javaClass.getSuperclassNameIndex() == 0); isAnnotationStyleAspect = false; ensureAspectJAttributesUnpacked(); } public void finishedWith() { // memory usage experiments.... // this.interfaces = null; // this.superClass = null; // this.fields = null; // this.methods = null; // this.pointcuts = null; // this.perClause = null; // this.weaverState = null; // this.lazyClassGen = null; // this next line frees up memory, but need to understand incremental // implications // before leaving it in. // getResolvedTypeX().setSourceContext(null); } public WeaverStateInfo getWeaverState() { return weaverState; } void setWeaverState(WeaverStateInfo weaverState) { this.weaverState = weaverState; } public void printWackyStuff(PrintStream out) { if (typeMungers.size() > 0) { out.println(" TypeMungers: " + typeMungers); } if (declares.size() > 0) { out.println(" declares: " + declares); } } /** * Return the lazyClassGen associated with this type. For aspect types, this value will be cached, since it is used to inline * advice. For non-aspect types, this lazyClassGen is always newly constructed. */ public LazyClassGen getLazyClassGen() { LazyClassGen ret = lazyClassGen; if (ret == null) { // System.err.println("creating lazy class gen for: " + this); ret = new LazyClassGen(this); // ret.print(System.err); // System.err.println("made LCG from : " + // this.getJavaClass().getSuperclassName ); if (isAspect()) { lazyClassGen = ret; } } return ret; } public boolean isSynthetic() { return getResolvedTypeX().isSynthetic(); } public AjAttribute.WeaverVersionInfo getWeaverVersionAttribute() { return wvInfo; } // -- annotation related public ResolvedType[] getAnnotationTypes() { ensureAnnotationsUnpacked(); return annotationTypes; } public AnnotationAJ[] getAnnotations() { ensureAnnotationsUnpacked(); return annotations; } public boolean hasAnnotation(UnresolvedType ofType) { // Due to re-entrancy we may be in the middle of unpacking the annotations already... in which case use this slow // alternative until the stack unwinds itself if (isUnpackingAnnotations()) { AnnotationGen annos[] = javaClass.getAnnotations(); if (annos == null || annos.length == 0) { return false; } else { String lookingForSignature = ofType.getSignature(); for (int a = 0; a < annos.length; a++) { AnnotationGen annotation = annos[a]; if (lookingForSignature.equals(annotation.getTypeSignature())) { return true; } } } return false; } ensureAnnotationsUnpacked(); for (int i = 0, max = annotationTypes.length; i < max; i++) { UnresolvedType ax = annotationTypes[i]; if (ax == null) { throw new RuntimeException("Annotation entry " + i + " on type " + this.getResolvedTypeX().getName() + " is null!"); } if (ax.equals(ofType)) { return true; } } return false; } public boolean isAnnotationWithRuntimeRetention() { return (getRetentionPolicy() == null ? false : getRetentionPolicy().equals("RUNTIME")); } public String getRetentionPolicy() { if ((bitflag & DISCOVERED_ANNOTATION_RETENTION_POLICY) == 0) { bitflag |= DISCOVERED_ANNOTATION_RETENTION_POLICY; retentionPolicy = null; // null means we have no idea if (isAnnotation()) { ensureAnnotationsUnpacked(); for (int i = annotations.length - 1; i >= 0; i--) { AnnotationAJ ax = annotations[i]; if (ax.getTypeName().equals(UnresolvedType.AT_RETENTION.getName())) { List values = ((BcelAnnotation) ax).getBcelAnnotation().getValues(); for (Iterator it = values.iterator(); it.hasNext();) { NameValuePair element = (NameValuePair) it.next(); EnumElementValue v = (EnumElementValue) element.getValue(); retentionPolicy = v.getEnumValueString(); return retentionPolicy; } } } } } return retentionPolicy; } public boolean canAnnotationTargetType() { AnnotationTargetKind[] targetKinds = getAnnotationTargetKinds(); if (targetKinds == null) { return true; } for (int i = 0; i < targetKinds.length; i++) { if (targetKinds[i].equals(AnnotationTargetKind.TYPE)) { return true; } } return false; } public AnnotationTargetKind[] getAnnotationTargetKinds() { if ((bitflag & DISCOVERED_ANNOTATION_TARGET_KINDS) != 0) { return annotationTargetKinds; } bitflag |= DISCOVERED_ANNOTATION_TARGET_KINDS; annotationTargetKinds = null; // null means we have no idea or the // @Target annotation hasn't been used List<AnnotationTargetKind> targetKinds = new ArrayList<AnnotationTargetKind>(); if (isAnnotation()) { AnnotationAJ[] annotationsOnThisType = getAnnotations(); for (int i = 0; i < annotationsOnThisType.length; i++) { AnnotationAJ a = annotationsOnThisType[i]; if (a.getTypeName().equals(UnresolvedType.AT_TARGET.getName())) { Set<String> targets = a.getTargets(); if (targets != null) { for (String targetKind : targets) { if (targetKind.equals("ANNOTATION_TYPE")) { targetKinds.add(AnnotationTargetKind.ANNOTATION_TYPE); } else if (targetKind.equals("CONSTRUCTOR")) { targetKinds.add(AnnotationTargetKind.CONSTRUCTOR); } else if (targetKind.equals("FIELD")) { targetKinds.add(AnnotationTargetKind.FIELD); } else if (targetKind.equals("LOCAL_VARIABLE")) { targetKinds.add(AnnotationTargetKind.LOCAL_VARIABLE); } else if (targetKind.equals("METHOD")) { targetKinds.add(AnnotationTargetKind.METHOD); } else if (targetKind.equals("PACKAGE")) { targetKinds.add(AnnotationTargetKind.PACKAGE); } else if (targetKind.equals("PARAMETER")) { targetKinds.add(AnnotationTargetKind.PARAMETER); } else if (targetKind.equals("TYPE")) { targetKinds.add(AnnotationTargetKind.TYPE); } } } } } if (!targetKinds.isEmpty()) { annotationTargetKinds = new AnnotationTargetKind[targetKinds.size()]; return targetKinds.toArray(annotationTargetKinds); } } return annotationTargetKinds; } // --- unpacking methods private boolean isUnpackingAnnotations() { return (bitflag & ANNOTATION_UNPACK_IN_PROGRESS) != 0; } private void ensureAnnotationsUnpacked() { if (isUnpackingAnnotations()) { throw new BCException("Re-entered weaver instance whilst unpacking annotations on " + this.className); } if (annotationTypes == null) { try { bitflag |= ANNOTATION_UNPACK_IN_PROGRESS; AnnotationGen annos[] = javaClass.getAnnotations(); if (annos == null || annos.length == 0) { annotationTypes = ResolvedType.NONE; annotations = AnnotationAJ.EMPTY_ARRAY; } else { World w = getResolvedTypeX().getWorld(); annotationTypes = new ResolvedType[annos.length]; annotations = new AnnotationAJ[annos.length]; for (int i = 0; i < annos.length; i++) { AnnotationGen annotation = annos[i]; String typeSignature = annotation.getTypeSignature(); ResolvedType rType = w.resolve(UnresolvedType.forSignature(typeSignature)); if (rType == null) { throw new RuntimeException("Whilst unpacking annotations on '" + getResolvedTypeX().getName() + "', failed to resolve type '" + typeSignature + "'"); } annotationTypes[i] = rType; annotations[i] = new BcelAnnotation(annotation, rType); } } } finally { bitflag &= ~ANNOTATION_UNPACK_IN_PROGRESS; } } } // --- public String getDeclaredGenericSignature() { ensureGenericInfoProcessed(); return declaredSignature; } private void ensureGenericSignatureUnpacked() { if ((bitflag & UNPACKED_GENERIC_SIGNATURE) != 0) { return; } bitflag |= UNPACKED_GENERIC_SIGNATURE; if (!getResolvedTypeX().getWorld().isInJava5Mode()) { return; } GenericSignature.ClassSignature cSig = getGenericClassTypeSignature(); if (cSig != null) { formalsForResolution = cSig.formalTypeParameters; if (isNested()) { // we have to find any type variables from the outer type before // proceeding with resolution. GenericSignature.FormalTypeParameter[] extraFormals = getFormalTypeParametersFromOuterClass(); if (extraFormals.length > 0) { List allFormals = new ArrayList(); for (int i = 0; i < formalsForResolution.length; i++) { allFormals.add(formalsForResolution[i]); } for (int i = 0; i < extraFormals.length; i++) { allFormals.add(extraFormals[i]); } formalsForResolution = new GenericSignature.FormalTypeParameter[allFormals.size()]; allFormals.toArray(formalsForResolution); } } GenericSignature.ClassTypeSignature superSig = cSig.superclassSignature; try { // this.superClass = // BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX( // superSig, formalsForResolution, // getResolvedTypeX().getWorld()); ResolvedType rt = BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(superSig, formalsForResolution, getResolvedTypeX().getWorld()); this.superclassSignature = rt.getSignature(); this.superclassName = rt.getName(); } catch (GenericSignatureFormatException e) { // development bug, fail fast with good info throw new IllegalStateException("While determining the generic superclass of " + this.className + " with generic signature " + getDeclaredGenericSignature() + " the following error was detected: " + e.getMessage()); } // this.interfaces = new // ResolvedType[cSig.superInterfaceSignatures.length]; if (cSig.superInterfaceSignatures.length == 0) { this.interfaceSignatures = NO_INTERFACE_SIGS; } else { this.interfaceSignatures = new String[cSig.superInterfaceSignatures.length]; for (int i = 0; i < cSig.superInterfaceSignatures.length; i++) { try { // this.interfaces[i] = // BcelGenericSignatureToTypeXConverter. // classTypeSignature2TypeX( // cSig.superInterfaceSignatures[i], // formalsForResolution, // getResolvedTypeX().getWorld()); this.interfaceSignatures[i] = BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX( cSig.superInterfaceSignatures[i], formalsForResolution, getResolvedTypeX().getWorld()) .getSignature(); } catch (GenericSignatureFormatException e) { // development bug, fail fast with good info throw new IllegalStateException("While determing the generic superinterfaces of " + this.className + " with generic signature " + getDeclaredGenericSignature() + " the following error was detected: " + e.getMessage()); } } } } if (isGeneric()) { // update resolved typex to point at generic type not raw type. ReferenceType genericType = (ReferenceType) this.resolvedTypeX.getGenericType(); // genericType.setSourceContext(this.resolvedTypeX.getSourceContext() // ); genericType.setStartPos(this.resolvedTypeX.getStartPos()); this.resolvedTypeX = genericType; } } public GenericSignature.FormalTypeParameter[] getAllFormals() { ensureGenericSignatureUnpacked(); if (formalsForResolution == null) { return new GenericSignature.FormalTypeParameter[0]; } else { return formalsForResolution; } } public ResolvedType getOuterClass() { if (!isNested()) { throw new IllegalStateException("Can't get the outer class of a non-nested type"); } // try finding outer class name from InnerClasses attribute assigned to this class for (Attribute attr : javaClass.getAttributes()) { if (attr instanceof InnerClasses) { // search for InnerClass entry that has current class as inner and some other class as outer InnerClass[] innerClss = ((InnerClasses) attr).getInnerClasses(); ConstantPool cpool = javaClass.getConstantPool(); for (InnerClass innerCls : innerClss) { // skip entries that miss any necessary component, 0 index means "undefined", from JVM Spec 2nd ed. par. 4.7.5 if (innerCls.getInnerClassIndex() == 0 || innerCls.getOuterClassIndex() == 0) { continue; } // resolve inner class name, check if it matches current class name ConstantClass innerClsInfo = (ConstantClass) cpool.getConstant(innerCls.getInnerClassIndex()); // class names in constant pool use '/' instead of '.', from JVM Spec 2nd ed. par. 4.2 String innerClsName = cpool.getConstantUtf8(innerClsInfo.getNameIndex()).getValue().replace('/', '.'); if (innerClsName.compareTo(className) == 0) { // resolve outer class name ConstantClass outerClsInfo = (ConstantClass) cpool.getConstant(innerCls.getOuterClassIndex()); // class names in constant pool use '/' instead of '.', from JVM Spec 2nd ed. par. 4.2 String outerClsName = cpool.getConstantUtf8(outerClsInfo.getNameIndex()).getValue().replace('/', '.'); UnresolvedType outer = UnresolvedType.forName(outerClsName); return outer.resolve(getResolvedTypeX().getWorld()); } } } } // try finding outer class name by assuming standard class name mangling convention of javac for this class int lastDollar = className.lastIndexOf('$'); String superClassName = className.substring(0, lastDollar); UnresolvedType outer = UnresolvedType.forName(superClassName); return outer.resolve(getResolvedTypeX().getWorld()); } private void ensureGenericInfoProcessed() { if ((bitflag & DISCOVERED_DECLARED_SIGNATURE) != 0) { return; } bitflag |= DISCOVERED_DECLARED_SIGNATURE; Signature sigAttr = AttributeUtils.getSignatureAttribute(javaClass.getAttributes()); declaredSignature = (sigAttr == null ? null : sigAttr.getSignature()); if (declaredSignature != null) { isGenericType = (declaredSignature.charAt(0) == '<'); } } public boolean isGeneric() { ensureGenericInfoProcessed(); return isGenericType; } @Override public String toString() { return (javaClass == null ? "BcelObjectType" : "BcelObjectTypeFor:" + className); } // --- state management public void evictWeavingState() { // Can't chuck all this away if (getResolvedTypeX().getWorld().couldIncrementalCompileFollow()) { return; } if (javaClass != null) { // Force retrieval of any lazy information ensureAnnotationsUnpacked(); ensureGenericInfoProcessed(); getDeclaredInterfaces(); getDeclaredFields(); getDeclaredMethods(); // The lazyClassGen is preserved for aspects - it exists to enable // around advice // inlining since the method will need 'injecting' into the affected // class. If // XnoInline is on, we can chuck away the lazyClassGen since it // won't be required // later. if (getResolvedTypeX().getWorld().isXnoInline()) { lazyClassGen = null; } // discard expensive bytecode array containing reweavable info if (weaverState != null) { weaverState.setReweavable(false); weaverState.setUnwovenClassFileData(null); } for (int i = methods.length - 1; i >= 0; i--) { methods[i].evictWeavingState(); } for (int i = fields.length - 1; i >= 0; i--) { fields[i].evictWeavingState(); } javaClass = null; this.artificial = true; // setSourceContext(SourceContextImpl.UNKNOWN_SOURCE_CONTEXT); // // bit naughty // interfaces=null; // force reinit - may get us the right // instances! // superClass=null; } } public void weavingCompleted() { hasBeenWoven = true; if (getResolvedTypeX().getWorld().isRunMinimalMemory()) { evictWeavingState(); } if (getSourceContext() != null && !getResolvedTypeX().isAspect()) { getSourceContext().tidy(); } } public boolean hasBeenWoven() { return hasBeenWoven; } @Override public boolean copySourceContext() { return false; } public void setExposedToWeaver(boolean b) { exposedToWeaver = b; } @Override public int getCompilerVersion() { return wvInfo.getMajorVersion(); } public void ensureConsistent() { superTypeReference.clear(); superInterfaceReferences.clear(); } }
314,130
Bug 314130 [plan] [ltw] [hcr] LTW, Reweaving and Hot Code Replace changes reflected every two saves of files
null
resolved fixed
cf0ee0c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-05-26T22:31:02Z"
"2010-05-24T16:53:20Z"
weaver/src/org/aspectj/weaver/bcel/BcelWorld.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur perClause support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.File; import java.io.IOException; import java.lang.reflect.Modifier; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.ConstantPool; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.INVOKEINTERFACE; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.MULTIANEWARRAY; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.util.ClassLoaderReference; import org.aspectj.apache.bcel.util.ClassLoaderRepository; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.NonCachingClassLoaderRepository; import org.aspectj.apache.bcel.util.Repository; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IRelationship; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.WeaveMessage; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.BCException; import org.aspectj.weaver.Checker; import org.aspectj.weaver.ICrossReferenceHandler; import org.aspectj.weaver.IWeavingSupport; import org.aspectj.weaver.Member; import org.aspectj.weaver.MemberImpl; import org.aspectj.weaver.MemberKind; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.loadtime.definition.Definition; import org.aspectj.weaver.loadtime.definition.DocumentParser; import org.aspectj.weaver.model.AsmRelationshipProvider; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.ParserException; import org.aspectj.weaver.patterns.PatternParser; import org.aspectj.weaver.patterns.TypePattern; import org.aspectj.weaver.tools.Trace; import org.aspectj.weaver.tools.TraceFactory; public class BcelWorld extends World implements Repository { private final ClassPathManager classPath; protected Repository delegate; private BcelWeakClassLoaderReference loaderRef; private final BcelWeavingSupport bcelWeavingSupport = new BcelWeavingSupport(); private boolean isXmlConfiguredWorld = false; private WeavingXmlConfig xmlConfiguration; private static Trace trace = TraceFactory.getTraceFactory().getTrace(BcelWorld.class); public BcelWorld() { this(""); } public BcelWorld(String cp) { this(makeDefaultClasspath(cp), IMessageHandler.THROW, null); } public IRelationship.Kind determineRelKind(ShadowMunger munger) { AdviceKind ak = ((Advice) munger).getKind(); if (ak.getKey() == AdviceKind.Before.getKey()) { return IRelationship.Kind.ADVICE_BEFORE; } else if (ak.getKey() == AdviceKind.After.getKey()) { return IRelationship.Kind.ADVICE_AFTER; } else if (ak.getKey() == AdviceKind.AfterThrowing.getKey()) { return IRelationship.Kind.ADVICE_AFTERTHROWING; } else if (ak.getKey() == AdviceKind.AfterReturning.getKey()) { return IRelationship.Kind.ADVICE_AFTERRETURNING; } else if (ak.getKey() == AdviceKind.Around.getKey()) { return IRelationship.Kind.ADVICE_AROUND; } else if (ak.getKey() == AdviceKind.CflowEntry.getKey() || ak.getKey() == AdviceKind.CflowBelowEntry.getKey() || ak.getKey() == AdviceKind.InterInitializer.getKey() || ak.getKey() == AdviceKind.PerCflowEntry.getKey() || ak.getKey() == AdviceKind.PerCflowBelowEntry.getKey() || ak.getKey() == AdviceKind.PerThisEntry.getKey() || ak.getKey() == AdviceKind.PerTargetEntry.getKey() || ak.getKey() == AdviceKind.Softener.getKey() || ak.getKey() == AdviceKind.PerTypeWithinEntry.getKey()) { // System.err.println("Dont want a message about this: "+ak); return null; } throw new RuntimeException("Shadow.determineRelKind: What the hell is it? " + ak); } @Override public void reportMatch(ShadowMunger munger, Shadow shadow) { if (getCrossReferenceHandler() != null) { getCrossReferenceHandler().addCrossReference(munger.getSourceLocation(), // What is being applied shadow.getSourceLocation(), // Where is it being applied determineRelKind(munger).getName(), // What kind of advice? ((Advice) munger).hasDynamicTests() // Is a runtime test being stuffed in the code? ); } if (!getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { reportWeavingMessage(munger, shadow); } if (getModel() != null) { AsmRelationshipProvider.addAdvisedRelationship(getModelAsAsmManager(), shadow, munger); } } /* * Report a message about the advice weave that has occurred. Some messing about to make it pretty ! This code is just asking * for an NPE to occur ... */ private void reportWeavingMessage(ShadowMunger munger, Shadow shadow) { Advice advice = (Advice) munger; AdviceKind aKind = advice.getKind(); // Only report on interesting advice kinds ... if (aKind == null || advice.getConcreteAspect() == null) { // We suspect someone is programmatically driving the weaver // (e.g. IdWeaveTestCase in the weaver testcases) return; } if (!(aKind.equals(AdviceKind.Before) || aKind.equals(AdviceKind.After) || aKind.equals(AdviceKind.AfterReturning) || aKind.equals(AdviceKind.AfterThrowing) || aKind.equals(AdviceKind.Around) || aKind.equals(AdviceKind.Softener))) { return; } // synchronized blocks are implemented with multiple monitor_exit instructions in the bytecode // (one for normal exit from the method, one for abnormal exit), we only want to tell the user // once we have advised the end of the sync block, even though under the covers we will have // woven both exit points if (shadow.getKind() == Shadow.SynchronizationUnlock) { if (advice.lastReportedMonitorExitJoinpointLocation == null) { // this is the first time through, let's continue... advice.lastReportedMonitorExitJoinpointLocation = shadow.getSourceLocation(); } else { if (areTheSame(shadow.getSourceLocation(), advice.lastReportedMonitorExitJoinpointLocation)) { // Don't report it again! advice.lastReportedMonitorExitJoinpointLocation = null; return; } // hmmm, this means some kind of nesting is going on, urgh advice.lastReportedMonitorExitJoinpointLocation = shadow.getSourceLocation(); } } String description = advice.getKind().toString(); String advisedType = shadow.getEnclosingType().getName(); String advisingType = advice.getConcreteAspect().getName(); Message msg = null; if (advice.getKind().equals(AdviceKind.Softener)) { msg = WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_SOFTENS, new String[] { advisedType, beautifyLocation(shadow.getSourceLocation()), advisingType, beautifyLocation(munger.getSourceLocation()) }, advisedType, advisingType); } else { boolean runtimeTest = advice.hasDynamicTests(); String joinPointDescription = shadow.toString(); msg = WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ADVISES, new String[] { joinPointDescription, advisedType, beautifyLocation(shadow.getSourceLocation()), description, advisingType, beautifyLocation(munger.getSourceLocation()), (runtimeTest ? " [with runtime test]" : "") }, advisedType, advisingType); // Boolean.toString(runtimeTest)}); } getMessageHandler().handleMessage(msg); } private boolean areTheSame(ISourceLocation locA, ISourceLocation locB) { if (locA == null) { return locB == null; } if (locB == null) { return false; } if (locA.getLine() != locB.getLine()) { return false; } File fA = locA.getSourceFile(); File fB = locA.getSourceFile(); if (fA == null) { return fB == null; } if (fB == null) { return false; } return fA.getName().equals(fB.getName()); } /* * Ensure we report a nice source location - particular in the case where the source info is missing (binary weave). */ private String beautifyLocation(ISourceLocation isl) { StringBuffer nice = new StringBuffer(); if (isl == null || isl.getSourceFile() == null || isl.getSourceFile().getName().indexOf("no debug info available") != -1) { nice.append("no debug info available"); } else { // can't use File.getName() as this fails when a Linux box encounters a path created on Windows and vice-versa int takeFrom = isl.getSourceFile().getPath().lastIndexOf('/'); if (takeFrom == -1) { takeFrom = isl.getSourceFile().getPath().lastIndexOf('\\'); } int binary = isl.getSourceFile().getPath().lastIndexOf('!'); if (binary != -1 && binary < takeFrom) { // we have been woven by a binary aspect String pathToBinaryLoc = isl.getSourceFile().getPath().substring(0, binary + 1); if (pathToBinaryLoc.indexOf(".jar") != -1) { // only want to add the extra info if we're from a jar file int lastSlash = pathToBinaryLoc.lastIndexOf('/'); if (lastSlash == -1) { lastSlash = pathToBinaryLoc.lastIndexOf('\\'); } nice.append(pathToBinaryLoc.substring(lastSlash + 1)); } } nice.append(isl.getSourceFile().getPath().substring(takeFrom + 1)); if (isl.getLine() != 0) { nice.append(":").append(isl.getLine()); } // if it's a binary file then also want to give the file name if (isl.getSourceFileName() != null) { nice.append("(from " + isl.getSourceFileName() + ")"); } } return nice.toString(); } private static List<String> makeDefaultClasspath(String cp) { List<String> classPath = new ArrayList<String>(); classPath.addAll(getPathEntries(cp)); classPath.addAll(getPathEntries(ClassPath.getClassPath())); return classPath; } private static List<String> getPathEntries(String s) { List<String> ret = new ArrayList<String>(); StringTokenizer tok = new StringTokenizer(s, File.pathSeparator); while (tok.hasMoreTokens()) { ret.add(tok.nextToken()); } return ret; } public BcelWorld(List classPath, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { // this.aspectPath = new ClassPathManager(aspectPath, handler); this.classPath = new ClassPathManager(classPath, handler); setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes delegate = this; } public BcelWorld(ClassPathManager cpm, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { classPath = cpm; setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes delegate = this; } /** * Build a World from a ClassLoader, for LTW support * * @param loader * @param handler * @param xrefHandler */ public BcelWorld(ClassLoader loader, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { classPath = null; loaderRef = new BcelWeakClassLoaderReference(loader); setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes // delegate = getClassLoaderRepositoryFor(loader); } public void ensureRepositorySetup() { if (delegate == null) { delegate = getClassLoaderRepositoryFor(loaderRef); } } public Repository getClassLoaderRepositoryFor(ClassLoaderReference loader) { if (bcelRepositoryCaching) { return new ClassLoaderRepository(loader); } else { return new NonCachingClassLoaderRepository(loader); } } public void addPath(String name) { classPath.addPath(name, this.getMessageHandler()); } // ---- various interactions with bcel public static Type makeBcelType(UnresolvedType type) { return Type.getType(type.getErasureSignature()); } static Type[] makeBcelTypes(UnresolvedType[] types) { Type[] ret = new Type[types.length]; for (int i = 0, len = types.length; i < len; i++) { ret[i] = makeBcelType(types[i]); } return ret; } static String[] makeBcelTypesAsClassNames(UnresolvedType[] types) { String[] ret = new String[types.length]; for (int i = 0, len = types.length; i < len; i++) { ret[i] = types[i].getName(); } return ret; } public static UnresolvedType fromBcel(Type t) { return UnresolvedType.forSignature(t.getSignature()); } static UnresolvedType[] fromBcel(Type[] ts) { UnresolvedType[] ret = new UnresolvedType[ts.length]; for (int i = 0, len = ts.length; i < len; i++) { ret[i] = fromBcel(ts[i]); } return ret; } public ResolvedType resolve(Type t) { return resolve(fromBcel(t)); } @Override protected ReferenceTypeDelegate resolveDelegate(ReferenceType ty) { String name = ty.getName(); ensureAdvancedConfigurationProcessed(); JavaClass jc = lookupJavaClass(classPath, name); if (jc == null) { return null; } else { return buildBcelDelegate(ty, jc, false, false); } } public BcelObjectType buildBcelDelegate(ReferenceType type, JavaClass jc, boolean artificial, boolean exposedToWeaver) { BcelObjectType ret = new BcelObjectType(type, jc, artificial, exposedToWeaver); return ret; } private JavaClass lookupJavaClass(ClassPathManager classPath, String name) { if (classPath == null) { try { ensureRepositorySetup(); JavaClass jc = delegate.loadClass(name); if (trace.isTraceEnabled()) { trace.event("lookupJavaClass", this, new Object[] { name, jc }); } return jc; } catch (ClassNotFoundException e) { if (trace.isTraceEnabled()) { trace.error("Unable to find class '" + name + "' in repository", e); } return null; } } ClassPathManager.ClassFile file = null; try { file = classPath.find(UnresolvedType.forName(name)); if (file == null) { return null; } ClassParser parser = new ClassParser(file.getInputStream(), file.getPath()); JavaClass jc = parser.parse(); return jc; } catch (IOException ioe) { return null; } finally { if (file != null) { file.close(); } } } // public BcelObjectType addSourceObjectType(JavaClass jc) { // return addSourceObjectType(jc.getClassName(), jc, -1); // } public BcelObjectType addSourceObjectType(JavaClass jc, boolean artificial) { return addSourceObjectType(jc.getClassName(), jc, artificial); } public BcelObjectType addSourceObjectType(String classname, JavaClass jc, boolean artificial) { BcelObjectType ret = null; if (!jc.getClassName().equals(classname)) { throw new RuntimeException(jc.getClassName() + "!=" + classname); } String signature = UnresolvedType.forName(jc.getClassName()).getSignature(); ResolvedType fromTheMap = typeMap.get(signature); if (fromTheMap != null && !(fromTheMap instanceof ReferenceType)) { // what on earth is it then? See pr 112243 StringBuffer exceptionText = new StringBuffer(); exceptionText.append("Found invalid (not a ReferenceType) entry in the type map. "); exceptionText.append("Signature=[" + signature + "] Found=[" + fromTheMap + "] Class=[" + fromTheMap.getClass() + "]"); throw new BCException(exceptionText.toString()); } ReferenceType nameTypeX = (ReferenceType) fromTheMap; if (nameTypeX == null) { if (jc.isGeneric() && isInJava5Mode()) { nameTypeX = ReferenceType.fromTypeX(UnresolvedType.forRawTypeName(jc.getClassName()), this); ret = buildBcelDelegate(nameTypeX, jc, artificial, true); ReferenceType genericRefType = new ReferenceType(UnresolvedType.forGenericTypeSignature(signature, ret .getDeclaredGenericSignature()), this); nameTypeX.setDelegate(ret); genericRefType.setDelegate(ret); nameTypeX.setGenericType(genericRefType); typeMap.put(signature, nameTypeX); } else { nameTypeX = new ReferenceType(signature, this); ret = buildBcelDelegate(nameTypeX, jc, artificial, true); typeMap.put(signature, nameTypeX); } } else { ret = buildBcelDelegate(nameTypeX, jc, artificial, true); } return ret; } public BcelObjectType addSourceObjectType(String classname, byte[] bytes, boolean artificial) { BcelObjectType ret = null; String signature = UnresolvedType.forName(classname).getSignature(); ResolvedType fromTheMap = typeMap.get(signature); if (fromTheMap != null && !(fromTheMap instanceof ReferenceType)) { // what on earth is it then? See pr 112243 StringBuffer exceptionText = new StringBuffer(); exceptionText.append("Found invalid (not a ReferenceType) entry in the type map. "); exceptionText.append("Signature=[" + signature + "] Found=[" + fromTheMap + "] Class=[" + fromTheMap.getClass() + "]"); throw new BCException(exceptionText.toString()); } ReferenceType nameTypeX = (ReferenceType) fromTheMap; if (nameTypeX == null) { JavaClass jc = Utility.makeJavaClass(classname, bytes); if (jc.isGeneric() && isInJava5Mode()) { nameTypeX = ReferenceType.fromTypeX(UnresolvedType.forRawTypeName(jc.getClassName()), this); ret = buildBcelDelegate(nameTypeX, jc, artificial, true); ReferenceType genericRefType = new ReferenceType(UnresolvedType.forGenericTypeSignature(signature, ret .getDeclaredGenericSignature()), this); nameTypeX.setDelegate(ret); genericRefType.setDelegate(ret); nameTypeX.setGenericType(genericRefType); typeMap.put(signature, nameTypeX); } else { nameTypeX = new ReferenceType(signature, this); ret = buildBcelDelegate(nameTypeX, jc, artificial, true); typeMap.put(signature, nameTypeX); } } else { Object o = nameTypeX.getDelegate(); if (!(o instanceof BcelObjectType)) { throw new IllegalStateException("For " + classname + " should be BcelObjectType, but is " + o.getClass()); } ret = (BcelObjectType) o; // byte[] bs = ret.javaClass.getBytes(); // if (bs.length != bytes.length) { // throw new RuntimeException("Shit"); // } if (ret.isArtificial()) { // System.out.println("Rebuilding " + nameTypeX.getName()); ret = buildBcelDelegate(nameTypeX, Utility.makeJavaClass(classname, bytes), artificial, true); } else { ret.setExposedToWeaver(true); } } return ret; } void deleteSourceObjectType(UnresolvedType ty) { typeMap.remove(ty.getSignature()); } public static Member makeFieldJoinPointSignature(LazyClassGen cg, FieldInstruction fi) { ConstantPool cpg = cg.getConstantPool(); return MemberImpl.field(fi.getClassName(cpg), (fi.opcode == Constants.GETSTATIC || fi.opcode == Constants.PUTSTATIC) ? Modifier.STATIC : 0, fi.getName(cpg), fi .getSignature(cpg)); } public Member makeJoinPointSignatureFromMethod(LazyMethodGen mg, MemberKind kind) { Member ret = mg.getMemberView(); if (ret == null) { int mods = mg.getAccessFlags(); if (mg.getEnclosingClass().isInterface()) { mods |= Modifier.INTERFACE; } return new ResolvedMemberImpl(kind, UnresolvedType.forName(mg.getClassName()), mods, fromBcel(mg.getReturnType()), mg .getName(), fromBcel(mg.getArgumentTypes())); } else { return ret; } } public Member makeJoinPointSignatureForMonitorEnter(LazyClassGen cg, InstructionHandle h) { return MemberImpl.monitorEnter(); } public Member makeJoinPointSignatureForMonitorExit(LazyClassGen cg, InstructionHandle h) { return MemberImpl.monitorExit(); } public Member makeJoinPointSignatureForArrayConstruction(LazyClassGen cg, InstructionHandle handle) { Instruction i = handle.getInstruction(); ConstantPool cpg = cg.getConstantPool(); Member retval = null; if (i.opcode == Constants.ANEWARRAY) { // ANEWARRAY arrayInstruction = (ANEWARRAY)i; Type ot = i.getType(cpg); UnresolvedType ut = fromBcel(ot); ut = UnresolvedType.makeArray(ut, 1); retval = MemberImpl.method(ut, Modifier.PUBLIC, ResolvedType.VOID, "<init>", new ResolvedType[] { ResolvedType.INT }); } else if (i instanceof MULTIANEWARRAY) { MULTIANEWARRAY arrayInstruction = (MULTIANEWARRAY) i; UnresolvedType ut = null; short dimensions = arrayInstruction.getDimensions(); ObjectType ot = arrayInstruction.getLoadClassType(cpg); if (ot != null) { ut = fromBcel(ot); ut = UnresolvedType.makeArray(ut, dimensions); } else { Type t = arrayInstruction.getType(cpg); ut = fromBcel(t); } ResolvedType[] parms = new ResolvedType[dimensions]; for (int ii = 0; ii < dimensions; ii++) { parms[ii] = ResolvedType.INT; } retval = MemberImpl.method(ut, Modifier.PUBLIC, ResolvedType.VOID, "<init>", parms); } else if (i.opcode == Constants.NEWARRAY) { // NEWARRAY arrayInstruction = (NEWARRAY)i; Type ot = i.getType(); UnresolvedType ut = fromBcel(ot); retval = MemberImpl.method(ut, Modifier.PUBLIC, ResolvedType.VOID, "<init>", new ResolvedType[] { ResolvedType.INT }); } else { throw new BCException("Cannot create array construction signature for this non-array instruction:" + i); } return retval; } public Member makeJoinPointSignatureForMethodInvocation(LazyClassGen cg, InvokeInstruction ii) { ConstantPool cpg = cg.getConstantPool(); String name = ii.getName(cpg); String declaring = ii.getClassName(cpg); UnresolvedType declaringType = null; String signature = ii.getSignature(cpg); int modifier = (ii instanceof INVOKEINTERFACE) ? Modifier.INTERFACE : (ii.opcode == Constants.INVOKESTATIC) ? Modifier.STATIC : (ii.opcode == Constants.INVOKESPECIAL && !name .equals("<init>")) ? Modifier.PRIVATE : 0; // in Java 1.4 and after, static method call of super class within // subclass method appears // as declared by the subclass in the bytecode - but they are not // see #104212 if (ii.opcode == Constants.INVOKESTATIC) { ResolvedType appearsDeclaredBy = resolve(declaring); // look for the method there for (Iterator<ResolvedMember> iterator = appearsDeclaredBy.getMethods(true, true); iterator.hasNext();) { ResolvedMember method = iterator.next(); if (Modifier.isStatic(method.getModifiers())) { if (name.equals(method.getName()) && signature.equals(method.getSignature())) { // we found it declaringType = method.getDeclaringType(); break; } } } } if (declaringType == null) { if (declaring.charAt(0) == '[') { declaringType = UnresolvedType.forSignature(declaring); } else { declaringType = UnresolvedType.forName(declaring); } } return MemberImpl.method(declaringType, modifier, name, signature); } @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append("BcelWorld("); // buf.append(shadowMungerMap); buf.append(")"); return buf.toString(); } /** * Retrieve a bcel delegate for an aspect - this will return NULL if the delegate is an EclipseSourceType and not a * BcelObjectType - this happens quite often when incrementally compiling. */ public static BcelObjectType getBcelObjectType(ResolvedType concreteAspect) { if (concreteAspect == null) { return null; } if (!(concreteAspect instanceof ReferenceType)) { // Might be Missing return null; } ReferenceTypeDelegate rtDelegate = ((ReferenceType) concreteAspect).getDelegate(); if (rtDelegate instanceof BcelObjectType) { return (BcelObjectType) rtDelegate; } else { return null; } } public void tidyUp() { // At end of compile, close any open files so deletion of those archives // is possible classPath.closeArchives(); typeMap.report(); ResolvedType.resetPrimitives(); } // / The repository interface methods public JavaClass findClass(String className) { return lookupJavaClass(classPath, className); } public JavaClass loadClass(String className) throws ClassNotFoundException { return lookupJavaClass(classPath, className); } public void storeClass(JavaClass clazz) { // doesn't need to do anything } public void removeClass(JavaClass clazz) { throw new RuntimeException("Not implemented"); } public JavaClass loadClass(Class clazz) throws ClassNotFoundException { throw new RuntimeException("Not implemented"); } public void clear() { delegate.clear(); // throw new RuntimeException("Not implemented"); } /** * The aim of this method is to make sure a particular type is 'ok'. Some operations on the delegate for a type modify it and * this method is intended to undo that... see pr85132 */ @Override public void validateType(UnresolvedType type) { ResolvedType result = typeMap.get(type.getSignature()); if (result == null) { return; // We haven't heard of it yet } if (!result.isExposedToWeaver()) { return; // cant need resetting } result.ensureConsistent(); // If we want to rebuild it 'from scratch' then: // ClassParser cp = new ClassParser(new // ByteArrayInputStream(newbytes),new String(cs)); // try { // rt.setDelegate(makeBcelObjectType(rt,cp.parse(),true)); // } catch (ClassFormatException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } } /** * Apply a single declare parents - return true if we change the type */ private boolean applyDeclareParents(DeclareParents p, ResolvedType onType) { boolean didSomething = false; List newParents = p.findMatchingNewParents(onType, true); if (!newParents.isEmpty()) { didSomething = true; BcelObjectType classType = BcelWorld.getBcelObjectType(onType); // System.err.println("need to do declare parents for: " + onType); for (Iterator j = newParents.iterator(); j.hasNext();) { ResolvedType newParent = (ResolvedType) j.next(); // We set it here so that the imminent matching for ITDs can // succeed - we // still haven't done the necessary changes to the class file // itself // (like transform super calls) - that is done in // BcelTypeMunger.mungeNewParent() // classType.addParent(newParent); onType.addParent(newParent); ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent); newParentMunger.setSourceLocation(p.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, getCrosscuttingMembersSet() .findAspectDeclaringParents(p)), false); } } return didSomething; } /** * Apply a declare @type - return true if we change the type */ private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedType onType, boolean reportProblems) { boolean didSomething = false; if (decA.matches(onType)) { if (onType.hasAnnotation(decA.getAnnotation().getType())) { // already has it return false; } AnnotationAJ annoX = decA.getAnnotation(); // check the annotation is suitable for the target boolean isOK = checkTargetOK(decA, onType, annoX); if (isOK) { didSomething = true; ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX); newAnnotationTM.setSourceLocation(decA.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM, decA.getAspect().resolve(this)), false); decA.copyAnnotationTo(onType); } } return didSomething; } /** * Checks for an @target() on the annotation and if found ensures it allows the annotation to be attached to the target type * that matched. */ private boolean checkTargetOK(DeclareAnnotation decA, ResolvedType onType, AnnotationAJ annoX) { if (annoX.specifiesTarget()) { if ((onType.isAnnotation() && !annoX.allowedOnAnnotationType()) || (!annoX.allowedOnRegularType())) { return false; } } return true; } // Hmmm - very similar to the code in BcelWeaver.weaveParentTypeMungers - // this code // doesn't need to produce errors/warnings though as it won't really be // weaving. protected void weaveInterTypeDeclarations(ResolvedType onType) { List<DeclareParents> declareParentsList = getCrosscuttingMembersSet().getDeclareParents(); if (onType.isRawType()) { onType = onType.getGenericType(); } onType.clearInterTypeMungers(); List<DeclareParents> decpToRepeat = new ArrayList<DeclareParents>(); boolean aParentChangeOccurred = false; boolean anAnnotationChangeOccurred = false; // First pass - apply all decp mungers for (Iterator<DeclareParents> i = declareParentsList.iterator(); i.hasNext();) { DeclareParents decp = i.next(); boolean typeChanged = applyDeclareParents(decp, onType); if (typeChanged) { aParentChangeOccurred = true; } else { // Perhaps it would have matched if a 'dec @type' had // modified the type if (!decp.getChild().isStarAnnotation()) { decpToRepeat.add(decp); } } } // Still first pass - apply all dec @type mungers for (Iterator i = getCrosscuttingMembersSet().getDeclareAnnotationOnTypes().iterator(); i.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation) i.next(); boolean typeChanged = applyDeclareAtType(decA, onType, true); if (typeChanged) { anAnnotationChangeOccurred = true; } } while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) { anAnnotationChangeOccurred = aParentChangeOccurred = false; List<DeclareParents> decpToRepeatNextTime = new ArrayList<DeclareParents>(); for (Iterator<DeclareParents> iter = decpToRepeat.iterator(); iter.hasNext();) { DeclareParents decp = iter.next(); boolean typeChanged = applyDeclareParents(decp, onType); if (typeChanged) { aParentChangeOccurred = true; } else { decpToRepeatNextTime.add(decp); } } for (Iterator iter = getCrosscuttingMembersSet().getDeclareAnnotationOnTypes().iterator(); iter.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation) iter.next(); boolean typeChanged = applyDeclareAtType(decA, onType, false); if (typeChanged) { anAnnotationChangeOccurred = true; } } decpToRepeat = decpToRepeatNextTime; } } @Override public IWeavingSupport getWeavingSupport() { return bcelWeavingSupport; } @Override public void reportCheckerMatch(Checker checker, Shadow shadow) { IMessage iMessage = new Message(checker.getMessage(shadow), shadow.toString(), checker.isError() ? IMessage.ERROR : IMessage.WARNING, shadow.getSourceLocation(), null, new ISourceLocation[] { checker.getSourceLocation() }, true, 0, -1, -1); getMessageHandler().handleMessage(iMessage); if (getCrossReferenceHandler() != null) { getCrossReferenceHandler() .addCrossReference( checker.getSourceLocation(), shadow.getSourceLocation(), (checker.isError() ? IRelationship.Kind.DECLARE_ERROR.getName() : IRelationship.Kind.DECLARE_WARNING .getName()), false); } if (getModel() != null) { AsmRelationshipProvider.addDeclareErrorOrWarningRelationship(getModelAsAsmManager(), shadow, checker); } } public AsmManager getModelAsAsmManager() { return (AsmManager) getModel(); // For now... always an AsmManager in a bcel environment } void raiseError(String message) { getMessageHandler().handleMessage(MessageUtil.error(message)); } /** * These are aop.xml files that can be used to alter the aspects that actually apply from those passed in - and also their scope * of application to other files in the system. * * @param xmlFiles list of File objects representing any aop.xml files passed in to configure the build process */ public void setXmlFiles(List<File> xmlFiles) { if (!isXmlConfiguredWorld && !xmlFiles.isEmpty()) { raiseError("xml configuration files only supported by the compiler when -xmlConfigured option specified"); return; } if (!xmlFiles.isEmpty()) { xmlConfiguration = new WeavingXmlConfig(this, WeavingXmlConfig.MODE_COMPILE); } for (File xmlfile : xmlFiles) { try { Definition d = DocumentParser.parse(xmlfile.toURI().toURL()); xmlConfiguration.add(d); } catch (MalformedURLException e) { raiseError("Unexpected problem processing XML config file '" + xmlfile.getName() + "' :" + e.getMessage()); } catch (Exception e) { raiseError("Unexpected problem processing XML config file '" + xmlfile.getName() + "' :" + e.getMessage()); } } } /** * Add a scoped aspects where the scoping was defined in an aop.xml file and this world is being used in a LTW configuration */ public void addScopedAspect(String name, String scope) { this.isXmlConfiguredWorld = true; if (xmlConfiguration == null) { xmlConfiguration = new WeavingXmlConfig(this, WeavingXmlConfig.MODE_LTW); } xmlConfiguration.addScopedAspect(name, scope); } public void setXmlConfigured(boolean b) { this.isXmlConfiguredWorld = b; } @Override public boolean isXmlConfigured() { return isXmlConfiguredWorld && xmlConfiguration != null; } public WeavingXmlConfig getXmlConfiguration() { return xmlConfiguration; } @Override public boolean isAspectIncluded(ResolvedType aspectType) { if (!isXmlConfigured()) { return true; } return xmlConfiguration.specifiesInclusionOfAspect(aspectType.getName()); } @Override public TypePattern getAspectScope(ResolvedType declaringType) { return xmlConfiguration.getScopeFor(declaringType.getName()); } /** * A WeavingXmlConfig is initially a collection of definitions from XML files - once the world is ready and weaving is running * it will initialize and transform those definitions into an optimized set of values (eg. resolve type patterns and string * names to real entities). It can then answer questions quickly: (1) is this aspect included in the weaving? (2) Is there a * scope specified for this aspect and does it include type X? * */ static class WeavingXmlConfig { final static int MODE_COMPILE = 1; final static int MODE_LTW = 2; private int mode; private boolean initialized = false; // Lazily done private List<Definition> definitions = new ArrayList<Definition>(); private List<String> resolvedIncludedAspects = new ArrayList<String>(); private Map<String, TypePattern> scopes = new HashMap<String, TypePattern>(); // these are not set for LTW mode (exclusion of these fast match patterns is handled before the weaver/world are used) private List<String> includedFastMatchPatterns = Collections.emptyList(); private List<TypePattern> includedPatterns = Collections.emptyList(); private List<String> excludedFastMatchPatterns = Collections.emptyList(); private List<TypePattern> excludedPatterns = Collections.emptyList(); private BcelWorld world; public WeavingXmlConfig(BcelWorld bcelWorld, int mode) { this.world = bcelWorld; this.mode = mode; } public void add(Definition d) { definitions.add(d); } public void addScopedAspect(String aspectName, String scope) { ensureInitialized(); resolvedIncludedAspects.add(aspectName); try { TypePattern scopePattern = new PatternParser(scope).parseTypePattern(); scopePattern.resolve(world); scopes.put(aspectName, scopePattern); if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) { world.getMessageHandler().handleMessage( MessageUtil.info("Aspect '" + aspectName + "' is scoped to apply against types matching pattern '" + scopePattern.toString() + "'")); } } catch (Exception e) { world.getMessageHandler().handleMessage( MessageUtil.error("Unable to parse scope as type pattern. Scope was '" + scope + "': " + e.getMessage())); } } public void ensureInitialized() { if (!initialized) { try { resolvedIncludedAspects = new ArrayList<String>(); // Process the definitions into something more optimal for (Definition definition : definitions) { List<String> aspectNames = definition.getAspectClassNames(); for (String name : aspectNames) { resolvedIncludedAspects.add(name); // TODO check for existence? // ResolvedType resolvedAspect = resolve(UnresolvedType.forName(name)); // if (resolvedAspect.isMissing()) { // // ERROR // } else { // resolvedIncludedAspects.add(resolvedAspect); // } String scope = definition.getScopeForAspect(name); if (scope != null) { // Resolve the type pattern try { TypePattern scopePattern = new PatternParser(scope).parseTypePattern(); scopePattern.resolve(world); scopes.put(name, scopePattern); if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) { world.getMessageHandler().handleMessage( MessageUtil.info("Aspect '" + name + "' is scoped to apply against types matching pattern '" + scopePattern.toString() + "'")); } } catch (Exception e) { // TODO definitions should remember which file they came from, for inclusion in this message world.getMessageHandler().handleMessage( MessageUtil.error("Unable to parse scope as type pattern. Scope was '" + scope + "': " + e.getMessage())); } } } try { List<String> includePatterns = definition.getIncludePatterns(); if (includePatterns.size() > 0) { includedPatterns = new ArrayList<TypePattern>(); includedFastMatchPatterns = new ArrayList<String>(); } for (String includePattern : includePatterns) { if (includePattern.endsWith("..*")) { // from 'blah.blah.blah..*' leave the 'blah.blah.blah.' includedFastMatchPatterns.add(includePattern.substring(0, includePattern.length() - 2)); } else { TypePattern includedPattern = new PatternParser(includePattern).parseTypePattern(); includedPatterns.add(includedPattern); } } List<String> excludePatterns = definition.getExcludePatterns(); if (excludePatterns.size() > 0) { excludedPatterns = new ArrayList<TypePattern>(); excludedFastMatchPatterns = new ArrayList<String>(); } for (String excludePattern : excludePatterns) { if (excludePattern.endsWith("..*")) { // from 'blah.blah.blah..*' leave the 'blah.blah.blah.' excludedFastMatchPatterns.add(excludePattern.substring(0, excludePattern.length() - 2)); } else { TypePattern excludedPattern = new PatternParser(excludePattern).parseTypePattern(); excludedPatterns.add(excludedPattern); } } } catch (ParserException pe) { // TODO definitions should remember which file they came from, for inclusion in this message world.getMessageHandler().handleMessage( MessageUtil.error("Unable to parse type pattern: " + pe.getMessage())); } } } finally { initialized = true; } } } public boolean specifiesInclusionOfAspect(String name) { ensureInitialized(); return resolvedIncludedAspects.contains(name); } public TypePattern getScopeFor(String name) { return scopes.get(name); } // Can't quite follow the same rules for exclusion as used for loadtime weaving: // "The set of types to be woven are those types matched by at least one weaver include element and not matched by any // weaver // exclude element. If there are no weaver include statements then all non-excluded types are included." // Since if the weaver is seeing it during this kind of build, the type is implicitly included. So all we should check // for is exclusion public boolean excludesType(ResolvedType type) { if (mode == MODE_LTW) { return false; } String typename = type.getName(); boolean excluded = false; for (String excludedPattern : excludedFastMatchPatterns) { if (typename.startsWith(excludedPattern)) { excluded = true; break; } } if (!excluded) { for (TypePattern excludedPattern : excludedPatterns) { if (excludedPattern.matchesStatically(type)) { excluded = true; break; } } } return excluded; } } public TypeMap getTypeMap() { return typeMap; } }
314,130
Bug 314130 [plan] [ltw] [hcr] LTW, Reweaving and Hot Code Replace changes reflected every two saves of files
null
resolved fixed
cf0ee0c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-05-26T22:31:02Z"
"2010-05-24T16:53:20Z"
weaver/src/org/aspectj/weaver/tools/WeavingAdaptor.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Matthew Webster, Adrian Colyer, * Martin Lippert initial implementation * ******************************************************************/ package org.aspectj.weaver.tools; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageContext; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IMessageHolder; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageHandler; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.MessageWriter; import org.aspectj.bridge.Version; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.util.FileUtil; import org.aspectj.util.LangUtil; import org.aspectj.weaver.IClassFileProvider; import org.aspectj.weaver.IUnwovenClassFile; import org.aspectj.weaver.IWeaveRequestor; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelObjectType; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.UnwovenClassFile; // OPTIMIZE add guards for all the debug/info/etc /** * This adaptor allows the AspectJ compiler to be embedded in an existing system to facilitate load-time weaving. It provides an * interface for a weaving class loader to provide a classpath to be woven by a set of aspects. A callback is supplied to allow a * class loader to define classes generated by the compiler during the weaving process. * <p> * A weaving class loader should create a <code>WeavingAdaptor</code> before any classes are defined, typically during construction. * The set of aspects passed to the adaptor is fixed for the lifetime of the adaptor although the classpath can be augmented. A * system property can be set to allow verbose weaving messages to be written to the console. * */ public class WeavingAdaptor implements IMessageContext { /** * System property used to turn on verbose weaving messages */ public static final String WEAVING_ADAPTOR_VERBOSE = "aj.weaving.verbose"; public static final String SHOW_WEAVE_INFO_PROPERTY = "org.aspectj.weaver.showWeaveInfo"; public static final String TRACE_MESSAGES_PROPERTY = "org.aspectj.tracing.messages"; private boolean enabled = false; protected boolean verbose = getVerbose(); protected BcelWorld bcelWorld; protected BcelWeaver weaver; private IMessageHandler messageHandler; private WeavingAdaptorMessageHolder messageHolder; private boolean abortOnError = false; protected GeneratedClassHandler generatedClassHandler; protected Map generatedClasses = new HashMap(); /* String -> UnwovenClassFile */ public BcelObjectType delegateForCurrentClass; // lazily initialized, should be used to prevent parsing bytecode multiple // times private boolean haveWarnedOnJavax = false; private int weavingSpecialTypes = 0; private static final int INITIALIZED = 0x1; private static final int WEAVE_JAVA_PACKAGE = 0x2; private static final int WEAVE_JAVAX_PACKAGE = 0x4; private static Trace trace = TraceFactory.getTraceFactory().getTrace(WeavingAdaptor.class); protected WeavingAdaptor() { } /** * Construct a WeavingAdaptor with a reference to a weaving class loader. The adaptor will automatically search the class loader * hierarchy to resolve classes. The adaptor will also search the hierarchy for WeavingClassLoader instances to determine the * set of aspects to be used ofr weaving. * * @param loader instance of <code>ClassLoader</code> */ public WeavingAdaptor(WeavingClassLoader loader) { // System.err.println("? WeavingAdaptor.<init>(" + loader +"," + aspectURLs.length + ")"); generatedClassHandler = loader; init(getFullClassPath((ClassLoader) loader), getFullAspectPath((ClassLoader) loader/* ,aspectURLs */)); } /** * Construct a WeavingAdator with a reference to a <code>GeneratedClassHandler</code>, a full search path for resolving classes * and a complete set of aspects. The search path must include classes loaded by the class loader constructing the * WeavingAdaptor and all its parents in the hierarchy. * * @param handler <code>GeneratedClassHandler</code> * @param classURLs the URLs from which to resolve classes * @param aspectURLs the aspects used to weave classes defined by this class loader */ public WeavingAdaptor(GeneratedClassHandler handler, URL[] classURLs, URL[] aspectURLs) { // System.err.println("? WeavingAdaptor.<init>()"); generatedClassHandler = handler; init(FileUtil.makeClasspath(classURLs), FileUtil.makeClasspath(aspectURLs)); } private List getFullClassPath(ClassLoader loader) { List list = new LinkedList(); for (; loader != null; loader = loader.getParent()) { if (loader instanceof URLClassLoader) { URL[] urls = ((URLClassLoader) loader).getURLs(); list.addAll(0, FileUtil.makeClasspath(urls)); } else { warn("cannot determine classpath"); } } list.addAll(0, makeClasspath(System.getProperty("sun.boot.class.path"))); return list; } private List getFullAspectPath(ClassLoader loader) { List list = new LinkedList(); for (; loader != null; loader = loader.getParent()) { if (loader instanceof WeavingClassLoader) { URL[] urls = ((WeavingClassLoader) loader).getAspectURLs(); list.addAll(0, FileUtil.makeClasspath(urls)); } } return list; } private static boolean getVerbose() { return Boolean.getBoolean(WEAVING_ADAPTOR_VERBOSE); } private void init(List classPath, List aspectPath) { abortOnError = true; createMessageHandler(); info("using classpath: " + classPath); info("using aspectpath: " + aspectPath); bcelWorld = new BcelWorld(classPath, messageHandler, null); bcelWorld.setXnoInline(false); bcelWorld.getLint().loadDefaultProperties(); if (LangUtil.is15VMOrGreater()) { bcelWorld.setBehaveInJava5Way(true); } weaver = new BcelWeaver(bcelWorld); registerAspectLibraries(aspectPath); enabled = true; } protected void createMessageHandler() { messageHolder = new WeavingAdaptorMessageHolder(new PrintWriter(System.err)); messageHandler = messageHolder; if (verbose) { messageHandler.dontIgnore(IMessage.INFO); } if (Boolean.getBoolean(SHOW_WEAVE_INFO_PROPERTY)) { messageHandler.dontIgnore(IMessage.WEAVEINFO); } info("AspectJ Weaver Version " + Version.text + " built on " + Version.time_text); //$NON-NLS-1$ } protected IMessageHandler getMessageHandler() { return messageHandler; } public IMessageHolder getMessageHolder() { return messageHolder; } protected void setMessageHandler(IMessageHandler mh) { if (mh instanceof ISupportsMessageContext) { ISupportsMessageContext smc = (ISupportsMessageContext) mh; smc.setMessageContext(this); } if (mh != messageHolder) { messageHolder.setDelegate(mh); } messageHolder.flushMessages(); } protected void disable() { if (trace.isTraceEnabled()) { trace.enter("disable", this); } enabled = false; messageHolder.flushMessages(); if (trace.isTraceEnabled()) { trace.exit("disable"); } } protected void enable() { enabled = true; messageHolder.flushMessages(); } protected boolean isEnabled() { return enabled; } /** * Appends URL to path used by the WeavingAdptor to resolve classes * * @param url to be appended to search path */ public void addURL(URL url) { File libFile = new File(url.getPath()); try { weaver.addLibraryJarFile(libFile); } catch (IOException ex) { warn("bad library: '" + libFile + "'"); } } /** * Weave a class using aspects previously supplied to the adaptor. * * @param name the name of the class * @param bytes the class bytes * @return the woven bytes * @exception IOException weave failed */ public byte[] weaveClass(String name, byte[] bytes) throws IOException { return weaveClass(name, bytes, false); } // Track if the weaver is already running on this thread - don't allow re-entrant calls private ThreadLocal<Boolean> weaverRunning = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return Boolean.FALSE; } }; /** * Weave a class using aspects previously supplied to the adaptor. * * @param name the name of the class * @param bytes the class bytes * @param mustWeave if true then this class *must* get woven (used for concrete aspects generated from XML) * @return the woven bytes * @exception IOException weave failed */ public byte[] weaveClass(String name, byte[] bytes, boolean mustWeave) throws IOException { if (trace==null) { // Pr231945: we are likely to be under tomcat and ENABLE_CLEAR_REFERENCES hasn't been set System.err.println("AspectJ Weaver cannot continue to weave, static state has been cleared. Are you under Tomcat? In order to weave '"+name+ "' during shutdown, 'org.apache.catalina.loader.WebappClassLoader.ENABLE_CLEAR_REFERENCES=false' must be set (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=231945)."); return bytes; } if (weaverRunning.get()) { // System.out.println("AJC: avoiding re-entrant call to transform " + name); return bytes; } try { weaverRunning.set(true); if (trace.isTraceEnabled()) { trace.enter("weaveClass", this, new Object[] { name, bytes }); } if (!enabled) { if (trace.isTraceEnabled()) { trace.exit("weaveClass", false); } return bytes; } boolean debugOn = !messageHandler.isIgnoring(Message.DEBUG); try { delegateForCurrentClass = null; name = name.replace('/', '.'); if (couldWeave(name, bytes)) { if (accept(name, bytes)) { // TODO @AspectJ problem // Annotation style aspects need to be included regardless in order to get // a valid aspectOf()/hasAspect() generated in them. However - if they are excluded // (via include/exclude in aop.xml) they really should only get aspectOf()/hasAspect() // and not be included in the full set of aspects being applied by 'this' weaver if (debugOn) { debug("weaving '" + name + "'"); } bytes = getWovenBytes(name, bytes); // temporarily out - searching for @Aspect annotated types is a slow thing to do - we should // expect the user to name them if they want them woven - just like code style // } else if (shouldWeaveAnnotationStyleAspect(name, bytes)) { // if (mustWeave) { // if (bcelWorld.getLint().mustWeaveXmlDefinedAspects.isEnabled()) { // bcelWorld.getLint().mustWeaveXmlDefinedAspects.signal(name, null); // } // } // // an @AspectJ aspect needs to be at least munged by the aspectOf munger // if (debugOn) { // debug("weaving '" + name + "'"); // } // bytes = getAtAspectJAspectBytes(name, bytes); } else if (debugOn) { debug("not weaving '" + name + "'"); } } else if (debugOn) { debug("cannot weave '" + name + "'"); } } finally { delegateForCurrentClass = null; } if (trace.isTraceEnabled()) { trace.exit("weaveClass", bytes); } return bytes; } finally { weaverRunning.set(false); } } /** * @param name * @return true if even valid to weave: either with an accept check or to munge it for @AspectJ aspectof support */ private boolean couldWeave(String name, byte[] bytes) { return !generatedClasses.containsKey(name) && shouldWeaveName(name); } // ATAJ protected boolean accept(String name, byte[] bytes) { return true; } protected boolean shouldDump(String name, boolean before) { return false; } private boolean shouldWeaveName(String name) { if ("osj".indexOf(name.charAt(0)) != -1) { if ((weavingSpecialTypes & INITIALIZED) == 0) { weavingSpecialTypes |= INITIALIZED; // initialize it Properties p = weaver.getWorld().getExtraConfiguration(); if (p != null) { boolean b = p.getProperty(World.xsetWEAVE_JAVA_PACKAGES, "false").equalsIgnoreCase("true"); if (b) { weavingSpecialTypes |= WEAVE_JAVA_PACKAGE; } b = p.getProperty(World.xsetWEAVE_JAVAX_PACKAGES, "false").equalsIgnoreCase("true"); if (b) { weavingSpecialTypes |= WEAVE_JAVAX_PACKAGE; } } } if (name.startsWith("org.aspectj.")) { return false; } if (name.startsWith("sun.reflect.")) {// JDK reflect return false; } if (name.startsWith("javax.")) { if ((weavingSpecialTypes & WEAVE_JAVAX_PACKAGE) != 0) { return true; } else { if (!haveWarnedOnJavax) { haveWarnedOnJavax = true; warn("javax.* types are not being woven because the weaver option '-Xset:weaveJavaxPackages=true' has not been specified"); } return false; } } if (name.startsWith("java.")) { if ((weavingSpecialTypes & WEAVE_JAVA_PACKAGE) != 0) { return true; } else { return false; } } } // boolean should = !(name.startsWith("org.aspectj.") // || (name.startsWith("java.") && (weavingSpecialTypes & WEAVE_JAVA_PACKAGE) == 0) // || (name.startsWith("javax.") && (weavingSpecialTypes & WEAVE_JAVAX_PACKAGE) == 0) // // || name.startsWith("$Proxy")//JDK proxies//FIXME AV is that 1.3 proxy ? fe. ataspect.$Proxy0 is a java5 proxy... // || name.startsWith("sun.reflect.")); return true; } /** * We allow @AJ aspect weaving so that we can add aspectOf() as part of the weaving (and not part of the source compilation) * * @param name * @param bytes bytecode (from classloader), allow to NOT lookup stuff on disk again during resolve * @return true if @Aspect */ private boolean shouldWeaveAnnotationStyleAspect(String name, byte[] bytes) { if (delegateForCurrentClass == null) { // if (weaver.getWorld().isASMAround()) return asmCheckAnnotationStyleAspect(bytes); // else ensureDelegateInitialized(name, bytes); } return (delegateForCurrentClass.isAnnotationStyleAspect()); } // private boolean asmCheckAnnotationStyleAspect(byte[] bytes) { // IsAtAspectAnnotationVisitor detector = new IsAtAspectAnnotationVisitor(); // // ClassReader cr = new ClassReader(bytes); // try { // cr.accept(detector, true);//, ClassReader.SKIP_DEBUG | ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES); // } catch (Exception spe) { // // if anything goes wrong, e.g., an NPE, then assume it's NOT an @AspectJ aspect... // System.err.println("Unexpected problem parsing bytes to discover @Aspect annotation"); // spe.printStackTrace(); // return false; // } // // return detector.isAspect(); // } protected void ensureDelegateInitialized(String name, byte[] bytes) { if (delegateForCurrentClass == null) { BcelWorld world = (BcelWorld) weaver.getWorld(); delegateForCurrentClass = world.addSourceObjectType(name, bytes, false); } } /** * Weave a set of bytes defining a class. * * @param name the name of the class being woven * @param bytes the bytes that define the class * @return byte[] the woven bytes for the class * @throws IOException */ private byte[] getWovenBytes(String name, byte[] bytes) throws IOException { WeavingClassFileProvider wcp = new WeavingClassFileProvider(name, bytes); weaver.weave(wcp); return wcp.getBytes(); } /** * Weave a set of bytes defining a class for only what is needed to turn @AspectJ aspect in a usefull form ie with aspectOf * method - see #113587 * * @param name the name of the class being woven * @param bytes the bytes that define the class * @return byte[] the woven bytes for the class * @throws IOException */ private byte[] getAtAspectJAspectBytes(String name, byte[] bytes) throws IOException { WeavingClassFileProvider wcp = new WeavingClassFileProvider(name, bytes); wcp.setApplyAtAspectJMungersOnly(); weaver.weave(wcp); return wcp.getBytes(); } private void registerAspectLibraries(List aspectPath) { // System.err.println("? WeavingAdaptor.registerAspectLibraries(" + aspectPath + ")"); for (Iterator i = aspectPath.iterator(); i.hasNext();) { String libName = (String) i.next(); addAspectLibrary(libName); } weaver.prepareForWeave(); } /* * Register an aspect library with this classloader for use during weaving. This class loader will also return (unmodified) any * of the classes in the library in response to a <code>findClass()</code> request. The library is not required to be on the * weavingClasspath given when this classloader was constructed. * * @param aspectLibraryJarFile a jar file representing an aspect library * * @throws IOException */ private void addAspectLibrary(String aspectLibraryName) { File aspectLibrary = new File(aspectLibraryName); if (aspectLibrary.isDirectory() || (FileUtil.isZipFile(aspectLibrary))) { try { info("adding aspect library: '" + aspectLibrary + "'"); weaver.addLibraryJarFile(aspectLibrary); } catch (IOException ex) { error("exception adding aspect library: '" + ex + "'"); } } else { error("bad aspect library: '" + aspectLibrary + "'"); } } private static List makeClasspath(String cp) { List ret = new ArrayList(); if (cp != null) { StringTokenizer tok = new StringTokenizer(cp, File.pathSeparator); while (tok.hasMoreTokens()) { ret.add(tok.nextToken()); } } return ret; } protected boolean debug(String message) { return MessageUtil.debug(messageHandler, message); } protected boolean info(String message) { return MessageUtil.info(messageHandler, message); } protected boolean warn(String message) { return MessageUtil.warn(messageHandler, message); } protected boolean warn(String message, Throwable th) { return messageHandler.handleMessage(new Message(message, IMessage.WARNING, th, null)); } protected boolean error(String message) { return MessageUtil.error(messageHandler, message); } protected boolean error(String message, Throwable th) { return messageHandler.handleMessage(new Message(message, IMessage.ERROR, th, null)); } public String getContextId() { return "WeavingAdaptor"; } /** * Dump the given bytcode in _dump/... (dev mode) * * @param name * @param b * @param before whether we are dumping before weaving * @throws Throwable */ protected void dump(String name, byte[] b, boolean before) { String dirName = getDumpDir(); if (before) { dirName = dirName + File.separator + "_before"; } String className = name.replace('.', '/'); final File dir; if (className.indexOf('/') > 0) { dir = new File(dirName + File.separator + className.substring(0, className.lastIndexOf('/'))); } else { dir = new File(dirName); } dir.mkdirs(); String fileName = dirName + File.separator + className + ".class"; try { // System.out.println("WeavingAdaptor.dump() fileName=" + new File(fileName).getAbsolutePath()); FileOutputStream os = new FileOutputStream(fileName); os.write(b); os.close(); } catch (IOException ex) { warn("unable to dump class " + name + " in directory " + dirName, ex); } } /** * @return the directory in which to dump - default is _ajdump but it */ protected String getDumpDir() { return "_ajdump"; } /** * Processes messages arising from weaver operations. Tell weaver to abort on any message more severe than warning. */ protected class WeavingAdaptorMessageHolder extends MessageHandler { private IMessageHandler delegate; private List savedMessages; protected boolean traceMessages = Boolean.getBoolean(TRACE_MESSAGES_PROPERTY); public WeavingAdaptorMessageHolder(PrintWriter writer) { this.delegate = new WeavingAdaptorMessageWriter(writer); super.dontIgnore(IMessage.WEAVEINFO); } private void traceMessage(IMessage message) { if (message instanceof WeaveMessage) { trace.debug(render(message)); } else if (message.isDebug()) { trace.debug(render(message)); } else if (message.isInfo()) { trace.info(render(message)); } else if (message.isWarning()) { trace.warn(render(message), message.getThrown()); } else if (message.isError()) { trace.error(render(message), message.getThrown()); } else if (message.isFailed()) { trace.fatal(render(message), message.getThrown()); } else if (message.isAbort()) { trace.fatal(render(message), message.getThrown()); } else { trace.error(render(message), message.getThrown()); } } protected String render(IMessage message) { return "[" + getContextId() + "] " + message.toString(); } public void flushMessages() { if (savedMessages == null) { savedMessages = new ArrayList(); savedMessages.addAll(super.getUnmodifiableListView()); clearMessages(); for (Iterator iter = savedMessages.iterator(); iter.hasNext();) { IMessage message = (IMessage) iter.next(); delegate.handleMessage(message); } } // accumulating = false; // messages.clear(); } public void setDelegate(IMessageHandler messageHandler) { delegate = messageHandler; } /* * IMessageHandler */ @Override public boolean handleMessage(IMessage message) throws AbortException { if (traceMessages) { traceMessage(message); } super.handleMessage(message); if (abortOnError && 0 <= message.getKind().compareTo(IMessage.ERROR)) { throw new AbortException(message); } // if (accumulating) { // boolean result = addMessage(message); // if (abortOnError && 0 <= message.getKind().compareTo(IMessage.ERROR)) { // throw new AbortException(message); // } // return result; // } // else return delegate.handleMessage(message); if (savedMessages != null) { delegate.handleMessage(message); } return true; } @Override public boolean isIgnoring(Kind kind) { return delegate.isIgnoring(kind); } @Override public void dontIgnore(IMessage.Kind kind) { if (null != kind && delegate != null) { delegate.dontIgnore(kind); } } @Override public void ignore(Kind kind) { if (null != kind && delegate != null) { delegate.ignore(kind); } } /* * IMessageHolder */ @Override public List getUnmodifiableListView() { // System.err.println("? WeavingAdaptorMessageHolder.getUnmodifiableListView() savedMessages=" + savedMessages); List allMessages = new ArrayList(); allMessages.addAll(savedMessages); allMessages.addAll(super.getUnmodifiableListView()); return allMessages; } } protected class WeavingAdaptorMessageWriter extends MessageWriter { private final Set ignoring = new HashSet(); private final IMessage.Kind failKind; public WeavingAdaptorMessageWriter(PrintWriter writer) { super(writer, true); ignore(IMessage.WEAVEINFO); ignore(IMessage.DEBUG); ignore(IMessage.INFO); this.failKind = IMessage.ERROR; } @Override public boolean handleMessage(IMessage message) throws AbortException { // boolean result = super.handleMessage(message); if (abortOnError && 0 <= message.getKind().compareTo(failKind)) { throw new AbortException(message); } return true; } @Override public boolean isIgnoring(Kind kind) { return ((null != kind) && (ignoring.contains(kind))); } /** * Set a message kind to be ignored from now on */ @Override public void ignore(IMessage.Kind kind) { if ((null != kind) && (!ignoring.contains(kind))) { ignoring.add(kind); } } /** * Remove a message kind from the list of those ignored from now on. */ @Override public void dontIgnore(IMessage.Kind kind) { if (null != kind) { ignoring.remove(kind); } } @Override protected String render(IMessage message) { return "[" + getContextId() + "] " + super.render(message); } } private class WeavingClassFileProvider implements IClassFileProvider { private final UnwovenClassFile unwovenClass; private final List unwovenClasses = new ArrayList(); /* List<UnovenClassFile> */ private IUnwovenClassFile wovenClass; private boolean isApplyAtAspectJMungersOnly = false; public WeavingClassFileProvider(String name, byte[] bytes) { ensureDelegateInitialized(name, bytes); this.unwovenClass = new UnwovenClassFile(name, delegateForCurrentClass.getResolvedTypeX().getName(), bytes); this.unwovenClasses.add(unwovenClass); if (shouldDump(name.replace('/', '.'), true)) { dump(name, bytes, true); } } public void setApplyAtAspectJMungersOnly() { isApplyAtAspectJMungersOnly = true; } public boolean isApplyAtAspectJMungersOnly() { return isApplyAtAspectJMungersOnly; } public byte[] getBytes() { if (wovenClass != null) { return wovenClass.getBytes(); } else { return unwovenClass.getBytes(); } } public Iterator getClassFileIterator() { return unwovenClasses.iterator(); } public IWeaveRequestor getRequestor() { return new IWeaveRequestor() { public void acceptResult(IUnwovenClassFile result) { if (wovenClass == null) { wovenClass = result; String name = result.getClassName(); if (shouldDump(name.replace('/', '.'), false)) { dump(name, result.getBytes(), false); } } /* Classes generated by weaver e.g. around closure advice */ else { String className = result.getClassName(); generatedClasses.put(className, result); generatedClasses.put(wovenClass.getClassName(), result); generatedClassHandler.acceptClass(className, result.getBytes()); } } public void processingReweavableState() { } public void addingTypeMungers() { } public void weavingAspects() { } public void weavingClasses() { } public void weaveCompleted() { ResolvedType.resetPrimitives(); if (delegateForCurrentClass != null) { delegateForCurrentClass.weavingCompleted(); } ResolvedType.resetPrimitives(); // bcelWorld.discardType(typeBeingProcessed.getResolvedTypeX()); // work in progress } }; } } }
314,766
Bug 314766 NPE when using aop.xml for compile time config
Reported on the list: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelWorld.isAspectIncluded(BcelWorld.java:942) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:80) at org.aspectj.weaver.Advice.match(Advice.java:106) at org.aspectj.weaver.bcel.BcelAdvice.match(BcelAdvice.java:149) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:3108) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2562)
resolved fixed
0e5ecd3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-05-27T20:11:51Z"
"2010-05-27T19:53:20Z"
org.aspectj.matcher/src/org/aspectj/weaver/Advice.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.util.Collections; import java.util.List; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.TypePattern; public abstract class Advice extends ShadowMunger { protected AjAttribute.AdviceAttribute attribute; protected transient AdviceKind kind; // alias for attribute.getKind() protected Member signature; // not necessarily declaring aspect, this is a semantics change from 1.0 protected ResolvedType concreteAspect; // null until after concretize // Just for Cflow*entry kinds protected List innerCflowEntries = Collections.EMPTY_LIST; protected int nFreeVars; protected TypePattern exceptionType; // just for Softener kind // if we are parameterized, these type may be different to the advice // signature types protected UnresolvedType[] bindingParameterTypes; protected boolean hasMatchedAtLeastOnce = false; // based on annotations on this advice protected List<Lint.Kind> suppressedLintKinds = null; public ISourceLocation lastReportedMonitorExitJoinpointLocation = null; public static Advice makeCflowEntry(World world, Pointcut entry, boolean isBelow, Member stackField, int nFreeVars, List innerCflowEntries, ResolvedType inAspect) { Advice ret = world.createAdviceMunger(isBelow ? AdviceKind.CflowBelowEntry : AdviceKind.CflowEntry, entry, stackField, 0, entry, inAspect); ret.innerCflowEntries = innerCflowEntries; ret.nFreeVars = nFreeVars; return ret; } public static Advice makePerCflowEntry(World world, Pointcut entry, boolean isBelow, Member stackField, ResolvedType inAspect, List innerCflowEntries) { Advice ret = world.createAdviceMunger(isBelow ? AdviceKind.PerCflowBelowEntry : AdviceKind.PerCflowEntry, entry, stackField, 0, entry, inAspect); ret.innerCflowEntries = innerCflowEntries; ret.concreteAspect = inAspect; return ret; } public static Advice makePerObjectEntry(World world, Pointcut entry, boolean isThis, ResolvedType inAspect) { Advice ret = world.createAdviceMunger(isThis ? AdviceKind.PerThisEntry : AdviceKind.PerTargetEntry, entry, null, 0, entry, inAspect); ret.concreteAspect = inAspect; return ret; } // PTWIMPL per type within entry advice is what initializes the aspect // instance in the matched type public static Advice makePerTypeWithinEntry(World world, Pointcut p, ResolvedType inAspect) { Advice ret = world.createAdviceMunger(AdviceKind.PerTypeWithinEntry, p, null, 0, p, inAspect); ret.concreteAspect = inAspect; return ret; } public static Advice makeSoftener(World world, Pointcut entry, TypePattern exceptionType, ResolvedType inAspect, IHasSourceLocation loc) { Advice ret = world.createAdviceMunger(AdviceKind.Softener, entry, null, 0, loc, inAspect); ret.exceptionType = exceptionType; return ret; } public Advice(AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature) { super(pointcut, attribute.getStart(), attribute.getEnd(), attribute.getSourceContext(), ShadowMungerAdvice); this.attribute = attribute; this.kind = attribute.getKind(); // alias this.signature = signature; if (signature != null) { bindingParameterTypes = signature.getParameterTypes(); } else { bindingParameterTypes = new UnresolvedType[0]; } } @Override public boolean match(Shadow shadow, World world) { if (super.match(shadow, world)) { if (shadow.getKind() == Shadow.ExceptionHandler) { if (kind.isAfter() || kind == AdviceKind.Around) { world.showMessage(IMessage.WARNING, WeaverMessages.format(WeaverMessages.ONLY_BEFORE_ON_HANDLER), getSourceLocation(), shadow.getSourceLocation()); return false; } } if (shadow.getKind() == Shadow.SynchronizationLock || shadow.getKind() == Shadow.SynchronizationUnlock) { if (kind == AdviceKind.Around // Don't work, see comments in SynchronizationTests // && attribute.getProceedCallSignatures()!=null // && attribute.getProceedCallSignatures().length!=0 ) { world.showMessage(IMessage.WARNING, WeaverMessages.format(WeaverMessages.NO_AROUND_ON_SYNCHRONIZATION), getSourceLocation(), shadow.getSourceLocation()); return false; } } if (hasExtraParameter() && kind == AdviceKind.AfterReturning) { ResolvedType resolvedExtraParameterType = getExtraParameterType().resolve(world); ResolvedType shadowReturnType = shadow.getReturnType().resolve(world); boolean matches = (resolvedExtraParameterType.isConvertableFrom(shadowReturnType) && shadow.getKind() .hasReturnValue()); if (matches && resolvedExtraParameterType.isParameterizedType()) { maybeIssueUncheckedMatchWarning(resolvedExtraParameterType, shadowReturnType, shadow, world); } return matches; } else if (hasExtraParameter() && kind == AdviceKind.AfterThrowing) { // pr119749 ResolvedType exceptionType = getExtraParameterType().resolve(world); if (!exceptionType.isCheckedException()) { return true; } UnresolvedType[] shadowThrows = shadow.getSignature().getExceptions(world); boolean matches = false; for (int i = 0; i < shadowThrows.length && !matches; i++) { ResolvedType type = shadowThrows[i].resolve(world); if (exceptionType.isAssignableFrom(type)) { matches = true; } } return matches; } else if (kind == AdviceKind.PerTargetEntry) { return shadow.hasTarget(); } else if (kind == AdviceKind.PerThisEntry) { return shadow.hasThis(); } else if (kind == AdviceKind.Around) { if (shadow.getKind() == Shadow.PreInitialization) { world.showMessage(IMessage.WARNING, WeaverMessages.format(WeaverMessages.AROUND_ON_PREINIT), getSourceLocation(), shadow.getSourceLocation()); return false; } else if (shadow.getKind() == Shadow.Initialization) { world.showMessage(IMessage.WARNING, WeaverMessages.format(WeaverMessages.AROUND_ON_INIT), getSourceLocation(), shadow.getSourceLocation()); return false; } else if (shadow.getKind() == Shadow.StaticInitialization && shadow.getEnclosingType().resolve(world).isInterface()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AROUND_ON_INTERFACE_STATICINIT, shadow .getEnclosingType().getName()), getSourceLocation(), shadow.getSourceLocation()); return false; } else { // System.err.println(getSignature().getReturnType() + // " from " + shadow.getReturnType()); if (getSignature().getReturnType() == ResolvedType.VOID) { if (shadow.getReturnType() != ResolvedType.VOID) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.NON_VOID_RETURN, shadow), getSourceLocation(), shadow.getSourceLocation()); return false; } } else if (getSignature().getReturnType().equals(UnresolvedType.OBJECT)) { return true; } else { ResolvedType shadowReturnType = shadow.getReturnType().resolve(world); ResolvedType adviceReturnType = getSignature().getGenericReturnType().resolve(world); if (shadowReturnType.isParameterizedType() && adviceReturnType.isRawType()) { // Set // < // Integer // > // and // Set ResolvedType shadowReturnGenericType = shadowReturnType.getGenericType(); // Set ResolvedType adviceReturnGenericType = adviceReturnType.getGenericType(); // Set if (shadowReturnGenericType.isAssignableFrom(adviceReturnGenericType) && world.getLint().uncheckedAdviceConversion.isEnabled()) { world.getLint().uncheckedAdviceConversion.signal(new String[] { shadow.toString(), shadowReturnType.getName(), adviceReturnType.getName() }, shadow.getSourceLocation(), new ISourceLocation[] { getSourceLocation() }); } } else if (!shadowReturnType.isAssignableFrom(adviceReturnType)) { // System.err.println(this + ", " + sourceContext + // ", " + start); world.showMessage(IMessage.ERROR, WeaverMessages .format(WeaverMessages.INCOMPATIBLE_RETURN_TYPE, shadow), getSourceLocation(), shadow .getSourceLocation()); return false; } } } } return true; } else { return false; } } /** * In after returning advice if we are binding the extra parameter to a parameterized type we may not be able to do a type-safe * conversion. * * @param resolvedExtraParameterType the type in the after returning declaration * @param shadowReturnType the type at the shadow * @param world */ private void maybeIssueUncheckedMatchWarning(ResolvedType afterReturningType, ResolvedType shadowReturnType, Shadow shadow, World world) { boolean inDoubt = !afterReturningType.isAssignableFrom(shadowReturnType); if (inDoubt && world.getLint().uncheckedArgument.isEnabled()) { String uncheckedMatchWith = afterReturningType.getSimpleBaseName(); if (shadowReturnType.isParameterizedType() && (shadowReturnType.getRawType() == afterReturningType.getRawType())) { uncheckedMatchWith = shadowReturnType.getSimpleName(); } if (!Utils.isSuppressing(getSignature().getAnnotations(), "uncheckedArgument")) { world.getLint().uncheckedArgument.signal(new String[] { afterReturningType.getSimpleName(), uncheckedMatchWith, afterReturningType.getSimpleBaseName(), shadow.toResolvedString(world) }, getSourceLocation(), new ISourceLocation[] { shadow.getSourceLocation() }); } } } // ---- public AdviceKind getKind() { return kind; } public Member getSignature() { return signature; } public boolean hasExtraParameter() { return (getExtraParameterFlags() & ExtraArgument) != 0; } protected int getExtraParameterFlags() { return attribute.getExtraParameterFlags(); } protected int getExtraParameterCount() { return countOnes(getExtraParameterFlags() & ParameterMask); } public UnresolvedType[] getBindingParameterTypes() { return bindingParameterTypes; } public void setBindingParameterTypes(UnresolvedType[] types) { bindingParameterTypes = types; } public static int countOnes(int bits) { int ret = 0; while (bits != 0) { if ((bits & 1) != 0) { ret += 1; } bits = bits >> 1; } return ret; } public int getBaseParameterCount() { return getSignature().getParameterTypes().length - getExtraParameterCount(); } public String[] getBaseParameterNames(World world) { String[] allNames = getSignature().getParameterNames(world); int extras = getExtraParameterCount(); if (extras == 0) { return allNames; } String[] result = new String[getBaseParameterCount()]; for (int i = 0; i < result.length; i++) { result[i] = allNames[i]; } return result; } /** * Return the type of the 'extra argument'. For either after returning or after throwing advice, the extra argument will be the * returned value or the thrown exception respectively. With annotation style the user may declare the parameters in any order, * whereas for code style they are in a well defined order. So there is some extra complexity in here for annotation style that * looks up the correct parameter in the advice signature by name, based on the name specified in the annotation. If this fails * then we 'fallback' to guessing at positions, where the extra argument is presumed to come at the end. * * @return the type of the extraParameter */ public UnresolvedType getExtraParameterType() { if (!hasExtraParameter()) { return ResolvedType.MISSING; } if (signature instanceof ResolvedMember) { ResolvedMember method = (ResolvedMember) signature; UnresolvedType[] parameterTypes = method.getGenericParameterTypes(); if (getConcreteAspect().isAnnotationStyleAspect()) { // Examine the annotation to determine the parameter name then look it up in the parameters for the method String[] pnames = method.getParameterNames(); if (pnames != null) { // It is worth attempting to look up the correct parameter AnnotationAJ[] annos = getSignature().getAnnotations(); String parameterToLookup = null; if (annos != null && (getKind() == AdviceKind.AfterThrowing || getKind() == AdviceKind.AfterReturning)) { for (int i = 0; i < annos.length && parameterToLookup == null; i++) { AnnotationAJ anno = annos[i]; String annosig = anno.getType().getSignature(); if (annosig.equals("Lorg/aspectj/lang/annotation/AfterThrowing;")) { // the 'throwing' value in the annotation will name the parameter to bind to parameterToLookup = anno.getStringFormOfValue("throwing"); } else if (annosig.equals("Lorg/aspectj/lang/annotation/AfterReturning;")) { // the 'returning' value in the annotation will name the parameter to bind to parameterToLookup = anno.getStringFormOfValue("returning"); } } } if (parameterToLookup != null) { for (int i = 0; i < pnames.length; i++) { if (pnames[i].equals(parameterToLookup)) { return parameterTypes[i]; } } } } // Don't think this code works so well... why isnt it getBaseParameterCount()-1 ? int baseParmCnt = getBaseParameterCount(); // bug 122742 - if we're an annotation style aspect then one // of the extra parameters could be JoinPoint which we want // to ignore while ((baseParmCnt + 1 < parameterTypes.length) && (parameterTypes[baseParmCnt].equals(AjcMemberMaker.TYPEX_JOINPOINT) || parameterTypes[baseParmCnt].equals(AjcMemberMaker.TYPEX_STATICJOINPOINT) || parameterTypes[baseParmCnt] .equals(AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT))) { baseParmCnt++; } return parameterTypes[baseParmCnt]; } else { return parameterTypes[getBaseParameterCount()]; } } else { return signature.getParameterTypes()[getBaseParameterCount()]; } } public UnresolvedType getDeclaringAspect() { return getOriginalSignature().getDeclaringType(); } protected Member getOriginalSignature() { return signature; } protected String extraParametersToString() { if (getExtraParameterFlags() == 0) { return ""; } else { return "(extraFlags: " + getExtraParameterFlags() + ")"; } } @Override public Pointcut getPointcut() { return pointcut; } // ---- /** * @param fromType is guaranteed to be a non-abstract aspect * @param clause has been concretized at a higher level */ @Override public ShadowMunger concretize(ResolvedType fromType, World world, PerClause clause) { // assert !fromType.isAbstract(); Pointcut p = pointcut.concretize(fromType, getDeclaringType(), signature.getArity(), this); if (clause != null) { Pointcut oldP = p; p = new AndPointcut(clause, p); p.copyLocationFrom(oldP); p.state = Pointcut.CONCRETE; // FIXME ? ATAJ copy unbound bindings to ignore p.m_ignoreUnboundBindingForNames = oldP.m_ignoreUnboundBindingForNames; } Advice munger = world.getWeavingSupport().createAdviceMunger(attribute, p, signature, fromType); munger.bindingParameterTypes = bindingParameterTypes; munger.setDeclaringType(getDeclaringType()); // System.err.println("concretizing here " + p + " with clause " + // clause); return munger; } // ---- from object @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("(").append(getKind()).append(extraParametersToString()); sb.append(": ").append(pointcut).append("->").append(signature).append(")"); return sb.toString(); // return "(" // + getKind() // + extraParametersToString() // + ": " // + pointcut // + "->" // + signature // + ")"; } // XXX this perhaps ought to take account of the other fields in advice ... @Override public boolean equals(Object other) { if (!(other instanceof Advice)) { return false; } Advice o = (Advice) other; return o.kind.equals(kind) && ((o.pointcut == null) ? (pointcut == null) : o.pointcut.equals(pointcut)) && ((o.signature == null) ? (signature == null) : o.signature.equals(signature)); // && (AsmManager.getDefault().getHandleProvider().dependsOnLocation() ? ((o.getSourceLocation() == null) ? // (getSourceLocation() == null) // : o.getSourceLocation().equals(getSourceLocation())) // : true) // pr134471 - remove when handles are improved // // to be independent of location // ; } private volatile int hashCode = 0; @Override public int hashCode() { if (hashCode == 0) { int result = 17; result = 37 * result + kind.hashCode(); result = 37 * result + ((pointcut == null) ? 0 : pointcut.hashCode()); result = 37 * result + ((signature == null) ? 0 : signature.hashCode()); hashCode = result; } return hashCode; } // ---- fields public static final int ExtraArgument = 0x01; public static final int ThisJoinPoint = 0x02; public static final int ThisJoinPointStaticPart = 0x04; public static final int ThisEnclosingJoinPointStaticPart = 0x08; public static final int ParameterMask = 0x0f; // For an if pointcut, this indicates it is hard wired to access a constant of either true or false public static final int ConstantReference = 0x10; // When the above flag is set, this indicates whether it is true or false public static final int ConstantValue = 0x20; public static final int CanInline = 0x40; // for testing only public void setLexicalPosition(int lexicalPosition) { start = lexicalPosition; } public ResolvedType getConcreteAspect() { return concreteAspect; } public boolean hasMatchedSomething() { return hasMatchedAtLeastOnce; } public void setHasMatchedSomething(boolean hasMatchedSomething) { hasMatchedAtLeastOnce = hasMatchedSomething; } public abstract boolean hasDynamicTests(); }
317,139
Bug 317139 NullPointerException during weaving
null
resolved fixed
92a52a2
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-06-29T00:07:59Z"
"2010-06-17T04:46:40Z"
weaver/src/org/aspectj/weaver/bcel/BcelObjectType.java
/* ******************************************************************* * Copyright (c) 2002 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * RonBodkin/AndyClement optimizations for memory consumption/speed * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.PrintStream; import java.lang.ref.WeakReference; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.AttributeUtils; import org.aspectj.apache.bcel.classfile.ConstantClass; import org.aspectj.apache.bcel.classfile.ConstantPool; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.InnerClass; import org.aspectj.apache.bcel.classfile.InnerClasses; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen; import org.aspectj.apache.bcel.classfile.annotation.EnumElementValue; import org.aspectj.apache.bcel.classfile.annotation.NameValuePair; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.GenericSignature; import org.aspectj.util.GenericSignature.FormalTypeParameter; import org.aspectj.weaver.AbstractReferenceTypeDelegate; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.AnnotationTargetKind; import org.aspectj.weaver.BCException; import org.aspectj.weaver.BindingScope; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.SourceContextImpl; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelGenericSignatureToTypeXConverter.GenericSignatureFormatException; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.DeclareErrorOrWarning; import org.aspectj.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.FormalBinding; import org.aspectj.weaver.patterns.IScope; import org.aspectj.weaver.patterns.PerClause; public class BcelObjectType extends AbstractReferenceTypeDelegate { public JavaClass javaClass; private boolean artificial; // Was the BcelObject built from an artificial set of bytes? Or from the real ondisk stuff? private LazyClassGen lazyClassGen = null; // set lazily if it's an aspect private int modifiers; private String className; private String superclassSignature; private String superclassName; private String[] interfaceSignatures; private ResolvedMember[] fields = null; private ResolvedMember[] methods = null; private ResolvedType[] annotationTypes = null; private AnnotationAJ[] annotations = null; private TypeVariable[] typeVars = null; private String retentionPolicy; private AnnotationTargetKind[] annotationTargetKinds; // Aspect related stuff (pointcuts *could* be in a java class) private AjAttribute.WeaverVersionInfo wvInfo = AjAttribute.WeaverVersionInfo.UNKNOWN; private ResolvedPointcutDefinition[] pointcuts = null; private ResolvedMember[] privilegedAccess = null; private WeaverStateInfo weaverState = null; private PerClause perClause = null; private List<ConcreteTypeMunger> typeMungers = Collections.emptyList(); private List<Declare> declares = Collections.emptyList(); private GenericSignature.FormalTypeParameter[] formalsForResolution = null; private String declaredSignature = null; private boolean hasBeenWoven = false; private boolean isGenericType = false; private boolean isInterface; private boolean isEnum; private boolean isAnnotation; private boolean isAnonymous; private boolean isNested; private boolean isObject = false; // set upon construction private boolean isAnnotationStyleAspect = false;// set upon construction private boolean isCodeStyleAspect = false; // not redundant with field // above! private WeakReference<ResolvedType> superTypeReference = new WeakReference<ResolvedType>(null); private WeakReference<ResolvedType[]> superInterfaceReferences = new WeakReference<ResolvedType[]>(null); private int bitflag = 0x0000; // discovery bits private static final int DISCOVERED_ANNOTATION_RETENTION_POLICY = 0x0001; private static final int UNPACKED_GENERIC_SIGNATURE = 0x0002; private static final int UNPACKED_AJATTRIBUTES = 0x0004; // see note(1) // below private static final int DISCOVERED_ANNOTATION_TARGET_KINDS = 0x0008; private static final int DISCOVERED_DECLARED_SIGNATURE = 0x0010; private static final int DISCOVERED_WHETHER_ANNOTATION_STYLE = 0x0020; private static final int ANNOTATION_UNPACK_IN_PROGRESS = 0x0100; private static final String[] NO_INTERFACE_SIGS = new String[] {}; /* * Notes: note(1): in some cases (perclause inheritance) we encounter unpacked state when calling getPerClause * * note(2): A BcelObjectType is 'damaged' if it has been modified from what was original constructed from the bytecode. This * currently happens if the parents are modified or an annotation is added - ideally BcelObjectType should be immutable but * that's a bigger piece of work. XXX */ BcelObjectType(ReferenceType resolvedTypeX, JavaClass javaClass, boolean artificial, boolean exposedToWeaver) { super(resolvedTypeX, exposedToWeaver); this.javaClass = javaClass; this.artificial = artificial; initializeFromJavaclass(); // ATAJ: set the delegate right now for @AJ pointcut, else it is done // too late to lookup // @AJ pc refs annotation in class hierarchy resolvedTypeX.setDelegate(this); ISourceContext sourceContext = resolvedTypeX.getSourceContext(); if (sourceContext == SourceContextImpl.UNKNOWN_SOURCE_CONTEXT) { sourceContext = new SourceContextImpl(this); setSourceContext(sourceContext); } // this should only ever be java.lang.Object which is // the only class in Java-1.4 with no superclasses isObject = (javaClass.getSuperclassNameIndex() == 0); ensureAspectJAttributesUnpacked(); // if (sourceContext instanceof SourceContextImpl) { // ((SourceContextImpl)sourceContext).setSourceFileName(javaClass. // getSourceFileName()); // } setSourcefilename(javaClass.getSourceFileName()); } // repeat initialization public void setJavaClass(JavaClass newclass, boolean artificial) { this.javaClass = newclass; this.artificial = artificial; resetState(); initializeFromJavaclass(); } @Override public boolean isCacheable() { return true; } private void initializeFromJavaclass() { isInterface = javaClass.isInterface(); isEnum = javaClass.isEnum(); isAnnotation = javaClass.isAnnotation(); isAnonymous = javaClass.isAnonymous(); isNested = javaClass.isNested(); modifiers = javaClass.getModifiers(); superclassName = javaClass.getSuperclassName(); className = javaClass.getClassName(); cachedGenericClassTypeSignature = null; } // --- getters // Java related public boolean isInterface() { return isInterface; } public boolean isEnum() { return isEnum; } public boolean isAnnotation() { return isAnnotation; } public boolean isAnonymous() { return isAnonymous; } public boolean isNested() { return isNested; } public int getModifiers() { return modifiers; } /** * Must take into account generic signature */ public ResolvedType getSuperclass() { if (isObject) { return null; } ResolvedType supertype = superTypeReference.get(); if (supertype == null) { ensureGenericSignatureUnpacked(); if (superclassSignature == null) { if (superclassName == null) { superclassName = javaClass.getSuperclassName(); } superclassSignature = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(superclassName)).getSignature(); } World world = getResolvedTypeX().getWorld(); supertype = world.resolve(UnresolvedType.forSignature(superclassSignature)); superTypeReference = new WeakReference<ResolvedType>(supertype); } return supertype; } public World getWorld() { return getResolvedTypeX().getWorld(); } /** * Retrieves the declared interfaces - this allows for the generic signature on a type. If specified then the generic signature * is used to work out the types - this gets around the results of erasure when the class was originally compiled. */ public ResolvedType[] getDeclaredInterfaces() { ResolvedType[] cachedInterfaceTypes = superInterfaceReferences.get(); if (cachedInterfaceTypes == null) { ensureGenericSignatureUnpacked(); ResolvedType[] interfaceTypes = null; if (interfaceSignatures == null) { String[] names = javaClass.getInterfaceNames(); if (names.length == 0) { interfaceSignatures = NO_INTERFACE_SIGS; interfaceTypes = ResolvedType.NONE; } else { interfaceSignatures = new String[names.length]; interfaceTypes = new ResolvedType[names.length]; for (int i = 0, len = names.length; i < len; i++) { interfaceTypes[i] = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(names[i])); interfaceSignatures[i] = interfaceTypes[i].getSignature(); } } } else { interfaceTypes = new ResolvedType[interfaceSignatures.length]; for (int i = 0, len = interfaceSignatures.length; i < len; i++) { interfaceTypes[i] = getResolvedTypeX().getWorld().resolve(UnresolvedType.forSignature(interfaceSignatures[i])); } } superInterfaceReferences = new WeakReference<ResolvedType[]>(interfaceTypes); return interfaceTypes; } else { return cachedInterfaceTypes; } } public ResolvedMember[] getDeclaredMethods() { ensureGenericSignatureUnpacked(); if (methods == null) { Method[] ms = javaClass.getMethods(); methods = new ResolvedMember[ms.length]; for (int i = ms.length - 1; i >= 0; i--) { methods[i] = new BcelMethod(this, ms[i]); } } return methods; } public ResolvedMember[] getDeclaredFields() { ensureGenericSignatureUnpacked(); if (fields == null) { Field[] fs = javaClass.getFields(); fields = new ResolvedMember[fs.length]; for (int i = 0, len = fs.length; i < len; i++) { fields[i] = new BcelField(this, fs[i]); } } return fields; } public TypeVariable[] getTypeVariables() { if (!isGeneric()) { return TypeVariable.NONE; } if (typeVars == null) { GenericSignature.ClassSignature classSig = getGenericClassTypeSignature(); typeVars = new TypeVariable[classSig.formalTypeParameters.length]; for (int i = 0; i < typeVars.length; i++) { GenericSignature.FormalTypeParameter ftp = classSig.formalTypeParameters[i]; try { typeVars[i] = BcelGenericSignatureToTypeXConverter.formalTypeParameter2TypeVariable(ftp, classSig.formalTypeParameters, getResolvedTypeX().getWorld()); } catch (GenericSignatureFormatException e) { // this is a development bug, so fail fast with good info throw new IllegalStateException("While getting the type variables for type " + this.toString() + " with generic signature " + classSig + " the following error condition was detected: " + e.getMessage()); } } } return typeVars; } public Collection<ConcreteTypeMunger> getTypeMungers() { return typeMungers; } public Collection<Declare> getDeclares() { return declares; } public Collection<ResolvedMember> getPrivilegedAccesses() { if (privilegedAccess == null) { return Collections.emptyList(); } return Arrays.asList(privilegedAccess); } public ResolvedMember[] getDeclaredPointcuts() { return pointcuts; } public boolean isAspect() { return perClause != null; } /** * Check if the type is an @AJ aspect (no matter if used from an LTW point of view). Such aspects are annotated with @Aspect * * @return true for @AJ aspect */ public boolean isAnnotationStyleAspect() { if ((bitflag & DISCOVERED_WHETHER_ANNOTATION_STYLE) == 0) { bitflag |= DISCOVERED_WHETHER_ANNOTATION_STYLE; isAnnotationStyleAspect = !isCodeStyleAspect && hasAnnotation(AjcMemberMaker.ASPECT_ANNOTATION); } return isAnnotationStyleAspect; } /** * Process any org.aspectj.weaver attributes stored against the class. */ private void ensureAspectJAttributesUnpacked() { if ((bitflag & UNPACKED_AJATTRIBUTES) != 0) { return; } bitflag |= UNPACKED_AJATTRIBUTES; IMessageHandler msgHandler = getResolvedTypeX().getWorld().getMessageHandler(); // Pass in empty list that can store things for readAj5 to process List<AjAttribute> l = null; try { l = Utility.readAjAttributes(className, javaClass.getAttributes(), getResolvedTypeX().getSourceContext(), getResolvedTypeX().getWorld(), AjAttribute.WeaverVersionInfo.UNKNOWN, new BcelConstantPoolReader(javaClass .getConstantPool())); } catch (RuntimeException re) { throw new RuntimeException("Problem processing attributes in " + javaClass.getFileName(), re); } List<ResolvedPointcutDefinition> pointcuts = new ArrayList<ResolvedPointcutDefinition>(); typeMungers = new ArrayList<ConcreteTypeMunger>(); declares = new ArrayList<Declare>(); processAttributes(l, pointcuts, false); l = AtAjAttributes.readAj5ClassAttributes(((BcelWorld) getResolvedTypeX().getWorld()).getModelAsAsmManager(), javaClass, getResolvedTypeX(), getResolvedTypeX().getSourceContext(), msgHandler, isCodeStyleAspect); AjAttribute.Aspect deferredAspectAttribute = processAttributes(l, pointcuts, true); if (pointcuts.size() == 0) { this.pointcuts = ResolvedPointcutDefinition.NO_POINTCUTS; } else { this.pointcuts = pointcuts.toArray(new ResolvedPointcutDefinition[pointcuts.size()]); } resolveAnnotationDeclares(l); if (deferredAspectAttribute != null) { // we can finally process the aspect and its associated perclause... perClause = deferredAspectAttribute.reifyFromAtAspectJ(this.getResolvedTypeX()); } if (isAspect() && !Modifier.isAbstract(getModifiers()) && isGeneric()) { msgHandler.handleMessage(MessageUtil.error("The generic aspect '" + getResolvedTypeX().getName() + "' must be declared abstract", getResolvedTypeX().getSourceLocation())); } } private AjAttribute.Aspect processAttributes(List<AjAttribute> attributeList, List<ResolvedPointcutDefinition> pointcuts, boolean fromAnnotations) { AjAttribute.Aspect deferredAspectAttribute = null; for (AjAttribute a : attributeList) { if (a instanceof AjAttribute.Aspect) { if (fromAnnotations) { deferredAspectAttribute = (AjAttribute.Aspect) a; } else { perClause = ((AjAttribute.Aspect) a).reify(this.getResolvedTypeX()); isCodeStyleAspect = true; } } else if (a instanceof AjAttribute.PointcutDeclarationAttribute) { pointcuts.add(((AjAttribute.PointcutDeclarationAttribute) a).reify()); } else if (a instanceof AjAttribute.WeaverState) { weaverState = ((AjAttribute.WeaverState) a).reify(); } else if (a instanceof AjAttribute.TypeMunger) { typeMungers.add(((AjAttribute.TypeMunger) a).reify(getResolvedTypeX().getWorld(), getResolvedTypeX())); } else if (a instanceof AjAttribute.DeclareAttribute) { declares.add(((AjAttribute.DeclareAttribute) a).getDeclare()); } else if (a instanceof AjAttribute.PrivilegedAttribute) { AjAttribute.PrivilegedAttribute privAttribute = (AjAttribute.PrivilegedAttribute) a; privilegedAccess = privAttribute.getAccessedMembers(); } else if (a instanceof AjAttribute.SourceContextAttribute) { if (getResolvedTypeX().getSourceContext() instanceof SourceContextImpl) { AjAttribute.SourceContextAttribute sca = (AjAttribute.SourceContextAttribute) a; ((SourceContextImpl) getResolvedTypeX().getSourceContext()).configureFromAttribute(sca.getSourceFileName(), sca .getLineBreaks()); setSourcefilename(sca.getSourceFileName()); } } else if (a instanceof AjAttribute.WeaverVersionInfo) { wvInfo = (AjAttribute.WeaverVersionInfo) a; // Set the weaver // version used to // build this type } else { throw new BCException("bad attribute " + a); } } return deferredAspectAttribute; } /** * Extra processing step needed because declares that come from annotations are not pre-resolved. We can't do the resolution * until *after* the pointcuts have been resolved. */ private void resolveAnnotationDeclares(List<AjAttribute> attributeList) { FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; IScope bindingScope = new BindingScope(getResolvedTypeX(), getResolvedTypeX().getSourceContext(), bindings); for (Iterator<AjAttribute> iter = attributeList.iterator(); iter.hasNext();) { AjAttribute a = iter.next(); if (a instanceof AjAttribute.DeclareAttribute) { Declare decl = (((AjAttribute.DeclareAttribute) a).getDeclare()); if (decl instanceof DeclareErrorOrWarning) { decl.resolve(bindingScope); } else if (decl instanceof DeclarePrecedence) { ((DeclarePrecedence) decl).setScopeForResolution(bindingScope); } } } } public PerClause getPerClause() { ensureAspectJAttributesUnpacked(); return perClause; } public JavaClass getJavaClass() { return javaClass; } public boolean isArtificial() { return artificial; } public void resetState() { if (javaClass == null) { // we might store the classname and allow reloading? // At this point we are relying on the world to not evict if it // might want to reweave multiple times throw new BCException("can't weave evicted type"); } bitflag = 0x0000; this.annotationTypes = null; this.annotations = null; this.interfaceSignatures = null; this.superclassSignature = null; this.superclassName = null; this.fields = null; this.methods = null; this.pointcuts = null; this.perClause = null; this.weaverState = null; this.lazyClassGen = null; hasBeenWoven = false; isObject = (javaClass.getSuperclassNameIndex() == 0); isAnnotationStyleAspect = false; ensureAspectJAttributesUnpacked(); } public void finishedWith() { // memory usage experiments.... // this.interfaces = null; // this.superClass = null; // this.fields = null; // this.methods = null; // this.pointcuts = null; // this.perClause = null; // this.weaverState = null; // this.lazyClassGen = null; // this next line frees up memory, but need to understand incremental // implications // before leaving it in. // getResolvedTypeX().setSourceContext(null); } public WeaverStateInfo getWeaverState() { return weaverState; } void setWeaverState(WeaverStateInfo weaverState) { this.weaverState = weaverState; } public void printWackyStuff(PrintStream out) { if (typeMungers.size() > 0) { out.println(" TypeMungers: " + typeMungers); } if (declares.size() > 0) { out.println(" declares: " + declares); } } /** * Return the lazyClassGen associated with this type. For aspect types, this value will be cached, since it is used to inline * advice. For non-aspect types, this lazyClassGen is always newly constructed. */ public LazyClassGen getLazyClassGen() { LazyClassGen ret = lazyClassGen; if (ret == null) { // System.err.println("creating lazy class gen for: " + this); ret = new LazyClassGen(this); // ret.print(System.err); // System.err.println("made LCG from : " + // this.getJavaClass().getSuperclassName ); if (isAspect()) { lazyClassGen = ret; } } return ret; } public boolean isSynthetic() { return getResolvedTypeX().isSynthetic(); } public AjAttribute.WeaverVersionInfo getWeaverVersionAttribute() { return wvInfo; } // -- annotation related public ResolvedType[] getAnnotationTypes() { ensureAnnotationsUnpacked(); return annotationTypes; } public AnnotationAJ[] getAnnotations() { ensureAnnotationsUnpacked(); return annotations; } public boolean hasAnnotation(UnresolvedType ofType) { // Due to re-entrancy we may be in the middle of unpacking the annotations already... in which case use this slow // alternative until the stack unwinds itself if (isUnpackingAnnotations()) { AnnotationGen annos[] = javaClass.getAnnotations(); if (annos == null || annos.length == 0) { return false; } else { String lookingForSignature = ofType.getSignature(); for (int a = 0; a < annos.length; a++) { AnnotationGen annotation = annos[a]; if (lookingForSignature.equals(annotation.getTypeSignature())) { return true; } } } return false; } ensureAnnotationsUnpacked(); for (int i = 0, max = annotationTypes.length; i < max; i++) { UnresolvedType ax = annotationTypes[i]; if (ax == null) { throw new RuntimeException("Annotation entry " + i + " on type " + this.getResolvedTypeX().getName() + " is null!"); } if (ax.equals(ofType)) { return true; } } return false; } public boolean isAnnotationWithRuntimeRetention() { return (getRetentionPolicy() == null ? false : getRetentionPolicy().equals("RUNTIME")); } public String getRetentionPolicy() { if ((bitflag & DISCOVERED_ANNOTATION_RETENTION_POLICY) == 0) { bitflag |= DISCOVERED_ANNOTATION_RETENTION_POLICY; retentionPolicy = null; // null means we have no idea if (isAnnotation()) { ensureAnnotationsUnpacked(); for (int i = annotations.length - 1; i >= 0; i--) { AnnotationAJ ax = annotations[i]; if (ax.getTypeName().equals(UnresolvedType.AT_RETENTION.getName())) { List<NameValuePair> values = ((BcelAnnotation) ax).getBcelAnnotation().getValues(); for (Iterator<NameValuePair> it = values.iterator(); it.hasNext();) { NameValuePair element = it.next(); EnumElementValue v = (EnumElementValue) element.getValue(); retentionPolicy = v.getEnumValueString(); return retentionPolicy; } } } } } return retentionPolicy; } public boolean canAnnotationTargetType() { AnnotationTargetKind[] targetKinds = getAnnotationTargetKinds(); if (targetKinds == null) { return true; } for (int i = 0; i < targetKinds.length; i++) { if (targetKinds[i].equals(AnnotationTargetKind.TYPE)) { return true; } } return false; } public AnnotationTargetKind[] getAnnotationTargetKinds() { if ((bitflag & DISCOVERED_ANNOTATION_TARGET_KINDS) != 0) { return annotationTargetKinds; } bitflag |= DISCOVERED_ANNOTATION_TARGET_KINDS; annotationTargetKinds = null; // null means we have no idea or the // @Target annotation hasn't been used List<AnnotationTargetKind> targetKinds = new ArrayList<AnnotationTargetKind>(); if (isAnnotation()) { AnnotationAJ[] annotationsOnThisType = getAnnotations(); for (int i = 0; i < annotationsOnThisType.length; i++) { AnnotationAJ a = annotationsOnThisType[i]; if (a.getTypeName().equals(UnresolvedType.AT_TARGET.getName())) { Set<String> targets = a.getTargets(); if (targets != null) { for (String targetKind : targets) { if (targetKind.equals("ANNOTATION_TYPE")) { targetKinds.add(AnnotationTargetKind.ANNOTATION_TYPE); } else if (targetKind.equals("CONSTRUCTOR")) { targetKinds.add(AnnotationTargetKind.CONSTRUCTOR); } else if (targetKind.equals("FIELD")) { targetKinds.add(AnnotationTargetKind.FIELD); } else if (targetKind.equals("LOCAL_VARIABLE")) { targetKinds.add(AnnotationTargetKind.LOCAL_VARIABLE); } else if (targetKind.equals("METHOD")) { targetKinds.add(AnnotationTargetKind.METHOD); } else if (targetKind.equals("PACKAGE")) { targetKinds.add(AnnotationTargetKind.PACKAGE); } else if (targetKind.equals("PARAMETER")) { targetKinds.add(AnnotationTargetKind.PARAMETER); } else if (targetKind.equals("TYPE")) { targetKinds.add(AnnotationTargetKind.TYPE); } } } } } if (!targetKinds.isEmpty()) { annotationTargetKinds = new AnnotationTargetKind[targetKinds.size()]; return targetKinds.toArray(annotationTargetKinds); } } return annotationTargetKinds; } // --- unpacking methods private boolean isUnpackingAnnotations() { return (bitflag & ANNOTATION_UNPACK_IN_PROGRESS) != 0; } private void ensureAnnotationsUnpacked() { if (isUnpackingAnnotations()) { throw new BCException("Re-entered weaver instance whilst unpacking annotations on " + this.className); } if (annotationTypes == null) { try { bitflag |= ANNOTATION_UNPACK_IN_PROGRESS; AnnotationGen annos[] = javaClass.getAnnotations(); if (annos == null || annos.length == 0) { annotationTypes = ResolvedType.NONE; annotations = AnnotationAJ.EMPTY_ARRAY; } else { World w = getResolvedTypeX().getWorld(); annotationTypes = new ResolvedType[annos.length]; annotations = new AnnotationAJ[annos.length]; for (int i = 0; i < annos.length; i++) { AnnotationGen annotation = annos[i]; String typeSignature = annotation.getTypeSignature(); ResolvedType rType = w.resolve(UnresolvedType.forSignature(typeSignature)); if (rType == null) { throw new RuntimeException("Whilst unpacking annotations on '" + getResolvedTypeX().getName() + "', failed to resolve type '" + typeSignature + "'"); } annotationTypes[i] = rType; annotations[i] = new BcelAnnotation(annotation, rType); } } } finally { bitflag &= ~ANNOTATION_UNPACK_IN_PROGRESS; } } } // --- public String getDeclaredGenericSignature() { ensureGenericInfoProcessed(); return declaredSignature; } private void ensureGenericSignatureUnpacked() { if ((bitflag & UNPACKED_GENERIC_SIGNATURE) != 0) { return; } bitflag |= UNPACKED_GENERIC_SIGNATURE; if (!getResolvedTypeX().getWorld().isInJava5Mode()) { return; } GenericSignature.ClassSignature cSig = getGenericClassTypeSignature(); if (cSig != null) { formalsForResolution = cSig.formalTypeParameters; if (isNested()) { // we have to find any type variables from the outer type before // proceeding with resolution. GenericSignature.FormalTypeParameter[] extraFormals = getFormalTypeParametersFromOuterClass(); if (extraFormals.length > 0) { List<FormalTypeParameter> allFormals = new ArrayList<FormalTypeParameter>(); for (int i = 0; i < formalsForResolution.length; i++) { allFormals.add(formalsForResolution[i]); } for (int i = 0; i < extraFormals.length; i++) { allFormals.add(extraFormals[i]); } formalsForResolution = new GenericSignature.FormalTypeParameter[allFormals.size()]; allFormals.toArray(formalsForResolution); } } GenericSignature.ClassTypeSignature superSig = cSig.superclassSignature; try { // this.superClass = // BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX( // superSig, formalsForResolution, // getResolvedTypeX().getWorld()); ResolvedType rt = BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(superSig, formalsForResolution, getResolvedTypeX().getWorld()); this.superclassSignature = rt.getSignature(); this.superclassName = rt.getName(); } catch (GenericSignatureFormatException e) { // development bug, fail fast with good info throw new IllegalStateException("While determining the generic superclass of " + this.className + " with generic signature " + getDeclaredGenericSignature() + " the following error was detected: " + e.getMessage()); } // this.interfaces = new // ResolvedType[cSig.superInterfaceSignatures.length]; if (cSig.superInterfaceSignatures.length == 0) { this.interfaceSignatures = NO_INTERFACE_SIGS; } else { this.interfaceSignatures = new String[cSig.superInterfaceSignatures.length]; for (int i = 0; i < cSig.superInterfaceSignatures.length; i++) { try { // this.interfaces[i] = // BcelGenericSignatureToTypeXConverter. // classTypeSignature2TypeX( // cSig.superInterfaceSignatures[i], // formalsForResolution, // getResolvedTypeX().getWorld()); this.interfaceSignatures[i] = BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX( cSig.superInterfaceSignatures[i], formalsForResolution, getResolvedTypeX().getWorld()) .getSignature(); } catch (GenericSignatureFormatException e) { // development bug, fail fast with good info throw new IllegalStateException("While determing the generic superinterfaces of " + this.className + " with generic signature " + getDeclaredGenericSignature() + " the following error was detected: " + e.getMessage()); } } } } if (isGeneric()) { // update resolved typex to point at generic type not raw type. ReferenceType genericType = (ReferenceType) this.resolvedTypeX.getGenericType(); // genericType.setSourceContext(this.resolvedTypeX.getSourceContext() // ); genericType.setStartPos(this.resolvedTypeX.getStartPos()); this.resolvedTypeX = genericType; } } public GenericSignature.FormalTypeParameter[] getAllFormals() { ensureGenericSignatureUnpacked(); if (formalsForResolution == null) { return new GenericSignature.FormalTypeParameter[0]; } else { return formalsForResolution; } } public ResolvedType getOuterClass() { if (!isNested()) { throw new IllegalStateException("Can't get the outer class of a non-nested type"); } // try finding outer class name from InnerClasses attribute assigned to this class for (Attribute attr : javaClass.getAttributes()) { if (attr instanceof InnerClasses) { // search for InnerClass entry that has current class as inner and some other class as outer InnerClass[] innerClss = ((InnerClasses) attr).getInnerClasses(); ConstantPool cpool = javaClass.getConstantPool(); for (InnerClass innerCls : innerClss) { // skip entries that miss any necessary component, 0 index means "undefined", from JVM Spec 2nd ed. par. 4.7.5 if (innerCls.getInnerClassIndex() == 0 || innerCls.getOuterClassIndex() == 0) { continue; } // resolve inner class name, check if it matches current class name ConstantClass innerClsInfo = (ConstantClass) cpool.getConstant(innerCls.getInnerClassIndex()); // class names in constant pool use '/' instead of '.', from JVM Spec 2nd ed. par. 4.2 String innerClsName = cpool.getConstantUtf8(innerClsInfo.getNameIndex()).getValue().replace('/', '.'); if (innerClsName.compareTo(className) == 0) { // resolve outer class name ConstantClass outerClsInfo = (ConstantClass) cpool.getConstant(innerCls.getOuterClassIndex()); // class names in constant pool use '/' instead of '.', from JVM Spec 2nd ed. par. 4.2 String outerClsName = cpool.getConstantUtf8(outerClsInfo.getNameIndex()).getValue().replace('/', '.'); UnresolvedType outer = UnresolvedType.forName(outerClsName); return outer.resolve(getResolvedTypeX().getWorld()); } } } } // try finding outer class name by assuming standard class name mangling convention of javac for this class int lastDollar = className.lastIndexOf('$'); String superClassName = className.substring(0, lastDollar); UnresolvedType outer = UnresolvedType.forName(superClassName); return outer.resolve(getResolvedTypeX().getWorld()); } private void ensureGenericInfoProcessed() { if ((bitflag & DISCOVERED_DECLARED_SIGNATURE) != 0) { return; } bitflag |= DISCOVERED_DECLARED_SIGNATURE; Signature sigAttr = AttributeUtils.getSignatureAttribute(javaClass.getAttributes()); declaredSignature = (sigAttr == null ? null : sigAttr.getSignature()); if (declaredSignature != null) { isGenericType = (declaredSignature.charAt(0) == '<'); } } public boolean isGeneric() { ensureGenericInfoProcessed(); return isGenericType; } @Override public String toString() { return (javaClass == null ? "BcelObjectType" : "BcelObjectTypeFor:" + className); } // --- state management public void evictWeavingState() { // Can't chuck all this away if (getResolvedTypeX().getWorld().couldIncrementalCompileFollow()) { return; } if (javaClass != null) { // Force retrieval of any lazy information ensureAnnotationsUnpacked(); ensureGenericInfoProcessed(); getDeclaredInterfaces(); getDeclaredFields(); getDeclaredMethods(); // The lazyClassGen is preserved for aspects - it exists to enable // around advice // inlining since the method will need 'injecting' into the affected // class. If // XnoInline is on, we can chuck away the lazyClassGen since it // won't be required // later. if (getResolvedTypeX().getWorld().isXnoInline()) { lazyClassGen = null; } // discard expensive bytecode array containing reweavable info if (weaverState != null) { weaverState.setReweavable(false); weaverState.setUnwovenClassFileData(null); } for (int i = methods.length - 1; i >= 0; i--) { methods[i].evictWeavingState(); } for (int i = fields.length - 1; i >= 0; i--) { fields[i].evictWeavingState(); } javaClass = null; this.artificial = true; // setSourceContext(SourceContextImpl.UNKNOWN_SOURCE_CONTEXT); // // bit naughty // interfaces=null; // force reinit - may get us the right // instances! // superClass=null; } } public void weavingCompleted() { hasBeenWoven = true; if (getResolvedTypeX().getWorld().isRunMinimalMemory()) { evictWeavingState(); } if (getSourceContext() != null && !getResolvedTypeX().isAspect()) { getSourceContext().tidy(); } } public boolean hasBeenWoven() { return hasBeenWoven; } @Override public boolean copySourceContext() { return false; } public void setExposedToWeaver(boolean b) { exposedToWeaver = b; } @Override public int getCompilerVersion() { return wvInfo.getMajorVersion(); } public void ensureConsistent() { superTypeReference.clear(); superInterfaceReferences.clear(); } }
317,743
Bug 317743 import handling and type lookup issues
Raised by Peter Melnikov on the mailing list. Two problems: 1) the binding scope being used for annotation style aspects accumulates lots of duplicate import prefixes in the SimpleScope object. 2) SimpleScope.lookupType tries the prefixes even if the type is already fully qualified. The combination of these issues causes a terrible mess. Lots of class lookup failures. Since the type cannot be 'partially qualified' it is silly to use the prefixes if the type is fully qualified.
resolved fixed
767bb85
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-06-29T00:12:05Z"
"2010-06-23T19:06:40Z"
org.aspectj.matcher/src/org/aspectj/weaver/BindingScope.java
/* ******************************************************************* * Copyright (c) 2006-2008 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * ******************************************************************/ package org.aspectj.weaver; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.patterns.FormalBinding; import org.aspectj.weaver.patterns.SimpleScope; /** * BindingScope that knows the enclosingType, which is needed for pointcut reference resolution * * @author Alexandre Vasseur */ public class BindingScope extends SimpleScope { private final ResolvedType m_enclosingType; private final ISourceContext m_sourceContext; public BindingScope(ResolvedType type, ISourceContext sourceContext, FormalBinding[] bindings) { super(type.getWorld(), bindings); m_enclosingType = type; m_sourceContext = sourceContext; } public ResolvedType getEnclosingType() { return m_enclosingType; } public ISourceLocation makeSourceLocation(IHasPosition location) { return m_sourceContext.makeSourceLocation(location); } public UnresolvedType lookupType(String name, IHasPosition location) { // bug 126560 if (m_enclosingType != null) { // add the package we're in to the list of imported // prefixes so that we can find types in the same package String pkgName = m_enclosingType.getPackageName(); if (pkgName != null && !pkgName.equals("")) { String[] currentImports = getImportedPrefixes(); String[] newImports = new String[currentImports.length + 1]; for (int i = 0; i < currentImports.length; i++) { newImports[i] = currentImports[i]; } newImports[currentImports.length] = pkgName.concat("."); setImportedPrefixes(newImports); } } return super.lookupType(name, location); } }
317,743
Bug 317743 import handling and type lookup issues
Raised by Peter Melnikov on the mailing list. Two problems: 1) the binding scope being used for annotation style aspects accumulates lots of duplicate import prefixes in the SimpleScope object. 2) SimpleScope.lookupType tries the prefixes even if the type is already fully qualified. The combination of these issues causes a terrible mess. Lots of class lookup failures. Since the type cannot be 'partially qualified' it is silly to use the prefixes if the type is fully qualified.
resolved fixed
767bb85
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-06-29T00:12:05Z"
"2010-06-23T19:06:40Z"
org.aspectj.matcher/src/org/aspectj/weaver/patterns/IScope.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.weaver.IHasPosition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; public interface IScope { /** returns the type corresponding to the name in this scope * returns ResolvedType.MISSING if no such type exists and reports a problem */ UnresolvedType lookupType(String name, IHasPosition location); World getWorld(); ResolvedType getEnclosingType(); // these next three are used to create {@link BindingTypePattern} objects. IMessageHandler getMessageHandler(); /** returns the formal associated with the name, or null if no such formal exists */ FormalBinding lookupFormal(String name); /** returns the formal with the index. Throws ArrayOutOfBounds exception if out of bounds */ FormalBinding getFormal(int i); int getFormalCount(); String[] getImportedPrefixes(); String[] getImportedNames(); void message(IMessage.Kind kind, IHasPosition location, String message); void message(IMessage.Kind kind, IHasPosition location1, IHasPosition location2, String message); void message(IMessage aMessage); //ISourceLocation makeSourceLocation(ILocation location); }
317,743
Bug 317743 import handling and type lookup issues
Raised by Peter Melnikov on the mailing list. Two problems: 1) the binding scope being used for annotation style aspects accumulates lots of duplicate import prefixes in the SimpleScope object. 2) SimpleScope.lookupType tries the prefixes even if the type is already fully qualified. The combination of these issues causes a terrible mess. Lots of class lookup failures. Since the type cannot be 'partially qualified' it is silly to use the prefixes if the type is fully qualified.
resolved fixed
767bb85
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-06-29T00:12:05Z"
"2010-06-23T19:06:40Z"
org.aspectj.matcher/src/org/aspectj/weaver/patterns/SimpleScope.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.SourceLocation; import org.aspectj.weaver.IHasPosition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; public class SimpleScope implements IScope { private World world; private ResolvedType enclosingType; protected FormalBinding[] bindings; private String[] importedPrefixes = javaLangPrefixArray; private String[] importedNames = ZERO_STRINGS; private static final String[] ZERO_STRINGS = new String[0]; private static final String[] javaLangPrefixArray = new String[] { "java.lang.", }; public SimpleScope(World world, FormalBinding[] bindings) { super(); this.world = world; this.bindings = bindings; } // ---- impl // XXX doesn't report any problems public UnresolvedType lookupType(String name, IHasPosition location) { for (int i = 0; i < importedNames.length; i++) { String importedName = importedNames[i]; // // make sure we're matching against the // // type name rather than part of it // if (importedName.endsWith("." + name)) { if (importedName.endsWith(name)) { return world.resolve(importedName); } } for (int i = 0; i < importedPrefixes.length; i++) { String importedPrefix = importedPrefixes[i]; ResolvedType tryType = world.resolve(UnresolvedType.forName(importedPrefix + name), true); if (!tryType.isMissing()) { return tryType; } } return world.resolve(UnresolvedType.forName(name), true); } public IMessageHandler getMessageHandler() { return world.getMessageHandler(); } public FormalBinding lookupFormal(String name) { for (int i = 0, len = bindings.length; i < len; i++) { if (bindings[i].getName().equals(name)) return bindings[i]; } return null; } public FormalBinding getFormal(int i) { return bindings[i]; } public int getFormalCount() { return bindings.length; } public String[] getImportedNames() { return importedNames; } public String[] getImportedPrefixes() { return importedPrefixes; } public void setImportedNames(String[] importedNames) { this.importedNames = importedNames; } public void setImportedPrefixes(String[] importedPrefixes) { this.importedPrefixes = importedPrefixes; } public static FormalBinding[] makeFormalBindings(UnresolvedType[] types, String[] names) { int len = types.length; FormalBinding[] bindings = new FormalBinding[len]; for (int i = 0; i < len; i++) { bindings[i] = new FormalBinding(types[i], names[i], i); } return bindings; } // ---- fields public ISourceLocation makeSourceLocation(IHasPosition location) { return new SourceLocation(ISourceLocation.NO_FILE, 0); } public void message(IMessage.Kind kind, IHasPosition location1, IHasPosition location2, String message) { message(kind, location1, message); message(kind, location2, message); } public void message(IMessage.Kind kind, IHasPosition location, String message) { getMessageHandler().handleMessage(new Message(message, kind, null, makeSourceLocation(location))); } public void message(IMessage aMessage) { getMessageHandler().handleMessage(aMessage); } public World getWorld() { return world; } public ResolvedType getEnclosingType() { return enclosingType; } }
317,743
Bug 317743 import handling and type lookup issues
Raised by Peter Melnikov on the mailing list. Two problems: 1) the binding scope being used for annotation style aspects accumulates lots of duplicate import prefixes in the SimpleScope object. 2) SimpleScope.lookupType tries the prefixes even if the type is already fully qualified. The combination of these issues causes a terrible mess. Lots of class lookup failures. Since the type cannot be 'partially qualified' it is silly to use the prefixes if the type is fully qualified.
resolved fixed
767bb85
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-06-29T00:12:05Z"
"2010-06-23T19:06:40Z"
org.aspectj.matcher/src/org/aspectj/weaver/patterns/WildTypePattern.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FileUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.BoundedReferenceType; import org.aspectj.weaver.CompressingDataOutputStream; import org.aspectj.weaver.IHasPosition; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.TypeFactory; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.UnresolvedTypeVariableReferenceType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; /** * The PatternParser always creates WildTypePatterns for type patterns in pointcut expressions (apart from *, which is sometimes * directly turned into TypePattern.ANY). resolveBindings() tries to work out what we've really got and turn it into a type pattern * that we can use for matching. This will normally be either an ExactTypePattern or a WildTypePattern. * * Here's how the process pans out for various generic and parameterized patterns: (see GenericsWildTypePatternResolvingTestCase) * * Foo where Foo exists and is generic Parser creates WildTypePattern namePatterns={Foo} resolveBindings resolves Foo to RT(Foo - * raw) return ExactTypePattern(LFoo;) * * Foo<String> where Foo exists and String meets the bounds Parser creates WildTypePattern namePatterns = {Foo}, * typeParameters=WTP{String} resolveBindings resolves typeParameters to ExactTypePattern(String) resolves Foo to RT(Foo) returns * ExactTypePattern(PFoo<String>; - parameterized) * * Foo<Str*> where Foo exists and takes one bound Parser creates WildTypePattern namePatterns = {Foo}, typeParameters=WTP{Str*} * resolveBindings resolves typeParameters to WTP{Str*} resolves Foo to RT(Foo) returns WildTypePattern(name = Foo, typeParameters = * WTP{Str*} isGeneric=false) * * Fo*<String> Parser creates WildTypePattern namePatterns = {Fo*}, typeParameters=WTP{String} resolveBindings resolves * typeParameters to ETP{String} returns WildTypePattern(name = Fo*, typeParameters = ETP{String} isGeneric=false) * * * Foo<?> * * Foo<? extends Number> * * Foo<? extends Number+> * * Foo<? super Number> * */ public class WildTypePattern extends TypePattern { private static final String GENERIC_WILDCARD_CHARACTER = "?"; // signature of ? is * private static final String GENERIC_WILDCARD_SIGNATURE_CHARACTER = "*"; // signature of ? is * private NamePattern[] namePatterns; private boolean failedResolution = false; int ellipsisCount; String[] importedPrefixes; String[] knownMatches; int dim; // SECRETAPI - just for testing, turns off boundschecking temporarily... public static boolean boundscheckingoff = false; // these next three are set if the type pattern is constrained by extends or super clauses, in which case the // namePatterns must have length 1 // TODO AMC: read/write/resolve of these fields TypePattern upperBound; // extends Foo TypePattern[] additionalInterfaceBounds; // extends Foo & A,B,C TypePattern lowerBound; // super Foo // if we have type parameters, these fields indicate whether we should be a generic type pattern or a parameterized // type pattern. We can only tell during resolve bindings. private boolean isGeneric = true; WildTypePattern(NamePattern[] namePatterns, boolean includeSubtypes, int dim, boolean isVarArgs, TypePatternList typeParams) { super(includeSubtypes, isVarArgs, typeParams); this.namePatterns = namePatterns; this.dim = dim; ellipsisCount = 0; for (int i = 0; i < namePatterns.length; i++) { if (namePatterns[i] == NamePattern.ELLIPSIS) { ellipsisCount++; } } setLocation(namePatterns[0].getSourceContext(), namePatterns[0].getStart(), namePatterns[namePatterns.length - 1].getEnd()); } public WildTypePattern(List names, boolean includeSubtypes, int dim) { this((NamePattern[]) names.toArray(new NamePattern[names.size()]), includeSubtypes, dim, false, TypePatternList.EMPTY); } public WildTypePattern(List names, boolean includeSubtypes, int dim, int endPos) { this(names, includeSubtypes, dim); this.end = endPos; } public WildTypePattern(List names, boolean includeSubtypes, int dim, int endPos, boolean isVarArg) { this(names, includeSubtypes, dim); this.end = endPos; this.isVarArgs = isVarArg; } public WildTypePattern(List names, boolean includeSubtypes, int dim, int endPos, boolean isVarArg, TypePatternList typeParams, TypePattern upperBound, TypePattern[] additionalInterfaceBounds, TypePattern lowerBound) { this((NamePattern[]) names.toArray(new NamePattern[names.size()]), includeSubtypes, dim, isVarArg, typeParams); this.end = endPos; this.upperBound = upperBound; this.lowerBound = lowerBound; this.additionalInterfaceBounds = additionalInterfaceBounds; } public WildTypePattern(List names, boolean includeSubtypes, int dim, int endPos, boolean isVarArg, TypePatternList typeParams) { this((NamePattern[]) names.toArray(new NamePattern[names.size()]), includeSubtypes, dim, isVarArg, typeParams); this.end = endPos; } public NamePattern[] getNamePatterns() { return namePatterns; } public TypePattern getUpperBound() { return upperBound; } public TypePattern getLowerBound() { return lowerBound; } public TypePattern[] getAdditionalIntefaceBounds() { return additionalInterfaceBounds; } // called by parser after parsing a type pattern, must bump dim as well as setting flag @Override public void setIsVarArgs(boolean isVarArgs) { this.isVarArgs = isVarArgs; if (isVarArgs) { this.dim += 1; } } /* * (non-Javadoc) * * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ @Override protected boolean couldEverMatchSameTypesAs(TypePattern other) { if (super.couldEverMatchSameTypesAs(other)) { return true; } // false is necessary but not sufficient UnresolvedType otherType = other.getExactType(); if (!ResolvedType.isMissing(otherType)) { if (namePatterns.length > 0) { if (!namePatterns[0].matches(otherType.getName())) { return false; } } } if (other instanceof WildTypePattern) { WildTypePattern owtp = (WildTypePattern) other; String mySimpleName = namePatterns[0].maybeGetSimpleName(); String yourSimpleName = owtp.namePatterns[0].maybeGetSimpleName(); if (mySimpleName != null && yourSimpleName != null) { return (mySimpleName.startsWith(yourSimpleName) || yourSimpleName.startsWith(mySimpleName)); } } return true; } // XXX inefficient implementation // we don't know whether $ characters are from nested types, or were // part of the declared type name (generated code often uses $s in type // names). More work required on our part to get this right... public static char[][] splitNames(String s, boolean convertDollar) { List ret = new ArrayList(); int startIndex = 0; while (true) { int breakIndex = s.indexOf('.', startIndex); // what about / if (convertDollar && (breakIndex == -1)) { breakIndex = s.indexOf('$', startIndex); // we treat $ like . here } if (breakIndex == -1) { break; } char[] name = s.substring(startIndex, breakIndex).toCharArray(); ret.add(name); startIndex = breakIndex + 1; } ret.add(s.substring(startIndex).toCharArray()); return (char[][]) ret.toArray(new char[ret.size()][]); } /** * @see org.aspectj.weaver.TypePattern#matchesExactly(IType) */ @Override protected boolean matchesExactly(ResolvedType type) { return matchesExactly(type, type); } @Override protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { String targetTypeName = type.getName(); // System.err.println("match: " + targetTypeName + ", " + knownMatches); //Arrays.asList(importedPrefixes)); // Ensure the annotation pattern is resolved annotationPattern.resolve(type.getWorld()); return matchesExactlyByName(targetTypeName, type.isAnonymous(), type.isNested()) && matchesParameters(type, STATIC) && matchesBounds(type, STATIC) && annotationPattern.matches(annotatedType, type.temporaryAnnotationTypes).alwaysTrue(); } // we've matched against the base (or raw) type, but if this type pattern specifies parameters or // type variables we need to make sure we match against them too private boolean matchesParameters(ResolvedType aType, MatchKind staticOrDynamic) { if (!isGeneric && typeParameters.size() > 0) { if (!aType.isParameterizedType()) { return false; } // we have to match type parameters return typeParameters.matches(aType.getResolvedTypeParameters(), staticOrDynamic).alwaysTrue(); } return true; } // we've matched against the base (or raw) type, but if this type pattern specifies bounds because // it is a ? extends or ? super deal then we have to match them too. private boolean matchesBounds(ResolvedType aType, MatchKind staticOrDynamic) { if (!(aType instanceof BoundedReferenceType)) { return true; } BoundedReferenceType boundedRT = (BoundedReferenceType) aType; if (upperBound == null && boundedRT.getUpperBound() != null) { // for upper bound, null can also match against Object - but anything else and we're out. if (!boundedRT.getUpperBound().getName().equals(UnresolvedType.OBJECT.getName())) { return false; } } if (lowerBound == null && boundedRT.getLowerBound() != null) { return false; } if (upperBound != null) { // match ? extends if (aType.isGenericWildcard() && boundedRT.isSuper()) { return false; } if (boundedRT.getUpperBound() == null) { return false; } return upperBound.matches((ResolvedType) boundedRT.getUpperBound(), staticOrDynamic).alwaysTrue(); } if (lowerBound != null) { // match ? super if (!(boundedRT.isGenericWildcard() && boundedRT.isSuper())) { return false; } return lowerBound.matches((ResolvedType) boundedRT.getLowerBound(), staticOrDynamic).alwaysTrue(); } return true; } /** * Used in conjunction with checks on 'isStar()' to tell you if this pattern represents '*' or '*[]' which are different ! */ public int getDimensions() { return dim; } @Override public boolean isArray() { return dim > 1; } /** * @param targetTypeName * @return */ private boolean matchesExactlyByName(String targetTypeName, boolean isAnonymous, boolean isNested) { // we deal with parameter matching separately... if (targetTypeName.indexOf('<') != -1) { targetTypeName = targetTypeName.substring(0, targetTypeName.indexOf('<')); } // we deal with bounds matching separately too... if (targetTypeName.startsWith(GENERIC_WILDCARD_CHARACTER)) { targetTypeName = GENERIC_WILDCARD_CHARACTER; } // XXX hack if (knownMatches == null && importedPrefixes == null) { return innerMatchesExactly(targetTypeName, isAnonymous, isNested); } if (isNamePatternStar()) { // we match if the dimensions match int numDimensionsInTargetType = 0; if (dim > 0) { int index; while ((index = targetTypeName.indexOf('[')) != -1) { numDimensionsInTargetType++; targetTypeName = targetTypeName.substring(index + 1); } if (numDimensionsInTargetType == dim) { return true; } else { return false; } } } // if our pattern is length 1, then known matches are exact matches // if it's longer than that, then known matches are prefixes of a sort if (namePatterns.length == 1) { if (isAnonymous) { // we've already ruled out "*", and no other name pattern should match an anonymous type return false; } for (int i = 0, len = knownMatches.length; i < len; i++) { if (knownMatches[i].equals(targetTypeName)) { return true; } } } else { for (int i = 0, len = knownMatches.length; i < len; i++) { String knownMatch = knownMatches[i]; // String knownPrefix = knownMatches[i] + "$"; // if (targetTypeName.startsWith(knownPrefix)) { if (targetTypeName.startsWith(knownMatch) && targetTypeName.length() > knownMatch.length() && targetTypeName.charAt(knownMatch.length()) == '$') { int pos = lastIndexOfDotOrDollar(knownMatch); if (innerMatchesExactly(targetTypeName.substring(pos + 1), isAnonymous, isNested)) { return true; } } } } // if any prefixes match, strip the prefix and check that the rest matches // assumes that prefixes have a dot at the end for (int i = 0, len = importedPrefixes.length; i < len; i++) { String prefix = importedPrefixes[i]; // System.err.println("prefix match? " + prefix + " to " + targetTypeName); if (targetTypeName.startsWith(prefix)) { if (innerMatchesExactly(targetTypeName.substring(prefix.length()), isAnonymous, isNested)) { return true; } } } return innerMatchesExactly(targetTypeName, isAnonymous, isNested); } private int lastIndexOfDotOrDollar(String string) { for (int pos = string.length() - 1; pos > -1; pos--) { char ch = string.charAt(pos); if (ch == '.' || ch == '$') { return pos; } } return -1; } private boolean innerMatchesExactly(String s, boolean isAnonymous, boolean convertDollar /* isNested */) { List<char[]> ret = new ArrayList<char[]>(); int startIndex = 0; while (true) { int breakIndex = s.indexOf('.', startIndex); // what about / if (convertDollar && (breakIndex == -1)) { breakIndex = s.indexOf('$', startIndex); // we treat $ like . here } if (breakIndex == -1) { break; } char[] name = s.substring(startIndex, breakIndex).toCharArray(); ret.add(name); startIndex = breakIndex + 1; } ret.add(s.substring(startIndex).toCharArray()); int namesLength = ret.size(); int patternsLength = namePatterns.length; int namesIndex = 0; int patternsIndex = 0; if ((!namePatterns[patternsLength - 1].isAny()) && isAnonymous) { return false; } if (ellipsisCount == 0) { if (namesLength != patternsLength) { return false; } while (patternsIndex < patternsLength) { if (!namePatterns[patternsIndex++].matches(ret.get(namesIndex++))) { return false; } } return true; } else if (ellipsisCount == 1) { if (namesLength < patternsLength - 1) { return false; } while (patternsIndex < patternsLength) { NamePattern p = namePatterns[patternsIndex++]; if (p == NamePattern.ELLIPSIS) { namesIndex = namesLength - (patternsLength - patternsIndex); } else { if (!p.matches(ret.get(namesIndex++))) { return false; } } } return true; } else { // System.err.print("match(\"" + Arrays.asList(namePatterns) + "\", \"" + Arrays.asList(names) + "\") -> "); boolean b = outOfStar(namePatterns, ret.toArray(new char[ret.size()][]), 0, 0, patternsLength - ellipsisCount, namesLength, ellipsisCount); // System.err.println(b); return b; } } private static boolean outOfStar(final NamePattern[] pattern, final char[][] target, int pi, int ti, int pLeft, int tLeft, final int starsLeft) { if (pLeft > tLeft) { return false; } while (true) { // invariant: if (tLeft > 0) then (ti < target.length && pi < pattern.length) if (tLeft == 0) { return true; } if (pLeft == 0) { return (starsLeft > 0); } if (pattern[pi] == NamePattern.ELLIPSIS) { return inStar(pattern, target, pi + 1, ti, pLeft, tLeft, starsLeft - 1); } if (!pattern[pi].matches(target[ti])) { return false; } pi++; ti++; pLeft--; tLeft--; } } private static boolean inStar(final NamePattern[] pattern, final char[][] target, int pi, int ti, final int pLeft, int tLeft, int starsLeft) { // invariant: pLeft > 0, so we know we'll run out of stars and find a real char in pattern // of course, we probably can't parse multiple ..'s in a row, but this keeps the algorithm // exactly parallel with that in NamePattern NamePattern patternChar = pattern[pi]; while (patternChar == NamePattern.ELLIPSIS) { starsLeft--; patternChar = pattern[++pi]; } while (true) { // invariant: if (tLeft > 0) then (ti < target.length) if (pLeft > tLeft) { return false; } if (patternChar.matches(target[ti])) { if (outOfStar(pattern, target, pi + 1, ti + 1, pLeft - 1, tLeft - 1, starsLeft)) { return true; } } ti++; tLeft--; } } /** * @see org.aspectj.weaver.TypePattern#matchesInstanceof(IType) */ @Override public FuzzyBoolean matchesInstanceof(ResolvedType type) { // XXX hack to let unmatched types just silently remain so if (maybeGetSimpleName() != null) { return FuzzyBoolean.NO; } type.getWorld().getMessageHandler().handleMessage( new Message("can't do instanceof matching on patterns with wildcards", IMessage.ERROR, null, getSourceLocation())); return FuzzyBoolean.NO; } public NamePattern extractName() { if (isIncludeSubtypes() || isVarArgs() || isArray() || (typeParameters.size() > 0)) { // we can't extract a name, the pattern is something like Foo+ and therefore // it is not ok to treat Foo as a method name! return null; } // System.err.println("extract from : " + Arrays.asList(namePatterns)); int len = namePatterns.length; if (len == 1 && !annotationPattern.isAny()) { return null; // can't extract } NamePattern ret = namePatterns[len - 1]; NamePattern[] newNames = new NamePattern[len - 1]; System.arraycopy(namePatterns, 0, newNames, 0, len - 1); namePatterns = newNames; // System.err.println(" left : " + Arrays.asList(namePatterns)); return ret; } /** * Method maybeExtractName. * * @param string * @return boolean */ public boolean maybeExtractName(String string) { int len = namePatterns.length; NamePattern ret = namePatterns[len - 1]; String simple = ret.maybeGetSimpleName(); if (simple != null && simple.equals(string)) { extractName(); return true; } return false; } /** * If this type pattern has no '.' or '*' in it, then return a simple string * * otherwise, this will return null; */ public String maybeGetSimpleName() { if (namePatterns.length == 1) { return namePatterns[0].maybeGetSimpleName(); } return null; } /** * If this type pattern has no '*' or '..' in it */ public String maybeGetCleanName() { if (namePatterns.length == 0) { throw new RuntimeException("bad name: " + namePatterns); } // System.out.println("get clean: " + this); StringBuffer buf = new StringBuffer(); for (int i = 0, len = namePatterns.length; i < len; i++) { NamePattern p = namePatterns[i]; String simpleName = p.maybeGetSimpleName(); if (simpleName == null) { return null; } if (i > 0) { buf.append("."); } buf.append(simpleName); } // System.out.println(buf); return buf.toString(); } @Override public TypePattern parameterizeWith(Map typeVariableMap, World w) { NamePattern[] newNamePatterns = new NamePattern[namePatterns.length]; for (int i = 0; i < namePatterns.length; i++) { newNamePatterns[i] = namePatterns[i]; } if (newNamePatterns.length == 1) { String simpleName = newNamePatterns[0].maybeGetSimpleName(); if (simpleName != null) { if (typeVariableMap.containsKey(simpleName)) { String newName = ((ReferenceType) typeVariableMap.get(simpleName)).getName().replace('$', '.'); StringTokenizer strTok = new StringTokenizer(newName, "."); newNamePatterns = new NamePattern[strTok.countTokens()]; int index = 0; while (strTok.hasMoreTokens()) { newNamePatterns[index++] = new NamePattern(strTok.nextToken()); } } } } WildTypePattern ret = new WildTypePattern(newNamePatterns, includeSubtypes, dim, isVarArgs, typeParameters .parameterizeWith(typeVariableMap, w)); ret.annotationPattern = this.annotationPattern.parameterizeWith(typeVariableMap, w); if (additionalInterfaceBounds == null) { ret.additionalInterfaceBounds = null; } else { ret.additionalInterfaceBounds = new TypePattern[additionalInterfaceBounds.length]; for (int i = 0; i < additionalInterfaceBounds.length; i++) { ret.additionalInterfaceBounds[i] = additionalInterfaceBounds[i].parameterizeWith(typeVariableMap, w); } } ret.upperBound = upperBound != null ? upperBound.parameterizeWith(typeVariableMap, w) : null; ret.lowerBound = lowerBound != null ? lowerBound.parameterizeWith(typeVariableMap, w) : null; ret.isGeneric = isGeneric; ret.knownMatches = knownMatches; ret.importedPrefixes = importedPrefixes; ret.copyLocationFrom(this); return ret; } /** * Need to determine if I'm really a pattern or a reference to a formal * * We may wish to further optimize the case of pattern vs. non-pattern * * We will be replaced by what we return */ @Override public TypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { if (isNamePatternStar()) { TypePattern anyPattern = maybeResolveToAnyPattern(scope, bindings, allowBinding, requireExactType); if (anyPattern != null) { if (requireExactType) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.WILDCARD_NOT_ALLOWED), getSourceLocation())); return NO; } else { return anyPattern; } } } TypePattern bindingTypePattern = maybeResolveToBindingTypePattern(scope, bindings, allowBinding, requireExactType); if (bindingTypePattern != null) { return bindingTypePattern; } annotationPattern = annotationPattern.resolveBindings(scope, bindings, allowBinding); // resolve any type parameters if (typeParameters != null && typeParameters.size() > 0) { typeParameters.resolveBindings(scope, bindings, allowBinding, requireExactType); isGeneric = false; } // resolve any bounds if (upperBound != null) { upperBound = upperBound.resolveBindings(scope, bindings, allowBinding, requireExactType); } if (lowerBound != null) { lowerBound = lowerBound.resolveBindings(scope, bindings, allowBinding, requireExactType); // amc - additional interface bounds only needed if we support type vars again. } String fullyQualifiedName = maybeGetCleanName(); if (fullyQualifiedName != null) { return resolveBindingsFromFullyQualifiedTypeName(fullyQualifiedName, scope, bindings, allowBinding, requireExactType); } else { if (requireExactType) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.WILDCARD_NOT_ALLOWED), getSourceLocation())); return NO; } importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; // pattern contains wildcards so can't be resolved to an ExactTypePattern... // XXX need to implement behavior for Lint.invalidWildcardTypeName } } private TypePattern maybeResolveToAnyPattern(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { // If there is an annotation specified we have to // use a special variant of Any TypePattern called // AnyWithAnnotation if (annotationPattern == AnnotationTypePattern.ANY) { if (dim == 0 && !isVarArgs && upperBound == null && lowerBound == null && (additionalInterfaceBounds == null || additionalInterfaceBounds.length == 0)) { // pr72531 return TypePattern.ANY; // ??? loses source location } } else if (!isVarArgs) { annotationPattern = annotationPattern.resolveBindings(scope, bindings, allowBinding); AnyWithAnnotationTypePattern ret = new AnyWithAnnotationTypePattern(annotationPattern); ret.setLocation(sourceContext, start, end); return ret; } return null; // can't resolve to a simple "any" pattern } private TypePattern maybeResolveToBindingTypePattern(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { String simpleName = maybeGetSimpleName(); if (simpleName != null) { FormalBinding formalBinding = scope.lookupFormal(simpleName); if (formalBinding != null) { if (bindings == null) { scope.message(IMessage.ERROR, this, "negation doesn't allow binding"); return this; } if (!allowBinding) { scope.message(IMessage.ERROR, this, "name binding only allowed in target, this, and args pcds"); return this; } BindingTypePattern binding = new BindingTypePattern(formalBinding, isVarArgs); binding.copyLocationFrom(this); bindings.register(binding, scope); return binding; } } return null; // not possible to resolve to a binding type pattern } private TypePattern resolveBindingsFromFullyQualifiedTypeName(String fullyQualifiedName, IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { String originalName = fullyQualifiedName; ResolvedType resolvedTypeInTheWorld = null; UnresolvedType type; // System.out.println("resolve: " + cleanName); // ??? this loop has too many inefficiencies to count resolvedTypeInTheWorld = lookupTypeInWorldIncludingPrefixes(scope.getWorld(), fullyQualifiedName, scope .getImportedPrefixes()); if (resolvedTypeInTheWorld.isGenericWildcard()) { type = resolvedTypeInTheWorld; } else { type = lookupTypeInScope(scope, fullyQualifiedName, this); } if ((type instanceof ResolvedType) && ((ResolvedType) type).isMissing()) { return resolveBindingsForMissingType(resolvedTypeInTheWorld, originalName, scope, bindings, allowBinding, requireExactType); } else { return resolveBindingsForExactType(scope, type, fullyQualifiedName, requireExactType); } } private UnresolvedType lookupTypeInScope(IScope scope, String typeName, IHasPosition location) { UnresolvedType type = null; while (ResolvedType.isMissing(type = scope.lookupType(typeName, location))) { int lastDot = typeName.lastIndexOf('.'); if (lastDot == -1) { break; } typeName = typeName.substring(0, lastDot) + '$' + typeName.substring(lastDot + 1); } return type; } /** * Searches the world for the ResolvedType with the given typeName. If one isn't found then for each of the supplied prefixes, * it prepends the typeName with the prefix and searches the world for the ResolvedType with this new name. If one still isn't * found then a MissingResolvedTypeWithKnownSignature is returned with the originally requested typeName (this ensures the * typeName makes sense). */ private ResolvedType lookupTypeInWorldIncludingPrefixes(World world, String typeName, String[] prefixes) { ResolvedType ret = lookupTypeInWorld(world, typeName); if (!ret.isMissing()) { return ret; } ResolvedType retWithPrefix = ret; int counter = 0; while (retWithPrefix.isMissing() && (counter < prefixes.length)) { retWithPrefix = lookupTypeInWorld(world, prefixes[counter] + typeName); counter++; } if (!retWithPrefix.isMissing()) { return retWithPrefix; } return ret; } private ResolvedType lookupTypeInWorld(World world, String typeName) { UnresolvedType ut = UnresolvedType.forName(typeName); ResolvedType ret = world.resolve(ut, true); while (ret.isMissing()) { int lastDot = typeName.lastIndexOf('.'); if (lastDot == -1) { break; } typeName = typeName.substring(0, lastDot) + '$' + typeName.substring(lastDot + 1); ret = world.resolve(UnresolvedType.forName(typeName), true); } return ret; } private TypePattern resolveBindingsForExactType(IScope scope, UnresolvedType aType, String fullyQualifiedName, boolean requireExactType) { TypePattern ret = null; if (aType.isTypeVariableReference()) { // we have to set the bounds on it based on the bounds of this pattern ret = resolveBindingsForTypeVariable(scope, (UnresolvedTypeVariableReferenceType) aType); } else if (typeParameters.size() > 0) { ret = resolveParameterizedType(scope, aType, requireExactType); } else if (upperBound != null || lowerBound != null) { // this must be a generic wildcard with bounds ret = resolveGenericWildcard(scope, aType); } else { if (dim != 0) { aType = UnresolvedType.makeArray(aType, dim); } ret = new ExactTypePattern(aType, includeSubtypes, isVarArgs); } ret.setAnnotationTypePattern(annotationPattern); ret.copyLocationFrom(this); return ret; } private TypePattern resolveGenericWildcard(IScope scope, UnresolvedType aType) { if (!aType.getSignature().equals(GENERIC_WILDCARD_SIGNATURE_CHARACTER)) { throw new IllegalStateException("Can only have bounds for a generic wildcard"); } boolean canBeExact = true; if ((upperBound != null) && ResolvedType.isMissing(upperBound.getExactType())) { canBeExact = false; } if ((lowerBound != null) && ResolvedType.isMissing(lowerBound.getExactType())) { canBeExact = false; } if (canBeExact) { ResolvedType type = null; if (upperBound != null) { if (upperBound.isIncludeSubtypes()) { canBeExact = false; } else { ReferenceType upper = (ReferenceType) upperBound.getExactType().resolve(scope.getWorld()); type = new BoundedReferenceType(upper, true, scope.getWorld()); } } else { if (lowerBound.isIncludeSubtypes()) { canBeExact = false; } else { ReferenceType lower = (ReferenceType) lowerBound.getExactType().resolve(scope.getWorld()); type = new BoundedReferenceType(lower, false, scope.getWorld()); } } if (canBeExact) { // might have changed if we find out include subtypes is set on one of the bounds... return new ExactTypePattern(type, includeSubtypes, isVarArgs); } } // we weren't able to resolve to an exact type pattern... // leave as wild type pattern importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; } private TypePattern resolveParameterizedType(IScope scope, UnresolvedType aType, boolean requireExactType) { ResolvedType rt = aType.resolve(scope.getWorld()); if (!verifyTypeParameters(rt, scope, requireExactType)) { return TypePattern.NO; // messages already isued } // Only if the type is exact *and* the type parameters are exact should we create an // ExactTypePattern for this WildTypePattern if (typeParameters.areAllExactWithNoSubtypesAllowed()) { TypePattern[] typePats = typeParameters.getTypePatterns(); UnresolvedType[] typeParameterTypes = new UnresolvedType[typePats.length]; for (int i = 0; i < typeParameterTypes.length; i++) { typeParameterTypes[i] = ((ExactTypePattern) typePats[i]).getExactType(); } // rt could be a parameterized type 156058 if (rt.isParameterizedType()) { rt = rt.getGenericType(); } ResolvedType type = TypeFactory.createParameterizedType(rt, typeParameterTypes, scope.getWorld()); if (isGeneric) { type = type.getGenericType(); } // UnresolvedType tx = UnresolvedType.forParameterizedTypes(aType,typeParameterTypes); // UnresolvedType type = scope.getWorld().resolve(tx,true); if (dim != 0) { type = ResolvedType.makeArray(type, dim); } return new ExactTypePattern(type, includeSubtypes, isVarArgs); } else { // AMC... just leave it as a wild type pattern then? importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; } } private TypePattern resolveBindingsForMissingType(ResolvedType typeFoundInWholeWorldSearch, String nameWeLookedFor, IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { if (requireExactType) { if (!allowBinding) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_BIND_TYPE, nameWeLookedFor), getSourceLocation())); } else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) { scope.getWorld().getLint().invalidAbsoluteTypeName.signal(nameWeLookedFor, getSourceLocation()); } return NO; } else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) { // Only put the lint warning out if we can't find it in the world if (typeFoundInWholeWorldSearch.isMissing()) { scope.getWorld().getLint().invalidAbsoluteTypeName.signal(nameWeLookedFor, getSourceLocation()); this.failedResolution = true; } } importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; } /** * We resolved the type to a type variable declared in the pointcut designator. Now we have to create either an exact type * pattern or a wild type pattern for it, with upper and lower bounds set accordingly. XXX none of this stuff gets serialized * yet * * @param scope * @param tvrType * @return */ private TypePattern resolveBindingsForTypeVariable(IScope scope, UnresolvedTypeVariableReferenceType tvrType) { Bindings emptyBindings = new Bindings(0); if (upperBound != null) { upperBound = upperBound.resolveBindings(scope, emptyBindings, false, false); } if (lowerBound != null) { lowerBound = lowerBound.resolveBindings(scope, emptyBindings, false, false); } if (additionalInterfaceBounds != null) { TypePattern[] resolvedIfBounds = new TypePattern[additionalInterfaceBounds.length]; for (int i = 0; i < resolvedIfBounds.length; i++) { resolvedIfBounds[i] = additionalInterfaceBounds[i].resolveBindings(scope, emptyBindings, false, false); } additionalInterfaceBounds = resolvedIfBounds; } if (upperBound == null && lowerBound == null && additionalInterfaceBounds == null) { // no bounds to worry about... ResolvedType rType = tvrType.resolve(scope.getWorld()); if (dim != 0) { rType = ResolvedType.makeArray(rType, dim); } return new ExactTypePattern(rType, includeSubtypes, isVarArgs); } else { // we have to set bounds on the TypeVariable held by tvrType before resolving it boolean canCreateExactTypePattern = true; if (upperBound != null && ResolvedType.isMissing(upperBound.getExactType())) { canCreateExactTypePattern = false; } if (lowerBound != null && ResolvedType.isMissing(lowerBound.getExactType())) { canCreateExactTypePattern = false; } if (additionalInterfaceBounds != null) { for (int i = 0; i < additionalInterfaceBounds.length; i++) { if (ResolvedType.isMissing(additionalInterfaceBounds[i].getExactType())) { canCreateExactTypePattern = false; } } } if (canCreateExactTypePattern) { TypeVariable tv = tvrType.getTypeVariable(); if (upperBound != null) { tv.setSuperclass(upperBound.getExactType()); } if (additionalInterfaceBounds != null) { UnresolvedType[] ifBounds = new UnresolvedType[additionalInterfaceBounds.length]; for (int i = 0; i < ifBounds.length; i++) { ifBounds[i] = additionalInterfaceBounds[i].getExactType(); } tv.setAdditionalInterfaceBounds(ifBounds); } ResolvedType rType = tvrType.resolve(scope.getWorld()); if (dim != 0) { rType = ResolvedType.makeArray(rType, dim); } return new ExactTypePattern(rType, includeSubtypes, isVarArgs); } return this; // leave as wild type pattern then } } /** * When this method is called, we have resolved the base type to an exact type. We also have a set of type patterns for the * parameters. Time to perform some basic checks: - can the base type be parameterized? (is it generic) - can the type parameter * pattern list match the number of parameters on the base type - do all parameter patterns meet the bounds of the respective * type variables If any of these checks fail, a warning message is issued and we return false. * * @return */ private boolean verifyTypeParameters(ResolvedType baseType, IScope scope, boolean requireExactType) { ResolvedType genericType = baseType.getGenericType(); if (genericType == null) { // issue message "does not match because baseType.getName() is not generic" scope.message(MessageUtil.warn(WeaverMessages.format(WeaverMessages.NOT_A_GENERIC_TYPE, baseType.getName()), getSourceLocation())); return false; } int minRequiredTypeParameters = typeParameters.size(); boolean foundEllipsis = false; TypePattern[] typeParamPatterns = typeParameters.getTypePatterns(); for (int i = 0; i < typeParamPatterns.length; i++) { if (typeParamPatterns[i] instanceof WildTypePattern) { WildTypePattern wtp = (WildTypePattern) typeParamPatterns[i]; if (wtp.ellipsisCount > 0) { foundEllipsis = true; minRequiredTypeParameters--; } } } TypeVariable[] tvs = genericType.getTypeVariables(); if ((tvs.length < minRequiredTypeParameters) || (!foundEllipsis && minRequiredTypeParameters != tvs.length)) { // issue message "does not match because wrong no of type params" String msg = WeaverMessages.format(WeaverMessages.INCORRECT_NUMBER_OF_TYPE_ARGUMENTS, genericType.getName(), new Integer(tvs.length)); if (requireExactType) { scope.message(MessageUtil.error(msg, getSourceLocation())); } else { scope.message(MessageUtil.warn(msg, getSourceLocation())); } return false; } // now check that each typeParameter pattern, if exact, matches the bounds // of the type variable. // pr133307 - delay verification until type binding completion, these next few lines replace // the call to checkBoundsOK if (!boundscheckingoff) { VerifyBoundsForTypePattern verification = new VerifyBoundsForTypePattern(scope, genericType, requireExactType, typeParameters, getSourceLocation()); scope.getWorld().getCrosscuttingMembersSet().recordNecessaryCheck(verification); } // return checkBoundsOK(scope,genericType,requireExactType); return true; } /** * By capturing the verification in this class, rather than performing it in verifyTypeParameters(), we can cope with situations * where the interactions between generics and declare parents would otherwise cause us problems. For example, if verifying as * we go along we may report a problem which would have been fixed by a declare parents that we haven't looked at yet. If we * create and store a verification object, we can verify this later when the type system is considered 'complete' */ static class VerifyBoundsForTypePattern implements IVerificationRequired { private final IScope scope; private final ResolvedType genericType; private final boolean requireExactType; private TypePatternList typeParameters = TypePatternList.EMPTY; private final ISourceLocation sLoc; public VerifyBoundsForTypePattern(IScope scope, ResolvedType genericType, boolean requireExactType, TypePatternList typeParameters, ISourceLocation sLoc) { this.scope = scope; this.genericType = genericType; this.requireExactType = requireExactType; this.typeParameters = typeParameters; this.sLoc = sLoc; } public void verify() { TypeVariable[] tvs = genericType.getTypeVariables(); TypePattern[] typeParamPatterns = typeParameters.getTypePatterns(); if (typeParameters.areAllExactWithNoSubtypesAllowed()) { for (int i = 0; i < tvs.length; i++) { UnresolvedType ut = typeParamPatterns[i].getExactType(); boolean continueCheck = true; // FIXME asc dont like this but ok temporary measure. If the type parameter // is itself a type variable (from the generic aspect) then assume it'll be // ok... (see pr112105) Want to break this? Run GenericAspectK test. if (ut.isTypeVariableReference()) { continueCheck = false; } // System.err.println("Verifying "+ut.getName()+" meets bounds for "+tvs[i]); if (continueCheck && !tvs[i].canBeBoundTo(ut.resolve(scope.getWorld()))) { // issue message that type parameter does not meet specification String parameterName = ut.getName(); if (ut.isTypeVariableReference()) { parameterName = ((TypeVariableReference) ut).getTypeVariable().getDisplayName(); } String msg = WeaverMessages.format(WeaverMessages.VIOLATES_TYPE_VARIABLE_BOUNDS, parameterName, new Integer(i + 1), tvs[i].getDisplayName(), genericType.getName()); if (requireExactType) { scope.message(MessageUtil.error(msg, sLoc)); } else { scope.message(MessageUtil.warn(msg, sLoc)); } } } } } } // pr133307 - moved to verification object // public boolean checkBoundsOK(IScope scope,ResolvedType genericType,boolean requireExactType) { // if (boundscheckingoff) return true; // TypeVariable[] tvs = genericType.getTypeVariables(); // TypePattern[] typeParamPatterns = typeParameters.getTypePatterns(); // if (typeParameters.areAllExactWithNoSubtypesAllowed()) { // for (int i = 0; i < tvs.length; i++) { // UnresolvedType ut = typeParamPatterns[i].getExactType(); // boolean continueCheck = true; // // FIXME asc dont like this but ok temporary measure. If the type parameter // // is itself a type variable (from the generic aspect) then assume it'll be // // ok... (see pr112105) Want to break this? Run GenericAspectK test. // if (ut.isTypeVariableReference()) { // continueCheck = false; // } // // if (continueCheck && // !tvs[i].canBeBoundTo(ut.resolve(scope.getWorld()))) { // // issue message that type parameter does not meet specification // String parameterName = ut.getName(); // if (ut.isTypeVariableReference()) parameterName = ((TypeVariableReference)ut).getTypeVariable().getDisplayName(); // String msg = // WeaverMessages.format( // WeaverMessages.VIOLATES_TYPE_VARIABLE_BOUNDS, // parameterName, // new Integer(i+1), // tvs[i].getDisplayName(), // genericType.getName()); // if (requireExactType) scope.message(MessageUtil.error(msg,getSourceLocation())); // else scope.message(MessageUtil.warn(msg,getSourceLocation())); // return false; // } // } // } // return true; // } @Override public boolean isStar() { boolean annPatternStar = annotationPattern == AnnotationTypePattern.ANY; return (isNamePatternStar() && annPatternStar && dim == 0); } private boolean isNamePatternStar() { return namePatterns.length == 1 && namePatterns[0].isAny(); } /** * returns those possible matches which I match exactly the last element of */ private String[] preMatch(String[] possibleMatches) { // if (namePatterns.length != 1) return CollectionUtil.NO_STRINGS; List ret = new ArrayList(); for (int i = 0, len = possibleMatches.length; i < len; i++) { char[][] names = splitNames(possibleMatches[i], true); // ??? not most efficient if (namePatterns[0].matches(names[names.length - 1])) { ret.add(possibleMatches[i]); continue; } if (possibleMatches[i].indexOf("$") != -1) { names = splitNames(possibleMatches[i], false); // ??? not most efficient if (namePatterns[0].matches(names[names.length - 1])) { ret.add(possibleMatches[i]); } } } return (String[]) ret.toArray(new String[ret.size()]); } // public void postRead(ResolvedType enclosingType) { // this.importedPrefixes = enclosingType.getImportedPrefixes(); // this.knownNames = prematch(enclosingType.getImportedNames()); // } @Override public String toString() { StringBuffer buf = new StringBuffer(); if (annotationPattern != AnnotationTypePattern.ANY) { buf.append('('); buf.append(annotationPattern.toString()); buf.append(' '); } for (int i = 0, len = namePatterns.length; i < len; i++) { NamePattern name = namePatterns[i]; if (name == null) { buf.append("."); } else { if (i > 0) { buf.append("."); } buf.append(name.toString()); } } if (upperBound != null) { buf.append(" extends "); buf.append(upperBound.toString()); } if (lowerBound != null) { buf.append(" super "); buf.append(lowerBound.toString()); } if (typeParameters != null && typeParameters.size() != 0) { buf.append("<"); buf.append(typeParameters.toString()); buf.append(">"); } if (includeSubtypes) { buf.append('+'); } if (isVarArgs) { buf.append("..."); } if (annotationPattern != AnnotationTypePattern.ANY) { buf.append(')'); } return buf.toString(); } @Override public boolean equals(Object other) { if (!(other instanceof WildTypePattern)) { return false; } WildTypePattern o = (WildTypePattern) other; int len = o.namePatterns.length; if (len != this.namePatterns.length) { return false; } if (this.includeSubtypes != o.includeSubtypes) { return false; } if (this.dim != o.dim) { return false; } if (this.isVarArgs != o.isVarArgs) { return false; } if (this.upperBound != null) { if (o.upperBound == null) { return false; } if (!this.upperBound.equals(o.upperBound)) { return false; } } else { if (o.upperBound != null) { return false; } } if (this.lowerBound != null) { if (o.lowerBound == null) { return false; } if (!this.lowerBound.equals(o.lowerBound)) { return false; } } else { if (o.lowerBound != null) { return false; } } if (!typeParameters.equals(o.typeParameters)) { return false; } for (int i = 0; i < len; i++) { if (!o.namePatterns[i].equals(this.namePatterns[i])) { return false; } } return (o.annotationPattern.equals(this.annotationPattern)); } @Override public int hashCode() { int result = 17; for (int i = 0, len = namePatterns.length; i < len; i++) { result = 37 * result + namePatterns[i].hashCode(); } result = 37 * result + annotationPattern.hashCode(); if (upperBound != null) { result = 37 * result + upperBound.hashCode(); } if (lowerBound != null) { result = 37 * result + lowerBound.hashCode(); } return result; } private static final byte VERSION = 1; // rev on change @Override public void write(CompressingDataOutputStream s) throws IOException { s.writeByte(TypePattern.WILD); s.writeByte(VERSION); s.writeShort(namePatterns.length); for (int i = 0; i < namePatterns.length; i++) { namePatterns[i].write(s); } s.writeBoolean(includeSubtypes); s.writeInt(dim); s.writeBoolean(isVarArgs); typeParameters.write(s); // ! change from M2 // ??? storing this information with every type pattern is wasteful of .class // file size. Storing it on enclosing types would be more efficient FileUtil.writeStringArray(knownMatches, s); FileUtil.writeStringArray(importedPrefixes, s); writeLocation(s); annotationPattern.write(s); // generics info, new in M3 s.writeBoolean(isGeneric); s.writeBoolean(upperBound != null); if (upperBound != null) { upperBound.write(s); } s.writeBoolean(lowerBound != null); if (lowerBound != null) { lowerBound.write(s); } s.writeInt(additionalInterfaceBounds == null ? 0 : additionalInterfaceBounds.length); if (additionalInterfaceBounds != null) { for (int i = 0; i < additionalInterfaceBounds.length; i++) { additionalInterfaceBounds[i].write(s); } } } public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { if (s.getMajorVersion() >= AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) { return readTypePattern150(s, context); } else { return readTypePatternOldStyle(s, context); } } public static TypePattern readTypePattern150(VersionedDataInputStream s, ISourceContext context) throws IOException { byte version = s.readByte(); if (version > VERSION) { throw new BCException("WildTypePattern was written by a more recent version of AspectJ, cannot read"); } int len = s.readShort(); NamePattern[] namePatterns = new NamePattern[len]; for (int i = 0; i < len; i++) { namePatterns[i] = NamePattern.read(s); } boolean includeSubtypes = s.readBoolean(); int dim = s.readInt(); boolean varArg = s.readBoolean(); TypePatternList typeParams = TypePatternList.read(s, context); WildTypePattern ret = new WildTypePattern(namePatterns, includeSubtypes, dim, varArg, typeParams); ret.knownMatches = FileUtil.readStringArray(s); ret.importedPrefixes = FileUtil.readStringArray(s); ret.readLocation(context, s); ret.setAnnotationTypePattern(AnnotationTypePattern.read(s, context)); // generics info, new in M3 ret.isGeneric = s.readBoolean(); if (s.readBoolean()) { ret.upperBound = TypePattern.read(s, context); } if (s.readBoolean()) { ret.lowerBound = TypePattern.read(s, context); } int numIfBounds = s.readInt(); if (numIfBounds > 0) { ret.additionalInterfaceBounds = new TypePattern[numIfBounds]; for (int i = 0; i < numIfBounds; i++) { ret.additionalInterfaceBounds[i] = TypePattern.read(s, context); } } return ret; } public static TypePattern readTypePatternOldStyle(VersionedDataInputStream s, ISourceContext context) throws IOException { int len = s.readShort(); NamePattern[] namePatterns = new NamePattern[len]; for (int i = 0; i < len; i++) { namePatterns[i] = NamePattern.read(s); } boolean includeSubtypes = s.readBoolean(); int dim = s.readInt(); WildTypePattern ret = new WildTypePattern(namePatterns, includeSubtypes, dim, false, null); ret.knownMatches = FileUtil.readStringArray(s); ret.importedPrefixes = FileUtil.readStringArray(s); ret.readLocation(context, s); return ret; } @Override public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public boolean hasFailedResolution() { return failedResolution; } }
317,743
Bug 317743 import handling and type lookup issues
Raised by Peter Melnikov on the mailing list. Two problems: 1) the binding scope being used for annotation style aspects accumulates lots of duplicate import prefixes in the SimpleScope object. 2) SimpleScope.lookupType tries the prefixes even if the type is already fully qualified. The combination of these issues causes a terrible mess. Lots of class lookup failures. Since the type cannot be 'partially qualified' it is silly to use the prefixes if the type is fully qualified.
resolved fixed
767bb85
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-06-29T00:12:05Z"
"2010-06-23T19:06:40Z"
org.aspectj.matcher/testsrc/org/aspectj/weaver/patterns/PatternsTests.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import org.aspectj.weaver.patterns.AndOrNotTestCase; import org.aspectj.weaver.patterns.ArgsTestCase; import org.aspectj.weaver.patterns.BindingTestCase; import org.aspectj.weaver.patterns.DeclareErrorOrWarningTestCase; import org.aspectj.weaver.patterns.ModifiersPatternTestCase; import org.aspectj.weaver.patterns.NamePatternParserTestCase; import org.aspectj.weaver.patterns.NamePatternTestCase; import org.aspectj.weaver.patterns.ParserTestCase; import org.aspectj.weaver.patterns.PatternsTests; import org.aspectj.weaver.patterns.PointcutRewriterTest; import org.aspectj.weaver.patterns.SignaturePatternTestCase; import org.aspectj.weaver.patterns.ThisOrTargetTestCase; import org.aspectj.weaver.patterns.TypePatternListTestCase; import org.aspectj.weaver.patterns.TypePatternTestCase; import org.aspectj.weaver.patterns.VisitorTestCase; import org.aspectj.weaver.patterns.WithinTestCase; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; public class PatternsTests extends TestCase { public static Test suite() { TestSuite suite = new TestSuite(PatternsTests.class.getName()); // $JUnit-BEGIN$ suite.addTestSuite(AndOrNotTestCase.class); suite.addTestSuite(BindingTestCase.class); suite.addTestSuite(DeclareErrorOrWarningTestCase.class); suite.addTestSuite(ModifiersPatternTestCase.class); suite.addTestSuite(NamePatternParserTestCase.class); suite.addTestSuite(NamePatternTestCase.class); suite.addTestSuite(ParserTestCase.class); suite.addTestSuite(SignaturePatternTestCase.class); suite.addTestSuite(ThisOrTargetTestCase.class); suite.addTestSuite(TypePatternListTestCase.class); suite.addTestSuite(TypePatternTestCase.class); suite.addTestSuite(WithinTestCase.class); suite.addTestSuite(ArgsTestCase.class); // suite.addTestSuite(AnnotationPatternTestCase.class); // suite.addTestSuite(AnnotationPatternMatchingTestCase.class); suite.addTestSuite(PointcutRewriterTest.class); suite.addTestSuite(VisitorTestCase.class); // $JUnit-END$ return suite; } public PatternsTests(String name) { super(name); } }
317,743
Bug 317743 import handling and type lookup issues
Raised by Peter Melnikov on the mailing list. Two problems: 1) the binding scope being used for annotation style aspects accumulates lots of duplicate import prefixes in the SimpleScope object. 2) SimpleScope.lookupType tries the prefixes even if the type is already fully qualified. The combination of these issues causes a terrible mess. Lots of class lookup failures. Since the type cannot be 'partially qualified' it is silly to use the prefixes if the type is fully qualified.
resolved fixed
767bb85
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-06-29T00:12:05Z"
"2010-06-23T19:06:40Z"
org.aspectj.matcher/testsrc/org/aspectj/weaver/patterns/SimpleScopeTests.java