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
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/TypePatternTestCase.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.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.CompressingDataOutputStream; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; import org.aspectj.weaver.reflect.ReflectionWorld; public class TypePatternTestCase extends PatternsTestCase { public World getWorld() { return new ReflectionWorld(true, this.getClass().getClassLoader()); } public void testStaticMatch() { checkMatch("java.lang.Object", "java.lang.Object", true); checkMatch("java.lang.Object+", "java.lang.Object", true); checkMatch("java.lang.Object+", "java.lang.String", true); checkMatch("java.lang.String+", "java.lang.Object", false); checkMatch("java.lang.Integer", "java.lang.String", false); checkMatch("java.lang.Integer", "int", false); checkMatch("java.lang.Number+", "java.lang.Integer", true); checkMatch("java..*", "java.lang.Integer", true); checkMatch("java..*", "java.lang.reflect.Modifier", true); checkMatch("java..*", "int", false); checkMatch("java..*", "javax.swing.Action", false); checkMatch("java..*+", "javax.swing.Action", true); checkMatch("*.*.Object", "java.lang.Object", true); checkMatch("*.Object", "java.lang.Object", false); checkMatch("*..*", "java.lang.Object", true); checkMatch("*..*", "int", false); checkMatch("java..Modifier", "java.lang.reflect.Modifier", true); checkMatch("java.lang.reflect.Mod..ifier", "java.lang.reflect.Modifier", false); checkMatch("java..reflect..Modifier", "java.lang.reflect.Modifier", true); checkMatch("java..lang..Modifier", "java.lang.reflect.Modifier", true); checkMatch("java..*..Modifier", "java.lang.reflect.Modifier", true); checkMatch("java..*..*..Modifier", "java.lang.reflect.Modifier", true); checkMatch("java..*..*..*..Modifier", "java.lang.reflect.Modifier", false); // checkMatch("java..reflect..Modifier", "java.lang.reflect.Modxifier", false); checkMatch("ja*va..Modifier", "java.lang.reflect.Modifier", true); checkMatch("java..*..Mod*ifier", "java.lang.reflect.Modifier", true); } // three levels: // 0. defined in current compilation unit, or imported by name // 1. defined in current package/type/whatever // 2. defined in package imported by * /** * We've decided not to test this here, but rather in any compilers */ public void testImportResolve() { // checkIllegalImportResolution("List", new String[] { "java.util", "java.awt", }, // ZERO_STRINGS); } // Assumption for bcweaver: Already resolved type patterns with no *s or ..'s into exact type // patterns. Exact type patterns don't have import lists. non-exact-type pattens don't // care about precedence, so the current package can be included with all the other packages, // and we don't care about compilation units, and we don't care about ordering. // only giving this wild-type patterns public void testImportMatch() { checkImportMatch("*List", new String[] { "java.awt.", }, ZERO_STRINGS, "java.awt.List", true); checkImportMatch("*List", new String[] { "java.awt.", }, ZERO_STRINGS, "java.awt.List", true); checkImportMatch("*List", new String[] { "java.awt.", }, ZERO_STRINGS, "java.util.List", false); checkImportMatch("*List", new String[] { "java.util.", }, ZERO_STRINGS, "java.awt.List", false); checkImportMatch("*List", new String[] { "java.util.", }, ZERO_STRINGS, "java.util.List", true); checkImportMatch("*List", ZERO_STRINGS, new String[] { "java.awt.List", }, "java.awt.List", true); checkImportMatch("awt.*List", ZERO_STRINGS, new String[] { "java.awt.List", }, "java.awt.List", false); checkImportMatch("*Foo", ZERO_STRINGS, new String[] { "java.awt.List", }, "java.awt.List", false); checkImportMatch("*List", new String[] { "java.util.", "java.awt.", }, ZERO_STRINGS, "java.util.List", true); checkImportMatch("*List", new String[] { "java.util.", "java.awt.", }, ZERO_STRINGS, "java.awt.List", true); checkImportMatch("*..List", new String[] { "java.util." }, ZERO_STRINGS, "java.util.List", true); checkImportMatch("*..List", new String[] { "java.util." }, ZERO_STRINGS, "java.awt.List", true); } public void testImportMatchWithInners() { checkImportMatch("*Entry", new String[] { "java.util.", "java.util.Map$" }, ZERO_STRINGS, "java.util.Map$Entry", true); checkImportMatch("java.util.Map.*Entry", ZERO_STRINGS, ZERO_STRINGS, "java.util.Map$Entry", true); checkImportMatch("*Entry", new String[] { "java.util.", }, ZERO_STRINGS, "java.util.Map$Entry", false); checkImportMatch("*.Entry", new String[] { "java.util.", }, ZERO_STRINGS, "java.util.Map$Entry", true); checkImportMatch("Map.*", new String[] { "java.util.", }, ZERO_STRINGS, "java.util.Map$Entry", true); checkImportMatch("Map.*", ZERO_STRINGS, new String[] { "java.util.Map" }, "java.util.Map$Entry", true); } private void checkImportMatch(String wildPattern, String[] importedPackages, String[] importedNames, String matchName, boolean shouldMatch) { WildTypePattern p = makeResolvedWildTypePattern(wildPattern, importedPackages, importedNames); checkPatternMatch(p, matchName, shouldMatch); } private WildTypePattern makeResolvedWildTypePattern(String wildPattern, String[] importedPackages, String[] importedNames) { WildTypePattern unresolved = (WildTypePattern) new PatternParser(wildPattern).parseTypePattern(); WildTypePattern resolved = resolve(unresolved, importedPackages, importedNames); return resolved; } private WildTypePattern resolve(WildTypePattern unresolved, String[] importedPrefixes, String[] importedNames) { TestScope scope = makeTestScope(); scope.setImportedPrefixes(importedPrefixes); scope.setImportedNames(importedNames); return (WildTypePattern) unresolved.resolveBindings(scope, Bindings.NONE, false, false); } public static final String[] ZERO_STRINGS = new String[0]; public void testInstanceofMatch() { checkInstanceofMatch("java.lang.Object", "java.lang.Object", FuzzyBoolean.YES); checkIllegalInstanceofMatch("java.lang.Object+", "java.lang.Object"); checkIllegalInstanceofMatch("java.lang.Object+", "java.lang.String"); checkIllegalInstanceofMatch("java.lang.String+", "java.lang.Object"); checkIllegalInstanceofMatch("java.lang.*", "java.lang.Object"); checkInstanceofMatch("java.lang.Integer", "java.lang.String", FuzzyBoolean.NO); checkInstanceofMatch("java.lang.Number", "java.lang.Integer", FuzzyBoolean.YES); checkInstanceofMatch("java.lang.Integer", "java.lang.Number", FuzzyBoolean.MAYBE); checkIllegalInstanceofMatch("java..Integer", "java.lang.Integer"); checkInstanceofMatch("*", "java.lang.Integer", FuzzyBoolean.YES); } public void testArrayMatch() { checkMatch("*[][]", "java.lang.Object", false); checkMatch("*[]", "java.lang.Object[]", true); checkMatch("*[][]", "java.lang.Object[][]", true); checkMatch("java.lang.Object+", "java.lang.Object[]", true); checkMatch("java.lang.Object[]", "java.lang.Object", false); checkMatch("java.lang.Object[]", "java.lang.Object[]", true); checkMatch("java.lang.Object[][]", "java.lang.Object[][]", true); checkMatch("java.lang.String[]", "java.lang.Object", false); checkMatch("java.lang.String[]", "java.lang.Object[]", false); checkMatch("java.lang.String[][]", "java.lang.Object[][]", false); checkMatch("java.lang.Object+[]", "java.lang.String[][]", true); checkMatch("java.lang.Object+[]", "java.lang.String[]", true); checkMatch("java.lang.Object+[]", "int[][]", true); checkMatch("java.lang.Object+[]", "int[]", false); } private void checkIllegalInstanceofMatch(String pattern, String name) { try { TypePattern p = makeTypePattern(pattern); ResolvedType type = world.resolve(name); p.matchesInstanceof(type); } catch (Throwable e) { return; } assertTrue("matching " + pattern + " with " + name + " should fail", false); } private void checkInstanceofMatch(String pattern, String name, FuzzyBoolean shouldMatch) { TypePattern p = makeTypePattern(pattern); ResolvedType type = world.resolve(name); p = p.resolveBindings(makeTestScope(), null, false, false); // System.out.println("type: " + p); FuzzyBoolean result = p.matchesInstanceof(type); String msg = "matches " + pattern + " to " + type; assertEquals(msg, shouldMatch, result); } private TestScope makeTestScope() { TestScope scope = new TestScope(ZERO_STRINGS, ZERO_STRINGS, world); return scope; } private TypePattern makeTypePattern(String pattern) { PatternParser pp = new PatternParser(pattern); TypePattern tp = pp.parseSingleTypePattern(); pp.checkEof(); return tp; } private void checkMatch(String pattern, String name, boolean shouldMatch) { TypePattern p = makeTypePattern(pattern); p = p.resolveBindings(makeTestScope(), null, false, false); checkPatternMatch(p, name, shouldMatch); } private void checkPatternMatch(TypePattern p, String name, boolean shouldMatch) { ResolvedType type = world.resolve(name); // System.out.println("type: " + type); boolean result = p.matchesStatically(type); String msg = "matches " + p + " to " + type + " expected "; if (shouldMatch) { assertTrue(msg + shouldMatch, result); } else { assertTrue(msg + shouldMatch, !result); } } public void testSerialization() throws IOException { String[] patterns = new String[] { "java.lang.Object", "java.lang.Object+", "java.lang.Integer", "int", "java..*", "java..util..*", "*.*.Object", "*", }; for (int i = 0, len = patterns.length; i < len; i++) { checkSerialization(patterns[i]); } } /** * Method checkSerialization. * * @param string */ private void checkSerialization(String string) throws IOException { TypePattern p = makeTypePattern(string); ByteArrayOutputStream bo = new ByteArrayOutputStream(); ConstantPoolSimulator cps = new ConstantPoolSimulator(); CompressingDataOutputStream out = new CompressingDataOutputStream(bo, cps); p.write(out); out.close(); ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); VersionedDataInputStream in = new VersionedDataInputStream(bi, cps); TypePattern newP = TypePattern.read(in, null); assertEquals("write/read", p, newP); } }
318,397
Bug 318397 Caching in EclipseSourceType is too aggressive
In fixing a recent Roo related issue (where annotations are resolved too early, before declare parents are done) a cache was introduced into EclipseSourceType (see ensureAnnotationTypesResolved()). The cache needs to be cleared if the set of annotation declarations changes - this can occur even after parsing because declare annotation can change them.
resolved fixed
fe049ea
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-06-30T00:20:30Z"
"2010-06-30T01:06:40Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseSourceType.java
/* ******************************************************************* * Copyright (c) 2002,2010 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 * 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.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.StandardAnnotation; 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.Declare; 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 * @author Andy Clement */ 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<Declare> declares = new ArrayList<Declare>(); public List<EclipseTypeMunger> typeMungers = new ArrayList<EclipseTypeMunger>(); private final EclipseFactory factory; private final SourceTypeBinding binding; private final TypeDeclaration declaration; private final CompilationUnitDeclaration unit; private boolean annotationsFullyResolved = false; private boolean annotationTypesAreResolved = false; private ResolvedType[] annotationTypes = null; private boolean discoveredAnnotationTargetKinds = false; private AnnotationTargetKind[] annotationTargetKinds; private AnnotationAJ[] annotations = null; 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<ResolvedMember> declaredPointcuts = new ArrayList<ResolvedMember>(); List<ResolvedMember> declaredMethods = new ArrayList<ResolvedMember>(); List<ResolvedMember> declaredFields = new ArrayList<ResolvedMember>(); 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); if (df != null) { 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) { boolean positionKnown = true; if (amd.binding.sourceMethod() == null) { if (amd.binding.declaringClass instanceof SourceTypeBinding) { SourceTypeBinding stb = ((SourceTypeBinding) amd.binding.declaringClass); if (stb.scope == null || stb.scope.referenceContext == null) { positionKnown = false; } } } if (positionKnown) { // pr229829 member.setSourceContext(new EclipseSourceContext(unit.compilationResult, amd.binding.sourceStart())); member.setPosition(amd.binding.sourceStart(), amd.binding.sourceEnd()); } else { member.setSourceContext(new EclipseSourceContext(unit.compilationResult, 0)); member.setPosition(0, 0); } } 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 = declaredPointcuts.toArray(new ResolvedPointcutDefinition[declaredPointcuts.size()]); this.declaredMethods = declaredMethods.toArray(new ResolvedMember[declaredMethods.size()]); this.declaredFields = 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 = "";// maybeGetExtraArgName(); 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); } } 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] == null) { // Something else is broken in this file and will be reported separately continue; } 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[j] == null) { // Something else is broken in this file and will be reported separately continue; } 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 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<AnnotationTargetKind> targetKinds = new ArrayList<AnnotationTargetKind>(); 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 targetKinds.toArray(annotationTargetKinds); } } return annotationTargetKinds; } /** * Ensure the annotation types have been resolved, where resolved means the eclipse type bindings have been converted to their * ResolvedType representations. This does not deeply resolve the annotations, it only does the type names. */ private void ensureAnnotationTypesResolved() { if (!annotationTypesAreResolved) { Annotation[] as = declaration.annotations; if (as == null) { annotationTypes = ResolvedType.NONE; } else { annotationTypes = new ResolvedType[as.length]; for (int a = 0; a < as.length; a++) { TypeBinding tb = as[a].type.resolveType(declaration.staticInitializerScope); if (tb == null) { annotationTypes[a] = ResolvedType.MISSING; } else { annotationTypes[a] = factory.fromTypeBindingToRTX(tb); } } } annotationTypesAreResolved = true; } } public boolean hasAnnotation(UnresolvedType ofType) { ensureAnnotationTypesResolved(); for (int a = 0, max = annotationTypes.length; a < max; a++) { if (ofType.equals(annotationTypes[a])) { 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 AnnotationAJ[] getAnnotations() { if (annotations != null) { return annotations; // only do this once } if (!annotationsFullyResolved) { TypeDeclaration.resolveAnnotations(declaration.staticInitializerScope, declaration.annotations, binding); annotationsFullyResolved = true; } Annotation[] as = declaration.annotations; if (as == null || as.length == 0) { annotations = AnnotationAJ.EMPTY_ARRAY; } else { annotations = new AnnotationAJ[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 AnnotationAJ 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; StandardAnnotation annotationAJ = new StandardAnnotation(annotationType, isRuntimeVisible); generateAnnotation(eclipseAnnotation, annotationAJ); return annotationAJ; } static class MissingImplementationException extends RuntimeException { MissingImplementationException(String reason) { super(reason); } } /** * Use the information in the supplied eclipse based annotation to fill in the standard annotation. * * @param annotation eclipse based annotation representation * @param annotationAJ AspectJ based annotation representation */ private void generateAnnotation(Annotation annotation, StandardAnnotation 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 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) { // Testcase for this clause is MultiProjectIncrementalTests.testAnnotations_pr262154() AnnotationValue av = EclipseAnnotationConvertor.generateElementValueForConstantExpression(defaultValue, defaultValueBinding); return new ArrayAnnotationValue(new AnnotationValue[] { av }); } 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() { ensureAnnotationTypesResolved(); return annotationTypes; } 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((sourceSc.scope.referenceContext)); } } 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 typeParameter) { String name = new String(typeParameter.name); ReferenceBinding superclassBinding = typeParameter.binding.superclass; UnresolvedType superclass = UnresolvedType.forSignature(new String(superclassBinding.signature())); UnresolvedType[] superinterfaces = null; ReferenceBinding[] superInterfaceBindings = typeParameter.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(typeParameter.binding.declaringElement)); tv.setRank(typeParameter.binding.rank); return tv; } }
321,641
Bug 321641 No way to exclude Proxool classes although excluded from AOP. Causing Veryfy error.
Build Identifier: 20100218-1602 For aspectJ 1.6.7 the setup works, however exactly the same setup but changing the aspectJ version to 1.6.8 or 1.6.9 derive to the same error: a piece of code excluded from the aop.xml is woven causing a Verify Error. We are using Proxool, proxy setup which in fact uses CGLIB to create a EnhancerProxy class. In order to avoid VerifyError exceptions the Proxool classes are excluded from aop.xml exactly in the same way the CGLIB workarround is commented in the aspectJ FAQ: <exclude within="*..*Proxool*"/> This is the error we got when we upgrade our 1.6.7 aspejctweaver.jar to 1.6.8. The same is got when using 1.6.9: jvm 3 | 2010/08/03 16:42:53 | java.lang.VerifyError: (class: oracle/jdbc/internal/OracleConnection$$EnhancerByProxool$$7f6320a8, method: getTdoCState signature: (Ljava/lang/String;Ljava/lang/String;)J) Inconsistent stack height 1 != 0 jvm 3 | 2010/08/03 16:42:53 | at java.lang.Class.getDeclaredMethods0(Native Method) jvm 3 | 2010/08/03 16:42:53 | at java.lang.Class.privateGetDeclaredMethods(Class.java:2427) jvm 3 | 2010/08/03 16:42:53 | at java.lang.Class.getDeclaredMethod(Class.java:1935) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.getCallbacksSetter(Enhancer.java:627) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.setCallbacksHelper(Enhancer.java:615) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.setThreadCallbacks(Enhancer.java:609) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.createUsingReflection(Enhancer.java:631) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.firstInstance(Enhancer.java:538) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:225) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.createHelper(Enhancer.java:377) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.create(Enhancer.java:285) .... As far as the Verify Error is got while deploying one of the applications that run on the serve we are no able to use the new versions of aspectJ because the application is not properly started up. Thank you very much in advance, Best regards. Reproducible: Always Steps to Reproduce: 1.Exclude Proxool classes from aop.xml using aspectj 1.6.7. It works 2.Upgrade to 1.6.8: it does not work. 3.Upgrade to 1.6.9: it does not work.
resolved fixed
85fd25d
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-08-10T15:11:54Z"
"2010-08-03T18:26:40Z"
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<TypePattern> m_aspectExcludeTypePattern = new ArrayList<TypePattern>(); private List<String> m_aspectExcludeStartsWith = new ArrayList<String>(); private List<TypePattern> m_aspectIncludeTypePattern = new ArrayList<TypePattern>(); private List<String> m_aspectIncludeStartsWith = new ArrayList<String>(); 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<Definition> parseDefinitions(final ClassLoader loader) { if (trace.isTraceEnabled()) { trace.enter("parseDefinitions", this); } List<Definition> definitions = new ArrayList<Definition>(); 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<URL> xmls = weavingContext.getResources(nextDefinition); // System.out.println("? registerDefinitions: found-aop.xml=" + xmls.hasMoreElements() + ", loader=" + loader); Set<URL> seenBefore = new HashSet<URL>(); while (xmls.hasMoreElements()) { URL xml = 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<Definition> 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<Definition> definitions) { String fastMatchInfo = null; for (Definition definition : definitions) { for (String exclude : definition.getAspectExcludePatterns()) { 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<Definition> definitions) { String fastMatchInfo = null; for (Definition definition : definitions) { for (String include : definition.getAspectIncludePatterns()) { 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<Definition> 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 (Definition definition : definitions) { for (String aspectClassName : definition.getAspectClassNames()) { if (acceptAspect(aspectClassName)) { info("register aspect " + aspectClassName); // System.err.println("? ClassLoaderWeavingAdaptor.registerAspects() aspectName=" + aspectClassName + // ", loader=" + loader + ", bundle=" + weavingContext.getClassLoaderName()); String requiredType = definition.getAspectRequires(aspectClassName); if (requiredType != null) { // This aspect expresses that it requires a type to be around, otherwise it should 'switch off' ((BcelWorld) weaver.getWorld()).addAspectRequires(aspectClassName, requiredType); } String definedScope = definition.getScopeForAspect(aspectClassName); if (definedScope != null) { ((BcelWorld) weaver.getWorld()).addScopedAspect(aspectClassName, definedScope); } // ResolvedType aspect = weaver.addLibraryAspect(aspectClassName); // generate key for SC if (namespace == null) { namespace = new StringBuffer(aspectClassName); } else { namespace = namespace.append(";").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 (Definition definition : definitions) { 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 if (includeStar) { return true; } if (!includeExactName.isEmpty()) { didSomeIncludeMatching = true; for (String exactname : includeExactName) { if (fastClassName.equals(exactname)) { return true; } } } for (int i = 0; i < m_includeStartsWith.size(); i++) { didSomeIncludeMatching = true; boolean fastaccept = fastClassName.startsWith(m_includeStartsWith.get(i)); if (fastaccept) { return true; } } 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(m_aspectExcludeStartsWith.get(i))) { return false; } } // INCLUDE: if one match then accept for (int i = 0; i < m_aspectIncludeStartsWith.size(); i++) { if (fastClassName.startsWith(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); } } }
321,641
Bug 321641 No way to exclude Proxool classes although excluded from AOP. Causing Veryfy error.
Build Identifier: 20100218-1602 For aspectJ 1.6.7 the setup works, however exactly the same setup but changing the aspectJ version to 1.6.8 or 1.6.9 derive to the same error: a piece of code excluded from the aop.xml is woven causing a Verify Error. We are using Proxool, proxy setup which in fact uses CGLIB to create a EnhancerProxy class. In order to avoid VerifyError exceptions the Proxool classes are excluded from aop.xml exactly in the same way the CGLIB workarround is commented in the aspectJ FAQ: <exclude within="*..*Proxool*"/> This is the error we got when we upgrade our 1.6.7 aspejctweaver.jar to 1.6.8. The same is got when using 1.6.9: jvm 3 | 2010/08/03 16:42:53 | java.lang.VerifyError: (class: oracle/jdbc/internal/OracleConnection$$EnhancerByProxool$$7f6320a8, method: getTdoCState signature: (Ljava/lang/String;Ljava/lang/String;)J) Inconsistent stack height 1 != 0 jvm 3 | 2010/08/03 16:42:53 | at java.lang.Class.getDeclaredMethods0(Native Method) jvm 3 | 2010/08/03 16:42:53 | at java.lang.Class.privateGetDeclaredMethods(Class.java:2427) jvm 3 | 2010/08/03 16:42:53 | at java.lang.Class.getDeclaredMethod(Class.java:1935) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.getCallbacksSetter(Enhancer.java:627) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.setCallbacksHelper(Enhancer.java:615) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.setThreadCallbacks(Enhancer.java:609) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.createUsingReflection(Enhancer.java:631) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.firstInstance(Enhancer.java:538) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:225) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.createHelper(Enhancer.java:377) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.create(Enhancer.java:285) .... As far as the Verify Error is got while deploying one of the applications that run on the serve we are no able to use the new versions of aspectJ because the application is not properly started up. Thank you very much in advance, Best regards. Reproducible: Always Steps to Reproduce: 1.Exclude Proxool classes from aop.xml using aspectj 1.6.7. It works 2.Upgrade to 1.6.8: it does not work. 3.Upgrade to 1.6.9: it does not work.
resolved fixed
85fd25d
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-08-10T15:11:54Z"
"2010-08-03T18:26:40Z"
loadtime/testsrc/org/aspectj/weaver/loadtime/ClassLoaderWeavingAdaptorTest.java
/******************************************************************************* * Copyright (c) 2006 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: * Matthew Webster - initial implementation *******************************************************************************/ package org.aspectj.weaver.loadtime; import java.io.File; import java.lang.reflect.Field; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.weaver.World; import org.aspectj.weaver.World.TypeMap; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.loadtime.definition.Definition; import org.aspectj.weaver.tools.WeavingAdaptor; public class ClassLoaderWeavingAdaptorTest extends TestCase { public void testClassLoaderWeavingAdaptor() { ClassLoader loader = new URLClassLoader(new URL[] {}, null); ClassLoaderWeavingAdaptor adaptor = new ClassLoaderWeavingAdaptor(); adaptor.initialize(loader, null); } public void testGetNamespace() { ClassLoader loader = new URLClassLoader(new URL[] {}, null); ClassLoaderWeavingAdaptor adaptor = new ClassLoaderWeavingAdaptor(); adaptor.initialize(loader, null); String namespace = adaptor.getNamespace(); assertEquals("Namespace should be empty", "", namespace); } public void testGeneratedClassesExistFor() { ClassLoader loader = new URLClassLoader(new URL[] {}, null); ClassLoaderWeavingAdaptor adaptor = new ClassLoaderWeavingAdaptor(); adaptor.initialize(loader, null); boolean exist = adaptor.generatedClassesExistFor("Junk"); assertFalse("There should be no generated classes", exist); } public void testFlushGeneratedClasses() { ClassLoader loader = new URLClassLoader(new URL[] {}, null); ClassLoaderWeavingAdaptor adaptor = new ClassLoaderWeavingAdaptor(); adaptor.initialize(loader, null); adaptor.flushGeneratedClasses(); boolean exist = adaptor.generatedClassesExistFor("Junk"); assertFalse("There should be no generated classes", exist); } /** * Testing fast excludes of the pattern "com.foo..*". World should not have any new types in it after rejection. */ public void testFastExclusionOne() throws Exception { TestClassLoaderWeavingAdaptor adaptor = getAdaptor(null, "testdata..*"); String orangesSub = "testdata.sub.Oranges"; JavaClass orangesClass = getClassFrom(orangesSub); byte[] orangesBytes = orangesClass.getBytes(); boolean accepted = adaptor.accept(orangesSub, orangesBytes); assertFalse("Should not be accepted", accepted); TypeMap map = accessTypeMap(adaptor); // The aspect assertEquals(1, map.getExpendableMap().size()); // primitives, void and jlObject assertEquals(10, map.getMainMap().size()); // Important thing here is that the rejection of testdata.sub.Oranges did not require it to be loaded into the world at all } /** * Testing fast includes of the pattern "*". World should not have any new types in it after inclusion. */ public void testFastInclusionOne() throws Exception { TestClassLoaderWeavingAdaptor adaptor = getAdaptor("*", null); String orangesSub = "testdata.sub.Oranges"; JavaClass orangesClass = getClassFrom(orangesSub); byte[] orangesBytes = orangesClass.getBytes(); boolean accepted = adaptor.accept(orangesSub, orangesBytes); assertTrue("Should be accepted", accepted); TypeMap map = accessTypeMap(adaptor); // The aspect assertEquals(1, map.getExpendableMap().size()); // primitives, void and jlObject assertEquals(10, map.getMainMap().size()); // Important thing here is that the rejection of testdata.sub.Oranges did not require it to be loaded into the world at all } /** * Testing fast excludes of the pattern "*Oranges". World should not have any new types in it after rejection. */ public void testFastExclusionTwo() throws Exception { TestClassLoaderWeavingAdaptor adaptor = getAdaptor(null, "*Oranges"); String oranges = "testdata.Oranges"; JavaClass orangesClass = getClassFrom(oranges); byte[] orangesBytes = orangesClass.getBytes(); boolean accepted = adaptor.accept(oranges, orangesBytes); assertFalse("Should not be accepted", accepted); TypeMap map = accessTypeMap(adaptor); // The aspect assertEquals(1, map.getExpendableMap().size()); // primitives, void and jlObject assertEquals(10, map.getMainMap().size()); String orangesSub = "testdata.sub.Oranges"; JavaClass orangesSubClass = getClassFrom(orangesSub); byte[] orangesSubBytes = orangesSubClass.getBytes(); accepted = adaptor.accept(orangesSub, orangesSubBytes); assertFalse("Should not be accepted", accepted); map = accessTypeMap(adaptor); // The aspect assertEquals(1, map.getExpendableMap().size()); // primitives, void and jlObject assertEquals(10, map.getMainMap().size()); } /** * Testing fast excludes of the pattern "*..*Oranges*". World should not have any new types in it after rejection. */ public void testFastExclusionThree() throws Exception { TestClassLoaderWeavingAdaptor adaptor = getAdaptor(null, "*..*ran*"); String oranges = "testdata.Oranges"; JavaClass orangesClass = getClassFrom(oranges); byte[] orangesBytes = orangesClass.getBytes(); boolean accepted = adaptor.accept(oranges, orangesBytes); assertFalse("Should not be accepted", accepted); TypeMap map = accessTypeMap(adaptor); // The aspect assertEquals(1, map.getExpendableMap().size()); // primitives, void and jlObject assertEquals(10, map.getMainMap().size()); String orangesSub = "testdata.sub.Oranges"; JavaClass orangesSubClass = getClassFrom(orangesSub); byte[] orangesSubBytes = orangesSubClass.getBytes(); accepted = adaptor.accept(orangesSub, orangesSubBytes); assertFalse("Should not be accepted", accepted); map = accessTypeMap(adaptor); // The aspect assertEquals(1, map.getExpendableMap().size()); // primitives, void and jlObject assertEquals(10, map.getMainMap().size()); String apples = "testdata.Apples"; JavaClass applesClass = getClassFrom(apples); byte[] applesBytes = applesClass.getBytes(); accepted = adaptor.accept(apples, applesBytes); assertTrue("Should be accepted", accepted); map = accessTypeMap(adaptor); // The aspect and the Apples type assertEquals(1, map.getExpendableMap().size()); // primitives, void and jlObject assertEquals(10, map.getMainMap().size()); } public void testIncludedWhenNonOptimalExclusion() throws Exception { TestClassLoaderWeavingAdaptor adaptor = getAdaptor(new String[] { "*", "FooBar" }, new String[] { "*..*ran*es*" }); String oranges = "testdata.Oranges"; JavaClass orangesClass = getClassFrom(oranges); byte[] orangesBytes = orangesClass.getBytes(); boolean accepted = false; // adaptor.accept(oranges, orangesBytes); // assertFalse("Should not be accepted", accepted); TypeMap map = accessTypeMap(adaptor); // // The aspect // assertEquals(1, map.getExpendableMap().size()); // primitives, void and jlObject assertEquals(10, map.getMainMap().size()); String apples = "testdata.Apples"; JavaClass applesClass = getClassFrom(apples); byte[] applesBytes = applesClass.getBytes(); accepted = adaptor.accept(apples, applesBytes); assertTrue("Should be accepted", accepted); map = accessTypeMap(adaptor); // // The aspect // assertEquals(1, map.getExpendableMap().size()); // // primitives, void and jlObject // assertEquals(10, map.getMainMap().size()); // // String apples = "testdata.Apples"; // JavaClass applesClass = getClassFrom(apples); // byte[] applesBytes = applesClass.getBytes(); // // accepted = adaptor.accept(apples, applesBytes); // assertTrue("Should be accepted", accepted); // map = accessTypeMap(adaptor); // // // The aspect and the Apples type // assertEquals(1, map.getExpendableMap().size()); // // primitives, void and jlObject // assertEquals(10, map.getMainMap().size()); } private void checkAccept(ClassLoaderWeavingAdaptor adaptor, String name) throws Exception { JavaClass clazz = getClassFrom(name); byte[] bytes = clazz.getBytes(); boolean accepted = adaptor.accept(name, bytes); assertTrue("Should be accepted", accepted); } private void checkNotAccept(ClassLoaderWeavingAdaptor adaptor, String name) throws Exception { JavaClass clazz = getClassFrom(name); byte[] bytes = clazz.getBytes(); boolean accepted = adaptor.accept(name, bytes); assertFalse("Should not be accepted", accepted); } /** * Test how multiple definitions are merged. Each Definition represents a different aop.xml file. */ public void testIncludedWhenNonOptimalExclusion2() throws Exception { Definition aopOne = new Definition(); aopOne.getIncludePatterns().add("*"); Definition aopTwo = new Definition(); aopTwo.getIncludePatterns().add("testdata.Apples+"); TestClassLoaderWeavingAdaptor adaptor = getAdaptor(aopOne, aopTwo); checkAccept(adaptor, "testdata.Oranges"); checkAccept(adaptor, "testdata.Apples"); adaptor = getAdaptor(aopTwo, aopOne); checkAccept(adaptor, "testdata.Oranges"); checkAccept(adaptor, "testdata.Apples"); } public void testIncludedWhenNonOptimalExclusion3() throws Exception { Definition aopOne = new Definition(); aopOne.getIncludePatterns().add("*"); Definition aopTwo = new Definition(); aopTwo.getIncludePatterns().add("java.sql.Connection+"); aopTwo.getIncludePatterns().add("java.sql.Statement+"); TestClassLoaderWeavingAdaptor adaptor = getAdaptor(aopOne, aopTwo); checkAccept(adaptor, "testdata.Apples"); checkAccept(adaptor, "testdata.MySqlStatement"); adaptor = getAdaptor(aopTwo, aopOne); checkAccept(adaptor, "testdata.Apples"); checkAccept(adaptor, "testdata.MySqlStatement"); } // Some excludes defined and some includes but importantly a star include public void testIncludedWhenNonOptimalExclusion4() throws Exception { Definition aopOne = new Definition(); aopOne.getIncludePatterns().add("*"); Definition aopTwo = new Definition(); aopTwo.getIncludePatterns().add("java.sql.Connection+"); aopTwo.getIncludePatterns().add("java.sql.Statement+"); Definition aopThree = new Definition(); aopThree.getExcludePatterns().add("com.jinspired..*"); aopThree.getExcludePatterns().add("$com.jinspired..*"); aopThree.getExcludePatterns().add("com.jinspired.jxinsight.server..*+"); TestClassLoaderWeavingAdaptor adaptor = getAdaptor(aopOne, aopTwo, aopThree); checkAccept(adaptor, "testdata.Apples"); checkAccept(adaptor, "testdata.MySqlStatement"); adaptor = getAdaptor(aopThree, aopTwo, aopOne); checkAccept(adaptor, "testdata.Apples"); checkAccept(adaptor, "testdata.MySqlStatement"); } // Some excludes defined and some includes but importantly an exact includename public void testIncludedWhenNonOptimalExclusion5() throws Exception { Definition aopOne = new Definition(); aopOne.getIncludePatterns().add("testdata.Apples"); Definition aopTwo = new Definition(); aopTwo.getIncludePatterns().add("java.sql.Connection+"); aopTwo.getIncludePatterns().add("java.sql.Statement+"); Definition aopThree = new Definition(); aopThree.getExcludePatterns().add("com.jinspired..*"); aopThree.getExcludePatterns().add("$com.jinspired..*"); aopThree.getExcludePatterns().add("com.jinspired.jxinsight.server..*+"); TestClassLoaderWeavingAdaptor adaptor = getAdaptor(aopOne, aopTwo, aopThree); checkAccept(adaptor, "testdata.Apples"); adaptor = getAdaptor(aopThree, aopTwo, aopOne); checkAccept(adaptor, "testdata.Apples"); } public void testIncludedWhenNonOptimalExclusion7() throws Exception { Definition aopOne = new Definition(); aopOne.getIncludePatterns().add("*"); aopOne.getExcludePatterns().add("*Fun*ky*"); // Definition aopTwo = new Definition(); // aopTwo.getIncludePatterns().add("java.sql.Connection+"); // aopTwo.getIncludePatterns().add("java.sql.Statement+"); // // Definition aopThree = new Definition(); // aopThree.getExcludePatterns().add("com.jinspired..*"); // aopThree.getExcludePatterns().add("$com.jinspired..*"); // aopThree.getExcludePatterns().add("com.jinspired.jxinsight.server..*+"); TestClassLoaderWeavingAdaptor adaptor = getAdaptor(aopOne); checkAccept(adaptor, "testdata.Apples"); // adaptor = getAdaptor(aopThree, aopTwo, aopOne); // // checkAccept(adaptor, "testdata.Apples"); } public void testIncludedWhenNonOptimalExclusion6() throws Exception { Definition aopOne = new Definition(); aopOne.getIncludePatterns().add("testdata..*"); Definition aopTwo = new Definition(); aopTwo.getIncludePatterns().add("java.sql.Connection+"); aopTwo.getIncludePatterns().add("java.sql.Statement+"); Definition aopThree = new Definition(); aopThree.getExcludePatterns().add("com.jinspired..*"); aopThree.getExcludePatterns().add("$com.jinspired..*"); aopThree.getExcludePatterns().add("com.jinspired.jxinsight.server..*+"); TestClassLoaderWeavingAdaptor adaptor = getAdaptor(aopOne, aopTwo, aopThree); checkAccept(adaptor, "testdata.Apples"); adaptor = getAdaptor(aopThree, aopTwo, aopOne); checkAccept(adaptor, "testdata.Apples"); } /** * Testing fast inclusion checking of exact include names eg. "testdata.sub.Oranges" */ public void testFastInclusionTwo() throws Exception { TestClassLoaderWeavingAdaptor adaptor = getAdaptor("testdata.sub.Oranges", null); String oranges = "testdata.Oranges"; JavaClass orangesClass = getClassFrom(oranges); byte[] orangesBytes = orangesClass.getBytes(); boolean accepted = adaptor.accept(oranges, orangesBytes); assertFalse("Should not be accepted", accepted); TypeMap map = accessTypeMap(adaptor); // The aspect assertEquals(1, map.getExpendableMap().size()); // primitives, void and jlObject assertEquals(10, map.getMainMap().size()); String orangesSub = "testdata.sub.Oranges"; JavaClass orangesSubClass = getClassFrom(orangesSub); byte[] orangesSubBytes = orangesSubClass.getBytes(); accepted = adaptor.accept(orangesSub, orangesSubBytes); assertTrue("Should be accepted", accepted); map = accessTypeMap(adaptor); // The aspect assertEquals(1, map.getExpendableMap().size()); // primitives, void and jlObject assertEquals(10, map.getMainMap().size()); String apples = "testdata.Apples"; JavaClass applesClass = getClassFrom(apples); byte[] applesBytes = applesClass.getBytes(); accepted = adaptor.accept(apples, applesBytes); assertFalse("Should not be accepted", accepted); map = accessTypeMap(adaptor); // The aspect and the Apples type assertEquals(1, map.getExpendableMap().size()); // primitives, void and jlObject assertEquals(10, map.getMainMap().size()); } /** * Testing fast excludes of the pattern groovy related pattern - */ // public void testFastExclusionFour() throws Exception { // TestClassLoaderWeavingAdaptor adaptor = getAdaptor("*", "testdata..* && !testdata.sub.Oran*"); // // String oranges = "testdata.Oranges"; // JavaClass orangesClass = getClassFrom(oranges); // byte[] orangesBytes = orangesClass.getBytes(); // // boolean accepted = adaptor.accept(oranges, orangesBytes); // assertFalse("Should not be accepted", accepted); // TypeMap map = accessTypeMap(adaptor); // // // The aspect // assertEquals(1, map.getExpendableMap().size()); // // // primitives, void and jlObject // assertEquals(10, map.getMainMap().size()); // // String orangesSub = "testdata.sub.Oranges"; // JavaClass orangesSubClass = getClassFrom(orangesSub); // byte[] orangesSubBytes = orangesSubClass.getBytes(); // // accepted = adaptor.accept(orangesSub, orangesSubBytes); // assertTrue("Should be accepted", accepted); // map = accessTypeMap(adaptor); // // // The aspect // assertEquals(1, map.getExpendableMap().size()); // // primitives, void and jlObject // assertEquals(10, map.getMainMap().size()); // } public void testAcceptanceSpeedStarDotDotStar() throws Exception { URLClassLoader loader = new URLClassLoader(new URL[] { new File("../loadtime/bin").toURI().toURL(), new File("../loadtime/testdata/anaspect.jar").toURI().toURL() }, null); JavaClass jc = getClassFrom("../loadtime/bin", "org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptorTest$TestOne"); byte[] bs = jc.getBytes(); jc = getClassFrom("../loadtime/bin", "org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptorTest$TestOneCGLIB"); byte[] bs2 = jc.getBytes(); // InputStream is = loader.getResourceAsStream("org.aspectj.weaver.loadtime.ClassLoaderWeaverAdaptorTests$TestOne"); assertNotNull(bs); TestWeavingContext wc = new TestWeavingContext(loader); Definition d = new Definition(); d.getExcludePatterns().add("*..*CGLIB*"); d.getAspectClassNames().add("AnAspect"); wc.addDefinition(d); ClassLoaderWeavingAdaptor adaptor = new ClassLoaderWeavingAdaptor(); adaptor.initialize(loader, wc); boolean exist = adaptor.generatedClassesExistFor("Junk"); assertFalse("There should be no generated classes", exist); // before: // Acceptance 331ms // Rejection 3368ms // after: // Acceptance 343ms // Rejection 80ms long stime = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { boolean b = adaptor.accept("org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptorTest$TestOne", bs); assertTrue("Should be accepted", b); } long etime = System.currentTimeMillis(); System.out.println("Acceptance " + (etime - stime) + "ms"); stime = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { adaptor.delegateForCurrentClass = null; boolean b = adaptor.accept("org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptorTest$TestOneCGLIB", bs2); assertFalse("Should not be accepting CGLIB", b); } etime = System.currentTimeMillis(); System.out.println("Rejection " + (etime - stime) + "ms"); } // TODO // shouldn't add it to the type patterns if we are going to fast handle it // include for exact name, what does it mean? // excludes="!xxxx" should also be fast matched... public void testAcceptanceSpeedExactName() throws Exception { URLClassLoader loader = new URLClassLoader(new URL[] { new File("../loadtime/bin").toURI().toURL(), new File("../loadtime/testdata/anaspect.jar").toURI().toURL() }, null); JavaClass jc = getClassFrom("../loadtime/bin", "org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptorTest$TestOne"); byte[] bs = jc.getBytes(); jc = getClassFrom("../loadtime/bin", "org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptorTest$TestOneCGLIB"); byte[] bs2 = jc.getBytes(); // InputStream is = loader.getResourceAsStream("org.aspectj.weaver.loadtime.ClassLoaderWeaverAdaptorTests$TestOne"); assertNotNull(bs); TestWeavingContext wc = new TestWeavingContext(loader); Definition d = new Definition(); d.getExcludePatterns().add("org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptorTest.TestOneCGLIB"); d.getAspectClassNames().add("AnAspect"); wc.addDefinition(d); TestClassLoaderWeavingAdaptor adaptor = new TestClassLoaderWeavingAdaptor(); adaptor.initialize(loader, wc); boolean exist = adaptor.generatedClassesExistFor("Junk"); assertFalse("There should be no generated classes", exist); // before: // Acceptance 331ms // Rejection 3160ms // after: // Acceptance 379ms // Rejection 103ms long stime = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { boolean b = adaptor.accept("org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptorTest$TestOne", bs); assertTrue("Should be accepted", b); } long etime = System.currentTimeMillis(); System.out.println("Acceptance " + (etime - stime) + "ms"); stime = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { adaptor.delegateForCurrentClass = null; boolean b = adaptor.accept("org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptorTest$TestOneCGLIB", bs2); assertFalse("Should not be accepting CGLIB", b); } etime = System.currentTimeMillis(); System.out.println("Rejection " + (etime - stime) + "ms"); BcelWorld world = adaptor.getWorld(); Field f = World.class.getDeclaredField("typeMap"); f.setAccessible(true); TypeMap typeMap = (TypeMap) f.get(world); System.out.println(typeMap.getExpendableMap().size()); System.out.println(typeMap.getMainMap().size()); printExpendableMap(typeMap.getExpendableMap()); printMainMap(typeMap.getMainMap()); } // --- infrastructure --- private TypeMap accessTypeMap(TestClassLoaderWeavingAdaptor adaptor) { return adaptor.getWorld().getTypeMap(); } public TestClassLoaderWeavingAdaptor getAdaptor(String includePattern, String excludePattern) { return getAdaptor(includePattern == null ? null : new String[] { includePattern }, excludePattern == null ? null : new String[] { excludePattern }); } public TestClassLoaderWeavingAdaptor getAdaptor(Definition... definitions) { try { URLClassLoader loader = new URLClassLoader(new URL[] { new File("../loadtime/bin").toURI().toURL(), new File("../loadtime/testdata/anaspect.jar").toURI().toURL() }, null); TestWeavingContext wc = new TestWeavingContext(loader); for (Definition definition : definitions) { // need some random aspect or the weaver will shut down! definition.getAspectClassNames().add("AnAspect"); wc.addDefinition(definition); } TestClassLoaderWeavingAdaptor adaptor = new TestClassLoaderWeavingAdaptor(); adaptor.initialize(loader, wc); return adaptor; } catch (Exception e) { throw new RuntimeException(e); } } public TestClassLoaderWeavingAdaptor getAdaptor(String[] includePatterns, String[] excludePatterns) { try { URLClassLoader loader = new URLClassLoader(new URL[] { new File("../loadtime/bin").toURI().toURL(), new File("../loadtime/testdata/anaspect.jar").toURI().toURL() }, null); TestWeavingContext wc = new TestWeavingContext(loader); Definition d = new Definition(); if (includePatterns != null) { for (String s : includePatterns) { d.getIncludePatterns().add(s); } } if (excludePatterns != null) { for (String s : excludePatterns) { d.getExcludePatterns().add(s); } } // need some random aspect or the weaver will shut down! d.getAspectClassNames().add("AnAspect"); wc.addDefinition(d); TestClassLoaderWeavingAdaptor adaptor = new TestClassLoaderWeavingAdaptor(); adaptor.initialize(loader, wc); return adaptor; } catch (Exception e) { throw new RuntimeException(e); } } private void printMaps(TypeMap map) { printExpendableMap(map.getExpendableMap()); printMainMap(map.getMainMap()); } private void printExpendableMap(Map m) { for (Object o : m.keySet()) { String sig = (String) o; System.out.println(sig + "=" + m.get(sig)); } } private void printMainMap(Map m) { for (Object o : m.keySet()) { String sig = (String) o; System.out.println(sig + "=" + m.get(sig)); } } static class TestClassLoaderWeavingAdaptor extends ClassLoaderWeavingAdaptor { public BcelWorld getWorld() { return bcelWorld; } } public static JavaClass getClassFrom(String clazzname) throws ClassNotFoundException { return getClassFrom("../loadtime/bin", clazzname); } public static JavaClass getClassFrom(String frompath, String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(frompath); return repos.loadClass(clazzname); } public static SyntheticRepository createRepos(String cpentry) { ClassPath cp = new ClassPath(cpentry + File.pathSeparator + System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } // // @Aspect // static class AnAspect { // // } class TestOne { } class TestOneCGLIB { } static class TestWeavingContext extends DefaultWeavingContext { List testList = new ArrayList(); public TestWeavingContext(ClassLoader loader) { super(loader); } public void addDefinition(Definition d) { testList.add(d); } @Override public List getDefinitions(final ClassLoader loader, final WeavingAdaptor adaptor) { return testList; } } } // --- testclasses and aspects ---
321,641
Bug 321641 No way to exclude Proxool classes although excluded from AOP. Causing Veryfy error.
Build Identifier: 20100218-1602 For aspectJ 1.6.7 the setup works, however exactly the same setup but changing the aspectJ version to 1.6.8 or 1.6.9 derive to the same error: a piece of code excluded from the aop.xml is woven causing a Verify Error. We are using Proxool, proxy setup which in fact uses CGLIB to create a EnhancerProxy class. In order to avoid VerifyError exceptions the Proxool classes are excluded from aop.xml exactly in the same way the CGLIB workarround is commented in the aspectJ FAQ: <exclude within="*..*Proxool*"/> This is the error we got when we upgrade our 1.6.7 aspejctweaver.jar to 1.6.8. The same is got when using 1.6.9: jvm 3 | 2010/08/03 16:42:53 | java.lang.VerifyError: (class: oracle/jdbc/internal/OracleConnection$$EnhancerByProxool$$7f6320a8, method: getTdoCState signature: (Ljava/lang/String;Ljava/lang/String;)J) Inconsistent stack height 1 != 0 jvm 3 | 2010/08/03 16:42:53 | at java.lang.Class.getDeclaredMethods0(Native Method) jvm 3 | 2010/08/03 16:42:53 | at java.lang.Class.privateGetDeclaredMethods(Class.java:2427) jvm 3 | 2010/08/03 16:42:53 | at java.lang.Class.getDeclaredMethod(Class.java:1935) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.getCallbacksSetter(Enhancer.java:627) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.setCallbacksHelper(Enhancer.java:615) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.setThreadCallbacks(Enhancer.java:609) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.createUsingReflection(Enhancer.java:631) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.firstInstance(Enhancer.java:538) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:225) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.createHelper(Enhancer.java:377) jvm 3 | 2010/08/03 16:42:53 | at org.logicalcobwebs.cglib.proxy.Enhancer.create(Enhancer.java:285) .... As far as the Verify Error is got while deploying one of the applications that run on the serve we are no able to use the new versions of aspectJ because the application is not properly started up. Thank you very much in advance, Best regards. Reproducible: Always Steps to Reproduce: 1.Exclude Proxool classes from aop.xml using aspectj 1.6.7. It works 2.Upgrade to 1.6.8: it does not work. 3.Upgrade to 1.6.9: it does not work.
resolved fixed
85fd25d
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-08-10T15:11:54Z"
"2010-08-03T18:26:40Z"
loadtime/testsrc/testdata/MessageService$$EnhancerByCGLIB$$6dd4e683.java
322,832
Bug 322832 early field resolution leading to problems for ITDs when declare parents in use
I have a type that is being used where a generic is being expected. That generic specifies an upper bound. The type only obeys the upper bound once a declare parents has applied to it. I have an intertype declaration (a field). When the ITD is applied we do some work to see if it clashes with existing fields. This causes existing fields to be resolved. If this resolution triggers a bounds check for the declare parents affected type before the declare parents has applied, a problem will be raised. Basically if the target of the declare is processed before the intertype then we are ok, but that is luck based. We should do the declare parents first (and declare annotation) and then do intertype declarations (since they may trigger this extra resolution).
resolved fixed
16adee6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-08-16T19:52:25Z"
"2010-08-16T20:20:00Z"
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.CommonPrinter; 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.ResolvedTypeMunger; 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<SourceTypeBinding> pendingTypesToWeave = new ArrayList<SourceTypeBinding>(); // 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<SourceTypeBinding> typesToProcess = new ArrayList<SourceTypeBinding>(); List<SourceTypeBinding> aspectsToProcess = new ArrayList<SourceTypeBinding>(); 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); TypeDeclaration typeDeclaration = stb.scope.referenceContext; if (typeDeclaration instanceof AspectDeclaration) { aspectsToProcess.add(stb); } } } factory.getWorld().getCrosscuttingMembersSet().reset(); // Need to do these before the other ITDs for (SourceTypeBinding aspectToProcess : aspectsToProcess) { processInterTypeMemberTypes(aspectToProcess.scope); } while (typesToProcess.size() > 0) { // removes types from the list as they are processed... collectAllITDsAndDeclares(typesToProcess.get(0), typesToProcess); } factory.finishTypeMungers(); // now do weaving List<ConcreteTypeMunger> typeMungers = factory.getTypeMungers(); List<DeclareParents> declareParents = factory.getDeclareParents(); List<DeclareAnnotation> 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, typesToProcess.get(0), typeMungers, declareParents, declareAnnotationOnTypes); } } else { // Order isn't important for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { 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<SourceTypeBinding> typesToProcess, SourceTypeBinding typeToWeave, List<ConcreteTypeMunger> typeMungers, List<DeclareParents> declareParents, List<DeclareAnnotation> 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; } /** * Applies any intertype member type declarations up front. */ private void processInterTypeMemberTypes(ClassScope classScope) { TypeDeclaration dec = classScope.referenceContext; if (dec instanceof AspectDeclaration) { ((AspectDeclaration) dec).processIntertypeMemberTypes(classScope); } // if we are going to support nested aspects making itd member types, copy the logic from the end of // buildInterTypeAndPerClause() which walks members } 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, List<ConcreteTypeMunger> typeMungers, List<DeclareParents> declareParents, List<DeclareAnnotation> 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); // inner type ITD support - may need this for some incremental cases... // List<ConcreteTypeMunger> ctms = factory.getWorld().getCrosscuttingMembersSet().getTypeMungersOfKind( // ResolvedTypeMunger.InnerClass); // // List<ConcreteTypeMunger> innerTypeMungers = new ArrayList<ConcreteTypeMunger>(); // // for (ConcreteTypeMunger ctm : ctms) { // // if (ctm.getMunger() != null && ctm.getMunger().getKind() == ResolvedTypeMunger.InnerClass) { // // innerTypeMungers.add(ctm); // // } // // } // // that includes the innertype one... // // doPendingWeaves at this level is about applying inner class // BinaryTypeBinding t = (BinaryTypeBinding) sourceType; // for (ConcreteTypeMunger ctm : innerTypeMungers) { // NewMemberClassTypeMunger nmctm = (NewMemberClassTypeMunger) ctm.getMunger(); // ReferenceBinding[] rbs = t.memberTypes; // UnresolvedType ut = factory.fromBinding(t); // if (ut.equals(nmctm.getTargetType())) { // // got a match here // SourceTypeBinding aspectTypeBinding = (SourceTypeBinding) factory.makeTypeBinding(ctm.getAspectType()); // // char[] mungerMemberTypeName = ("$" + nmctm.getMemberTypeName()).toCharArray(); // ReferenceBinding innerTypeBinding = null; // for (ReferenceBinding innerType : aspectTypeBinding.memberTypes) { // char[] compounded = CharOperation.concatWith(innerType.compoundName, '.'); // if (org.aspectj.org.eclipse.jdt.core.compiler.CharOperation.endsWith(compounded, mungerMemberTypeName)) { // innerTypeBinding = innerType; // break; // } // } // // may be unresolved if the aspect type binding was a BinaryTypeBinding // if (innerTypeBinding instanceof UnresolvedReferenceBinding) { // innerTypeBinding = BinaryTypeBinding // .resolveType(innerTypeBinding, factory.getLookupEnvironment(), true); // } // t.memberTypes(); // cause initialization // t.memberTypes = new ReferenceBinding[] { innerTypeBinding }; // // int stop = 1; // // The inner type from the aspect should be put into the membertypebindings for this // // } // } } } else { weaveInterTypeDeclarations(sourceType, factory.getTypeMungers(), factory.getDeclareParents(), factory.getDeclareAnnotationOnTypes(), true); } } private void weaveInterTypeDeclarations(SourceTypeBinding sourceType, List<ConcreteTypeMunger> typeMungers, List<DeclareParents> declareParents, List<DeclareAnnotation> 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(); onType.ensureConsistent(); // 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<DeclareAnnotation> decaToRepeat = new ArrayList<DeclareAnnotation>(); 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) { if (factory.pushinCollector != null) { factory.pushinCollector.tagAsMunged(sourceType, decp.getParents().get(0)); } anyNewParents = true; } else { if (!decp.getChild().isStarAnnotation()) { decpToRepeat.add(decp); } } } } for (Iterator<DeclareAnnotation> i = declareAnnotationOnTypes.iterator(); i.hasNext();) { DeclareAnnotation deca = 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) { if (factory.pushinCollector != null) { factory.pushinCollector.tagAsMunged(sourceType, decp.getParents().get(0)); } 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) { if (factory.pushinCollector != null) { factory.pushinCollector.tagAsMunged(sourceType, deca.getAnnotationString()); } anyNewAnnotations = true; forRemoval.add(deca); } } decaToRepeat.removeAll(forRemoval); } for (Iterator<ConcreteTypeMunger> 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); if (munger.getMunger() != null && munger.getMunger().getKind() == ResolvedTypeMunger.InnerClass) { // Must do these right now, because if we do an ITD member afterwards it may attempt to reference the // type being applied (the call above 'addInterTypeMunger' will fail for these ITDs if it needed // it to be in place) if (munger.munge(sourceType, onType)) { if (factory.pushinCollector != null) { factory.pushinCollector.tagAsMunged(sourceType, munger.getSourceMethod()); } } } } } onType.checkInterTypeMungers(); for (Iterator i = onType.getInterTypeMungers().iterator(); i.hasNext();) { EclipseTypeMunger munger = (EclipseTypeMunger) i.next(); if (munger.getMunger() == null || munger.getMunger().getKind() != ResolvedTypeMunger.InnerClass) { if (munger.munge(sourceType, onType)) { if (factory.pushinCollector != null) { factory.pushinCollector.tagAsMunged(sourceType, munger.getSourceMethod()); } } } } // 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; AbstractMethodDeclaration methodDecl = null; // Might have to retrieve the annotation through BCEL and construct an // eclipse one for it. if (stb instanceof BinaryTypeBinding) { toAdd = retrieveAnnotationFromBinaryTypeBinding(decA, stb); if (toAdd != null && toAdd.length > 0 && 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) { char[] declareSelector = decA.getAnnotationMethod().toCharArray(); ReferenceBinding rb = stb; String declaringAspectName = decA.getDeclaringType().getRawName(); while (rb != null && !new String(CharOperation.concatWith(rb.compoundName, '.')).equals(declaringAspectName)) { rb = rb.superclass(); } MethodBinding[] mbs = rb.getMethods(declareSelector); ReferenceBinding declaringBinding = mbs[0].declaringClass; if (declaringBinding instanceof ParameterizedTypeBinding) { // Unwrap - this means we don't allow the type of the annotation to be parameterized, may need to revisit that declaringBinding = ((ParameterizedTypeBinding) declaringBinding).type; } if (declaringBinding instanceof BinaryTypeBinding) { toAdd = retrieveAnnotationFromBinaryTypeBinding(decA, declaringBinding); if (toAdd != null && toAdd.length > 0 && toAdd[0].resolvedType != null) { abits = toAdd[0].resolvedType.getAnnotationTagBits(); } } else { abits = mbs[0].getAnnotationTagBits(); // ensure resolved TypeDeclaration typeDecl = ((SourceTypeBinding) declaringBinding).scope.referenceContext; 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); if (factory.pushinCollector != null) { factory.pushinCollector.tagAsMunged(sourceType, new CommonPrinter((methodDecl == null ? null : methodDecl.scope)) .printAnnotation(toAdd[0]).toString()); } return true; } private Annotation[] retrieveAnnotationFromBinaryTypeBinding(DeclareAnnotation decA, ReferenceBinding declaringBinding) { ReferenceType rt = (ReferenceType) factory.fromEclipse(declaringBinding); 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 Annotation[] 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(); // } return toAdd; } } return null; } /** * 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"); // } // // } // }
322,039
Bug 322039 Fully qualified ITD has incorrect handle identifier
In the following aspect: public aspect Aspect { public void q2.ThisClass.something2() {} } In aspectJ, the ITD has the following handle identifier (notice that the ITD name is not fully qualified): =AspectJ Project/src2<p*Aspect.aj'Aspect)ThisClass.something2 However, it should be (with fully qualified name): =AspectJ Project/src2<p*Aspect.aj'Aspect)q2.ThisClass.something2 This means that fully qualified ITDs cannot be navigated to or searched. I'm a little surprised that this doesn't work because I thought I had tests for it...
resolved fixed
6b35ea4
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-08-18T17:29:04Z"
"2010-08-07T00:13:20Z"
tests/multiIncremental/pr322039/base/src/p/Azpect.java
322,039
Bug 322039 Fully qualified ITD has incorrect handle identifier
In the following aspect: public aspect Aspect { public void q2.ThisClass.something2() {} } In aspectJ, the ITD has the following handle identifier (notice that the ITD name is not fully qualified): =AspectJ Project/src2<p*Aspect.aj'Aspect)ThisClass.something2 However, it should be (with fully qualified name): =AspectJ Project/src2<p*Aspect.aj'Aspect)q2.ThisClass.something2 This means that fully qualified ITDs cannot be navigated to or searched. I'm a little surprised that this doesn't work because I thought I had tests for it...
resolved fixed
6b35ea4
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-08-18T17:29:04Z"
"2010-08-07T00:13:20Z"
tests/multiIncremental/pr322039/base/src/q2/Code.java
322,039
Bug 322039 Fully qualified ITD has incorrect handle identifier
In the following aspect: public aspect Aspect { public void q2.ThisClass.something2() {} } In aspectJ, the ITD has the following handle identifier (notice that the ITD name is not fully qualified): =AspectJ Project/src2<p*Aspect.aj'Aspect)ThisClass.something2 However, it should be (with fully qualified name): =AspectJ Project/src2<p*Aspect.aj'Aspect)q2.ThisClass.something2 This means that fully qualified ITDs cannot be navigated to or searched. I'm a little surprised that this doesn't work because I thought I had tests for it...
resolved fixed
6b35ea4
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-08-18T17:29:04Z"
"2010-08-07T00:13:20Z"
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.Collections; import java.util.Comparator; 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.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.aspectj.ajde.core.ICompilerConfiguration; import org.aspectj.ajde.core.TestOutputLocationManager; import org.aspectj.ajde.core.internal.AjdeCoreBuildManager; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.core.builder.AjBuildManager; 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.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.asm.internal.Relationship; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.Message; import org.aspectj.tools.ajc.Ajc; import org.aspectj.util.FileUtil; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.World; /** * 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 { public void testIncrementalITDInners3() throws Exception { AjdeInteractionTestbed.VERBOSE = true; String p = "prInner3"; initialiseProject(p); build(p); checkWasFullBuild(); // touch the aspect making the ITD member type alter(p, "inc1"); build(p); checkWasntFullBuild(); // touch the aspect making the ITD that depends on the member type alter(p, "inc2"); build(p); checkWasntFullBuild(); // touch the type affected by the ITDs alter(p, "inc3"); build(p); checkWasntFullBuild(); } // mixing ITDs with inner type intertypes public void testIncrementalITDInners2() throws Exception { String p = "prInner2"; initialiseProject(p); build(p); checkWasFullBuild(); // touch the aspect making the ITD member type alter(p, "inc1"); build(p); checkWasntFullBuild(); // touch the aspect making the ITD that depends on the member type alter(p, "inc2"); build(p); checkWasntFullBuild(); // touch the type affected by the ITDs alter(p, "inc3"); build(p); checkWasntFullBuild(); } public void testIncrementalITDInners() throws Exception { String p = "prInner"; initialiseProject(p); build(p); checkWasFullBuild(); alter(p, "inc1"); build(p); checkWasntFullBuild(); } /* * public void testIncrementalAspectWhitespace() throws Exception { AjdeInteractionTestbed.VERBOSE = true; String p = "xxx"; * initialiseProject(p); configureNonStandardCompileOptions(p, "-showWeaveInfo"); configureShowWeaveInfoMessages(p, true); * build(p); * * List weaveMessages = getWeavingMessages(p); if (weaveMessages.size() != 0) { for (Iterator iterator = * weaveMessages.iterator(); iterator.hasNext();) { Object object = iterator.next(); System.out.println(object); } } * checkWasFullBuild(); assertNoErrors(p); alter(p, "inc1"); build(p); checkWasntFullBuild(); assertNoErrors(p); } */ public void testIncrementalGenericItds_pr280676() throws Exception { String p = "pr280676"; initialiseProject(p); build(p); checkWasFullBuild(); assertNoErrors(p); alter(p, "inc1"); // remove type variables from ITD field build(p); checkWasFullBuild(); assertNoErrors(p); alter(p, "inc2"); // remove type variables from ITD method build(p); checkWasFullBuild(); assertNoErrors(p); alter(p, "inc3"); // readded type variables on ITD method build(p); checkWasFullBuild(); assertNoErrors(p); } public void testIncrementalGenericItds_pr280676_2() throws Exception { String p = "pr280676_2"; initialiseProject(p); build(p); checkWasFullBuild(); assertNoErrors(p); alter(p, "inc1"); // remove type variables from target type build(p); List errors = getErrorMessages(p); // Build errors: // error at N:\temp\ajcSandbox\aspectj16_3\ajcTest60379.tmp\pr280676_2\src\p\A.java:8:0::0 a.ls cannot be resolved or is not // a field // error at N:\temp\ajcSandbox\aspectj16_3\ajcTest60379.tmp\pr280676_2\src\p\Foo.aj:8:0::0 Type parameters can not be // specified in the ITD target type - the target type p.A is not generic. // error at N:\temp\ajcSandbox\aspectj16_3\ajcTest60379.tmp\pr280676_2\src\p\Foo.aj:12:0::0 Type parameters can not be // specified in the ITD target type - the target type p.A is not generic. // error at N:\temp\ajcSandbox\aspectj16_3\ajcTest60379.tmp\pr280676_2\src\p\Foo.aj:8:0::0 Type parameters can not be // specified in the ITD target type - the target type p.A is not generic. // error at N:\temp\ajcSandbox\aspectj16_3\ajcTest60379.tmp\pr280676_2\src\p\Foo.aj:12:0::0 Type parameters can not be // specified in the ITD target type - the target type p.A is not generic. assertEquals(5, errors.size()); } public void testAdviceHandles_pr284771() throws Exception { String p = "pr284771"; initialiseProject(p); build(p); printModel(p); IRelationshipMap irm = getModelFor(p).getRelationshipMap(); List<IRelationship> rels = irm.get("=pr284771<test*AspectTrace.aj'AspectTrace&before"); assertNotNull(rels); assertEquals(2, ((Relationship) rels.get(0)).getTargets().size()); rels = irm.get("=pr284771<test*AspectTrace.aj'AspectTrace&before!2"); assertNotNull(rels); assertEquals(2, ((Relationship) rels.get(0)).getTargets().size()); } /** * Test that the declare parents in the super aspect gets a relationship from the type declaring it. */ public void testAspectInheritance_322446() throws Exception { String p ="pr322446"; initialiseProject(p); build(p); IRelationshipMap irm = getModelFor(p).getRelationshipMap(); // Hid:1:(targets=1) =pr322446<{Class.java[Class (aspect declarations) =pr322446<{AbstractAspect.java'AbstractAspect`declare parents // Hid:2:(targets=1) =pr322446<{AbstractAspect.java'AbstractAspect`declare parents (declared on) =pr322446<{Class.java[Class List<IRelationship> rels = irm.get("=pr322446<{AbstractAspect.java'AbstractAspect`declare parents"); assertNotNull(rels); } public void testAspectInheritance_322446_2() throws Exception { String p ="pr322446_2"; initialiseProject(p); build(p); IProgramElement thisAspectNode = getModelFor(p).getHierarchy().findElementForType("","Sub"); assertEquals("{Code=[I]}",thisAspectNode.getDeclareParentsMap().toString()); } // found whilst looking at 322446 hence that is the testdata name public void testAspectInheritance_322664() throws Exception { AjdeInteractionTestbed.VERBOSE=true; String p ="pr322446_3"; initialiseProject(p); build(p); assertNoErrors(p); alter(p,"inc1"); build(p); // should be some errors: // error at N:\temp\ajcSandbox\aspectj16_1\ajcTest3209787521625191676.tmp\pr322446_3\src\AbstractAspect.java:5:0::0 can't bind type name 'T' // error at N:\temp\ajcSandbox\aspectj16_1\ajcTest3209787521625191676.tmp\pr322446_3\src\AbstractAspect.java:8:0::0 Incorrect number of arguments for type AbstractAspect<S>; it cannot be parameterized with arguments <X, Y> List<IMessage> errors = getErrorMessages(p); assertTrue(errors!=null && errors.size()>0); alter(p,"inc2"); build(p); // that build would contain an exception if the bug were around assertNoErrors(p); } // TODO (asc) these tests don't actually verify anything! // public void testAtDeclareParents_280658() throws Exception { // AjdeInteractionTestbed.VERBOSE = true; // String lib = "pr280658_decp"; // initialiseProject(lib); // build(lib); // checkWasFullBuild(); // // String cli = "pr280658_target"; // initialiseProject(cli); // // configureAspectPath(cli, getProjectRelativePath(lib, "bin")); // build(cli); // checkWasFullBuild(); // printModel(cli); // } // // public void testAtDeclareMixin_280651() throws Exception { // AjdeInteractionTestbed.VERBOSE = true; // String lib = "pr280651_decmix"; // initialiseProject(lib); // build(lib); // checkWasFullBuild(); // // String cli = "pr280658_target"; // initialiseProject(cli); // // configureAspectPath(cli, getProjectRelativePath(lib, "bin")); // build(cli); // checkWasFullBuild(); // printModel(cli); // } // Testing that declare annotation model entries preserve the fully qualified type of the annotation public void testDecAnnoState_pr286539() throws Exception { String p = "pr286539"; initialiseProject(p); build(p); printModel(p); IProgramElement decpPE = getModelFor(p).getHierarchy().findElementForHandle( "=pr286539<p.q.r{Aspect.java'Asp`declare parents"); assertNotNull(decpPE); String s = ((decpPE.getParentTypes()).get(0)); assertEquals("p.q.r.Int", s); decpPE = getModelFor(p).getHierarchy().findElementForHandle("=pr286539<p.q.r{Aspect.java'Asp`declare parents!2"); assertNotNull(decpPE); s = ((decpPE.getParentTypes()).get(0)); assertEquals("p.q.r.Int", s); IProgramElement decaPE = getModelFor(p).getHierarchy().findElementForHandle( "=pr286539<p.q.r{Aspect.java'Asp`declare \\@type"); assertNotNull(decaPE); assertEquals("p.q.r.Foo", decaPE.getAnnotationType()); decaPE = getModelFor(p).getHierarchy().findElementForHandle("=pr286539<p.q.r{Aspect.java'Asp`declare \\@type!2"); assertNotNull(decaPE); assertEquals("p.q.r.Goo", decaPE.getAnnotationType()); decaPE = getModelFor(p).getHierarchy().findElementForHandle("=pr286539<p.q.r{Aspect.java'Asp`declare \\@field"); assertNotNull(decaPE); assertEquals("p.q.r.Foo", decaPE.getAnnotationType()); decaPE = getModelFor(p).getHierarchy().findElementForHandle("=pr286539<p.q.r{Aspect.java'Asp`declare \\@method"); assertNotNull(decaPE); assertEquals("p.q.r.Foo", decaPE.getAnnotationType()); decaPE = getModelFor(p).getHierarchy().findElementForHandle("=pr286539<p.q.r{Aspect.java'Asp`declare \\@constructor"); assertNotNull(decaPE); assertEquals("p.q.r.Foo", decaPE.getAnnotationType()); } public void testQualifiedInnerTypeRefs_269082() throws Exception { String p = "pr269082"; initialiseProject(p); build(p); printModel(p); IProgramElement root = getModelFor(p).getHierarchy().getRoot(); IProgramElement ipe = findElementAtLine(root, 7); assertEquals("=pr269082<a{ClassUsingInner.java[ClassUsingInner~foo~QMyInner;~QObject;~QString;", ipe.getHandleIdentifier()); ipe = findElementAtLine(root, 9); assertEquals("=pr269082<a{ClassUsingInner.java[ClassUsingInner~goo~QClassUsingInner.MyInner;~QObject;~QString;", ipe .getHandleIdentifier()); ipe = findElementAtLine(root, 11); assertEquals("=pr269082<a{ClassUsingInner.java[ClassUsingInner~hoo~Qa.ClassUsingInner.MyInner;~QObject;~QString;", ipe .getHandleIdentifier()); } // just simple incremental build - no code change, just the aspect touched public void testIncrementalFqItds_280380() throws Exception { String p = "pr280380"; initialiseProject(p); build(p); // printModel(p); alter(p, "inc1"); build(p); // should not be an error about f.AClass not being found assertNoErrors(p); // printModel(p); } public void testIncrementalAdvisingItdJoinpointsAccessingPrivFields_307120() throws Exception { String p = "pr307120"; initialiseProject(p); build(p); // Hid:1:(targets=1) =pr307120<{Test.java}Test)A.getFoo?field-get(int A.foo) (advised by) =pr307120<{Test.java}Test&before // Hid:2:(targets=1) =pr307120<{A.java[A (aspect declarations) =pr307120<{Test.java}Test)A.getFoo // Hid:3:(targets=1) =pr307120<{Test.java}Test&before (advises) =pr307120<{Test.java}Test)A.getFoo?field-get(int A.foo) // Hid:4:(targets=1) =pr307120<{Test.java}Test)A.getFoo (declared on) =pr307120<{A.java[A alter(p, "inc1"); assertEquals(4, getRelationshipCount(p)); build(p); // Hid:1:(targets=1) =pr307120<{A.java[A (aspect declarations) =pr307120<{Test.java}Test)A.getFoo // Hid:2:(targets=1) =pr307120<{Test.java}Test)A.getFoo (declared on) =pr307120<{A.java[A // These two are missing without the fix: // Hid:1:(targets=1) =pr307120<{Test.java}Test)A.getFoo?field-get(int A.foo) (advised by) =pr307120<{Test.java}Test&before // Hid:7:(targets=1) =pr307120<{Test.java}Test&before (advises) =pr307120<{Test.java}Test)A.getFoo?field-get(int A.foo) assertNoErrors(p); assertEquals(4, getRelationshipCount(p)); } public void testIncrementalAdvisingItdJoinpointsAccessingPrivFields_307120_pipelineOff() throws Exception { String p = "pr307120"; initialiseProject(p); configureNonStandardCompileOptions(p, "-Xset:pipelineCompilation=false"); build(p); // Hid:1:(targets=1) =pr307120<{Test.java}Test)A.getFoo?field-get(int A.foo) (advised by) =pr307120<{Test.java}Test&before // Hid:2:(targets=1) =pr307120<{A.java[A (aspect declarations) =pr307120<{Test.java}Test)A.getFoo // Hid:3:(targets=1) =pr307120<{Test.java}Test&before (advises) =pr307120<{Test.java}Test)A.getFoo?field-get(int A.foo) // Hid:4:(targets=1) =pr307120<{Test.java}Test)A.getFoo (declared on) =pr307120<{A.java[A alter(p, "inc1"); assertEquals(4, getRelationshipCount(p)); build(p); // Hid:1:(targets=1) =pr307120<{A.java[A (aspect declarations) =pr307120<{Test.java}Test)A.getFoo // Hid:2:(targets=1) =pr307120<{Test.java}Test)A.getFoo (declared on) =pr307120<{A.java[A // These two are missing without the fix: // Hid:1:(targets=1) =pr307120<{Test.java}Test)A.getFoo?field-get(int A.foo) (advised by) =pr307120<{Test.java}Test&before // Hid:7:(targets=1) =pr307120<{Test.java}Test&before (advises) =pr307120<{Test.java}Test)A.getFoo?field-get(int A.foo) assertNoErrors(p); assertEquals(4, getRelationshipCount(p)); } // More sophisticated variant of above. public void testIncrementalAdvisingItdJoinpointsAccessingPrivFields_307120_2_pipelineOff() throws Exception { String p = "pr307120_3"; initialiseProject(p); configureNonStandardCompileOptions(p, "-Xset:pipelineCompilation=false"); build(p); assertNoErrors(p); // Hid:1:(targets=1) =pr307120_3<{TargetAugmenter.java}TargetAugmenter)Target.setIt)QString; (declared on) // =pr307120_3<{Target.java[Target // Hid:2:(targets=1) =pr307120_3<{Target.java[Target (aspect declarations) // =pr307120_3<{TargetAugmenter.java}TargetAugmenter)Target.setIt)QString; // these are missing under this bug: // Hid:3:(targets=1) =pr307120_3<{Advisor.java}Advisor&around&QObject;&QObject; (advises) // =pr307120_3<{TargetAugmenter.java}TargetAugmenter)Target.setIt)QString;?field-set(java.lang.String Target.it) // Hid:4:(targets=1) =pr307120_3<{TargetAugmenter.java}TargetAugmenter)Target.setIt)QString;?field-set(java.lang.String // Target.it) (advised by) =pr307120_3<{Advisor.java}Advisor&around&QObject;&QObject; assertEquals(4, getRelationshipCount(p)); alter(p, "inc1"); build(p); assertEquals(4, getRelationshipCount(p)); assertNoErrors(p); } // More sophisticated variant of above. public void testIncrementalAdvisingItdJoinpointsAccessingPrivFields_307120_2() throws Exception { String p = "pr307120_2"; initialiseProject(p); build(p); assertNoErrors(p); // Hid:2:(targets=1) =pr307120_2<{TargetAugmenter.java}TargetAugmenter)Target.setIt)QString; (declared on) // =pr307120_2<{Target.java[Target // Hid:8:(targets=1) =pr307120_2<{TargetAugmenter.java}TargetAugmenter)Target.getIt (declared on) // =pr307120_2<{Target.java[Target // Hid:5:(targets=2) =pr307120_2<{Target.java[Target (aspect declarations) // =pr307120_2<{TargetAugmenter.java}TargetAugmenter)Target.getIt // Hid:6:(targets=2) =pr307120_2<{Target.java[Target (aspect declarations) // =pr307120_2<{TargetAugmenter.java}TargetAugmenter)Target.setIt)QString; // Hid:1:(targets=1) =pr307120_2<{TargetAugmenter.java}TargetAugmenter)Target.setIt)QString;?field-set(java.lang.String // Target.it) (advised by) =pr307120_2<{Advisor.java}Advisor&around&QObject;&QObject; // Hid:3:(targets=1) =pr307120_2<{TargetAugmenter.java}TargetAugmenter)Target.getIt?field-get(java.lang.String Target.it) // (advised by) =pr307120_2<{Advisor.java}Advisor&around&QObject; // Hid:4:(targets=1) =pr307120_2<{Advisor.java}Advisor&around&QObject; (advises) // =pr307120_2<{TargetAugmenter.java}TargetAugmenter)Target.getIt?field-get(java.lang.String Target.it) // Hid:7:(targets=1) =pr307120_2<{Advisor.java}Advisor&around&QObject;&QObject; (advises) // =pr307120_2<{TargetAugmenter.java}TargetAugmenter)Target.setIt)QString;?field-set(java.lang.String Target.it) assertEquals(8, getRelationshipCount(p)); alter(p, "inc1"); build(p); assertEquals(8, getRelationshipCount(p)); assertNoErrors(p); } // // More sophisticated variant of above. // public void testIncrementalAdvisingItdJoinpointsAccessingPrivFields_307120_4_pipelineOff() throws Exception { // String p = "pr307120_4"; // initialiseProject(p); // configureNonStandardCompileOptions(p, "-Xset:pipelineCompilation=false"); // build(p); // assertNoErrors(p); // // printModel(p); // assertEquals(4, getRelationshipCount(p)); // alter(p, "inc1"); // build(p); // // assertEquals(4, getRelationshipCount(p)); // assertNoErrors(p); // } // modified aspect so target is fully qualified on the incremental change public void testIncrementalFqItds_280380_2() throws Exception { String p = "pr280380"; initialiseProject(p); build(p); // printModel(p); assertEquals(4, getModelFor(p).getRelationshipMap().getEntries().size()); // Hid:1:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.xxxx // Hid:2:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.y // Hid:3:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.AClass_new // Hid:4:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.y (declared on) =pr280380<f{AClass.java[AClass // Hid:5:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.AClass_new (declared on) =pr280380<f{AClass.java[AClass // Hid:6:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.xxxx (declared on) =pr280380<f{AClass.java[AClass alter(p, "inc2"); build(p); // should not be an error about f.AClass not being found assertNoErrors(p); // printModel(p); assertEquals(4, getModelFor(p).getRelationshipMap().getEntries().size()); // Hid:1:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.xxxx // Hid:2:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.y // Hid:3:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.AClass_new // Hid:4:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.y (declared on) =pr280380<f{AClass.java[AClass // Hid:5:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.AClass_new (declared on) =pr280380<f{AClass.java[AClass // Hid:6:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.xxxx (declared on) =pr280380<f{AClass.java[AClass } public void testIncrementalFqItds_280380_3() throws Exception { String p = "pr280380"; initialiseProject(p); build(p); // printModel(p); assertEquals(4, getModelFor(p).getRelationshipMap().getEntries().size()); // Hid:1:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.xxxx // Hid:2:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.y // Hid:3:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.AClass_new // Hid:4:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.y (declared on) =pr280380<f{AClass.java[AClass // Hid:5:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.AClass_new (declared on) =pr280380<f{AClass.java[AClass // Hid:6:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.xxxx (declared on) =pr280380<f{AClass.java[AClass printModel(p); assertNotNull(getModelFor(p).getRelationshipMap().get("=pr280380<g*AnAspect.aj'AnAspect,AClass.xxxx")); alter(p, "inc2"); build(p); assertNoErrors(p); printModel(p); // On this build the relationship should have changed to include the fully qualified target assertEquals(4, getModelFor(p).getRelationshipMap().getEntries().size()); assertNotNull(getModelFor(p).getRelationshipMap().get("=pr280380<g*AnAspect.aj'AnAspect,AClass.xxxx")); // Hid:1:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.xxxx // Hid:2:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.y // Hid:3:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.AClass_new // Hid:4:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.y (declared on) =pr280380<f{AClass.java[AClass // Hid:5:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.AClass_new (declared on) =pr280380<f{AClass.java[AClass // Hid:6:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.xxxx (declared on) =pr280380<f{AClass.java[AClass } public void testIncrementalCtorItdHandle_280383() throws Exception { String p = "pr280383"; initialiseProject(p); build(p); printModel(p); IRelationshipMap irm = getModelFor(p).getRelationshipMap(); List rels = irm.get("=pr280383<f{AnAspect.java'AnAspect)f.AClass.f_AClass_new"); assertNotNull(rels); } // public void testArraysGenerics() throws Exception { // String p = "pr283864"; // initialiseProject(p); // build(p); // printModel(p); // // IRelationshipMap irm = getModelFor(p).getRelationshipMap(); // // List rels = irm.get("=pr280383<f{AnAspect.java}AnAspect)f.AClass.f_AClass_new"); // // assertNotNull(rels); // } public void testSimilarITDS() throws Exception { String p = "pr283657"; initialiseProject(p); build(p); printModel(p); // Hid:1:(targets=1) =pr283657<{Aspect.java}Aspect)Target.foo (declared on) =pr283657<{Aspect.java[Target // Hid:2:(targets=1) =pr283657<{Aspect.java}Aspect)Target.foo!2 (declared on) =pr283657<{Aspect.java[Target // Hid:3:(targets=2) =pr283657<{Aspect.java[Target (aspect declarations) =pr283657<{Aspect.java}Aspect)Target.foo // Hid:4:(targets=2) =pr283657<{Aspect.java[Target (aspect declarations) =pr283657<{Aspect.java}Aspect)Target.foo!2 IRelationshipMap irm = getModelFor(p).getRelationshipMap(); List<IRelationship> rels = irm.get("=pr283657<{Aspect.java'Aspect,Target.foo"); assertNotNull(rels); rels = irm.get("=pr283657<{Aspect.java'Aspect)Target.foo!2"); assertNotNull(rels); } public void testIncrementalAnnotationMatched_276399() throws Exception { String p = "pr276399"; initialiseProject(p); addSourceFolderForSourceFile(p, getProjectRelativePath(p, "src/X.aj"), "src"); addSourceFolderForSourceFile(p, getProjectRelativePath(p, "src/C.java"), "src"); build(p); IRelationshipMap irm = getModelFor(p).getRelationshipMap(); IRelationship ir = irm.get("=pr276399/src<*X.aj'X&after").get(0); assertNotNull(ir); alter(p, "inc1"); build(p); printModel(p); irm = getModelFor(p).getRelationshipMap(); List<IRelationship> rels = irm.get("=pr276399/src<*X.aj'X&after"); // should be gone after the inc build assertNull(rels); } public void testHandleCountDecA_pr278255() throws Exception { String p = "pr278255"; initialiseProject(p); build(p); printModelAndRelationships(p); IRelationshipMap irm = getModelFor(p).getRelationshipMap(); List<IRelationship> l = irm.get("=pr278255<{A.java'X`declare \\@type"); assertNotNull(l); IRelationship ir = l.get(0); assertNotNull(ir); } public void testIncrementalItdDefaultCtor() { String p = "pr275032"; initialiseProject(p); build(p); assertEquals(0, getErrorMessages(p).size()); alter(p, "inc1"); build(p); // error is: inter-type declaration from X conflicts with existing member: void A.<init>() // List ms = getErrorMessages(p); assertEquals(4, getErrorMessages(p).size()); // Why 4 errors? I believe the problem is: // 2 errors are reported when there is a clash - one against the aspect, one against the affected target type. // each of the two errors are recorded against the compilation result for the aspect and the target // So it comes out as 4 - but for now I am tempted to leave it because at least it shows there is a problem... assertTrue("Was:" + getErrorMessages(p).get(0), getErrorMessages(p).get(0).toString().indexOf("conflicts") != -1); } public void testOutputLocationCallbacks2() { String p = "pr268827_ol_res"; initialiseProject(p); Map m = new HashMap(); m.put("a.txt", new File(getFile(p, "src/a.txt"))); configureResourceMap(p, m); CustomOLM olm = new CustomOLM(getProjectRelativePath(p, ".").toString()); configureOutputLocationManager(p, olm); build(p); checkCompileWeaveCount(p, 2, 2); assertEquals(3, olm.writeCount); alter(p, "inc1"); // this contains a new B.java that doesn't have the aspect inside it build(p); checkCompileWeaveCount(p, 3, 1); assertEquals(1, olm.removeCount); // B.class removed } public void testOutputLocationCallbacks() { String p = "pr268827_ol"; initialiseProject(p); CustomOLM olm = new CustomOLM(getProjectRelativePath(p, ".").toString()); configureOutputLocationManager(p, olm); build(p); checkCompileWeaveCount(p, 2, 3); alter(p, "inc1"); // this contains a new Foo.java that no longer has Extra class in it build(p); checkCompileWeaveCount(p, 1, 1); assertEquals(1, olm.removeCount); } public void testOutputLocationCallbacksFileAdd() { String p = "pr268827_ol2"; initialiseProject(p); CustomOLM olm = new CustomOLM(getProjectRelativePath(p, ".").toString()); configureOutputLocationManager(p, olm); build(p); assertEquals(3, olm.writeCount); olm.writeCount = 0; checkCompileWeaveCount(p, 2, 3); alter(p, "inc1"); // this contains a new file Boo.java build(p); assertEquals(1, olm.writeCount); checkCompileWeaveCount(p, 1, 1); // assertEquals(1, olm.removeCount); } static class CustomOLM extends TestOutputLocationManager { public int writeCount = 0; public int removeCount = 0; public CustomOLM(String testProjectPath) { super(testProjectPath); } @Override public void reportFileWrite(String outputfile, int filetype) { super.reportFileWrite(outputfile, filetype); writeCount++; System.out.println("Written " + outputfile); // System.out.println("Written " + outputfile + " " + filetype); } @Override public void reportFileRemove(String outputfile, int filetype) { super.reportFileRemove(outputfile, filetype); removeCount++; System.out.println("Removed " + outputfile); // System.out.println("Removed " + outputfile + " " + filetype); } } public void testBrokenCodeDeca_268611() { String p = "pr268611"; initialiseProject(p); build(p); checkWasFullBuild(); assertEquals(1, getErrorMessages(p).size()); assertTrue(((Message) getErrorMessages(p).get(0)).getMessage().indexOf( "Syntax error on token \")\", \"name pattern\" expected") != -1); } public void testIncrementalMixin() { String p = "mixin"; initialiseProject(p); build(p); checkWasFullBuild(); assertEquals(0, getErrorMessages(p).size()); alter(p, "inc1"); build(p); checkWasntFullBuild(); assertEquals(0, getErrorMessages(p).size()); } public void testUnusedPrivates_pr266420() { String p = "pr266420"; initialiseProject(p); 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"); javaOptions.put("org.eclipse.jdt.core.compiler.problem.unusedPrivateMember", "warning"); configureJavaOptionsMap(p, javaOptions); build(p); checkWasFullBuild(); List warnings = getWarningMessages(p); assertEquals(0, warnings.size()); alter(p, "inc1"); build(p); checkWasntFullBuild(); warnings = getWarningMessages(p); assertEquals(0, warnings.size()); } public void testExtendingITDAspectOnClasspath_PR298704() throws Exception { String base = "pr298704_baseaspects"; String test = "pr298704_testaspects"; initialiseProject(base); initialiseProject(test); configureNewProjectDependency(test, base); build(base); build(test); checkWasFullBuild(); assertNoErrors(test); IRelationshipMap irm = getModelFor(test).getRelationshipMap(); assertEquals(7, irm.getEntries().size()); } public void testPR265729() { AjdeInteractionTestbed.VERBOSE = true; String lib = "pr265729_lib"; initialiseProject(lib); // addClasspathEntryChanged(lib, getProjectRelativePath(p1, // "bin").toString()); build(lib); checkWasFullBuild(); String cli = "pr265729_client"; initialiseProject(cli); // addClasspathEntry(cli, new File("../lib/junit/junit.jar")); configureAspectPath(cli, getProjectRelativePath(lib, "bin")); build(cli); checkWasFullBuild(); IProgramElement root = getModelFor(cli).getHierarchy().getRoot(); // dumptree(root, 0); // PrintWriter pw = new PrintWriter(System.out); // try { // getModelFor(cli).dumprels(pw); // pw.flush(); // } catch (Exception e) { // } IRelationshipMap irm = getModelFor(cli).getRelationshipMap(); IRelationship ir = irm.get("=pr265729_client<be.cronos.aop{App.java[App").get(0); // This type should be affected by an ITD and a declare parents // could be either way round String h1 = ir.getTargets().get(0); String h2 = ir.getTargets().get(1); // For some ITD: public void I.g(String s) {} // Node in tree: I.g(java.lang.String) [inter-type method] // Handle: =pr265729_client<be.cronos.aop{App.java}X)I.g)QString; if (!h1.endsWith("parents")) { String h3 = h1; h1 = h2; h2 = h3; } // ITD from the test program: // public String InterTypeAspectInterface.foo(int i,List list,App a) { assertEquals("=pr265729_client/binaries<be.cronos.aop.aspects(InterTypeAspect.class'InterTypeAspect`declare parents", h1); assertEquals( "=pr265729_client/binaries<be.cronos.aop.aspects(InterTypeAspect.class'InterTypeAspect)InterTypeAspectInterface.foo)I)QList;)QSerializable;", h2); IProgramElement binaryDecp = getModelFor(cli).getHierarchy().getElement(h1); assertNotNull(binaryDecp); IProgramElement binaryITDM = getModelFor(cli).getHierarchy().getElement(h2); assertNotNull(binaryITDM); // @see AsmRelationshipProvider.createIntertypeDeclaredChild() List ptypes = binaryITDM.getParameterTypes(); assertEquals("int", new String((char[]) ptypes.get(0))); assertEquals("java.util.List", new String((char[]) ptypes.get(1))); assertEquals("java.io.Serializable", new String((char[]) ptypes.get(2))); // param names not set // List pnames = binaryITDM.getParameterNames(); // assertEquals("i", new String((char[]) pnames.get(0))); // assertEquals("list", new String((char[]) pnames.get(1))); // assertEquals("b", new String((char[]) pnames.get(2))); assertEquals("java.lang.String", binaryITDM.getCorrespondingType(true)); } public void testXmlConfiguredProject() { AjdeInteractionTestbed.VERBOSE = true; String p = "xmlone"; initialiseProject(p); configureNonStandardCompileOptions(p, "-showWeaveInfo");// -xmlConfigured"); configureShowWeaveInfoMessages(p, true); addXmlConfigFile(p, getProjectRelativePath(p, "p/aop.xml").toString()); build(p); checkWasFullBuild(); List weaveMessages = getWeavingMessages(p); if (weaveMessages.size() != 1) { for (Iterator iterator = weaveMessages.iterator(); iterator.hasNext();) { Object object = iterator.next(); System.out.println(object); } fail("Expected just one weave message. The aop.xml should have limited the weaving"); } } public void testDeclareParentsInModel() { String p = "decps"; initialiseProject(p); build(p); IProgramElement decp = getModelFor(p).getHierarchy().findElementForHandle("=decps<a{A.java'A`declare parents"); List<String> ps = decp.getParentTypes(); assertNotNull(ps); assertEquals(2, ps.size()); int count = 0; for (Iterator<String> iterator = ps.iterator(); iterator.hasNext();) { String type = iterator.next(); if (type.equals("java.io.Serializable")) { count++; } if (type.equals("a.Goo")) { count++; } } assertEquals("Should have found the two types in: " + ps, 2, count); } public void testConstructorAdvice_pr261380() throws Exception { String p = "261380"; initialiseProject(p); build(p); IRelationshipMap irm = getModelFor(p).getRelationshipMap(); IRelationship ir = irm.get("=261380<test{C.java'X&before").get(0); List targets = ir.getTargets(); assertEquals(1, targets.size()); System.out.println(targets.get(0)); String handle = (String) targets.get(0); assertEquals("Expected the handle for the code node inside the constructor decl", "=261380<test{C.java[C~C?constructor-call(void test.C.<init>())", handle); } /* * 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(getModelFor("P4"), "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(getModelFor("P4"), "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(getModelFor("P4"), "pack", "C", true)); // This will be the line 7 entry in A.java IProgramElement advice = findAdvice(checkForNode(getModelFor("P4"), "pack", "A", true)); IRelationshipMap asmRelMap = getModelFor("P4").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 = getModelFor("P4").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 = getModelFor("P4").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 testPr148285() { String p = "PR148285_2"; initialiseProject(p); // Single source file A.aj defines A and C build(p); checkWasFullBuild(); alter(p, "inc1"); // Second source introduced C.java, defines C build(p); checkWasntFullBuild(); List msgs = getErrorMessages(p); assertEquals("error message should be 'The type C is already defined' ", "The type C is already defined", ((IMessage) msgs .get(0)).getMessage()); alter("PR148285_2", "inc2"); // type C in A.aj is commented out build("PR148285_2"); checkWasntFullBuild(); msgs = getErrorMessages(p); assertTrue("There should be no errors reported:\n" + getErrorMessages(p), msgs.isEmpty()); } public void testIncrementalAndAnnotations() { initialiseProject("Annos"); build("Annos"); checkWasFullBuild(); checkCompileWeaveCount("Annos", 4, 4); AsmManager model = getModelFor("Annos"); assertEquals("Should be 3 relationships ", 3, model.getRelationshipMap().getEntries().size()); alter("Annos", "inc1"); // Comment out the annotation on Parent build("Annos"); checkWasntFullBuild(); assertEquals("Should be no relationships ", 0, model.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, model.getRelationshipMap().getEntries().size()); checkCompileWeaveCount("Annos", 3, 3); } // package a.b.c; // // public class A { // } // // aspect X { // B A.foo(C c) { return null; } // declare parents: A implements java.io.Serializable; // } // // class B {} // class C {} public void testITDFQNames_pr252702() { String p = "itdfq"; AjdeInteractionTestbed.VERBOSE = true; initialiseProject(p); build(p); AsmManager model = getModelFor(p); dumptree(model.getHierarchy().getRoot(), 0); IProgramElement root = model.getHierarchy().getRoot(); ProgramElement theITD = (ProgramElement) findElementAtLine(root, 7); Map<String, Object> m = theITD.kvpairs; for (Iterator<String> iterator = m.keySet().iterator(); iterator.hasNext();) { String type = iterator.next(); System.out.println(type + " = " + m.get(type)); } // return type of the ITD assertEquals("a.b.c.B", theITD.getCorrespondingType(true)); List<char[]> ptypes = theITD.getParameterTypes(); for (Iterator<char[]> iterator = ptypes.iterator(); iterator.hasNext();) { char[] object = iterator.next(); System.out.println("p = " + new String(object)); } ProgramElement decp = (ProgramElement) findElementAtLine(root, 8); m = decp.kvpairs; for (Iterator<String> iterator = m.keySet().iterator(); iterator.hasNext();) { String type = iterator.next(); System.out.println(type + " = " + m.get(type)); } List<String> l = decp.getParentTypes(); assertEquals("java.io.Serializable", l.get(0)); ProgramElement ctorDecp = (ProgramElement) findElementAtLine(root, 16); String ctordecphandle = ctorDecp.getHandleIdentifier(); assertEquals("=itdfq<a.b.c{A.java'XX)B.B_new)QString;", ctordecphandle); // 252702 // , // comment // 7 } public void testBrokenHandles_pr247742() { String p = "BrokenHandles"; initialiseProject(p); // alter(p, "inc1"); build(p); // alter(p, "inc2"); // build(p); AsmManager model = getModelFor(p); dumptree(model.getHierarchy().getRoot(), 0); IProgramElement root = model.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 testNPEIncremental_pr262218() { AjdeInteractionTestbed.VERBOSE = true; String p = "pr262218"; initialiseProject(p); build(p); checkWasFullBuild(); alter(p, "inc1"); build(p); checkWasntFullBuild(); List l = getCompilerErrorMessages(p); assertEquals("Unexpected compiler error", 0, l.size()); } public void testDeclareAnnotationNPE_298504() { AjdeInteractionTestbed.VERBOSE = true; String p = "pr298504"; initialiseProject(p); build(p); List l = getErrorMessages(p); assertTrue(l.toString().indexOf("ManagedResource cannot be resolved to a type") != -1); // checkWasFullBuild(); alter(p, "inc1"); build(p); // checkWasntFullBuild(); l = getCompilerErrorMessages(p); assertTrue(l.toString().indexOf("NullPointerException") == -1); l = getErrorMessages(p); assertTrue(l.toString().indexOf("ManagedResource cannot be resolved to a type") != -1); } public void testIncrementalAnnoStyle_pr286341() { AjdeInteractionTestbed.VERBOSE = true; String base = "pr286341_base"; initialiseProject(base); build(base); checkWasFullBuild(); String p = "pr286341"; initialiseProject(p); configureAspectPath(p, getProjectRelativePath(base, "bin")); addClasspathEntry(p, getProjectRelativePath(base, "bin")); build(p); checkWasFullBuild(); assertNoErrors(p); alter(p, "inc1"); build(p); checkWasntFullBuild(); assertNoErrors(p); } public void testImports_pr263487() { String p2 = "importProb2"; initialiseProject(p2); build(p2); checkWasFullBuild(); String p = "importProb"; initialiseProject(p); build(p); configureAspectPath(p, getProjectRelativePath(p2, "bin")); checkWasFullBuild(); build(p); build(p); build(p); alter(p, "inc1"); addProjectSourceFileChanged(p, getProjectRelativePath(p, "src/p/Code.java")); // addProjectSourceFileChanged(p, getProjectRelativePath(p, // "src/q/Asp.java")); build(p); checkWasntFullBuild(); List l = getCompilerErrorMessages(p); assertEquals("Unexpected compiler error", 0, l.size()); } public void testBuildingBrokenCode_pr263323() { AjdeInteractionTestbed.VERBOSE = true; String p = "brokenCode"; initialiseProject(p); build(p); checkWasFullBuild(); alter(p, "inc1"); // break the aspect build(p); checkWasntFullBuild(); alter(p, "inc2"); // whitespace change on affected file build(p); checkWasntFullBuild(); List l = getCompilerErrorMessages(p); assertEquals("Unexpected compiler error", 0, l.size()); } /* * public void testNPEGenericCtor_pr260944() { AjdeInteractionTestbed.VERBOSE = true; String p = "pr260944"; * initialiseProject(p); build(p); checkWasFullBuild(); alter(p, "inc1"); build(p); checkWasntFullBuild(); List l = * getCompilerErrorMessages(p); assertEquals("Unexpected compiler error", 0, l.size()); } */ public void testItdProb() { AjdeInteractionTestbed.VERBOSE = true; String p = "itdprob"; initialiseProject(p); build(p); checkWasFullBuild(); alter(p, "inc1"); build(p); checkWasntFullBuild(); List l = getCompilerErrorMessages(p); assertEquals("Unexpected compiler error", 0, l.size()); } /* * public void testGenericITD_pr262257() throws IOException { String p = "pr262257"; initialiseProject(p); build(p); * checkWasFullBuild(); * * dumptree(getModelFor(p).getHierarchy().getRoot(), 0); PrintWriter pw = new PrintWriter(System.out); * getModelFor(p).dumprels(pw); pw.flush(); } */ public void testAnnotations_pr262154() { String p = "pr262154"; initialiseProject(p); build(p); checkWasFullBuild(); alter(p, "inc1"); build(p); List l = getCompilerErrorMessages(p); assertEquals("Unexpected compiler error", 0, l.size()); } public void testAnnotations_pr255555() { String p = "pr255555"; initialiseProject(p); build(p); checkCompileWeaveCount(p, 2, 1); } public void testSpacewarHandles() { // String p = "SpaceWar"; String p = "Simpler"; initialiseProject(p); build(p); dumptree(getModelFor(p).getHierarchy().getRoot(), 0); // incomplete } /** * Test what is in the model for package declarations and import statements. Package Declaration nodes are new in AspectJ 1.6.4. * Import statements are contained with an 'import references' node. */ public void testImportHandles() { String p = "Imports"; initialiseProject(p); build(p); IProgramElement root = getModelFor(p).getHierarchy().getRoot(); // Looking for 'package p.q' IProgramElement ipe = findElementAtLine(root, 1); ipe = ipe.getChildren().get(0); // package decl is // first entry in // the type System.out.println(ipe.getHandleIdentifier() + " " + ipe.getKind()); assertEquals(IProgramElement.Kind.PACKAGE_DECLARATION, ipe.getKind()); assertEquals("=Imports<p.q*Example.aj%p.q", ipe.getHandleIdentifier()); assertEquals("package p.q;", ipe.getSourceSignature()); assertEquals(ipe.getSourceLocation().getOffset(), 8); // "package p.q" - // location of // p.q // Looking for import containing containing string and integer ipe = findElementAtLine(root, 3); // first import ipe = ipe.getParent(); // imports container System.out.println(ipe.getHandleIdentifier() + " " + ipe.getKind()); dumptree(getModelFor(p).getHierarchy().getRoot(), 0); assertEquals("=Imports<p.q*Example.aj#", ipe.getHandleIdentifier()); } public void testAdvisingCallJoinpointsInITDS_pr253067() { String p = "pr253067"; initialiseProject(p); build(p); // Check for a code node at line 5 - if there is one then we created it // correctly when building // the advice relationship IProgramElement root = getModelFor(p).getHierarchy().getRoot(); IProgramElement code = findElementAtLine(root, 5); assertEquals("=pr253067<aa*AdvisesC.aj'AdvisesC)C.nothing?method-call(int aa.C.nothing())", code.getHandleIdentifier()); // dumptree(getModelFor(p).getHierarchy().getRoot(), 0); // Ajc.dumpAJDEStructureModel(getModelFor("pr253067"), // "after inc build where first advised line is gone"); } public void testHandles_DeclareAnno_pr249216_c9() { String p = "pr249216"; initialiseProject(p); build(p); IProgramElement root = getModelFor(p).getHierarchy().getRoot(); IProgramElement code = findElementAtLine(root, 4); // the @ should be escapified assertEquals("=pr249216<{Deca.java'X`declare \\@type", code.getHandleIdentifier()); // dumptree(getModelFor(p).getHierarchy().getRoot(), 0); // Ajc.dumpAJDEStructureModel(getModelFor(p), // "after inc build where first advised line is gone"); } public void testNullDelegateBrokenCode_pr251940() { String p = "pr251940"; initialiseProject(p); build(p); checkForError(p, "The type F must implement the inherited"); } public void testBeanExample() throws Exception { String p = "BeanExample"; initialiseProject(p); build(p); dumptree(getModelFor(p).getHierarchy().getRoot(), 0); PrintWriter pw = new PrintWriter(System.out); getModelFor(p).dumprels(pw); pw.flush(); // incomplete } private void checkIfContainsFile(Set s, String filename, boolean shouldBeFound) { StringBuffer sb = new StringBuffer("Set of files\n"); for (Iterator iterator = s.iterator(); iterator.hasNext();) { Object object = iterator.next(); sb.append(object).append("\n"); } for (Iterator iterator = s.iterator(); iterator.hasNext();) { File fname = (File) iterator.next(); if (fname.getName().endsWith(filename)) { if (!shouldBeFound) { System.out.println(sb.toString()); fail("Unexpectedly found file " + filename); } else { return; } } } if (shouldBeFound) { System.out.println(sb.toString()); fail("Did not find filename " + filename); } } // /** // * Checking return values of the AsmManager API calls that can be invoked // post incremental build that tell the caller which // * files had their relationships altered. As well as the affected (woven) // files, it is possible to query the aspects that wove // * those files. // */ // public void testChangesOnBuild() throws Exception { // String p = "ChangesOnBuild"; // initialiseProject(p); // build(p); // // Not incremental // checkIfContainsFile(AsmManager.getDefault().getModelChangesOnLastBuild(), // "A.java", false); // alter(p, "inc1"); // build(p); // // Incremental // checkIfContainsFile(AsmManager.getDefault().getModelChangesOnLastBuild(), // "A.java", true); // checkIfContainsFile(AsmManager.getDefault(). // getAspectsWeavingFilesOnLastBuild(), "X.java", true); // checkIfContainsFile(AsmManager.getDefault(). // getAspectsWeavingFilesOnLastBuild(), "Y.java", false); // } public void testITDIncremental_pr192877() { String p = "PR192877"; initialiseProject(p); build(p); checkWasFullBuild(); alter(p, "inc1"); build(p); checkWasntFullBuild(); } public void testIncrementalBuildsWithItds_pr259528() { String p = "pr259528"; AjdeInteractionTestbed.VERBOSE = true; initialiseProject(p); build(p); checkWasFullBuild(); alter(p, "inc1"); build(p); checkWasntFullBuild(); } public void testAdviceHandlesAreJDTCompatible() { String p = "AdviceHandles"; initialiseProject(p); addSourceFolderForSourceFile(p, getProjectRelativePath(p, "src/Handles.aj"), "src"); build(p); IProgramElement root = getModelFor(p).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 findFile(IProgramElement whereToLook, String filesubstring) { if (whereToLook.getSourceLocation() != null && whereToLook.getKind().equals(IProgramElement.Kind.FILE_ASPECTJ) && whereToLook.getSourceLocation().getSourceFile().toString().indexOf(filesubstring) != -1) { return whereToLook; } List kids = whereToLook.getChildren(); for (Iterator iterator = kids.iterator(); iterator.hasNext();) { IProgramElement object = (IProgramElement) iterator.next(); if (object.getSourceLocation() != null && object.getKind().equals(IProgramElement.Kind.FILE_ASPECTJ) && object.getSourceLocation().getSourceFile().toString().indexOf(filesubstring) != -1) { return whereToLook; } IProgramElement gotSomething = findFile(object, filesubstring); if (gotSomething != null) { return gotSomething; } } return null; } 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"); // src1 source folder slashed as per 264563 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 = getModelFor("MultiSource").getHierarchy().findElementForHandle("=MultiSource/src1"); IProgramElement CodeOneClass = getModelFor("MultiSource").getHierarchy().findElementForHandle( "=MultiSource/src1{CodeOne.java[CodeOne"); IProgramElement srcTwoPackage = getModelFor("MultiSource").getHierarchy().findElementForHandle("=MultiSource/src2<pkg"); IProgramElement srcThreePackage = getModelFor("MultiSource").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); } // Now the source folders are more complex 'src/java/main' and // 'src/java/tests' public void testModelWithMultipleSourceFolders2() { initialiseProject("MultiSource"); // File sourceFolderOne = getProjectRelativePath("MultiSource", // "src/java/main"); // File sourceFolderTwo = getProjectRelativePath("MultiSource", "src2"); // File sourceFolderThree = getProjectRelativePath("MultiSource", // "src3"); addSourceFolderForSourceFile("MultiSource", getProjectRelativePath("MultiSource", "src1/CodeOne.java"), "src/java/main"); addSourceFolderForSourceFile("MultiSource", getProjectRelativePath("MultiSource", "src2/CodeTwo.java"), "src/java/main"); addSourceFolderForSourceFile("MultiSource", getProjectRelativePath("MultiSource", "src3/pkg/CodeThree.java"), "src/java/tests"); build("MultiSource"); IProgramElement srcOne = getModelFor("MultiSource").getHierarchy().findElementForHandleOrCreate( "=MultiSource/src\\/java\\/main", false); IProgramElement CodeOneClass = getModelFor("MultiSource").getHierarchy().findElementForHandle( "=MultiSource/src\\/java\\/main{CodeOne.java[CodeOne"); IProgramElement srcTwoPackage = getModelFor("MultiSource").getHierarchy().findElementForHandle( "=MultiSource/src\\/java\\/tests<pkg"); IProgramElement srcThreePackage = getModelFor("MultiSource").getHierarchy().findElementForHandle( "=MultiSource/src\\/java\\/testssrc3<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 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(getModelFor(bug2).getHierarchy().getRoot(), 0); PrintWriter pw = new PrintWriter(System.out); getModelFor(bug2).dumprels(pw); pw.flush(); IProgramElement root = getModelFor(bug2).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_pr274558() throws Exception { String base = "bug274558depending"; String depending = "bug274558base"; // addSourceFolderForSourceFile(bug2, getProjectRelativePath(bug2, "src/C.java"), "src"); initialiseProject(base); initialiseProject(depending); configureAspectPath(depending, getProjectRelativePath(base, "bin")); build(base); build(depending); printModel(depending); IProgramElement root = getModelFor(depending).getHierarchy().getRoot(); assertEquals("=bug274558base/binaries<r(DeclaresITD.class'DeclaresITD,InterfaceForITD.x", findElementAtLine(root, 4) .getHandleIdentifier()); // assertEquals("=AspectPathTwo/binaries<(Asp2.class}Asp2&before", findElementAtLine(root, 16).getHandleIdentifier()); } public void testAspectPath_pr265693() throws IOException { String bug = "AspectPath3"; String bug2 = "AspectPath4"; addSourceFolderForSourceFile(bug2, getProjectRelativePath(bug2, "src/C.java"), "src"); initialiseProject(bug); initialiseProject(bug2); configureAspectPath(bug2, getProjectRelativePath(bug, "bin")); build(bug); build(bug2); // dumptree(getModelFor(bug2).getHierarchy().getRoot(), 0); // PrintWriter pw = new PrintWriter(System.out); // getModelFor(bug2).dumprels(pw); // pw.flush(); IProgramElement root = getModelFor(bug2).getHierarchy().getRoot(); IProgramElement binariesNode = getChild(root, "binaries"); assertNotNull(binariesNode); IProgramElement packageNode = binariesNode.getChildren().get(0); assertEquals("a.b.c", packageNode.getName()); IProgramElement fileNode = packageNode.getChildren().get(0); assertEquals(IProgramElement.Kind.FILE, fileNode.getKind()); } private IProgramElement getChild(IProgramElement start, String name) { if (start.getName().equals(name)) { return start; } List kids = start.getChildren(); if (kids != null) { for (int i = 0; i < kids.size(); i++) { IProgramElement found = getChild((IProgramElement) kids.get(i), name); if (found != null) { return found; } } } return null; } public void testHandleQualification_pr265993() throws IOException { String p = "pr265993"; initialiseProject(p); build(p); IProgramElement root = getModelFor(p).getHierarchy().getRoot(); // dumptree(getModelFor(p).getHierarchy().getRoot(), 0); // PrintWriter pw = new PrintWriter(System.out); // getModelFor(p).dumprels(pw); // pw.flush(); assertEquals("=pr265993<{A.java[A~m~QString;~Qjava.lang.String;", findElementAtLine(root, 3).getHandleIdentifier()); assertEquals("=pr265993<{A.java[A~m2~QList;", findElementAtLine(root, 5).getHandleIdentifier()); assertEquals("=pr265993<{A.java[A~m3~Qjava.util.ArrayList;", findElementAtLine(root, 6).getHandleIdentifier()); assertEquals("=pr265993<{A.java[A~m4~QMap\\<Qjava.lang.String;QList;>;", findElementAtLine(root, 8).getHandleIdentifier()); assertEquals("=pr265993<{A.java[A~m5~Qjava.util.Map\\<Qjava.lang.String;QList;>;", findElementAtLine(root, 9) .getHandleIdentifier()); assertEquals("=pr265993<{A.java[A~m6~QMap\\<\\[IQList;>;", findElementAtLine(root, 10).getHandleIdentifier()); assertEquals("=pr265993<{A.java[A~m7~\\[I", findElementAtLine(root, 11).getHandleIdentifier()); assertEquals("=pr265993<{A.java[A~m8~\\[Qjava.lang.String;", findElementAtLine(root, 12).getHandleIdentifier()); assertEquals("=pr265993<{A.java[A~m9~\\[QString;", findElementAtLine(root, 13).getHandleIdentifier()); assertEquals("=pr265993<{A.java[A~m10~\\[\\[QList\\<QString;>;", findElementAtLine(root, 14).getHandleIdentifier()); assertEquals("=pr265993<{A.java[A~m11~Qjava.util.List\\<QT;>;", findElementAtLine(root, 15).getHandleIdentifier()); assertEquals("=pr265993<{A.java[A~m12~\\[QT;", findElementAtLine(root, 16).getHandleIdentifier()); assertEquals("=pr265993<{A.java[A~m13~QClass\\<QT;>;~QObject;~QString;", findElementAtLine(root, 17).getHandleIdentifier()); } public void testHandlesForAnnotationStyle_pr269286() throws IOException { String p = "pr269286"; initialiseProject(p); build(p); IProgramElement root = getModelFor(p).getHierarchy().getRoot(); dumptree(getModelFor(p).getHierarchy().getRoot(), 0); PrintWriter pw = new PrintWriter(System.out); getModelFor(p).dumprels(pw); pw.flush(); assertEquals("=pr269286<{Logger.java[Logger", findElementAtLine(root, 4).getHandleIdentifier()); // type assertEquals("=pr269286<{Logger.java[Logger~boo", findElementAtLine(root, 7).getHandleIdentifier()); // before assertEquals("=pr269286<{Logger.java[Logger~aoo", findElementAtLine(root, 11).getHandleIdentifier()); // after assertEquals("=pr269286<{Logger.java[Logger~aroo", findElementAtLine(root, 15).getHandleIdentifier()); // around // pointcuts are not fixed - seems to buggy handling of them internally assertEquals("=pr269286<{Logger.java[Logger\"ooo", findElementAtLine(root, 20).getHandleIdentifier()); // DeclareWarning assertEquals("=pr269286<{Logger.java[Logger^message", findElementAtLine(root, 24).getHandleIdentifier()); // DeclareError assertEquals("=pr269286<{Logger.java[Logger^message2", findElementAtLine(root, 27).getHandleIdentifier()); } public void testHandleCountersForAdvice() throws IOException { String p = "prx"; initialiseProject(p); build(p); // System.out.println("Handle Counters For Advice Output"); IProgramElement root = getModelFor(p).getHierarchy().getRoot(); // dumptree(getModelFor(p).getHierarchy().getRoot(), 0); // PrintWriter pw = new PrintWriter(System.out); // getModelFor(p).dumprels(pw); // pw.flush(); IProgramElement ff = findFile(root, "ProcessAspect.aj"); assertEquals("=prx<com.kronos.aspects*ProcessAspect.aj'ProcessAspect&after&QMyProcessor;", findElementAtLine(root, 22) .getHandleIdentifier()); assertEquals("=prx<com.kronos.aspects*ProcessAspect.aj'ProcessAspect&after&QMyProcessor;!2", findElementAtLine(root, 68) .getHandleIdentifier()); } /** * A change is made to an aspect on the aspectpath (staticinitialization() advice is added) for another project. * <p> * Managing the aspectpath is hard. We want to do a minimal build of this project which means recognizing what kind of changes * have occurred on the aspectpath. Was it a regular class or an aspect? Was it a structural change to that aspect? * <p> * The filenames for .class files created that contain aspects is stored in the AjState.aspectClassFiles field. When a change is * detected we can see who was managing the location where the change occurred and ask them if the .class file contained an * aspect. Right now a change detected like this will cause a full build. We might improve the detection logic here but it isn't * trivial: * <ul> * <li>Around advice is inlined. Changing the body of an around advice would not normally be thought of as a structural change * (as it does not change the signature of the class) but due to inlining it is a change we would need to pay attention to as it * will affect types previously woven with that advice. * <li>Annotation style aspects include pointcuts in strings. Changes to these are considered non-structural but clearly they do * affect what might be woven. * </ul> */ public void testAspectPath_pr249212_c1() throws IOException { String p1 = "AspectPathOne"; String p2 = "AspectPathTwo"; addSourceFolderForSourceFile(p2, getProjectRelativePath(p2, "src/C.java"), "src"); initialiseProject(p1); initialiseProject(p2); configureAspectPath(p2, getProjectRelativePath(p1, "bin")); build(p1); build(p2); alter(p1, "inc1"); build(p1); // Modify the aspect Asp2 to include staticinitialization() // advice checkWasFullBuild(); Set s = getModelFor(p1).getModelChangesOnLastBuild(); assertTrue("Should be empty as was full build:" + s, s.isEmpty()); // prod the build of the second project with some extra info to tell it // more precisely about the change: addClasspathEntryChanged(p2, getProjectRelativePath(p1, "bin").toString()); configureAspectPath(p2, getProjectRelativePath(p1, "bin")); build(p2); checkWasFullBuild(); // dumptree(AsmManager.getDefault().getHierarchy().getRoot(), 0); // PrintWriter pw = new PrintWriter(System.out); // AsmManager.getDefault().dumprels(pw); // pw.flush(); // Not incremental assertTrue("Should be empty as was full build:" + s, s.isEmpty()); // Set s = AsmManager.getDefault().getModelChangesOnLastBuild(); // checkIfContainsFile(AsmManager.getDefault().getModelChangesOnLastBuild // (), "C.java", true); } // 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() { 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() { 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 = getModelFor("pr240360").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, getModelFor("pr240360").getRelationshipMap().getEntries().size()); // Readd the erroneous type alter("pr240360", "inc1"); build("pr240360"); checkWasntFullBuild(); checkCompileWeaveCount("pr240360", 1, 0); assertEquals(relmapLength, getModelFor("pr240360").getRelationshipMap().getEntries().size()); // Change the advice alter("pr240360", "inc2"); build("pr240360"); checkWasFullBuild(); checkCompileWeaveCount("pr240360", 6, 4); assertEquals(relmapLength, getModelFor("pr240360").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"); 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()); } /** * This test is verifying the behaviour of the code that iterates through the type hierarchy for some type. There are two ways * to do it - an approach that grabs all the information up front or an approach that works through iterators and only processes * as much data as necessary to satisfy the caller. The latter approach could be much faster - especially if the matching * process typically looks for a method in the declaring type. */ public void xtestOptimizedMemberLookup() { String p = "oml"; initialiseProject(p); build(p); AjdeCoreBuildManager buildManager = getCompilerForProjectWithName(p).getBuildManager(); AjBuildManager ajBuildManager = buildManager.getAjBuildManager(); World w = ajBuildManager.getWorld(); // Type A has no hierarchy (well, Object) and defines 3 methods checkType(w, "com.foo.A"); // Type B extends B2. Two methods in B2, three in B checkType(w, "com.foo.B"); // Type C implements an interface checkType(w, "com.foo.C"); // Type CC extends a class that implements an interface checkType(w, "com.foo.CC"); // Type CCC implements an interface that extends another interface checkType(w, "com.foo.CCC"); // Type CCC implements an interface that extends another interface checkType(w, "com.foo.CCC"); checkType(w, "GenericMethodInterface"); checkType(w, "GenericInterfaceChain"); // Some random classes from rt.jar that did reveal some problems: checkType(w, "java.lang.StringBuffer"); checkType(w, "com.sun.corba.se.impl.encoding.CDRInputObject"); checkTypeHierarchy(w, "com.sun.corba.se.impl.interceptors.PIHandlerImpl$RequestInfoStack", true); checkType(w, "com.sun.corba.se.impl.interceptors.PIHandlerImpl$RequestInfoStack"); checkType(w, "DeclareWarningAndInterfaceMethodCW"); checkType(w, "ICanGetSomething"); checkType(w, "B"); checkType(w, "C"); // checkRtJar(w); // only works if the JDK path is setup ok in checkRtJar // speedCheck(w); } private void checkRtJar(World w) { System.out.println("Processing everything in rt.jar: ~16000 classes"); try { ZipFile zf = new ZipFile("c:/jvms/jdk1.6.0_06/jre/lib/rt.jar"); Enumeration e = zf.entries(); int count = 1; while (e.hasMoreElements()) { ZipEntry ze = (ZipEntry) e.nextElement(); String n = ze.getName(); if (n.endsWith(".class")) { n = n.replace('/', '.'); n = n.substring(0, n.length() - 6); if ((count % 100) == 0) { System.out.print(count + " "); } if ((count % 1000) == 0) { System.out.println(); } checkType(w, n); count++; } } zf.close(); } catch (IOException t) { t.printStackTrace(); fail(t.toString()); } System.out.println(); } /** * Compare time taken to grab them all and look at them and iterator through them all. */ private void speedCheck(World w) { long stime = System.currentTimeMillis(); try { ZipFile zf = new ZipFile("c:/jvms/jdk1.6.0_06/jre/lib/rt.jar"); Enumeration e = zf.entries(); while (e.hasMoreElements()) { ZipEntry ze = (ZipEntry) e.nextElement(); String n = ze.getName(); if (n.endsWith(".class")) { n = n.replace('/', '.'); n = n.substring(0, n.length() - 6); ResolvedType typeA = w.resolve(n); assertFalse(typeA.isMissing()); List<ResolvedMember> viaIteratorList = getThemAll(typeA.getMethods(true, true)); viaIteratorList = getThemAll(typeA.getMethods(false, true)); } } zf.close(); } catch (IOException t) { t.printStackTrace(); fail(t.toString()); } long etime = System.currentTimeMillis(); System.out.println("Time taken for 'iterator' approach: " + (etime - stime) + "ms"); stime = System.currentTimeMillis(); try { ZipFile zf = new ZipFile("c:/jvms/jdk1.6.0_06/jre/lib/rt.jar"); Enumeration e = zf.entries(); while (e.hasMoreElements()) { ZipEntry ze = (ZipEntry) e.nextElement(); String n = ze.getName(); if (n.endsWith(".class")) { n = n.replace('/', '.'); n = n.substring(0, n.length() - 6); ResolvedType typeA = w.resolve(n); assertFalse(typeA.isMissing()); List<ResolvedMember> viaIteratorList = typeA.getMethodsWithoutIterator(false, true, true); viaIteratorList = typeA.getMethodsWithoutIterator(false, true, false); } } zf.close(); } catch (IOException t) { t.printStackTrace(); fail(t.toString()); } etime = System.currentTimeMillis(); System.out.println("Time taken for 'grab all up front' approach: " + (etime - stime) + "ms"); } private void checkType(World w, String name) { checkTypeHierarchy(w, name, true); checkTypeHierarchy(w, name, false); checkMethods(w, name, true); checkMethods(w, name, false); } private void checkMethods(World w, String name, boolean wantGenerics) { ResolvedType typeA = w.resolve(name); assertFalse(typeA.isMissing()); List<ResolvedMember> viaIteratorList = getThemAll(typeA.getMethods(wantGenerics, true)); List<ResolvedMember> directlyList = typeA.getMethodsWithoutIterator(true, true, wantGenerics); Collections.sort(viaIteratorList, new ResolvedMemberComparator()); Collections.sort(directlyList, new ResolvedMemberComparator()); compare(viaIteratorList, directlyList, name); // System.out.println(toString(viaIteratorList, directlyList, genericsAware)); } private static class ResolvedMemberComparator implements Comparator<ResolvedMember> { public int compare(ResolvedMember o1, ResolvedMember o2) { return o1.toString().compareTo(o2.toString()); } } private void checkTypeHierarchy(World w, String name, boolean wantGenerics) { ResolvedType typeA = w.resolve(name); assertFalse(typeA.isMissing()); List<String> viaIteratorList = exhaustTypeIterator(typeA.getHierarchy(wantGenerics, false)); List<ResolvedType> typeDirectlyList = typeA.getHierarchyWithoutIterator(true, true, wantGenerics); assertFalse(viaIteratorList.isEmpty()); List<String> directlyList = new ArrayList<String>(); for (ResolvedType type : typeDirectlyList) { String n = type.getName(); if (!directlyList.contains(n)) { directlyList.add(n); } } Collections.sort(viaIteratorList); Collections.sort(directlyList); compareTypeLists(viaIteratorList, directlyList); // System.out.println("ShouldBeGenerics?" + wantGenerics + "\n" + typeListsToString(viaIteratorList, directlyList)); } private void compare(List<ResolvedMember> viaIteratorList, List<ResolvedMember> directlyList, String typename) { assertEquals(typename + "\n" + toString(directlyList), typename + "\n" + toString(viaIteratorList)); } private void compareTypeLists(List<String> viaIteratorList, List<String> directlyList) { assertEquals(typeListToString(directlyList), typeListToString(viaIteratorList)); } private String toString(List<ResolvedMember> list) { StringBuffer sb = new StringBuffer(); for (ResolvedMember m : list) { sb.append(m).append("\n"); } return sb.toString(); } private String typeListToString(List<String> list) { StringBuffer sb = new StringBuffer(); for (String m : list) { sb.append(m).append("\n"); } return sb.toString(); } private String toString(List<ResolvedMember> one, List<ResolvedMember> two, boolean shouldIncludeGenerics) { StringBuffer sb = new StringBuffer(); sb.append("Through iterator\n"); for (ResolvedMember m : one) { sb.append(m).append("\n"); } sb.append("Directly retrieved\n"); for (ResolvedMember m : one) { sb.append(m).append("\n"); } return sb.toString(); } private String typeListsToString(List<String> one, List<String> two) { StringBuffer sb = new StringBuffer(); sb.append("Through iterator\n"); for (String m : one) { sb.append(">" + m).append("\n"); } sb.append("Directly retrieved\n"); for (String m : one) { sb.append(">" + m).append("\n"); } return sb.toString(); } private List<ResolvedMember> getThemAll(Iterator<ResolvedMember> methods) { List<ResolvedMember> allOfThem = new ArrayList<ResolvedMember>(); while (methods.hasNext()) { allOfThem.add(methods.next()); } return allOfThem; } private List<String> exhaustTypeIterator(Iterator<ResolvedType> types) { List<String> allOfThem = new ArrayList<String>(); while (types.hasNext()) { allOfThem.add(types.next().getName()); } return allOfThem; } /** * 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(getModelFor("P1"), "pkg", "C", true); build("P2"); checkForNode(getModelFor("P2"), "pkg", "C", false); build("P1"); checkForNode(getModelFor("P1"), "pkg", "C", true); build("P2"); checkForNode(getModelFor("P2"), "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(getModelFor("P1"), "pkg", "C", true); build("P2"); checkForNode(getModelFor("P2"), "pkg", "C", false); build("P1"); checkForNode(getModelFor("P1"), "pkg", "C", true); build("P2"); checkForNode(getModelFor("P2"), "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 = (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 = (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"); // This should be an incremental build now - because of the changes // under 259649 checkWasntFullBuild(); // 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() { 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", (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", (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]", (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, (getWarningMessages("PR134541").get(0)) .getSourceLocation().getLine()); alter("PR134541", "inc1"); build("PR134541"); // if (getModelFor("PR134541").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, (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 = getModelFor("JDTLikeHandleProvider").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 = getModelFor("JDTLikeHandleProvider").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 = getModelFor("JDTLikeHandleProvider").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 = getModelFor("JDTLikeHandleProvider").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 = getModelFor("JDTLikeHandleProvider").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 = getModelFor("JDTLikeHandleProvider").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 = getModelFor("JDTLikeHandleProvider").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"); AsmManager model = getModelFor("PR134471"); // Step2. Quick check that the advice points to something... IProgramElement nodeForTypeA = checkForNode(model, "pkg", "A", true); IProgramElement nodeForAdvice = findAdvice(nodeForTypeA); List relatedElements = getRelatedElements(model, 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(model, findCode(checkForNode(model, "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"); model = getModelFor("PR134471"); // Step5. Quick check that the advice points to something... nodeForTypeA = checkForNode(model, "pkg", "A", true); nodeForAdvice = findAdvice(nodeForTypeA); relatedElements = getRelatedElements(model, 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(model, findCode(checkForNode(model, "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"); AsmManager model = getModelFor("PR134471_2"); // Step2. confirm advice is from correct location IProgramElement programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "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"); model = getModelFor("PR134471_2"); 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(model, findCode(checkForNode(model, "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"); AsmManager model = getModelFor("PR134471"); // Step2. confirm advice is from correct location IProgramElement programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "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"); model = getModelFor("PR134471"); // Step4. Quick check that the advice points to something... IProgramElement nodeForTypeA = checkForNode(model, "pkg", "A", true); IProgramElement nodeForAdvice = findAdvice(nodeForTypeA); List relatedElements = getRelatedElements(model, nodeForAdvice, 1); // Step5. No change to the file C but it should still be advised // afterwards alter("PR134471", "inc2"); build("PR134471"); checkWasntFullBuild(); model = getModelFor("PR134471"); // Step6. confirm advice is from correct location programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "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(); AsmManager model = getModelFor("PR134471_3"); // Step2. confirm declare warning is from correct location, decw matches // line 7 in pkg.C IProgramElement programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "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(model, findCode(checkForNode(model, "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"); model = getModelFor("PR134471_3"); 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(model, findCode(checkForNode(model, "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(); model = getModelFor("PR134471_3"); // Step7. confirm declare warning is from correct location, decw (now at // line 12) in pkg.A matches line 7 in pkg.C programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "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(); AsmManager model = getModelFor("PR134471_3"); // Step2. confirm declare warning is from correct location, decw matches // line 7 in pkg.C IProgramElement programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "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(model, findCode(checkForNode(model, "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"); model = getModelFor("PR134471_3"); 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(model, findCode(checkForNode(model, "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(); model = getModelFor("PR134471_3"); // Step7. confirm declare warning is from correct location, decw (now at // line 12) in pkg.A matches line 7 in pkg.C programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "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(model, findCode(checkForNode(model, "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, (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, (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"); 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<String,String> javaOptions = new Hashtable<String,String>(); 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<IMessage> 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<String,String> javaOptions = new Hashtable<String,String>(); 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<String,String> javaOptions = new Hashtable<String,String>(); 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<File> s = new HashSet<File>(); s.add(f); configureInPath("inpathTesting", s); build("inpathTesting"); // the declare warning matches one place so expect one warning message List<IMessage> 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); } // warning about cant change parents of Object is fine public void testInpathHandles_271201() throws Exception { AjdeInteractionTestbed.VERBOSE = true; String p = "inpathHandles"; initialiseProject(p); String inpathTestingDir = getWorkingDir() + File.separator + "inpathHandles"; String inpathDir = inpathTestingDir + File.separator + "binpath"; // set up the inpath to have the directory on it's path System.out.println(inpathDir); File f = new File(inpathDir); Set s = new HashSet(); s.add(f); configureInPath(p, s); build(p); IProgramElement root = getModelFor(p).getHierarchy().getRoot(); // alter(p,"inc1"); // build(p); dumptree(root, 0); PrintWriter pw = new PrintWriter(System.out); try { getModelFor(p).dumprels(pw); pw.flush(); } catch (Exception e) { } List l = getModelFor(p).getRelationshipMap().get("=inpathHandles/,<codep(Code.class[Code"); assertNotNull(l); } // warning about cant change parents of Object is fine public void testInpathHandles_IncrementalCompilation_271201() throws Exception { AjdeInteractionTestbed.VERBOSE = true; String p = "inpathHandles"; initialiseProject(p); String inpathTestingDir = getWorkingDir() + File.separator + "inpathHandles"; String inpathDir = inpathTestingDir + File.separator + "binpath"; // set up the inpath to have the directory on it's path File f = new File(inpathDir); Set<File> s = new HashSet<File>(); s.add(f); configureInPath(p, s); // This build will weave a declare parents into the inpath class codep.Code build(p); assertNotNull(getModelFor(p).getRelationshipMap().get("=inpathHandles/,<codep(Code.class[Code")); IProgramElement root = getModelFor(p).getHierarchy().getRoot(); // This alteration introduces a new source file B.java, the build should not // damage phantom handle based relationships alter(p, "inc1"); build(p); assertNotNull(getModelFor(p).getRelationshipMap().get("=inpathHandles/,<codep(Code.class[Code")); assertNotNull(getModelFor(p).getRelationshipMap().get("=inpathHandles<p{B.java[B")); // This alteration removes B.java, the build should not damage phantom handle based relationships String fileB = getWorkingDir().getAbsolutePath() + File.separatorChar + "inpathHandles" + File.separatorChar + "src" + File.separatorChar + "p" + File.separatorChar + "B.java"; (new File(fileB)).delete(); build(p); assertNotNull(getModelFor(p).getRelationshipMap().get("=inpathHandles/,<codep(Code.class[Code")); assertNull(getModelFor(p).getRelationshipMap().get("=inpathHandles<p{B.java[B")); } public void testInpathHandles_WithInpathMap_271201() throws Exception { AjdeInteractionTestbed.VERBOSE = true; String p = "inpathHandles"; initialiseProject(p); String inpathTestingDir = getWorkingDir() + File.separator + "inpathHandles"; String inpathDir = inpathTestingDir + File.separator + "binpath";// + File.separator+ "codep"; // String expectedOutputDir = inpathTestingDir + File.separator + "bin"; // set up the inpath to have the directory on it's path System.out.println(inpathDir); File f = new File(inpathDir); Set<File> s = new HashSet<File>(); s.add(f); Map<File,String> m = new HashMap<File,String>(); m.put(f, "wibble"); configureOutputLocationManager(p, new TestOutputLocationManager(getProjectRelativePath(p, ".").toString(), m)); configureInPath(p, s); build(p); IProgramElement root = getModelFor(p).getHierarchy().getRoot(); // alter(p,"inc1"); // build(p); dumptree(root, 0); PrintWriter pw = new PrintWriter(System.out); try { getModelFor(p).dumprels(pw); pw.flush(); } catch (Exception e) { } List<IRelationship> l = getModelFor(p).getRelationshipMap().get("=inpathHandles/,wibble<codep(Code.class[Code"); assertNotNull(l); } private void printModelAndRelationships(String p) { IProgramElement root = getModelFor(p).getHierarchy().getRoot(); dumptree(root, 0); PrintWriter pw = new PrintWriter(System.out); try { getModelFor(p).dumprels(pw); pw.flush(); } catch (Exception e) { } } public void testInpathHandles_IncrementalCompilation_RemovingInpathEntries_271201() throws Exception { AjdeInteractionTestbed.VERBOSE = true; String p = "inpathHandles2"; initialiseProject(p); String inpathDir = getWorkingDir() + File.separator + "inpathHandles2" + File.separator + "binpath"; // set up the inpath to have the directory on it's path File f = new File(inpathDir); configureInPath(p, f); // This build will weave a declare parents into the inpath class codep.A and codep.B build(p); assertNotNull(getModelFor(p).getRelationshipMap().get("=inpathHandles2/,<codep(A.class[A")); // Not let us delete one of the inpath .class files assertTrue(new File(inpathDir, "codep" + File.separator + "A.class").delete()); setNextChangeResponse(p, ICompilerConfiguration.EVERYTHING); build(p); // printModelAndRelationships(p); } // warning about cant change parents of Object is fine // public void testInpathJars_271201() throws Exception { // AjdeInteractionTestbed.VERBOSE = true; // String p = "inpathJars"; // initialiseProject(p); // // String inpathTestingDir = getWorkingDir() + File.separator + "inpathJars"; // String inpathDir = inpathTestingDir + File.separator + "code.jar"; // // 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); // Map m = new HashMap(); // m.put(f, "Gibble"); // configureOutputLocationManager(p, new TestOutputLocationManager(getProjectRelativePath(p, ".").toString(), m)); // configureInPath(p, s); // build(p); // // // alter(p,"inc1"); // // build(p); // List l = getModelFor(p).getRelationshipMap().get("=inpathJars/,Gibble<codep(Code.class[Code"); // assertNotNull(l); // } // --- 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(AsmManager model, IProgramElement programElement, int expected) { List relatedElements = getRelatedElements(model, programElement); StringBuffer debugString = new StringBuffer(); if (relatedElements != null) { for (Iterator iter = relatedElements.iterator(); iter.hasNext();) { String element = (String) iter.next(); debugString.append(model.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(AsmManager model, IProgramElement programElement) { List rels = getRelatedElements(model, programElement, 1); return model.getHierarchy().findElementForHandle((String) rels.get(0)); } private List<String> getRelatedElements(AsmManager model, IProgramElement advice) { List<String> output = null; IRelationshipMap map = model.getRelationshipMap(); List<IRelationship> rels = map.get(advice); if (rels == null) { fail("Did not find any related elements!"); } for (Iterator<IRelationship> iter = rels.iterator(); iter.hasNext();) { IRelationship element = iter.next(); List<String> targets = element.getTargets(); if (output == null) { output = new ArrayList<String>(); } 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<IProgramElement> 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(AsmManager model, String packageName, String typeName, boolean shouldBeFound) { IProgramElement ipe = model.getHierarchy().findElementForType(packageName, typeName); if (shouldBeFound) { if (ipe == null) { printModel(model); } assertTrue("Should have been able to find '" + packageName + "." + typeName + "' in the asm", ipe != null); } else { if (ipe != null) { printModel(model); } assertTrue("Should have NOT been able to find '" + packageName + "." + typeName + "' in the asm", ipe == null); } return ipe; } private void printModel(AsmManager model) { try { AsmManager.dumptree(model.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); } }
323,417
Bug 323417 Sometimes StackOverflow is got while weaving
Build Identifier: 1.6.10 While weaving LifeRay 6.0.5 over tomcat 6.0.26 sometimes the next exceptions appear: java.lang.StackOverflowError at java.lang.String.indexOf(String.java:1521) at org.aspectj.weaver.TypeFactory.createTypeFromSignature(TypeFactory.java:199) at org.aspectj.weaver.UnresolvedType.forSignature(UnresolvedType.java:375) at org.aspectj.weaver.UnresolvedType.getRawType(UnresolvedType.java:533) at org.aspectj.weaver.ResolvedType.getRawType(ResolvedType.java:2400) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:430) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:399) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:430) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:399) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:430) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:399) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:430) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:399) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:430) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:399) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:430) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:399) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:430) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:399) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:430) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:399) ... Reproducible: Sometimes
resolved fixed
f631ad6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-08-25T01:46:42Z"
"2010-08-23T19:00:00Z"
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, Abraham Nevado * ******************************************************************/ package org.aspectj.weaver; import java.lang.ref.Reference; 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.IMessage; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.context.PinpointingMessageHandler; import org.aspectj.util.IStructureModel; import org.aspectj.weaver.UnresolvedType.TypeKind; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.DeclareSoft; import org.aspectj.weaver.patterns.DeclareTypeErrorOrWarning; 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<PointcutDesignatorHandler> 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; /** Should timing information be reported (as info messages)? */ private boolean timing = false; private boolean timingPeriodically = true; /** 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 runMinimalMemorySet = false; private boolean shouldPipelineCompilation = true; private boolean shouldGenerateStackMaps = false; protected boolean bcelRepositoryCaching = xsetBCEL_REPOSITORY_CACHING_DEFAULT.equalsIgnoreCase("true"); private boolean fastMethodPacking = false; private int itdVersion = 2; // defaults to 2nd generation itds // Minimal Model controls whether model entities that are not involved in relationships are deleted post-build private boolean minimalModel = false; private boolean targettingRuntime1_6_10 = false; private boolean completeBinaryTypes = false; private boolean overWeaving = false; public boolean forDEBUG_structuralChangesCode = false; public boolean forDEBUG_bridgingCode = false; public boolean optimizedMatching = true; protected long timersPerJoinpoint = 25000; protected long timersPerType = 250; public int infoMessagesEnabled = 0; // 0=uninitialized, 1=no, 2=yes 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<RuntimeException> 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 ResolvedType.NONE; } 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 = getWildcard(); 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 ResolvedType result = typeMap.get(signature); if (result == null && !ret.isMissing()) { ret = ensureRawTypeIfNecessary(ret); typeMap.put(signature, ret); return ret; } if (result == null) { return ret; } else { return result; } } // Only need one representation of '?' in a world - can be shared private BoundedReferenceType wildcard; private BoundedReferenceType getWildcard() { if (wildcard == null) { wildcard = new BoundedReferenceType(this); } return wildcard; } /** * 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<RuntimeException>(); } 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) { resolved = ensureRawTypeIfNecessary(ty); typeMap.put(ty.getSignature(), resolved); resolved = ty; } resolved.world = this; return resolved; } /** * When the world is operating in 1.5 mode, the TypeMap should only contain RAW types and never directly generic types. The RAW * type will contain a reference to the generic type. * * @param type a possibly generic type for which the raw needs creating as it is not currently in the world * @return a type suitable for putting into the world */ private ResolvedType ensureRawTypeIfNecessary(ResolvedType type) { if (!isInJava5Mode() || type.isRawType()) { return type; } // Key requirement here is if it is generic, create a RAW entry to be put in the map that points to it if (type instanceof ReferenceType && ((ReferenceType) type).getDelegate() != null && type.isGenericType()) { ReferenceType rawType = new ReferenceType(type.getSignature(), this); rawType.typeKind = UnresolvedType.TypeKind.RAW; ReferenceTypeDelegate delegate = ((ReferenceType) type).getDelegate(); rawType.setDelegate(delegate); rawType.setGenericType((ReferenceType) type); return rawType; } // probably parameterized... return type; } /** * 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 ReferenceType resolveToReferenceType(String name) { return (ReferenceType) resolve(name); } 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 ====================== ResolvedType rt = resolveGenericTypeFor(ty, false); ReferenceType genericType = (ReferenceType) rt; 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 = getWildcard(); } 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); } private boolean allLintIgnored = false; public void setAllLintIgnored() { allLintIgnored = true; } public boolean areAllLintIgnored() { return allLintIgnored; } 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, ResolvedType declaringAspect) { AjAttribute.AdviceAttribute attribute = new AjAttribute.AdviceAttribute(kind, p, extraParameterFlags, loc.getStart(), loc.getEnd(), loc.getSourceContext()); return getWeavingSupport().createAdviceMunger(attribute, p, signature, declaringAspect); } /** * 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<DeclareParents> getDeclareParents() { return crosscuttingMembersSet.getDeclareParents(); } public List<DeclareAnnotation> getDeclareAnnotationOnTypes() { return crosscuttingMembersSet.getDeclareAnnotationOnTypes(); } public List<DeclareAnnotation> getDeclareAnnotationOnFields() { return crosscuttingMembersSet.getDeclareAnnotationOnFields(); } public List<DeclareAnnotation> getDeclareAnnotationOnMethods() { return crosscuttingMembersSet.getDeclareAnnotationOnMethods(); } public List<DeclareTypeErrorOrWarning> getDeclareTypeEows() { return crosscuttingMembersSet.getDeclareTypeEows(); } public List<DeclareSoft> 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 boolean isMinimalModel() { ensureAdvancedConfigurationProcessed(); return minimalModel; } public boolean isTargettingRuntime1_6_10() { ensureAdvancedConfigurationProcessed(); return targettingRuntime1_6_10; } public void setBehaveInJava5Way(boolean b) { behaveInJava5Way = b; } /** * Set the timing option (whether to collect timing info), this will also need INFO messages turned on for the message handler * being used. The reportPeriodically flag should be set to false under AJDT so numbers just come out at the end. */ public void setTiming(boolean timersOn, boolean reportPeriodically) { timing = timersOn; timingPeriodically = reportPeriodically; } /** * 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(); } public boolean areInfoMessagesEnabled() { if (infoMessagesEnabled == 0) { infoMessagesEnabled = (messageHandler.isIgnoring(IMessage.INFO) ? 1 : 2); } return infoMessagesEnabled == 2; } /** * 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 final static String xsetOVERWEAVING = "overWeaving"; public final static String xsetOPTIMIZED_MATCHING = "optimizedMatching"; public final static String xsetTIMERS_PER_JOINPOINT = "timersPerJoinpoint"; public final static String xsetTIMERS_PER_FASTMATCH_CALL = "timersPerFastMatchCall"; public final static String xsetITD_VERSION = "itdVersion"; public final static String xsetITD_VERSION_ORIGINAL = "1"; public final static String xsetITD_VERSION_2NDGEN = "2"; public final static String xsetITD_VERSION_DEFAULT = xsetITD_VERSION_2NDGEN; public final static String xsetMINIMAL_MODEL = "minimalModel"; public final static String xsetTARGETING_RUNTIME_1610 = "targetRuntime1_6_10"; public boolean isInJava5Mode() { return behaveInJava5Way; } public boolean isTimingEnabled() { return timing; } 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). */ public static class TypeMap { // 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 public List<String> addedSinceLastDemote; public List<String> writtenClasses; private static boolean debug = false; public static boolean useExpendableMap = true; // configurable for reliable testing private boolean demotionSystemActive; private boolean debugDemotion = false; public int policy = USE_WEAK_REFS; // Map of types that never get thrown away final Map<String, ResolvedType> tMap = new HashMap<String, ResolvedType>(); // Map of types that may be ejected from the cache if we need space final Map<String, Reference<ResolvedType>> expendableMap = Collections .synchronizedMap(new WeakHashMap<String, Reference<ResolvedType>>()); private final World w; // profiling tools... private boolean memoryProfiling = false; private int maxExpendableMapSize = -1; private int collectedTypes = 0; private final ReferenceQueue<ResolvedType> rq = new ReferenceQueue<ResolvedType>(); // private static Trace trace = TraceFactory.getTraceFactory().getTrace(World.TypeMap.class); TypeMap(World w) { // Demotion activated when switched on and loadtime weaving or in AJDT demotionSystemActive = w.isDemotionActive() && (w.isLoadtimeWeaving() || w.couldIncrementalCompileFollow()); addedSinceLastDemote = new ArrayList<String>(); writtenClasses = new ArrayList<String>(); this.w = w; memoryProfiling = false;// !w.getMessageHandler().isIgnoring(Message. // INFO); } // For testing public Map<String, Reference<ResolvedType>> getExpendableMap() { return expendableMap; } // For testing public Map<String, ResolvedType> getMainMap() { return tMap; } public int demote() { return demote(false); } /** * 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(boolean atEndOfCompile) { if (!demotionSystemActive) { return 0; } if (debugDemotion) { System.out.println("Demotion running " + addedSinceLastDemote); } boolean isLtw = w.isLoadtimeWeaving(); int demotionCounter = 0; if (isLtw) { // Loadtime weaving demotion strategy for (String key : addedSinceLastDemote) { ResolvedType type = tMap.get(key); if (type != null && !type.isAspect() && !type.equals(UnresolvedType.OBJECT) && !type.isPrimitiveType()) { if (type.isParameterizedOrRawType()) { type = type.getGenericType(); } List<ConcreteTypeMunger> typeMungers = type.getInterTypeMungers(); if (typeMungers == null || typeMungers.size() == 0) { tMap.remove(key); insertInExpendableMap(key, type); demotionCounter++; } } } addedSinceLastDemote.clear(); } else { // Compile time demotion strategy List<String> forRemoval = new ArrayList<String>(); for (String key : addedSinceLastDemote) { ResolvedType type = tMap.get(key); if (type == null) { // TODO not 100% sure why it is not there, where did it go? forRemoval.add(key); continue; } if (!writtenClasses.contains(type.getName())) { // COSTLY continue; } if (type != null && !type.isAspect() && !type.equals(UnresolvedType.OBJECT) && !type.isPrimitiveType()) { if (type.isParameterizedOrRawType()) { type = type.getGenericType(); } List<ConcreteTypeMunger> typeMungers = type.getInterTypeMungers(); if (typeMungers == null || typeMungers.size() == 0) { /* * if (type.isNested()) { try { ReferenceType rt = (ReferenceType) w.resolve(type.getOutermostType()); * if (!rt.isMissing()) { ReferenceTypeDelegate delegate = ((ReferenceType) type).getDelegate(); boolean * isWeavable = delegate == null ? false : delegate.isExposedToWeaver(); boolean hasBeenWoven = delegate * == null ? false : delegate.hasBeenWoven(); if (isWeavable && !hasBeenWoven) { // skip demotion of * this inner type for now continue; } } } catch (ClassCastException cce) { cce.printStackTrace(); * System.out.println("outer of " + key + " is not a reftype? " + type.getOutermostType()); // throw new * IllegalStateException(cce); } } */ ReferenceTypeDelegate delegate = ((ReferenceType) type).getDelegate(); boolean isWeavable = delegate == null ? false : delegate.isExposedToWeaver(); boolean hasBeenWoven = delegate == null ? false : delegate.hasBeenWoven(); if (!isWeavable || hasBeenWoven) { if (debugDemotion) { System.out.println("Demoting " + key); } forRemoval.add(key); tMap.remove(key); insertInExpendableMap(key, type); demotionCounter++; } } else { // no need to try this again, it will never be demoted writtenClasses.remove(type.getName()); forRemoval.add(key); } } else { writtenClasses.remove(type.getName()); // no need to try this again, it will never be demoted forRemoval.add(key); } } addedSinceLastDemote.removeAll(forRemoval); } if (debugDemotion) { System.out.println("Demoted " + demotionCounter + " types. Types remaining in fixed set #" + tMap.keySet().size() + ". addedSinceLastDemote size is " + addedSinceLastDemote.size()); System.out.println("writtenClasses.size() = " + writtenClasses.size() + ": " + writtenClasses); } if (atEndOfCompile) { if (debugDemotion) { System.out.println("Clearing writtenClasses"); } writtenClasses.clear(); } return demotionCounter; } private void insertInExpendableMap(String key, ResolvedType type) { if (useExpendableMap) { if (!expendableMap.containsKey(key)) { if (policy == USE_SOFT_REFS) { expendableMap.put(key, new SoftReference<ResolvedType>(type)); } else { expendableMap.put(key, new WeakReference<ResolvedType>(type)); } } } } /** * 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.isCacheable()) { return 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; } // TODO should this be in as a permanent assertion? /* * if ((type instanceof ReferenceType) && type.getWorld().isInJava5Mode() && (((ReferenceType) type).getDelegate() != * null) && type.isGenericType()) { throw new BCException("Attempt to add generic type to typemap " + type.toString() + * " (should be raw)"); } */ if (w.isExpendable(type)) { if (useExpendableMap) { // Dont use reference queue for tracking if not profiling... if (policy == USE_WEAK_REFS) { if (memoryProfiling) { expendableMap.put(key, new WeakReference<ResolvedType>(type, rq)); } else { expendableMap.put(key, new WeakReference<ResolvedType>(type)); } } else if (policy == USE_SOFT_REFS) { if (memoryProfiling) { expendableMap.put(key, new SoftReference<ResolvedType>(type, rq)); } else { expendableMap.put(key, new SoftReference<ResolvedType>(type)); } // } else { // expendableMap.put(key, type); } } if (memoryProfiling && expendableMap.size() > maxExpendableMapSize) { maxExpendableMapSize = expendableMap.size(); } return type; } else { if (demotionSystemActive) { // System.out.println("Added since last demote " + key); addedSinceLastDemote.add(key); } return 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 = tMap.get(key); if (ret == null) { if (policy == USE_WEAK_REFS) { WeakReference<ResolvedType> ref = (WeakReference<ResolvedType>) expendableMap.get(key); if (ref != null) { ret = ref.get(); } } else if (policy == USE_SOFT_REFS) { SoftReference<ResolvedType> ref = (SoftReference<ResolvedType>) expendableMap.get(key); if (ref != null) { ret = ref.get(); } // } else { // return (ResolvedType) expendableMap.get(key); } } return ret; } /** Remove a type from the map */ public ResolvedType remove(String key) { ResolvedType ret = tMap.remove(key); if (ret == null) { if (policy == USE_WEAK_REFS) { WeakReference<ResolvedType> wref = (WeakReference<ResolvedType>) expendableMap.remove(key); if (wref != null) { ret = wref.get(); } } else if (policy == USE_SOFT_REFS) { SoftReference<ResolvedType> wref = (SoftReference<ResolvedType>) expendableMap.remove(key); if (wref != null) { ret = wref.get(); } // } else { // ret = (ResolvedType) expendableMap.remove(key); } } return ret; } public void classWriteEvent(String classname) { // that is a name com.Foo and not a signature Lcom/Foo; boooooooooo! if (demotionSystemActive) { writtenClasses.add(classname); } if (debugDemotion) { System.out.println("Class write event for " + classname); } } // 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<PrecedenceCacheKey, Integer> cachedResults; public AspectPrecedenceCalculator(World forSomeWorld) { world = forSomeWorld; cachedResults = new HashMap<PrecedenceCacheKey, Integer>(); } /** * 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 (cachedResults.get(key)).intValue(); } else { int order = 0; DeclarePrecedence orderer = null; // Records the declare // precedence statement that // gives the first ordering for (Iterator<Declare> 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 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; } @Override public boolean equals(Object obj) { if (!(obj instanceof PrecedenceCacheKey)) { return false; } PrecedenceCacheKey other = (PrecedenceCacheKey) obj; return (aspect1 == other.aspect1 && aspect2 == other.aspect2); } @Override 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) --- public boolean isDemotionActive() { return false; } // --- 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<Class<?>, TypeVariable[]> workInProgress1 = new HashMap<Class<?>, TypeVariable[]>(); public TypeVariable[] getTypeVariablesCurrentlyBeingProcessed(Class<?> baseClass) { return 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")); } // ITD Versions // 1 is the first version in use up to AspectJ 1.6.8 // 2 is from 1.6.9 onwards s = p.getProperty(xsetITD_VERSION, xsetITD_VERSION_DEFAULT); if (s.equals(xsetITD_VERSION_ORIGINAL)) { itdVersion = 1; } s = p.getProperty(xsetMINIMAL_MODEL, "false"); if (s.equalsIgnoreCase("true")) { minimalModel = true; } s = p.getProperty(xsetTARGETING_RUNTIME_1610, "false"); if (s.equalsIgnoreCase("true")) { targettingRuntime1_6_10 = true; } 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); // default is: ON (for ltw) OFF (for ctw) if (s != null) { boolean b = typeMap.demotionSystemActive; if (b && s.equalsIgnoreCase("false")) { System.out.println("typeDemotion=false: type demotion switched OFF"); typeMap.demotionSystemActive = false; } else if (!b && s.equalsIgnoreCase("true")) { System.out.println("typeDemotion=true: type demotion switched ON"); typeMap.demotionSystemActive = true; } } s = p.getProperty(xsetOVERWEAVING, "false"); if (s.equalsIgnoreCase("true")) { overWeaving = true; } s = p.getProperty(xsetTYPE_DEMOTION_DEBUG, "false"); if (s.equalsIgnoreCase("true")) { typeMap.debugDemotion = true; } s = p.getProperty(xsetTYPE_REFS, "true"); if (s.equalsIgnoreCase("false")) { typeMap.policy = TypeMap.USE_SOFT_REFS; } runMinimalMemorySet = p.getProperty(xsetRUN_MINIMAL_MEMORY) != null; 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"); s = p.getProperty(xsetOPTIMIZED_MATCHING, "true"); optimizedMatching = s.equalsIgnoreCase("true"); if (!optimizedMatching) { getMessageHandler().handleMessage(MessageUtil.info("[optimizedMatching=false] optimized matching turned off")); } s = p.getProperty(xsetTIMERS_PER_JOINPOINT, "25000"); try { timersPerJoinpoint = Integer.parseInt(s); } catch (Exception e) { getMessageHandler().handleMessage(MessageUtil.error("unable to process timersPerJoinpoint value of " + s)); timersPerJoinpoint = 25000; } s = p.getProperty(xsetTIMERS_PER_FASTMATCH_CALL, "250"); try { timersPerType = Integer.parseInt(s); } catch (Exception e) { getMessageHandler().handleMessage(MessageUtil.error("unable to process timersPerType value of " + s)); timersPerType = 250; } } try { String value = System.getProperty("aspectj.overweaving", "false"); if (value.equalsIgnoreCase("true")) { System.out.println("ASPECTJ: aspectj.overweaving=true: overweaving switched ON"); overWeaving = true; } value = System.getProperty("aspectj.typeDemotion", "false"); if (value.equalsIgnoreCase("true")) { System.out.println("ASPECTJ: aspectj.typeDemotion=true: type demotion switched ON"); typeMap.demotionSystemActive = true; } value = System.getProperty("aspectj.minimalModel", "false"); if (value.equalsIgnoreCase("true")) { System.out.println("ASPECTJ: aspectj.minimalModel=true: minimal model switched ON"); minimalModel = true; } } catch (Throwable t) { System.err.println("ASPECTJ: Unable to read system properties"); t.printStackTrace(); } checkedAdvancedConfiguration = true; } } public boolean isRunMinimalMemory() { ensureAdvancedConfigurationProcessed(); return runMinimalMemory; } public boolean isRunMinimalMemorySet() { ensureAdvancedConfigurationProcessed(); return runMinimalMemorySet; } 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<PointcutDesignatorHandler>(); } pointcutDesignators.add(designatorHandler); } public Set<PointcutDesignatorHandler> getRegisteredPointcutHandlers() { if (pointcutDesignators == null) { return Collections.emptySet(); } return pointcutDesignators; } public void reportMatch(ShadowMunger munger, Shadow shadow) { } public boolean isOverWeaving() { return overWeaving; } 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; } /** * Determine if the named aspect requires a particular type around in order to be useful. The type is named in the aop.xml file * against the aspect. * * @return true if there is a type missing that this aspect really needed around */ public boolean hasUnsatisfiedDependency(ResolvedType aspectType) { return false; } public TypePattern getAspectScope(ResolvedType declaringType) { return null; } public Map<String, ResolvedType> getFixed() { return typeMap.tMap; } public Map<String, Reference<ResolvedType>> 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())); } // map from aspect > excluded types // memory issue here? private Map<ResolvedType, Set<ResolvedType>> exclusionMap = new HashMap<ResolvedType, Set<ResolvedType>>(); public Map<ResolvedType, Set<ResolvedType>> getExclusionMap() { return exclusionMap; } private TimeCollector timeCollector = null; /** * Record the time spent matching a pointcut - this will accumulate over the lifetime of this world/weaver and be reported every * 25000 join points. */ public void record(Pointcut pointcut, long timetaken) { if (timeCollector == null) { ensureAdvancedConfigurationProcessed(); timeCollector = new TimeCollector(this); } timeCollector.record(pointcut, timetaken); } /** * Record the time spent fastmatching a pointcut - this will accumulate over the lifetime of this world/weaver and be reported * every 250 types. */ public void recordFastMatch(Pointcut pointcut, long timetaken) { if (timeCollector == null) { ensureAdvancedConfigurationProcessed(); timeCollector = new TimeCollector(this); } timeCollector.recordFastMatch(pointcut, timetaken); } public void reportTimers() { if (timeCollector != null && !timingPeriodically) { timeCollector.report(); timeCollector = new TimeCollector(this); } } private static class TimeCollector { private World world; long joinpointCount; long typeCount; long perJoinpointCount; long perTypes; Map<String, Long> joinpointsPerPointcut = new HashMap<String, Long>(); Map<String, Long> timePerPointcut = new HashMap<String, Long>(); Map<String, Long> fastMatchTimesPerPointcut = new HashMap<String, Long>(); Map<String, Long> fastMatchTypesPerPointcut = new HashMap<String, Long>(); TimeCollector(World world) { this.perJoinpointCount = world.timersPerJoinpoint; this.perTypes = world.timersPerType; this.world = world; this.joinpointCount = 0; this.typeCount = 0; this.joinpointsPerPointcut = new HashMap<String, Long>(); this.timePerPointcut = new HashMap<String, Long>(); } public void report() { long totalTime = 0L; for (String p : joinpointsPerPointcut.keySet()) { totalTime += timePerPointcut.get(p); } world.getMessageHandler().handleMessage( MessageUtil.info("Pointcut matching cost (total=" + (totalTime / 1000000) + "ms for " + joinpointCount + " joinpoint match calls):")); for (String p : joinpointsPerPointcut.keySet()) { StringBuffer sb = new StringBuffer(); sb.append("Time:" + (timePerPointcut.get(p) / 1000000) + "ms (jps:#" + joinpointsPerPointcut.get(p) + ") matching against " + p); world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString())); } world.getMessageHandler().handleMessage(MessageUtil.info("---")); totalTime = 0L; for (String p : fastMatchTimesPerPointcut.keySet()) { totalTime += fastMatchTimesPerPointcut.get(p); } world.getMessageHandler().handleMessage( MessageUtil.info("Pointcut fast matching cost (total=" + (totalTime / 1000000) + "ms for " + typeCount + " fast match calls):")); for (String p : fastMatchTimesPerPointcut.keySet()) { StringBuffer sb = new StringBuffer(); sb.append("Time:" + (fastMatchTimesPerPointcut.get(p) / 1000000) + "ms (types:#" + fastMatchTypesPerPointcut.get(p) + ") fast matching against " + p); world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString())); } world.getMessageHandler().handleMessage(MessageUtil.info("---")); } void record(Pointcut pointcut, long timetakenInNs) { joinpointCount++; String pointcutText = pointcut.toString(); Long jpcounter = joinpointsPerPointcut.get(pointcutText); if (jpcounter == null) { jpcounter = 1L; } else { jpcounter++; } joinpointsPerPointcut.put(pointcutText, jpcounter); Long time = timePerPointcut.get(pointcutText); if (time == null) { time = timetakenInNs; } else { time += timetakenInNs; } timePerPointcut.put(pointcutText, time); if (world.timingPeriodically) { if ((joinpointCount % perJoinpointCount) == 0) { long totalTime = 0L; for (String p : joinpointsPerPointcut.keySet()) { totalTime += timePerPointcut.get(p); } world.getMessageHandler().handleMessage( MessageUtil.info("Pointcut matching cost (total=" + (totalTime / 1000000) + "ms for " + joinpointCount + " joinpoint match calls):")); for (String p : joinpointsPerPointcut.keySet()) { StringBuffer sb = new StringBuffer(); sb.append("Time:" + (timePerPointcut.get(p) / 1000000) + "ms (jps:#" + joinpointsPerPointcut.get(p) + ") matching against " + p); world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString())); } world.getMessageHandler().handleMessage(MessageUtil.info("---")); } } } void recordFastMatch(Pointcut pointcut, long timetakenInNs) { typeCount++; String pointcutText = pointcut.toString(); Long typecounter = fastMatchTypesPerPointcut.get(pointcutText); if (typecounter == null) { typecounter = 1L; } else { typecounter++; } fastMatchTypesPerPointcut.put(pointcutText, typecounter); Long time = fastMatchTimesPerPointcut.get(pointcutText); if (time == null) { time = timetakenInNs; } else { time += timetakenInNs; } fastMatchTimesPerPointcut.put(pointcutText, time); if (world.timingPeriodically) { if ((typeCount % perTypes) == 0) { long totalTime = 0L; for (String p : fastMatchTimesPerPointcut.keySet()) { totalTime += fastMatchTimesPerPointcut.get(p); } world.getMessageHandler().handleMessage( MessageUtil.info("Pointcut fast matching cost (total=" + (totalTime / 1000000) + "ms for " + typeCount + " fast match calls):")); for (String p : fastMatchTimesPerPointcut.keySet()) { StringBuffer sb = new StringBuffer(); sb.append("Time:" + (fastMatchTimesPerPointcut.get(p) / 1000000) + "ms (types:#" + fastMatchTypesPerPointcut.get(p) + ") fast matching against " + p); world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString())); } world.getMessageHandler().handleMessage(MessageUtil.info("---")); } } } } public TypeMap getTypeMap() { return typeMap; } public static void reset() { ResolvedType.resetPrimitives(); } /** * Returns the version of ITD that this world wants to create. The default is the new style (2) but in some cases where there * might be a clash, the old style can be used. It is set through the option -Xset:itdVersion=1 * * @return the ITD version this world wants to create - 1=oldstyle 2=new, transparent style */ public int getItdVersion() { return itdVersion; } // if not loadtime weaving then we are compile time weaving or post-compile time weaving public abstract boolean isLoadtimeWeaving(); public void classWriteEvent(char[][] compoundName) { // override if interested in write events } }
323,634
Bug 323634 NPE parameterizing perclause
java.lang.NullPointerException at org.aspectj.weaver.ReferenceType.getPerClause(ReferenceType.java:823) at org.aspectj.weaver.patterns.PerFromSuper.lookupConcretePerClause(PerFromSuper.java:82) at org.aspectj.weaver.patterns.PerFromSuper.concretize(PerFromSuper.java:61) at org.aspectj.weaver.CrosscuttingMembers.setPerClause(CrosscuttingMembers.java:512) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers(ResolvedType.java:748) ... oBuildJob.run(AutoBuildJob.java:242) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
resolved fixed
ce16a06
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-08-25T16:41:33Z"
"2010-08-25T15:26:40Z"
org.aspectj.matcher/src/org/aspectj/weaver/ReferenceType.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 * Andy Clement - June 2005 - separated out from ResolvedType * ******************************************************************/ package org.aspectj.weaver; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.PerClause; /** * A reference type represents some 'real' type, not a primitive, not an array - but a real type, for example java.util.List. Each * ReferenceType has a delegate that is the underlying artifact - either an eclipse artifact or a bcel artifact. If the type * represents a raw type (i.e. there is a generic form) then the genericType field is set to point to the generic type. If it is for * a parameterized type then the generic type is also set to point to the generic form. */ public class ReferenceType extends ResolvedType { public static final ReferenceType[] EMPTY_ARRAY = new ReferenceType[0]; /** * For generic types, this list holds references to all the derived raw and parameterized versions. We need this so that if the * generic delegate is swapped during incremental compilation, the delegate of the derivatives is swapped also. */ private final List<ReferenceType> derivativeTypes = new ArrayList<ReferenceType>(); /** * For parameterized types (or the raw type) - this field points to the actual reference type from which they are derived. */ ReferenceType genericType = null; ReferenceTypeDelegate delegate = null; int startPos = 0; int endPos = 0; // cached values for members ResolvedMember[] parameterizedMethods = null; ResolvedMember[] parameterizedFields = null; ResolvedMember[] parameterizedPointcuts = null; WeakReference<ResolvedType[]> parameterizedInterfaces = new WeakReference<ResolvedType[]>(null); Collection<Declare> parameterizedDeclares = null; // Collection parameterizedTypeMungers = null; // During matching it can be necessary to temporary mark types as annotated. For example // a declare @type may trigger a separate declare parents to match, and so the annotation // is temporarily held against the referencetype, the annotation will be properly // added to the class during weaving. private ResolvedType[] annotationTypes = null; private AnnotationAJ[] annotations = null; // Similarly these are temporary replacements and additions for the superclass and // superinterfaces private ResolvedType newSuperclass; private ResolvedType[] newInterfaces; // ??? should set delegate before any use public ReferenceType(String signature, World world) { super(signature, world); } public ReferenceType(String signature, String signatureErasure, World world) { super(signature, signatureErasure, world); } public static ReferenceType fromTypeX(UnresolvedType tx, World world) { ReferenceType rt = new ReferenceType(tx.getErasureSignature(), world); rt.typeKind = tx.typeKind; return rt; } /** * Constructor used when creating a parameterized type. */ public ReferenceType(ResolvedType theGenericType, ResolvedType[] theParameters, World aWorld) { super(makeParameterizedSignature(theGenericType, theParameters), theGenericType.signatureErasure, aWorld); ReferenceType genericReferenceType = (ReferenceType) theGenericType; this.typeParameters = theParameters; this.genericType = genericReferenceType; this.typeKind = TypeKind.PARAMETERIZED; this.delegate = genericReferenceType.getDelegate(); genericReferenceType.addDependentType(this); } /** * Constructor used when creating a raw type. */ // public ReferenceType( // ResolvedType theGenericType, // World aWorld) { // super(theGenericType.getErasureSignature(), // theGenericType.getErasureSignature(), // aWorld); // ReferenceType genericReferenceType = (ReferenceType) theGenericType; // this.typeParameters = null; // this.genericType = genericReferenceType; // this.typeKind = TypeKind.RAW; // this.delegate = genericReferenceType.getDelegate(); // genericReferenceType.addDependentType(this); // } private void addDependentType(ReferenceType dependent) { this.derivativeTypes.add(dependent); } @Override public String getSignatureForAttribute() { if (genericType == null || typeParameters == null) { return getSignature(); } return makeDeclaredSignature(genericType, typeParameters); } /** * Create a reference type for a generic type */ public ReferenceType(UnresolvedType genericType, World world) { super(genericType.getSignature(), world); typeKind = TypeKind.GENERIC; } @Override public boolean isClass() { return getDelegate().isClass(); } @Override public int getCompilerVersion() { return getDelegate().getCompilerVersion(); } @Override public boolean isGenericType() { return !isParameterizedType() && !isRawType() && getDelegate().isGeneric(); } public String getGenericSignature() { String sig = getDelegate().getDeclaredGenericSignature(); return (sig == null) ? "" : sig; } @Override public AnnotationAJ[] getAnnotations() { return getDelegate().getAnnotations(); } @Override public void addAnnotation(AnnotationAJ annotationX) { if (annotations == null) { annotations = new AnnotationAJ[1]; annotations[0] = annotationX; } else { AnnotationAJ[] newAnnotations = new AnnotationAJ[annotations.length + 1]; System.arraycopy(annotations, 0, newAnnotations, 1, annotations.length); newAnnotations[0] = annotationX; annotations = newAnnotations; } addAnnotationType(annotationX.getType()); } public boolean hasAnnotation(UnresolvedType ofType) { boolean onDelegate = getDelegate().hasAnnotation(ofType); if (onDelegate) { return true; } if (annotationTypes != null) { for (int i = 0; i < annotationTypes.length; i++) { if (annotationTypes[i].equals(ofType)) { return true; } } } return false; } private void addAnnotationType(ResolvedType ofType) { if (annotationTypes == null) { annotationTypes = new ResolvedType[1]; annotationTypes[0] = ofType; } else { ResolvedType[] newAnnotationTypes = new ResolvedType[annotationTypes.length + 1]; System.arraycopy(annotationTypes, 0, newAnnotationTypes, 1, annotationTypes.length); newAnnotationTypes[0] = ofType; annotationTypes = newAnnotationTypes; } } @Override public ResolvedType[] getAnnotationTypes() { if (getDelegate() == null) { throw new BCException("Unexpected null delegate for type " + this.getName()); } if (annotationTypes == null) { // there are no extras: return getDelegate().getAnnotationTypes(); } else { ResolvedType[] delegateAnnotationTypes = getDelegate().getAnnotationTypes(); ResolvedType[] result = new ResolvedType[annotationTypes.length + delegateAnnotationTypes.length]; System.arraycopy(delegateAnnotationTypes, 0, result, 0, delegateAnnotationTypes.length); System.arraycopy(annotationTypes, 0, result, delegateAnnotationTypes.length, annotationTypes.length); return result; } } @Override public String getNameAsIdentifier() { return getRawName().replace('.', '_'); } @Override public AnnotationAJ getAnnotationOfType(UnresolvedType ofType) { AnnotationAJ[] axs = getDelegate().getAnnotations(); if (axs == null) { if (annotations != null) { String searchSig = ofType.getSignature(); for (int i = 0; i < annotations.length; i++) { if (annotations[i].getTypeSignature().equals(searchSig)) { return annotations[i]; } } } return null; } for (int i = 0; i < axs.length; i++) { if (axs[i].getTypeSignature().equals(ofType.getSignature())) { return axs[i]; } } return null; } @Override public boolean isAspect() { return getDelegate().isAspect(); } @Override public boolean isAnnotationStyleAspect() { return getDelegate().isAnnotationStyleAspect(); } @Override public boolean isEnum() { return getDelegate().isEnum(); } @Override public boolean isAnnotation() { return getDelegate().isAnnotation(); } @Override public boolean isAnonymous() { return getDelegate().isAnonymous(); } @Override public boolean isNested() { return getDelegate().isNested(); } public ResolvedType getOuterClass() { return getDelegate().getOuterClass(); } public String getRetentionPolicy() { return getDelegate().getRetentionPolicy(); } @Override public boolean isAnnotationWithRuntimeRetention() { return getDelegate().isAnnotationWithRuntimeRetention(); } @Override public boolean canAnnotationTargetType() { return getDelegate().canAnnotationTargetType(); } @Override public AnnotationTargetKind[] getAnnotationTargetKinds() { return getDelegate().getAnnotationTargetKinds(); } // true iff the statement "this = (ThisType) other" would compile @Override public boolean isCoerceableFrom(ResolvedType o) { ResolvedType other = o.resolve(world); if (this.isAssignableFrom(other) || other.isAssignableFrom(this)) { return true; } if (this.isParameterizedType() && other.isParameterizedType()) { return isCoerceableFromParameterizedType(other); } if (this.isParameterizedType() && other.isRawType()) { return ((ReferenceType) this.getRawType()).isCoerceableFrom(other.getGenericType()); } if (this.isRawType() && other.isParameterizedType()) { return this.getGenericType().isCoerceableFrom((other.getRawType())); } if (!this.isInterface() && !other.isInterface()) { return false; } if (this.isFinal() || other.isFinal()) { return false; } // ??? needs to be Methods, not just declared methods? JLS 5.5 unclear ResolvedMember[] a = getDeclaredMethods(); ResolvedMember[] b = other.getDeclaredMethods(); // ??? is this cast // always safe for (int ai = 0, alen = a.length; ai < alen; ai++) { for (int bi = 0, blen = b.length; bi < blen; bi++) { if (!b[bi].isCompatibleWith(a[ai])) { return false; } } } return true; } private final boolean isCoerceableFromParameterizedType(ResolvedType other) { if (!other.isParameterizedType()) { return false; } ResolvedType myRawType = getRawType(); ResolvedType theirRawType = other.getRawType(); if (myRawType == theirRawType || myRawType.isCoerceableFrom(theirRawType)) { if (getTypeParameters().length == other.getTypeParameters().length) { // there's a chance it can be done ResolvedType[] myTypeParameters = getResolvedTypeParameters(); ResolvedType[] theirTypeParameters = other.getResolvedTypeParameters(); for (int i = 0; i < myTypeParameters.length; i++) { if (myTypeParameters[i] != theirTypeParameters[i]) { // thin ice now... but List<String> may still be // coerceable from e.g. List<T> if (myTypeParameters[i].isGenericWildcard()) { BoundedReferenceType wildcard = (BoundedReferenceType) myTypeParameters[i]; if (!wildcard.canBeCoercedTo(theirTypeParameters[i])) { return false; } } else if (myTypeParameters[i].isTypeVariableReference()) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) myTypeParameters[i]; TypeVariable tv = tvrt.getTypeVariable(); tv.resolve(world); if (!tv.canBeBoundTo(theirTypeParameters[i])) { return false; } } else if (theirTypeParameters[i].isTypeVariableReference()) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) theirTypeParameters[i]; TypeVariable tv = tvrt.getTypeVariable(); tv.resolve(world); if (!tv.canBeBoundTo(myTypeParameters[i])) { return false; } } else if (theirTypeParameters[i].isGenericWildcard()) { BoundedReferenceType wildcard = (BoundedReferenceType) theirTypeParameters[i]; if (!wildcard.canBeCoercedTo(myTypeParameters[i])) { return false; } } else { return false; } } } return true; } // } else { // // we do this walk for situations like the following: // // Base<T>, Sub<S,T> extends Base<S> // // is Sub<Y,Z> coerceable from Base<X> ??? // for (Iterator i = getDirectSupertypes(); i.hasNext();) { // ReferenceType parent = (ReferenceType) i.next(); // if (parent.isCoerceableFromParameterizedType(other)) // return true; // } } return false; } @Override public boolean isAssignableFrom(ResolvedType other) { return isAssignableFrom(other, false); } // TODO rewrite this method - it is a terrible mess // true iff the statement "this = other" would compile. @Override public boolean isAssignableFrom(ResolvedType other, boolean allowMissing) { if (other.isPrimitiveType()) { if (!world.isInJava5Mode()) { return false; } if (ResolvedType.validBoxing.contains(this.getSignature() + other.getSignature())) { return true; } } if (this == other) { return true; } if (this.getSignature().equals("Ljava/lang/Object;")) { return true; } if (!isTypeVariableReference() && other.getSignature().equals("Ljava/lang/Object;")) { return false; } boolean thisRaw = this.isRawType(); if (thisRaw && other.isParameterizedOrGenericType()) { return isAssignableFrom(other.getRawType()); } boolean thisGeneric = this.isGenericType(); if (thisGeneric && other.isParameterizedOrRawType()) { return isAssignableFrom(other.getGenericType()); } if (this.isParameterizedType()) { // look at wildcards... if (((ReferenceType) this.getRawType()).isAssignableFrom(other)) { boolean wildcardsAllTheWay = true; ResolvedType[] myParameters = this.getResolvedTypeParameters(); for (int i = 0; i < myParameters.length; i++) { if (!myParameters[i].isGenericWildcard()) { wildcardsAllTheWay = false; } else { BoundedReferenceType boundedRT = (BoundedReferenceType) myParameters[i]; if (boundedRT.isExtends() || boundedRT.isSuper()) { wildcardsAllTheWay = false; } } } if (wildcardsAllTheWay && !other.isParameterizedType()) { return true; } // we have to match by parameters one at a time ResolvedType[] theirParameters = other.getResolvedTypeParameters(); boolean parametersAssignable = true; if (myParameters.length == theirParameters.length) { for (int i = 0; i < myParameters.length && parametersAssignable; i++) { if (myParameters[i] == theirParameters[i]) { continue; } // dont do this: pr253109 // if (myParameters[i].isAssignableFrom(theirParameters[i], allowMissing)) { // continue; // } ResolvedType mp = myParameters[i]; ResolvedType tp = theirParameters[i]; if (mp.isParameterizedType() && tp.isParameterizedType()) { if (mp.getGenericType().equals(tp.getGenericType())) { UnresolvedType[] mtps = mp.getTypeParameters(); UnresolvedType[] ttps = tp.getTypeParameters(); for (int ii = 0; ii < mtps.length; ii++) { if (mtps[ii].isTypeVariableReference() && ttps[ii].isTypeVariableReference()) { TypeVariable mtv = ((TypeVariableReferenceType) mtps[ii]).getTypeVariable(); boolean b = mtv.canBeBoundTo((ResolvedType) ttps[ii]); if (!b) {// TODO incomplete testing here I think parametersAssignable = false; break; } } else { parametersAssignable = false; break; } } continue; } else { parametersAssignable = false; break; } } if (myParameters[i].isTypeVariableReference() && theirParameters[i].isTypeVariableReference()) { TypeVariable myTV = ((TypeVariableReferenceType) myParameters[i]).getTypeVariable(); // TypeVariable theirTV = ((TypeVariableReferenceType) theirParameters[i]).getTypeVariable(); boolean b = myTV.canBeBoundTo(theirParameters[i]); if (!b) {// TODO incomplete testing here I think parametersAssignable = false; break; } else { continue; } } if (!myParameters[i].isGenericWildcard()) { parametersAssignable = false; break; } else { BoundedReferenceType wildcardType = (BoundedReferenceType) myParameters[i]; if (!wildcardType.alwaysMatches(theirParameters[i])) { parametersAssignable = false; break; } } } } else { parametersAssignable = false; } if (parametersAssignable) { return true; } } } // eg this=T other=Ljava/lang/Object; if (isTypeVariableReference() && !other.isTypeVariableReference()) { TypeVariable aVar = ((TypeVariableReference) this).getTypeVariable(); return aVar.resolve(world).canBeBoundTo(other); } if (other.isTypeVariableReference()) { TypeVariableReferenceType otherType = (TypeVariableReferenceType) other; if (this instanceof TypeVariableReference) { return ((TypeVariableReference) this).getTypeVariable().resolve(world) .canBeBoundTo(otherType.getTypeVariable().getFirstBound().resolve(world));// pr171952 // return // ((TypeVariableReference)this).getTypeVariable()==otherType // .getTypeVariable(); } else { // FIXME asc should this say canBeBoundTo?? return this.isAssignableFrom(otherType.getTypeVariable().getFirstBound().resolve(world)); } } if (allowMissing && other.isMissing()) { return false; } ResolvedType[] interfaces = other.getDeclaredInterfaces(); for (ResolvedType intface : interfaces) { boolean b; if (thisRaw && intface.isParameterizedOrGenericType()) { b = this.isAssignableFrom(intface.getRawType(), allowMissing); } else { b = this.isAssignableFrom(intface, allowMissing); } if (b) { return true; } } ResolvedType superclass = other.getSuperclass(); if (superclass != null) { boolean b; if (thisRaw && superclass.isParameterizedOrGenericType()) { b = this.isAssignableFrom(superclass.getRawType(), allowMissing); } else { b = this.isAssignableFrom(superclass, allowMissing); } if (b) { return true; } } return false; } @Override public ISourceContext getSourceContext() { return getDelegate().getSourceContext(); } @Override public ISourceLocation getSourceLocation() { ISourceContext isc = getDelegate().getSourceContext(); return isc.makeSourceLocation(new Position(startPos, endPos)); } @Override public boolean isExposedToWeaver() { return (getDelegate() == null) || delegate.isExposedToWeaver(); } @Override public WeaverStateInfo getWeaverState() { return getDelegate().getWeaverState(); } @Override public ResolvedMember[] getDeclaredFields() { if (parameterizedFields != null) { return parameterizedFields; } if (isParameterizedType() || isRawType()) { ResolvedMember[] delegateFields = getDelegate().getDeclaredFields(); parameterizedFields = new ResolvedMember[delegateFields.length]; for (int i = 0; i < delegateFields.length; i++) { parameterizedFields[i] = delegateFields[i].parameterizedWith(getTypesForMemberParameterization(), this, isParameterizedType()); } return parameterizedFields; } else { return getDelegate().getDeclaredFields(); } } /** * Find out from the generic signature the true signature of any interfaces I implement. If I am parameterized, these may then * need to be parameterized before returning. */ @Override public ResolvedType[] getDeclaredInterfaces() { ResolvedType[] interfaces = parameterizedInterfaces.get(); if (interfaces != null) { return interfaces; } ResolvedType[] delegateInterfaces = getDelegate().getDeclaredInterfaces(); if (newInterfaces != null) { // OPTIMIZE does this part of the method trigger often? ResolvedType[] extraInterfaces = new ResolvedType[delegateInterfaces.length + newInterfaces.length]; System.arraycopy(delegateInterfaces, 0, extraInterfaces, 0, delegateInterfaces.length); System.arraycopy(newInterfaces, 0, extraInterfaces, delegateInterfaces.length, newInterfaces.length); delegateInterfaces = extraInterfaces; } if (isParameterizedType()) { // UnresolvedType[] paramTypes = // getTypesForMemberParameterization(); interfaces = new ResolvedType[delegateInterfaces.length]; for (int i = 0; i < delegateInterfaces.length; i++) { // We may have to sub/super set the set of parametertypes if the // implemented interface // needs more or less than this type does. (pr124803/pr125080) if (delegateInterfaces[i].isParameterizedType()) { interfaces[i] = delegateInterfaces[i].parameterize(getMemberParameterizationMap()).resolve(world); } else { interfaces[i] = delegateInterfaces[i]; } } parameterizedInterfaces = new WeakReference<ResolvedType[]>(interfaces); return interfaces; } else if (isRawType()) { UnresolvedType[] paramTypes = getTypesForMemberParameterization(); interfaces = new ResolvedType[delegateInterfaces.length]; for (int i = 0, max = interfaces.length; i < max; i++) { interfaces[i] = delegateInterfaces[i]; if (interfaces[i].isGenericType()) { // a generic supertype of a raw type is replaced by its raw // equivalent interfaces[i] = interfaces[i].getRawType().resolve(getWorld()); } else if (interfaces[i].isParameterizedType()) { // a parameterized supertype collapses any type vars to // their upper bounds UnresolvedType[] toUseForParameterization = determineThoseTypesToUse(interfaces[i], paramTypes); interfaces[i] = interfaces[i].parameterizedWith(toUseForParameterization); } } parameterizedInterfaces = new WeakReference<ResolvedType[]>(interfaces); return interfaces; } if (getDelegate().isCacheable()) { parameterizedInterfaces = new WeakReference<ResolvedType[]>(delegateInterfaces); } return delegateInterfaces; } // private String toString(ResolvedType[] delegateInterfaces) { // StringBuffer sb = new StringBuffer(); // if (delegateInterfaces != null) { // for (ResolvedType rt : delegateInterfaces) { // sb.append(rt).append(" "); // } // } // return sb.toString(); // } /** * Locates the named type variable in the list of those on this generic type and returns the type parameter from the second list * supplied. Returns null if it can't be found */ // private UnresolvedType findTypeParameterInList(String name, // TypeVariable[] tvarsOnThisGenericType, UnresolvedType[] // paramTypes) { // int position = -1; // for (int i = 0; i < tvarsOnThisGenericType.length; i++) { // TypeVariable tv = tvarsOnThisGenericType[i]; // if (tv.getName().equals(name)) position = i; // } // if (position == -1 ) return null; // return paramTypes[position]; // } /** * It is possible this type has multiple type variables but the interface we are about to parameterize only uses a subset - this * method determines the subset to use by looking at the type variable names used. For example: <code> * class Foo<T extends String,E extends Number> implements SuperInterface<T> {} * </code> where <code> * interface SuperInterface<Z> {} * </code> In that example, a use of the 'Foo' raw type should know that it implements the SuperInterface<String>. */ private UnresolvedType[] determineThoseTypesToUse(ResolvedType parameterizedInterface, UnresolvedType[] paramTypes) { // What are the type parameters for the supertype? UnresolvedType[] tParms = parameterizedInterface.getTypeParameters(); UnresolvedType[] retVal = new UnresolvedType[tParms.length]; // Go through the supertypes type parameters, if any of them is a type // variable, use the // real type variable on the declaring type. // it is possibly overkill to look up the type variable - ideally the // entry in the type parameter list for the // interface should be the a ref to the type variable in the current // type ... but I'm not 100% confident right now. for (int i = 0; i < tParms.length; i++) { UnresolvedType tParm = tParms[i]; if (tParm.isTypeVariableReference()) { TypeVariableReference tvrt = (TypeVariableReference) tParm; TypeVariable tv = tvrt.getTypeVariable(); int rank = getRank(tv.getName()); // -1 probably means it is a reference to a type variable on the // outer generic type (see pr129566) if (rank != -1) { retVal[i] = paramTypes[rank]; } else { retVal[i] = tParms[i]; } } else { retVal[i] = tParms[i]; } } return retVal; } /** * Returns the position within the set of type variables for this type for the specified type variable name. Returns -1 if there * is no type variable with the specified name. */ private int getRank(String tvname) { TypeVariable[] thisTypesTVars = getGenericType().getTypeVariables(); for (int i = 0; i < thisTypesTVars.length; i++) { TypeVariable tv = thisTypesTVars[i]; if (tv.getName().equals(tvname)) { return i; } } return -1; } @Override public ResolvedMember[] getDeclaredMethods() { if (parameterizedMethods != null) { return parameterizedMethods; } if (isParameterizedType() || isRawType()) { ResolvedMember[] delegateMethods = getDelegate().getDeclaredMethods(); UnresolvedType[] parameters = getTypesForMemberParameterization(); parameterizedMethods = new ResolvedMember[delegateMethods.length]; for (int i = 0; i < delegateMethods.length; i++) { parameterizedMethods[i] = delegateMethods[i].parameterizedWith(parameters, this, isParameterizedType()); } return parameterizedMethods; } else { return getDelegate().getDeclaredMethods(); } } @Override public ResolvedMember[] getDeclaredPointcuts() { if (parameterizedPointcuts != null) { return parameterizedPointcuts; } if (isParameterizedType()) { ResolvedMember[] delegatePointcuts = getDelegate().getDeclaredPointcuts(); parameterizedPointcuts = new ResolvedMember[delegatePointcuts.length]; for (int i = 0; i < delegatePointcuts.length; i++) { parameterizedPointcuts[i] = delegatePointcuts[i].parameterizedWith(getTypesForMemberParameterization(), this, isParameterizedType()); } return parameterizedPointcuts; } else { return getDelegate().getDeclaredPointcuts(); } } private UnresolvedType[] getTypesForMemberParameterization() { UnresolvedType[] parameters = null; if (isParameterizedType()) { parameters = getTypeParameters(); } else if (isRawType()) { // raw type, use upper bounds of type variables on generic type TypeVariable[] tvs = getGenericType().getTypeVariables(); parameters = new UnresolvedType[tvs.length]; for (int i = 0; i < tvs.length; i++) { parameters[i] = tvs[i].getFirstBound(); } } return parameters; } @Override public TypeVariable[] getTypeVariables() { if (this.typeVariables == null) { this.typeVariables = getDelegate().getTypeVariables(); for (int i = 0; i < this.typeVariables.length; i++) { this.typeVariables[i].resolve(world); } } return this.typeVariables; } @Override public PerClause getPerClause() { PerClause pclause = getDelegate().getPerClause(); if (isParameterizedType()) { // could cache the result here... Map<String, UnresolvedType> parameterizationMap = getAjMemberParameterizationMap(); pclause = (PerClause) pclause.parameterizeWith(parameterizationMap, world); } return pclause; } @Override public Collection<Declare> getDeclares() { if (parameterizedDeclares != null) { return parameterizedDeclares; } Collection<Declare> declares = null; if (ajMembersNeedParameterization()) { Collection<Declare> genericDeclares = getDelegate().getDeclares(); parameterizedDeclares = new ArrayList<Declare>(); Map<String, UnresolvedType> parameterizationMap = getAjMemberParameterizationMap(); for (Declare declareStatement : genericDeclares) { parameterizedDeclares.add(declareStatement.parameterizeWith(parameterizationMap, world)); } declares = parameterizedDeclares; } else { declares = getDelegate().getDeclares(); } for (Declare d : declares) { d.setDeclaringType(this); } return declares; } @Override public Collection<ConcreteTypeMunger> getTypeMungers() { return getDelegate().getTypeMungers(); } // GENERICITDFIX // // Map parameterizationMap = getAjMemberParameterizationMap(); // // // if (parameterizedTypeMungers != null) return parameterizedTypeMungers; // Collection ret = null; // if (ajMembersNeedParameterization()) { // Collection genericDeclares = delegate.getTypeMungers(); // parameterizedTypeMungers = new ArrayList(); // Map parameterizationMap = getAjMemberParameterizationMap(); // for (Iterator iter = genericDeclares.iterator(); iter.hasNext();) { // ConcreteTypeMunger munger = (ConcreteTypeMunger)iter.next(); // parameterizedTypeMungers.add(munger.parameterizeWith(parameterizationMap, // world)); // } // ret = parameterizedTypeMungers; // } else { // ret = delegate.getTypeMungers(); // } // return ret; // } @Override public Collection<ResolvedMember> getPrivilegedAccesses() { return getDelegate().getPrivilegedAccesses(); } @Override public int getModifiers() { return getDelegate().getModifiers(); } WeakReference<ResolvedType> superclassReference = new WeakReference<ResolvedType>(null); @Override public ResolvedType getSuperclass() { ResolvedType ret = null;// superclassReference.get(); // if (ret != null) { // return ret; // } if (newSuperclass != null) { if (this.isParameterizedType() && newSuperclass.isParameterizedType()) { return newSuperclass.parameterize(getMemberParameterizationMap()).resolve(getWorld()); } if (getDelegate().isCacheable()) { superclassReference = new WeakReference<ResolvedType>(ret); } return newSuperclass; } try { world.setTypeVariableLookupScope(this); ret = getDelegate().getSuperclass(); } finally { world.setTypeVariableLookupScope(null); } if (this.isParameterizedType() && ret.isParameterizedType()) { ret = ret.parameterize(getMemberParameterizationMap()).resolve(getWorld()); } if (getDelegate().isCacheable()) { superclassReference = new WeakReference<ResolvedType>(ret); } return ret; } public ReferenceTypeDelegate getDelegate() { return delegate; } public void setDelegate(ReferenceTypeDelegate delegate) { // Don't copy from BcelObjectType to EclipseSourceType - the context may // be tidied (result null'd) after previous weaving if (this.delegate != null && this.delegate.copySourceContext() && this.delegate.getSourceContext() != SourceContextImpl.UNKNOWN_SOURCE_CONTEXT) { ((AbstractReferenceTypeDelegate) delegate).setSourceContext(this.delegate.getSourceContext()); } this.delegate = delegate; for (ReferenceType dependent : derivativeTypes) { dependent.setDelegate(delegate); } // If we are raw, we have a generic type - we should ensure it uses the // same delegate if (isRawType() && getGenericType() != null) { ReferenceType genType = (ReferenceType) getGenericType(); if (genType.getDelegate() != delegate) { // avoids circular updates genType.setDelegate(delegate); } } clearParameterizationCaches(); ensureConsistent(); } private void clearParameterizationCaches() { parameterizedFields = null; parameterizedInterfaces.clear(); parameterizedMethods = null; parameterizedPointcuts = null; superclassReference = new WeakReference<ResolvedType>(null); } public int getEndPos() { return endPos; } public int getStartPos() { return startPos; } public void setEndPos(int endPos) { this.endPos = endPos; } public void setStartPos(int startPos) { this.startPos = startPos; } @Override public boolean doesNotExposeShadowMungers() { return getDelegate().doesNotExposeShadowMungers(); } public String getDeclaredGenericSignature() { return getDelegate().getDeclaredGenericSignature(); } public void setGenericType(ReferenceType rt) { genericType = rt; // Should we 'promote' this reference type from simple to raw? // makes sense if someone is specifying that it has a generic form if (typeKind == TypeKind.SIMPLE) { typeKind = TypeKind.RAW; signatureErasure = signature; } } public void demoteToSimpleType() { genericType = null; typeKind = TypeKind.SIMPLE; signatureErasure = null; } @Override public ResolvedType getGenericType() { if (isGenericType()) { return this; } return genericType; } /** * a parameterized signature starts with a "P" in place of the "L", see the comment on signatures in UnresolvedType. * * @param aGenericType * @param someParameters * @return */ private static String makeParameterizedSignature(ResolvedType aGenericType, ResolvedType[] someParameters) { String rawSignature = aGenericType.getErasureSignature(); StringBuffer ret = new StringBuffer(); ret.append(PARAMETERIZED_TYPE_IDENTIFIER); ret.append(rawSignature.substring(1, rawSignature.length() - 1)); ret.append("<"); for (int i = 0; i < someParameters.length; i++) { ret.append(someParameters[i].getSignature()); } ret.append(">;"); return ret.toString(); } private static String makeDeclaredSignature(ResolvedType aGenericType, UnresolvedType[] someParameters) { StringBuffer ret = new StringBuffer(); String rawSig = aGenericType.getErasureSignature(); ret.append(rawSig.substring(0, rawSig.length() - 1)); ret.append("<"); for (int i = 0; i < someParameters.length; i++) { ret.append(((ReferenceType) someParameters[i]).getSignatureForAttribute()); } ret.append(">;"); return ret.toString(); } @Override public void ensureConsistent() { annotations = null; annotationTypes = null; newSuperclass = null; newInterfaces = null; typeVariables = null; parameterizedInterfaces.clear(); superclassReference = new WeakReference<ResolvedType>(null); if (getDelegate() != null) { delegate.ensureConsistent(); } } @Override public void addParent(ResolvedType newParent) { if (newParent.isClass()) { newSuperclass = newParent; superclassReference = new WeakReference<ResolvedType>(null); } else { if (newInterfaces == null) { newInterfaces = new ResolvedType[1]; newInterfaces[0] = newParent; } else { ResolvedType[] existing = getDelegate().getDeclaredInterfaces(); if (existing != null) { for (int i = 0; i < existing.length; i++) { if (existing[i].equals(newParent)) { return; // already has this interface } } } ResolvedType[] newNewInterfaces = new ResolvedType[newInterfaces.length + 1]; System.arraycopy(newInterfaces, 0, newNewInterfaces, 1, newInterfaces.length); newNewInterfaces[0] = newParent; newInterfaces = newNewInterfaces; } parameterizedInterfaces.clear(); } } }
320,468
Bug 320468 ModifiersPattern.getModifierFlag() is not thread safe
Build Identifier: org.aspectj.weaver_1.6.0.20080423100000.jar ModifiersPattern.getModifierFlag() is a non-synchronized static method using the static Map modifierFlags. This can lead to a ConcurrentModificationException when this code is executed in a multi-threaded environment. A stack trace showing the erroneous behavior is appended at the end of this bug report. In our case multithreading is introduced by using Spring DM. This leads to many application contexts being initialized in parallel. Each of them can contain pointcut expression, which are processed in independent threads. Spring AOP enters the "AspectJ world" calling PointcutParser.parsePointcutExpression(). Since there is no guarantee that a ConcurrentModificationException is thrown it is also possible that concurrent read/write accesses to the modifierFlags map are not recognized and incorrect values are used. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactoryProxy': Post-processing of the FactoryBean's object failed; nested exception is java.util.ConcurrentModificationException: concurrent access to HashMap attempted by Thread[SpringOsgiExtenderThread-43,5,spring-osgi-extender[6dee6dee]-threads] at org.springframework.beans.factory.support.FactoryBeanRegistrySupport$1.run(FactoryBeanRegistrySupport.java:142) at java.security.AccessController.doPrivileged(AccessController.java:219) at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:116) at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:91) at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1288) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:217) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:425) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728) at org.springframework.osgi.context.support.AbstractDelegatedExecutionApplicationContext.access$1600(AbstractDelegatedExecutionApplicationContext.java:69) at org.springframework.osgi.context.support.AbstractDelegatedExecutionApplicationContext$4.run(AbstractDelegatedExecutionApplicationContext.java:355) at org.springframework.osgi.util.internal.PrivilegedUtils.executeWithCustomTCCL(PrivilegedUtils.java:85) at org.springframework.osgi.context.support.AbstractDelegatedExecutionApplicationContext.completeRefresh(AbstractDelegatedExecutionApplicationContext.java:320) at org.springframework.osgi.extender.internal.dependencies.startup.DependencyWaiterApplicationContextExecutor$CompleteRefreshTask.run(DependencyWaiterApplicationContextExecutor.java:136) at java.lang.Thread.run(Thread.java:811) Caused by: java.util.ConcurrentModificationException: concurrent access to HashMap attempted by Thread[SpringOsgiExtenderThread-43,5,spring-osgi-extender[6dee6dee]-threads] at java.util.HashMap.onEntry(HashMap.java:214) at java.util.HashMap.transfer(HashMap.java:686) at java.util.HashMap.resize(HashMap.java:676) at java.util.HashMap.addEntry(HashMap.java:1049) at java.util.HashMap.put(HashMap.java:561) at org.aspectj.weaver.patterns.ModifiersPattern.getModifierFlag(ModifiersPattern.java:87) at org.aspectj.weaver.patterns.PatternParser.parseModifiersPattern(PatternParser.java:1169) at org.aspectj.weaver.patterns.PatternParser.parseMethodOrConstructorSignaturePattern(PatternParser.java:1248) at org.aspectj.weaver.patterns.PatternParser.parseKindedPointcut(PatternParser.java:603) at org.aspectj.weaver.patterns.PatternParser.parseSinglePointcut(PatternParser.java:317) at org.aspectj.weaver.patterns.PatternParser.parseAtomicPointcut(PatternParser.java:295) at org.aspectj.weaver.patterns.PatternParser.parsePointcut(PatternParser.java:256) at org.aspectj.weaver.tools.PointcutParser.resolvePointcutExpression(PointcutParser.java:328) at org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression(PointcutParser.java:309) at org.springframework.aop.aspectj.AspectJExpressionPointcut.buildPointcutExpression(AspectJExpressionPointcut.java:206) at org.springframework.aop.aspectj.AspectJExpressionPointcut.checkReadyToMatch(AspectJExpressionPointcut.java:193) at org.springframework.aop.aspectj.AspectJExpressionPointcut.getClassFilter(AspectJExpressionPointcut.java:174) at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:195) at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:250) at org.springframework.aop.support.AopUtils.findAdvisorsThatCanApply(AopUtils.java:284) at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findAdvisorsThatCanApply(AbstractAdvisorAutoProxyCreator.java:113) at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:85) at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:66) at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:362) at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:325) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:361) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.postProcessObjectFromFactoryBean(AbstractAutowireCapableBeanFactory.java:1429) at org.springframework.beans.factory.support.FactoryBeanRegistrySupport$1.run(FactoryBeanRegistrySupport.java:139) ... 15 more Reproducible: Sometimes
resolved fixed
e0e1330
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-08-26T15:20:03Z"
"2010-07-21T08:13:20Z"
org.aspectj.matcher/src/org/aspectj/weaver/patterns/ModifiersPattern.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.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import org.aspectj.weaver.CompressingDataOutputStream; import org.aspectj.weaver.VersionedDataInputStream; public class ModifiersPattern extends PatternNode { private int requiredModifiers; private int forbiddenModifiers; public static final ModifiersPattern ANY = new ModifiersPattern(0, 0); public ModifiersPattern(int requiredModifiers, int forbiddenModifiers) { this.requiredModifiers = requiredModifiers; this.forbiddenModifiers = forbiddenModifiers; } public String toString() { if (this == ANY) { return ""; } String ret = Modifier.toString(requiredModifiers); if (forbiddenModifiers == 0) { return ret; } else { return ret + " !" + Modifier.toString(forbiddenModifiers); } } public boolean equals(Object other) { if (!(other instanceof ModifiersPattern)) { return false; } ModifiersPattern o = (ModifiersPattern) other; return o.requiredModifiers == this.requiredModifiers && o.forbiddenModifiers == this.forbiddenModifiers; } public int hashCode() { int result = 17; result = 37 * result + requiredModifiers; result = 37 * result + forbiddenModifiers; return result; } public boolean matches(int modifiers) { return ((modifiers & requiredModifiers) == requiredModifiers) && ((modifiers & forbiddenModifiers) == 0); } public static ModifiersPattern read(VersionedDataInputStream s) throws IOException { int requiredModifiers = s.readShort(); int forbiddenModifiers = s.readShort(); if (requiredModifiers == 0 && forbiddenModifiers == 0) { return ANY; } return new ModifiersPattern(requiredModifiers, forbiddenModifiers); } public void write(CompressingDataOutputStream s) throws IOException { // s.writeByte(MODIFIERS_PATTERN); s.writeShort(requiredModifiers); s.writeShort(forbiddenModifiers); } private static Map modifierFlags = null; public static int getModifierFlag(String name) { if (modifierFlags == null) { modifierFlags = new HashMap(); int flag = 1; while (flag <= Modifier.STRICT) { String flagName = Modifier.toString(flag); modifierFlags.put(flagName, new Integer(flag)); flag = flag << 1; } } Integer flag = (Integer) modifierFlags.get(name); if (flag == null) { return -1; } return flag.intValue(); } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
324,135
Bug 324135 ArrayIndexOutOfBoundsException at AjState.java:1767
Build Identifier: 20100617-1415 Using AspectJ version: 1.6.10.20100817163700 I hit the blow exception after saving a edited java file. java.lang.ArrayIndexOutOfBoundsException at org.aspectj.ajdt.internal.core.builder.AjState.hasStructuralChanges(AjState.java:1767) at org.aspectj.ajdt.internal.core.builder.AjState.recordClassFile(AjState.java:1510) at org.aspectj.ajdt.internal.core.builder.AjState.noteResult(AjState.java:1322) at org.aspectj.ajdt.internal.core.builder.AjBuildManager$3.acceptResult(AjBuildManager.java:1049) at org.aspectj.ajdt.internal.compiler.AjPipeli ... b.run(AutoBuildJob.java:242) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54) Compile error: ArrayIndexOutOfBoundsException thrown: 14 Reproducible: Didn't try
resolved fixed
88fab6a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-09-01T00:29:30Z"
"2010-08-31T21: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 * Andy Clement overhauled * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.File; 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.ajdt.internal.core.builder.AjBuildConfig.BinarySourceFile; import org.aspectj.apache.bcel.classfile.ClassParser; 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.IBinaryNestedType; 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.CompressingDataOutputStream; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.TypeDelegateResolver; import org.aspectj.weaver.bcel.UnwovenClassFile; /** * Maintains state needed for incremental compilation */ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateResolver { // 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; static int PATHID_CLASSPATH = 0; static int PATHID_ASPECTPATH = 1; static int PATHID_INPATH = 2; 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 final char[][] EMPTY_CHAR_ARRAY = new char[0][]; // now follows non static, but transient state - no need to write out, doesn't need reinitializing // State recreated for each build: /** * 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<File> affectedFiles = new HashSet<File>(); // 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<File> addedFiles; private Set<File> deletedFiles; private Set<BinarySourceFile> addedBinaryFiles; private Set<BinarySourceFile> deletedBinaryFiles; // For a particular build run, this set records the changes to classesFromName public final Set<String> deltaAddedClasses = new HashSet<String>(); // now follows non static, but transient state - no need to write out, DOES need reinitializing when read AjState instance // reloaded private final AjBuildManager buildManager; private INameEnvironment nameEnvironment; // now follows normal state that must be written out private boolean couldBeSubsequentIncrementalBuild = false; private boolean batchBuildRequiredThisTime = false; private AjBuildConfig buildConfig; private long lastSuccessfulFullBuildTime = -1; private final Hashtable<String, Long> structuralChangesSinceLastFullBuild = new Hashtable<String, Long>(); private long lastSuccessfulBuildTime = -1; private long currentBuildTime = -1; private AsmManager structureModel; /** * For a given source file, records the ClassFiles (which contain a fully qualified name and a file name) that were created when * the source file was compiled. Populated in noteResult and used in addDependentsOf(File) */ private final Map<File, List<ClassFile>> fullyQualifiedTypeNamesResultingFromCompilationUnit = new HashMap<File, List<ClassFile>>(); /** * Source files defining aspects Populated in noteResult and used in processDeletedFiles */ private final Set<File> sourceFilesDefiningAspects = new HashSet<File>(); /** * Populated in noteResult to record the set of types that should be recompiled if the given file is modified or deleted. * Referred to during addAffectedSourceFiles when calculating incremental compilation set. */ private final Map<File, ReferenceCollection> references = new HashMap<File, ReferenceCollection>(); /** * 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<String, List<UnwovenClassFile>> binarySourceFiles = new HashMap<String, List<UnwovenClassFile>>(); /** * 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<String, List<ClassFile>> inputClassFilesBySource = new HashMap<String, List<ClassFile>>(); /** * A list of the .class files created by this state that contain aspects. */ private final List<String> aspectClassFiles = new ArrayList<String>(); /** * 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<String, CompactTypeStructureRepresentation> resolvedTypeStructuresFromLastBuild = new HashMap<String, CompactTypeStructureRepresentation>(); /** * 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<String, File>(); /** * 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<File>(); private final Map<String, File> resources = new HashMap<String, File>(); SoftHashMap/* <baseDir,SoftHashMap<theFile,className>> */fileToClassNameMap = new SoftHashMap(); private BcelWeaver weaver; private BcelWorld world; // --- below here is unsorted state // --- 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.emptySet(); deletedFiles = Collections.emptySet(); } else { Set<File> oldFiles = new HashSet<File>(buildConfig.getFiles()); Set<File> newFiles = new HashSet<File>(newBuildConfig.getFiles()); addedFiles = new HashSet<File>(newFiles); addedFiles.removeAll(oldFiles); deletedFiles = new HashSet<File>(oldFiles); deletedFiles.removeAll(newFiles); } Set<BinarySourceFile> oldBinaryFiles = new HashSet<BinarySourceFile>(buildConfig.getBinaryFiles()); Set<BinarySourceFile> newBinaryFiles = new HashSet<BinarySourceFile>(newBuildConfig.getBinaryFiles()); addedBinaryFiles = new HashSet<BinarySourceFile>(newBinaryFiles); addedBinaryFiles.removeAll(oldBinaryFiles); deletedBinaryFiles = new HashSet<BinarySourceFile>(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<File> deletedFiles) { for (File deletedFile : deletedFiles) { if (this.sourceFilesDefiningAspects.contains(deletedFile)) { removeAllResultsOfLastBuild(); if (stateListener != null) { stateListener.detectedAspectDeleted(deletedFile); } return false; } List<ClassFile> classes = fullyQualifiedTypeNamesResultingFromCompilationUnit.get(deletedFile); if (classes != null) { for (ClassFile cf : classes) { resolvedTypeStructuresFromLastBuild.remove(cf.fullyQualifiedTypeName); } } } return true; } private Collection<File> getModifiedFiles() { return getModifiedFiles(lastSuccessfulBuildTime); } Collection<File> getModifiedFiles(long lastBuildTime) { Set<File> ret = new HashSet<File>(); // 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<File> i = buildConfig.getFiles().iterator(); i.hasNext();) { 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<BinarySourceFile> getModifiedBinaryFiles() { return getModifiedBinaryFiles(lastSuccessfulBuildTime); } Collection<BinarySourceFile> getModifiedBinaryFiles(long lastBuildTime) { List<BinarySourceFile> ret = new ArrayList<BinarySourceFile>(); // not our job to account for new and deleted files for (Iterator<BinarySourceFile> i = buildConfig.getBinaryFiles().iterator(); i.hasNext();) { AjBuildConfig.BinarySourceFile bsfile = 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 void recordDecision(String decision) { getListener().recordDecision(decision); } /** * 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, int pathid) { if (!dir.isDirectory()) { if (listenerDefined()) { recordDecision("ClassFileChangeChecking: not a directory so forcing full build: '" + dir.getPath() + "'"); } return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD; } // Are we managing that output directory? AjState state = IncrementalStateManager.findStateManagingOutputLocation(dir); if (listenerDefined()) { if (state != null) { recordDecision("ClassFileChangeChecking: found state instance managing output location : " + dir); } else { recordDecision("ClassFileChangeChecking: 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("ClassFileChangeChecking: 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( "ClassFileChangeChecking: queried JDT and '" + dir + "' is apparently unchanged so not performing timestamp check"); } return CLASS_FILE_NO_CHANGES; } } } List<File> classFiles = FileUtil.listClassFiles(dir); for (Iterator<File> iterator = classFiles.iterator(); iterator.hasNext();) { File classFile = iterator.next(); if (CHECK_STATE_FIRST && state != null) { // Next section reworked based on bug 270033: // if it is an aspect we may or may not be in trouble depending on whether (a) we depend on it (b) it is on the // classpath or the aspectpath if (state.isAspect(classFile)) { boolean hasStructuralChanges = state.hasStructuralChangedSince(classFile, lastSuccessfulBuildTime); if (hasStructuralChanges || isTypeWeReferTo(classFile)) { if (hasStructuralChanges) { if (listenerDefined()) { getListener().recordDecision( "ClassFileChangeChecking: aspect found that has structurally changed : " + classFile); } return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD; } else { // must be 'isTypeWeReferTo()' if (pathid == PATHID_CLASSPATH) { if (listenerDefined()) { getListener().recordDecision( "ClassFileChangeChecking: aspect found that this project refers to : " + classFile + " but only referred to via classpath"); } } else { if (listenerDefined()) { getListener().recordDecision( "ClassFileChangeChecking: aspect found that this project refers to : " + classFile + " from either inpath/aspectpath, switching to full build"); } return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD; } } } else { // it is an aspect but we don't refer to it: // - for CLASSPATH I think this is OK, we can continue and try an // incremental build // - for ASPECTPATH we don't know what else might be touched in this project // and must rebuild if (pathid == PATHID_CLASSPATH) { if (listenerDefined()) { getListener() .recordDecision( "ClassFileChangeChecking: found aspect on classpath but this project doesn't reference it, continuing to try for incremental build : " + classFile); } } else { if (listenerDefined()) { getListener().recordDecision( "ClassFileChangeChecking: found aspect on aspectpath/inpath - can't determine if this project is affected, must full build: " + classFile); } return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD; } } } if (state.hasStructuralChangedSince(classFile, lastSuccessfulBuildTime)) { if (listenerDefined()) { getListener().recordDecision("ClassFileChangeChecking: structural change detected in : " + classFile); } isTypeWeReferTo(classFile); } } 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)) { if (state.hasStructuralChangedSince(classFile, lastSuccessfulBuildTime) || isTypeWeReferTo(classFile)) { // further improvements possible if (listenerDefined()) { getListener().recordDecision( "ClassFileChangeChecking: aspect found that has structurally changed or that this project depends upon : " + classFile); } return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD; } else { // it is an aspect but we don't refer to it: // - for CLASSPATH I think this is OK, we can continue and try an // incremental build // - for ASPECTPATH we don't know what else might be touched in this project // and must rebuild if (pathid == PATHID_CLASSPATH) { if (listenerDefined()) { getListener() .recordDecision( "ClassFileChangeChecking: found aspect on classpath but this project doesn't reference it, continuing to try for incremental build : " + classFile); } } else { if (listenerDefined()) { getListener().recordDecision( "ClassFileChangeChecking: found aspect on aspectpath/inpath - can't determine if this project is affected, must full build: " + classFile); } return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD; } } } if (state.hasStructuralChangedSince(classFile, lastSuccessfulBuildTime)) { if (listenerDefined()) { getListener().recordDecision( "ClassFileChangeChecking: structural change detected in : " + classFile); } isTypeWeReferTo(classFile); } else { if (listenerDefined()) { getListener().recordDecision( "ClassFileChangeChecking: 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)) { 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()); } @SuppressWarnings("rawtypes") 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; @SuppressWarnings("unchecked") 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; } } /** * 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); } int newlyAffectedFiles = 0; for (Iterator<Map.Entry<File, ReferenceCollection>> i = references.entrySet().iterator(); i.hasNext();) { Map.Entry<File, ReferenceCollection> entry = i.next(); ReferenceCollection refs = entry.getValue(); if (refs != null && refs.includes(qualifiedNames, simpleNames)) { if (listenerDefined()) { getListener().recordDecision( toString() + ": type " + new String(className) + " is depended upon by '" + entry.getKey() + "'"); } newlyAffectedFiles++; // possibly the beginnings of addressing the second point in 270033 comment 3 // List/*ClassFile*/ cfs = (List)this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(entry.getKey()); affectedFiles.add(entry.getKey()); } } if (newlyAffectedFiles > 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 = 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<Map.Entry<String, Long>> entries = structuralChangesSinceLastFullBuild.entrySet(); for (Iterator<Map.Entry<String, Long>> iterator = entries.iterator(); iterator.hasNext();) { Map.Entry<String, Long> entry = iterator.next(); Long l = 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<File> oldOutputLocs = getOutputLocations(previousConfig); Set<String> alreadyAnalysedPaths = new HashSet<String>(); List<String> oldClasspath = previousConfig.getClasspath(); List<String> newClasspath = newConfig.getClasspath(); if (stateListener != null) { stateListener.aboutToCompareClasspaths(oldClasspath, newClasspath); } if (classpathChangedAndNeedsFullBuild(oldClasspath, newClasspath, true, oldOutputLocs, alreadyAnalysedPaths)) { return true; } List<File> oldAspectpath = previousConfig.getAspectpath(); List<File> newAspectpath = newConfig.getAspectpath(); if (changedAndNeedsFullBuild(oldAspectpath, newAspectpath, true, oldOutputLocs, alreadyAnalysedPaths, PATHID_ASPECTPATH)) { return true; } List<File> oldInPath = previousConfig.getInpath(); List<File> newInPath = newConfig.getInpath(); if (changedAndNeedsFullBuild(oldInPath, newInPath, false, oldOutputLocs, alreadyAnalysedPaths, PATHID_INPATH)) { return true; } List<File> oldInJars = previousConfig.getInJars(); List<File> newInJars = newConfig.getInJars(); if (changedAndNeedsFullBuild(oldInJars, newInJars, false, oldOutputLocs, alreadyAnalysedPaths, PATHID_INPATH)) { 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<String> iterator = modifiedCpElements.iterator(); iterator.hasNext();) { File cpElement = new File(iterator.next()); if (cpElement.exists() && !cpElement.isDirectory()) { if (cpElement.lastModified() > lastSuccessfulBuildTime) { return true; } } else { int classFileChanges = classFileChangedInDirSinceLastBuildRequiringFullBuild(cpElement, PATHID_CLASSPATH); 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<File> outputLocs = new ArrayList<File>(); // Is there a default location? if (config.getOutputDir() != null) { try { outputLocs.add(config.getOutputDir().getCanonicalFile()); } catch (IOException e) { } } if (config.getCompilationResultDestinationManager() != null) { List<File> dirs = config.getCompilationResultDestinationManager().getAllOutputLocations(); for (Iterator<File> iterator = dirs.iterator(); iterator.hasNext();) { File f = 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) { 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<File> outputLocs, Set<String> alreadyAnalysedPaths, int pathid) { 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<File> iterator = outputLocs.iterator(); !foundMatch && iterator.hasNext();) { File dir = 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, pathid); 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<String> oldPath, List<String> newPath, boolean checkClassFiles, List<File> outputLocs, Set<String> alreadyAnalysedPaths) { 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(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<File> iterator = outputLocs.iterator(); !foundMatch && iterator.hasNext();) { File dir = 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, PATHID_CLASSPATH); if (classFileChanges == CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD) { return true; } } } } } return false; } public Set<File> getFilesToCompile(boolean firstPass) { Set<File> thisTime = new HashSet<File>(); if (firstPass) { compiledSourceFiles = new HashSet<File>(); Collection<File> 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<File> fIter = addedFiles.iterator(); fIter.hasNext();) { File o = fIter.next(); // TODO isn't it a set?? why do this 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<UnwovenClassFile>> getBinaryFilesToCompile(boolean firstTime) { if (lastSuccessfulBuildTime == -1 || buildConfig == null || !maybeIncremental()) { return binarySourceFiles; } // else incremental... Map<String, List<UnwovenClassFile>> toWeave = new HashMap<String, List<UnwovenClassFile>>(); if (firstTime) { List<BinarySourceFile> addedOrModified = new ArrayList<BinarySourceFile>(); addedOrModified.addAll(addedBinaryFiles); addedOrModified.addAll(getModifiedBinaryFiles()); for (Iterator<BinarySourceFile> iter = addedOrModified.iterator(); iter.hasNext();) { AjBuildConfig.BinarySourceFile bsf = iter.next(); UnwovenClassFile ucf = createUnwovenClassFile(bsf); if (ucf == null) { continue; } List<UnwovenClassFile> ucfs = new ArrayList<UnwovenClassFile>(); ucfs.add(ucf); recordTypeChanged(ucf.getClassName()); binarySourceFiles.put(bsf.binSrc.getPath(), ucfs); List<ClassFile> cfs = new ArrayList<ClassFile>(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<List<ClassFile>> iter = this.inputClassFilesBySource.values().iterator(); iter.hasNext();) { List<ClassFile> cfs = iter.next(); for (ClassFile cf : cfs) { cf.deleteFromFileSystem(buildConfig); } } for (Iterator<File> iterator = classesFromName.values().iterator(); iterator.hasNext();) { File f = iterator.next(); new ClassFile("", f).deleteFromFileSystem(buildConfig); } Set<Map.Entry<String, File>> resourceEntries = resources.entrySet(); for (Iterator<Map.Entry<String, File>> iter = resourceEntries.iterator(); iter.hasNext();) { Map.Entry<String, File> resourcePair = iter.next(); File sourcePath = resourcePair.getValue(); File outputLoc = getOutputLocationFor(buildConfig, sourcePath); if (outputLoc != null) { outputLoc = new File(outputLoc, 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 (File deletedFile : deletedFiles) { addDependentsOf(deletedFile); List<ClassFile> cfs = this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(deletedFile); this.fullyQualifiedTypeNamesResultingFromCompilationUnit.remove(deletedFile); if (cfs != null) { for (ClassFile cf : cfs) { deleteClassFile(cf); } } } } private void deleteBinaryClassFiles() { // range of bsf is ucfs, domain is files (.class and jars) in inpath/jars for (BinarySourceFile deletedFile : deletedBinaryFiles) { List<ClassFile> cfs = this.inputClassFilesBySource.get(deletedFile.binSrc.getPath()); for (Iterator<ClassFile> iterator = cfs.iterator(); iterator.hasNext();) { deleteClassFile(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 = classesFromName.get(unwovenClassFiles[i].getClassName()); recordClassFile(unwovenClassFiles[i], lastTimeRound); String name = unwovenClassFiles[i].getClassName(); if (lastTimeRound == null) { deltaAddedClasses.add(name); } classesFromName.put(name, 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<ClassFile> classFiles = 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 (ClassFile cf : classFiles) { recordTypeChanged(cf.fullyQualifiedTypeName); resolvedTypeStructuresFromLastBuild.remove(cf.fullyQualifiedTypeName); // } // for (ClassFile cf : classFiles) { deleteClassFile(cf); } } } private void removeFromClassFilesIfPresent(String className, List<ClassFile> classFiles) { ClassFile victim = null; for (ClassFile cf : classFiles) { 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<ClassFile> classFiles = new ArrayList<ClassFile>(); 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<char[]> iterator = compiledTypes.keySet().iterator(); iterator.hasNext();) { char[] className = 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 comparisons 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 = 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()); } } /** * 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. * * @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)) { IBinaryField existing = existingFs[j]; if (!modifiersEqual(field.getModifiers(), existing.getModifiers())) { return true; } if (!CharOperation.equals(existing.getTypeName(), field.getTypeName())) { return true; } char[] existingGSig = existing.getGenericSignature(); char[] fieldGSig = field.getGenericSignature(); if ((existingGSig == null && fieldGSig != null) || (existingGSig != null && fieldGSig == null)) { return true; } if (existingGSig != null) { if (!CharOperation.equals(existingGSig, fieldGSig)) { 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 IBinaryMethod existing = existingMs[j]; if (!modifiersEqual(method.getModifiers(), existing.getModifiers())) { return true; } if (exceptionClausesDiffer(existing, method)) { return true; } char[] existingGSig = existing.getGenericSignature(); char[] methodGSig = method.getGenericSignature(); if ((existingGSig == null && methodGSig != null) || (existingGSig != null && methodGSig == null)) { return true; } if (existingGSig != null) { if (!CharOperation.equals(existingGSig, methodGSig)) { return true; } } continue new_method_loop; } } } return true; // (no match found) } // check for differences in inner types // TODO could make order insensitive IBinaryNestedType[] binaryNestedTypes = reader.getMemberTypes(); IBinaryNestedType[] existingBinaryNestedTypes = existingType.getMemberTypes(); if ((binaryNestedTypes == null && existingBinaryNestedTypes != null) || (binaryNestedTypes != null && existingBinaryNestedTypes == null)) { return true; } if (binaryNestedTypes != null) { int bnLength = binaryNestedTypes.length; for (int m = 0; m < bnLength; m++) { IBinaryNestedType bnt = binaryNestedTypes[m]; IBinaryNestedType existingBnt = existingBinaryNestedTypes[m]; if (!CharOperation.equals(bnt.getName(), existingBnt.getName())) { return true; } } } return false; } /** * For two methods, discover if there has been a change in the exception types specified. * * @return true if the exception types have changed */ private boolean exceptionClausesDiffer(IBinaryMethod lastMethod, IBinaryMethod newMethod) { char[][] previousExceptionTypeNames = lastMethod.getExceptionTypeNames(); char[][] newExceptionTypeNames = newMethod.getExceptionTypeNames(); int pLength = previousExceptionTypeNames.length; int nLength = newExceptionTypeNames.length; if (pLength != nLength) { return true; } if (pLength == 0) { return false; } // TODO could be insensitive to an order change for (int i = 0; i < pLength; i++) { if (!CharOperation.equals(previousExceptionTypeNames[i], newExceptionTypeNames[i])) { return true; } } 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 stringifySet(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<File> addTo, Set<File> 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: '" + stringifySet(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<Map.Entry<File, ReferenceCollection>> i = references.entrySet().iterator(); i.hasNext();) { Map.Entry<File, ReferenceCollection> entry = i.next(); ReferenceCollection refs = entry.getValue(); if (refs != null && refs.includes(qualifiedNames, simpleNames)) { 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<ClassFile> cfs = this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(sourceFile); if (cfs != null) { for (ClassFile cf : cfs) { 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; world.addTypeDelegateResolver(this); } 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<String, List<UnwovenClassFile>>(); } public void recordBinarySource(String fromPathName, List<UnwovenClassFile> unwovenClassFiles) { this.binarySourceFiles.put(fromPathName, unwovenClassFiles); if (this.maybeIncremental()) { List<ClassFile> simpleClassFiles = new LinkedList<ClassFile>(); for (UnwovenClassFile ucf : unwovenClassFiles) { 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<String, List<UnwovenClassFile>> getBinarySourceMap() { return this.binarySourceFiles; } public Map<String, File> 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<File> getAddedFiles() { return this.addedFiles; } /** * @return Returns the deletedFiles. */ public Set<File> 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 String toString() { StringBuilder s = new StringBuilder(); s.append("ClassFile(type=").append(fullyQualifiedTypeName).append(",location=").append(locationOnDisk).append(")"); return s.toString(); } 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<String, char[]> getAspectNamesToFileNameMap() { return aspectsFromFileNames; } public void initializeAspectNamesToFileNameMap() { this.aspectsFromFileNames = new HashMap<String, char[]>(); } // 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 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); } public void write(CompressingDataOutputStream dos) throws IOException { // weaver weaver.write(dos); // world // model // local state } /** * See if we can create a delegate from a CompactTypeStructure - TODO better comment */ public ReferenceTypeDelegate getDelegate(ReferenceType referenceType) { File f = classesFromName.get(referenceType.getName()); if (f == null) { return null; // not heard of it } try { ClassParser parser = new ClassParser(f.toString()); return world.buildBcelDelegate(referenceType, parser.parse(), true, false); } catch (IOException e) { System.err.println("Failed to recover "+referenceType); e.printStackTrace(); } return null; } }
318,899
Bug 318899 NPE with @args matching Argument by Type
null
resolved fixed
2a8d684
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-09-01T04:19:01Z"
"2010-07-05T14:26:40Z"
org.aspectj.matcher/src/org/aspectj/weaver/reflect/ShadowMatchImpl.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.reflect; import java.lang.reflect.Member; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.And; import org.aspectj.weaver.ast.Call; import org.aspectj.weaver.ast.FieldGetCall; import org.aspectj.weaver.ast.HasAnnotation; import org.aspectj.weaver.ast.ITestVisitor; import org.aspectj.weaver.ast.Instanceof; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Not; import org.aspectj.weaver.ast.Or; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; import org.aspectj.weaver.internal.tools.MatchingContextBasedTest; import org.aspectj.weaver.patterns.ExposedState; import org.aspectj.weaver.tools.DefaultMatchingContext; import org.aspectj.weaver.tools.JoinPointMatch; import org.aspectj.weaver.tools.MatchingContext; import org.aspectj.weaver.tools.PointcutParameter; import org.aspectj.weaver.tools.ShadowMatch; /** * @author colyer Implementation of ShadowMatch for reflection based worlds. */ public class ShadowMatchImpl implements ShadowMatch { private FuzzyBoolean match; private ExposedState state; private Test residualTest; private PointcutParameter[] params; private Member withinCode; private Member subject; private Class<?> withinType; private MatchingContext matchContext = new DefaultMatchingContext(); public ShadowMatchImpl(FuzzyBoolean match, Test test, ExposedState state, PointcutParameter[] params) { this.match = match; this.residualTest = test; this.state = state; this.params = params; } public void setWithinCode(Member aMember) { this.withinCode = aMember; } public void setSubject(Member aMember) { this.subject = aMember; } public void setWithinType(Class<?> aClass) { this.withinType = aClass; } public boolean alwaysMatches() { return match.alwaysTrue(); } public boolean maybeMatches() { return match.maybeTrue(); } public boolean neverMatches() { return match.alwaysFalse(); } public JoinPointMatch matchesJoinPoint(Object thisObject, Object targetObject, Object[] args) { if (neverMatches()) { return JoinPointMatchImpl.NO_MATCH; } if (new RuntimeTestEvaluator(residualTest, thisObject, targetObject, args, this.matchContext).matches()) { return new JoinPointMatchImpl(getPointcutParameters(thisObject, targetObject, args)); } else { return JoinPointMatchImpl.NO_MATCH; } } /* * (non-Javadoc) * * @see org.aspectj.weaver.tools.ShadowMatch#setMatchingContext(org.aspectj.weaver.tools.MatchingContext) */ public void setMatchingContext(MatchingContext aMatchContext) { this.matchContext = aMatchContext; } private PointcutParameter[] getPointcutParameters(Object thisObject, Object targetObject, Object[] args) { Var[] vars = state.vars; PointcutParameterImpl[] bindings = new PointcutParameterImpl[params.length]; for (int i = 0; i < bindings.length; i++) { bindings[i] = new PointcutParameterImpl(params[i].getName(), params[i].getType()); bindings[i].setBinding(((ReflectionVar) vars[i]).getBindingAtJoinPoint(thisObject, targetObject, args, subject, withinCode, withinType)); } return bindings; } private static class RuntimeTestEvaluator implements ITestVisitor { private boolean matches = true; private final Test test; private final Object thisObject; private final Object targetObject; private final Object[] args; private final MatchingContext matchContext; public RuntimeTestEvaluator(Test aTest, Object thisObject, Object targetObject, Object[] args, MatchingContext context) { this.test = aTest; this.thisObject = thisObject; this.targetObject = targetObject; this.args = args; this.matchContext = context; } public boolean matches() { test.accept(this); return matches; } public void visit(And e) { boolean leftMatches = new RuntimeTestEvaluator(e.getLeft(), thisObject, targetObject, args, matchContext).matches(); if (!leftMatches) { matches = false; } else { matches = new RuntimeTestEvaluator(e.getRight(), thisObject, targetObject, args, matchContext).matches(); } } public void visit(Instanceof instanceofTest) { ReflectionVar v = (ReflectionVar) instanceofTest.getVar(); Object value = v.getBindingAtJoinPoint(thisObject, targetObject, args); World world = v.getType().getWorld(); ResolvedType desiredType = instanceofTest.getType().resolve(world); ResolvedType actualType = world.resolve(value.getClass().getName()); matches = desiredType.isAssignableFrom(actualType); } public void visit(MatchingContextBasedTest matchingContextTest) { matches = matchingContextTest.matches(this.matchContext); } public void visit(Not not) { matches = !new RuntimeTestEvaluator(not.getBody(), thisObject, targetObject, args, matchContext).matches(); } public void visit(Or or) { boolean leftMatches = new RuntimeTestEvaluator(or.getLeft(), thisObject, targetObject, args, matchContext).matches(); if (leftMatches) { matches = true; } else { matches = new RuntimeTestEvaluator(or.getRight(), thisObject, targetObject, args, matchContext).matches(); } } public void visit(Literal literal) { if (literal == Literal.FALSE) { matches = false; } else { matches = true; } } public void visit(Call call) { throw new UnsupportedOperationException("Can't evaluate call test at runtime"); } public void visit(FieldGetCall fieldGetCall) { throw new UnsupportedOperationException("Can't evaluate fieldGetCall test at runtime"); } public void visit(HasAnnotation hasAnnotation) { ReflectionVar v = (ReflectionVar) hasAnnotation.getVar(); Object value = v.getBindingAtJoinPoint(thisObject, targetObject, args); World world = v.getType().getWorld(); ResolvedType actualVarType = world.resolve(value.getClass().getName()); ResolvedType requiredAnnotationType = hasAnnotation.getAnnotationType().resolve(world); matches = actualVarType.hasAnnotation(requiredAnnotationType); } } }
318,899
Bug 318899 NPE with @args matching Argument by Type
null
resolved fixed
2a8d684
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-09-01T04:19:01Z"
"2010-07-05T14:26:40Z"
org.aspectj.matcher/testsrc/org/aspectj/weaver/patterns/ThisOrTargetTestCase.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, runtime reflection extensions * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.IOException; import java.lang.reflect.Method; import junit.framework.TestCase; import org.aspectj.util.LangUtil; import org.aspectj.weaver.tools.JoinPointMatch; import org.aspectj.weaver.tools.PointcutExpression; import org.aspectj.weaver.tools.PointcutParameter; import org.aspectj.weaver.tools.PointcutParser; import org.aspectj.weaver.tools.ShadowMatch; /** * @author hugunin * * To change this generated comment edit the template variable "typecomment": Window>Preferences>Java>Templates. To enable * and disable the creation of type comments go to Window>Preferences>Java>Code Generation. */ public class ThisOrTargetTestCase extends TestCase { private boolean needToSkip = false; /** this condition can occur on the build machine only, and is way too complex to fix right now... */ private boolean needToSkipPointcutParserTests() { if (!LangUtil.is15VMOrGreater()) return false; try { Class.forName("org.aspectj.weaver.reflect.Java15ReflectionBasedReferenceTypeDelegate", false, this.getClass() .getClassLoader());// ReflectionBasedReferenceTypeDelegate.class.getClassLoader()); } catch (ClassNotFoundException cnfEx) { return true; } return false; } protected void setUp() throws Exception { super.setUp(); needToSkip = needToSkipPointcutParserTests(); } /** * Constructor for PatternTestCase. * * @param name */ public ThisOrTargetTestCase(String name) { super(name); } public void testMatchJP() throws Exception { if (needToSkip) return; PointcutParser parser = PointcutParser .getPointcutParserSupportingAllPrimitivesAndUsingSpecifiedClassloaderForResolution(this.getClass().getClassLoader()); PointcutExpression thisEx = parser.parsePointcutExpression("this(Exception)"); PointcutExpression thisIOEx = parser.parsePointcutExpression("this(java.io.IOException)"); PointcutExpression targetEx = parser.parsePointcutExpression("target(Exception)"); PointcutExpression targetIOEx = parser.parsePointcutExpression("target(java.io.IOException)"); Method toString = Object.class.getMethod("toString", new Class[0]); checkMatches(thisEx.matchesMethodCall(toString, toString), new Exception(), null, null); checkNoMatch(thisIOEx.matchesMethodCall(toString, toString), new Exception(), null, null); checkNoMatch(targetEx.matchesMethodCall(toString, toString), new Exception(), new Object(), null); checkNoMatch(targetIOEx.matchesMethodCall(toString, toString), new Exception(), new Exception(), null); checkMatches(thisEx.matchesMethodCall(toString, toString), new IOException(), null, null); checkMatches(thisIOEx.matchesMethodCall(toString, toString), new IOException(), null, null); checkNoMatch(thisEx.matchesMethodCall(toString, toString), new Object(), null, null); checkNoMatch(thisIOEx.matchesMethodCall(toString, toString), new Exception(), null, null); checkMatches(targetEx.matchesMethodCall(toString, toString), new Exception(), new Exception(), null); checkNoMatch(targetIOEx.matchesMethodCall(toString, toString), new Exception(), new Exception(), null); checkMatches(targetIOEx.matchesMethodCall(toString, toString), new Exception(), new IOException(), null); } public void testBinding() throws Exception { if (needToSkip) return; PointcutParser parser = PointcutParser .getPointcutParserSupportingAllPrimitivesAndUsingSpecifiedClassloaderForResolution(this.getClass().getClassLoader()); PointcutParameter ex = parser.createPointcutParameter("ex", Exception.class); PointcutParameter ioEx = parser.createPointcutParameter("ioEx", IOException.class); PointcutExpression thisEx = parser.parsePointcutExpression("this(ex)", Exception.class, new PointcutParameter[] { ex }); PointcutExpression targetIOEx = parser.parsePointcutExpression("target(ioEx)", Exception.class, new PointcutParameter[] { ioEx }); Method toString = Object.class.getMethod("toString", new Class[0]); ShadowMatch sMatch = thisEx.matchesMethodCall(toString, toString); Exception exceptionParameter = new Exception(); IOException ioExceptionParameter = new IOException(); JoinPointMatch jpMatch = sMatch.matchesJoinPoint(exceptionParameter, null, null); assertTrue("should match", jpMatch.matches()); PointcutParameter[] bindings = jpMatch.getParameterBindings(); assertEquals("one binding", 1, bindings.length); assertEquals("should be exceptionParameter", exceptionParameter, bindings[0].getBinding()); assertEquals("ex", bindings[0].getName()); sMatch = targetIOEx.matchesMethodCall(toString, toString); jpMatch = sMatch.matchesJoinPoint(exceptionParameter, ioExceptionParameter, null); assertTrue("should match", jpMatch.matches()); bindings = jpMatch.getParameterBindings(); assertEquals("one binding", 1, bindings.length); assertEquals("should be ioExceptionParameter", ioExceptionParameter, bindings[0].getBinding()); assertEquals("ioEx", bindings[0].getName()); } private void checkMatches(ShadowMatch sMatch, Object thisObj, Object targetObj, Object[] args) { assertTrue("match expected", sMatch.matchesJoinPoint(thisObj, targetObj, args).matches()); } private void checkNoMatch(ShadowMatch sMatch, Object thisObj, Object targetObj, Object[] args) { assertFalse("no match expected", sMatch.matchesJoinPoint(thisObj, targetObj, args).matches()); } /** * Method checkSerialization. * * @param string */ // private void checkSerialization(String string) throws IOException { // Pointcut p = makePointcut(string); // ByteArrayOutputStream bo = new ByteArrayOutputStream(); // DataOutputStream out = new DataOutputStream(bo); // p.write(out); // out.close(); // // ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); // DataInputStream in = new DataInputStream(bi); // Pointcut newP = Pointcut.read(in, null); // // assertEquals("write/read", p, newP); // } }
324,190
Bug 324190 NullPointerException in AjBuildManager.findOutputDirsForAspects when compiling AspectJ project generated with Maven
Build Identifier: 20100617-1415 When I compile my AspectJ project, I get an AspectJ Internal Compiler Error. The stack trace is : java.lang.NullPointerException at org.aspectj.ajdt.internal.core.builder.AjBuildManager.findOutputDirsForAspects(AjBuildManager.java:725) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.writeOutxmlFile(AjBuildManager.java:652) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performBuild(AjBuildManager.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:181) at org.aspectj.a ... on$1.run(GlobalBuildAction.java:179) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54) I digged a bit and looked into the classes. It would seem that AjState.getAspectNamesToFileNameMap() can return null in AjBuildManager.findOutputDirsForAspects. It is taken in account when AjBuildConfig.getCompilationResultDestinationManager() returns null or a list with one element, but not when it returns a list with several elements. Reproducible: Always Steps to Reproduce: Always happen in my configuration, but I didn't try to make it happen again in another workspace. Here are the steps I followed. 1. Generate a AspectJ project with Maven using the pom.xml I'll join 2. Create an aspect with a few pointcuts and a few advices 3. Compile (not with maven, the Eclipse compilation)
resolved fixed
03c43f5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-09-01T15:00:33Z"
"2010-09-01T14: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.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<File> 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) { BcelWorld bcelWorld = getBcelWorld(); bcelWorld.reportTimers(); bcelWorld.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 = 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<File, List<String>> outputDirsAndAspects = findOutputDirsForAspects(); Set<Map.Entry<File, List<String>>> outputDirs = outputDirsAndAspects.entrySet(); for (Iterator<Map.Entry<File, List<String>>> iterator = outputDirs.iterator(); iterator.hasNext();) { Map.Entry<File, List<String>> entry = iterator.next(); File outputDir = entry.getKey(); List<String> aspects = 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<File, List<String>> outputDirsToAspects = new HashMap<File, List<String>>(); Map<String, char[]> 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<String> aspectNames = new ArrayList<String>(); if (aspectNamesToFileNames != null) { Set<String> keys = aspectNamesToFileNames.keySet(); for (String name : keys) { 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<String>()); } Set<Map.Entry<String, char[]>> entrySet = aspectNamesToFileNames.entrySet(); for (Iterator<Map.Entry<String, char[]>> iterator = entrySet.iterator(); iterator.hasNext();) { Map.Entry<String, char[]> entry = iterator.next(); String aspectName = entry.getKey(); char[] fileName = entry.getValue(); File outputDir = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass( new File(new String(fileName))); if (!outputDirsToAspects.containsKey(outputDir)) { outputDirsToAspects.put(outputDir, new ArrayList<String>()); } ((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<String, IProgramElement>()); // 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.setTiming(buildConfig.isTiming(), false); 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 (File inJar : buildConfig.getInJars()) { List<UnwovenClassFile> unwovenClasses = bcelWeaver.addJarFile(inJar, outputDir, false); state.recordBinarySource(inJar.getPath(), unwovenClasses); } for (File inPathElement : buildConfig.getInpath()) { 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<UnwovenClassFile> 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<UnwovenClassFile> ucfl = new ArrayList<UnwovenClassFile>(); 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<File> 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<File> fIterator = files.iterator(); fIterator.hasNext();) { File f = 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<String> cps = buildConfig.getFullClasspath(); Dump.saveFullClasspath(cps); String[] classpaths = new String[cps.size()]; for (int i = 0; i < cps.size(); i++) { classpaths[i] = cps.get(i); } environment = new StatefulNameEnvironment(getLibraryAccess(classpaths, filenames), state.getClassNameToFileMap(), state); state.setNameEnvironment(environment); } else { ((StatefulNameEnvironment) environment).update(state.getClassNameToFileMap(), state.deltaAddedClasses); state.deltaAddedClasses.clear(); } 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; // le = 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<ClassFile> classFiles = unitResult.compiledTypes.values(); boolean shouldAddAspectName = (buildConfig.getOutxmlName() != null); for (Iterator<ClassFile> iter = classFiles.iterator(); iter.hasNext();) { 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); getWorld().classWriteEvent(classFile.getCompoundName()); 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(); } try { BufferedOutputStream os = FileUtil.makeOutputStream(new File(outFile)); os.write(classFile.getBytes()); os.close(); } catch (FileNotFoundException fnfe) { IMessage msg = new Message("unable to write out class file: '" + filename + "' - reason: " + fnfe.getMessage(), IMessage.ERROR, null, new SourceLocation(new File(outFile), 0)); handler.handleMessage(msg); } 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 if (p.isFile() && p.getName().indexOf("org.aspectj.runtime") != -1) { // likely to be a variant from the springsource bundle repo b272591 return null; } 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(), buildConfig.isMakeReflectable(), state); } else { return new AjCompilerAdapter(forCompiler, batchCompile, getBcelWorld(), getWeaver(), factory, getInterimResultRequestor(), progressListener, this, // IOutputFilenameProvider this, // IBinarySourceProvider state.getBinarySourceMap(), buildConfig.isTerminateAfterCompilation(), buildConfig.getProceedOnError(), buildConfig.isNoAtAspectJAnnotationProcessing(), buildConfig.isMakeReflectable(), 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; } }
324,804
Bug 324804 NullPointerException at AspectJElementHierarchy.java:677
Build Identifier: 20100617-1415 After removing a "throws" clause from the constructor of a class and then saving I got the following error: java.lang.NullPointerException at org.aspectj.asm.internal.AspectJElementHierarchy.getCanonicalFilePath(AspectJElementHierarchy.java:677) at org.aspectj.asm.internal.AspectJElementHierarchy.updateHandleMap(AspectJElementHierarchy.java:641) at org.aspectj.asm.AsmManager.removeStructureModelForFiles(AsmManager.java:572) at org.aspectj.asm.AsmManager.processDelta(AsmManager.java:604) at org.aspectj.ajdt.internal.core.builder.AjBuildManager ... oBuildJob.run(AutoBuildJob.java:242) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54) Compile error: NullPointerException thrown: null Reproducible: Didn't try
resolved fixed
6249672
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2010-09-09T16:24:43Z"
"2010-09-08T23: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.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 * @author Andy Clement */ public class AspectJElementHierarchy implements IHierarchy { private static final long serialVersionUID = 6462734311117048620L; private transient AsmManager asm; protected IProgramElement root = null; protected String configFile = null; // Access to the handleMap and typeMap are now synchronized - at least the find methods and the updateHandleMap function // see pr305788 private Map<String, IProgramElement> fileMap = null; private Map<String, IProgramElement> handleMap = new HashMap<String, IProgramElement>(); private Map<String, IProgramElement> 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 String toSummaryString() { StringBuilder s = new StringBuilder(); s.append("FileMap has "+fileMap.size()+" entries\n"); s.append("HandleMap has "+handleMap.size()+" entries\n"); s.append("TypeMap has "+handleMap.size()+" entries\n"); s.append("FileMap:\n"); for (Map.Entry<String,IProgramElement> fileMapEntry: fileMap.entrySet()) { s.append(fileMapEntry).append("\n"); } s.append("TypeMap:\n"); for (Map.Entry<String,IProgramElement> typeMapEntry: typeMap.entrySet()) { s.append(typeMapEntry).append("\n"); } s.append("HandleMap:\n"); for (Map.Entry<String,IProgramElement> handleMapEntry: handleMap.entrySet()) { s.append(handleMapEntry).append("\n"); } return s.toString(); } public void setRoot(IProgramElement root) { this.root = root; handleMap = new HashMap<String, IProgramElement>(); typeMap = new HashMap<String, IProgramElement>(); } public void addToFileMap(String key, IProgramElement value) { fileMap.put(key, value); } public boolean removeFromFileMap(String canonicalFilePath) { return fileMap.remove(canonicalFilePath) != null; } public void setFileMap(HashMap<String, IProgramElement> fileMap) { this.fileMap = fileMap; } public Object findInFileMap(Object key) { return fileMap.get(key); } public Set<Map.Entry<String, IProgramElement>> 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 (IProgramElement node : parent.getChildren()) { 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 (IProgramElement node : parent.getChildren()) { 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) { synchronized (this) { // 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 = typeMap.get(key); if (cachedValue != null) { return cachedValue; } List<IProgramElement> packageNodes = findMatchingPackages(packageName); for (IProgramElement pkg : packageNodes) { // this searches each file for a class for (IProgramElement fileNode : pkg.getChildren()) { 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<IProgramElement> children = root.getChildren(); // The children might be source folders or packages if (children.size() == 0) { return Collections.emptyList(); } if ((children.get(0)).getKind() == IProgramElement.Kind.SOURCE_FOLDER) { String searchPackageName = (packagename == null ? "" : packagename); // default package means match on "" // dealing with source folders List<IProgramElement> matchingPackageNodes = new ArrayList<IProgramElement>(); for (IProgramElement sourceFolder : children) { List<IProgramElement> possiblePackageNodes = sourceFolder.getChildren(); for (IProgramElement possiblePackageNode : possiblePackageNodes) { 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<IProgramElement> result = new ArrayList<IProgramElement>(); result.add(root); return result; } List<IProgramElement> result = new ArrayList<IProgramElement>(); for (IProgramElement possiblePackage : children) { 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 (IProgramElement possiblePackage2 : possiblePackage.getChildren()) { 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.emptyList(); } else { return result; } } } private IProgramElement findClassInNodes(Collection<IProgramElement> 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 (IProgramElement classNode : nodes) { 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 (IProgramElement child : node.getChildren()) { IProgramElement foundit = findNodeForSourceFile(child, 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 (IProgramElement child : node.getChildren()) { 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 (IProgramElement child : node.getChildren()) { IProgramElement foundNode = findNodeForSourceLineHelper(child, 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 (IProgramElement child : node.getChildren()) { 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 = null; synchronized (this) { ipe = 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 (IProgramElement node : parent.getChildren()) { 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(); } public void forget(IProgramElement compilationUnitNode,IProgramElement typeNode) { String k = null; synchronized (this) { // handle map // type map for (Map.Entry<String,IProgramElement> typeMapEntry: typeMap.entrySet()) { if (typeMapEntry.getValue()==typeNode) { k = typeMapEntry.getKey(); break; } } if (k!=null) { typeMap.remove(k); } } if (compilationUnitNode!=null) { k = null; for (Map.Entry<String,IProgramElement> entry: fileMap.entrySet()) { if (entry.getValue()==compilationUnitNode) { k = entry.getKey();break; } } if (k!=null) { fileMap.remove(k); } } } // TODO rename this method ... it does more than just the handle map public void updateHandleMap(Set<String> deletedFiles) { // Only delete the entries we need to from the handle map - for performance reasons List<String> forRemoval = new ArrayList<String>(); Set<String> k = null; synchronized (this) { k = handleMap.keySet(); for (String handle : k) { IProgramElement ipe = handleMap.get(handle); if (deletedFiles.contains(getCanonicalFilePath(ipe))) { forRemoval.add(handle); } } for (String handle : forRemoval) { handleMap.remove(handle); } forRemoval.clear(); k = typeMap.keySet(); for (String typeName : k) { IProgramElement ipe = typeMap.get(typeName); if (deletedFiles.contains(getCanonicalFilePath(ipe))) { forRemoval.add(typeName); } } for (String typeName : forRemoval) { typeMap.remove(typeName); } forRemoval.clear(); } for (Map.Entry<String, IProgramElement> entry : fileMap.entrySet()) { String filePath = entry.getKey(); if (deletedFiles.contains(getCanonicalFilePath(entry.getValue()))) { forRemoval.add(filePath); } } for (String filePath : forRemoval) { 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 ""; } }
282,379
Bug 282379 [plan] spaces in file names causes AspectJ weaver to fail
The WeavingAdaptor requires the aspect path to be composed by URLs. The URL of a file is encoded, for example if it contains spaces they will be represented with %20. It then converts these file:// urls to simple string paths, and then tries to access files pointed by those paths. This is done inside the FileUtil.makeClasspath(URL[]) . This method uses URL.getPath() to obtain the path. But this method does not decode the string, it returns it as it is in the URL. When later this string is used to create a new File instance, that file contains an invalid path, and the weaver fails as follows : Caused by: org.aspectj.bridge.AbortException: bad aspect library: '/home/sym/path%20with%20space/aspect-library.jar' at org.aspectj.weaver.tools.WeavingAdaptor$WeavingAdaptorMessageHolder.handleMessage(WeavingAdaptor.java:624) at org.aspectj.bridge.MessageUtil.error(MessageUtil.java:80) at org.aspectj.weaver.tools.WeavingAdaptor.error(WeavingAdaptor.java:504) at org.aspectj.weaver.tools.WeavingAdaptor.addAspectLibrary(WeavingAdaptor.java:472) at org.aspectj.weaver.tools.WeavingAdaptor.registerAspectLibraries(WeavingAdaptor.java:447) at org.aspectj.weaver.tools.WeavingAdaptor.init(WeavingAdaptor.java:177) at org.aspectj.weaver.tools.WeavingAdaptor.<init>(WeavingAdaptor.java:112) This issue is quite important, because on older windows "Documents and Settings" is an unfortunately common path, for example Maven stores there its repository. Multiple solutions are possible for this simple bug, in order of impact : - Decode the string obtained by URL.getPath() using URLEncoder.decode() - Use Files instead of Strings and let Java handle the URL, using the File(URI) constructor - Don't assume that aspect libraries are files, and hence that urls are file url, and use URLConnection to fetch aspect library contents.
resolved fixed
5648105
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-02-05T21:29:00Z"
"2009-07-03T14:06:40Z"
util/src/org/aspectj/util/FileUtil.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.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.io.Reader; import java.io.StringReader; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * */ public class FileUtil { /** default parent directory File when a file has a null parent */ public static final File DEFAULT_PARENT = new File("."); // XXX user.dir? /** unmodifiable List of String source file suffixes (including leading ".") */ public static final List<String> SOURCE_SUFFIXES = Collections.unmodifiableList(Arrays.asList(new String[] { ".java", ".aj" })); public static final FileFilter ZIP_FILTER = new FileFilter() { public boolean accept(File file) { return isZipFile(file); } public String toString() { return "ZIP_FILTER"; } }; // public static final FileFilter SOURCE_FILTER = new FileFilter() { // public boolean accept(File file) { // return hasSourceSuffix(file); // } // // public String toString() { // return "SOURCE_FILTER"; // } // }; final static int[] INT_RA = new int[0]; /** accept all files */ public static final FileFilter ALL = new FileFilter() { public boolean accept(File f) { return true; } }; public static final FileFilter DIRS_AND_WRITABLE_CLASSES = new FileFilter() { public boolean accept(File file) { return ((null != file) && (file.isDirectory() || (file.canWrite() && file.getName().toLowerCase().endsWith(".class")))); } }; private static final boolean PERMIT_CVS; static { String name = FileUtil.class.getName() + ".PERMIT_CVS"; PERMIT_CVS = LangUtil.getBoolean(name, false); } /** @return true if file exists and is a zip file */ public static boolean isZipFile(File file) { try { return (null != file) && new ZipFile(file) != null; } catch (IOException e) { return false; } } /** @return true if path ends with .zip or .jar */ // public static boolean hasZipSuffix(String path) { // return ((null != path) && (0 != zipSuffixLength(path))); // } /** @return 0 if file has no zip/jar suffix or 4 otherwise */ public static int zipSuffixLength(File file) { return (null == file ? 0 : zipSuffixLength(file.getPath())); } /** @return 0 if no zip/jar suffix or 4 otherwise */ public static int zipSuffixLength(String path) { if ((null != path) && (4 < path.length())) { String test = path.substring(path.length() - 4).toLowerCase(); if (".zip".equals(test) || ".jar".equals(test)) { return 4; } } return 0; } /** @return true if file path has a source suffix */ public static boolean hasSourceSuffix(File file) { return ((null != file) && hasSourceSuffix(file.getPath())); } /** @return true if path ends with .java or .aj */ public static boolean hasSourceSuffix(String path) { return ((null != path) && (0 != sourceSuffixLength(path))); } /** * @return 0 if file has no source suffix or the length of the suffix otherwise */ public static int sourceSuffixLength(File file) { return (null == file ? 0 : sourceSuffixLength(file.getPath())); } /** @return 0 if no source suffix or the length of the suffix otherwise */ public static int sourceSuffixLength(String path) { if (LangUtil.isEmpty(path)) { return 0; } for (Iterator<String> iter = SOURCE_SUFFIXES.iterator(); iter.hasNext();) { String suffix = iter.next(); if (path.endsWith(suffix) || path.toLowerCase().endsWith(suffix)) { return suffix.length(); } } return 0; } /** @return true if this is a readable directory */ public static boolean canReadDir(File dir) { return ((null != dir) && dir.canRead() && dir.isDirectory()); } /** @return true if this is a readable file */ public static boolean canReadFile(File file) { return ((null != file) && file.canRead() && file.isFile()); } /** @return true if dir is a writable directory */ public static boolean canWriteDir(File dir) { return ((null != dir) && dir.canWrite() && dir.isDirectory()); } /** @return true if this is a writable file */ public static boolean canWriteFile(File file) { return ((null != file) && file.canWrite() && file.isFile()); } // /** // * @throws IllegalArgumentException unless file is readable and not a // * directory // */ // public static void throwIaxUnlessCanReadFile(File file, String label) { // if (!canReadFile(file)) { // throw new IllegalArgumentException(label + " not readable file: " + // file); // } // } /** * @throws IllegalArgumentException unless dir is a readable directory */ public static void throwIaxUnlessCanReadDir(File dir, String label) { if (!canReadDir(dir)) { throw new IllegalArgumentException(label + " not readable dir: " + dir); } } /** * @throws IllegalArgumentException unless file is readable and not a directory */ public static void throwIaxUnlessCanWriteFile(File file, String label) { if (!canWriteFile(file)) { throw new IllegalArgumentException(label + " not writable file: " + file); } } /** @throws IllegalArgumentException unless dir is a readable directory */ public static void throwIaxUnlessCanWriteDir(File dir, String label) { if (!canWriteDir(dir)) { throw new IllegalArgumentException(label + " not writable dir: " + dir); } } /** @return array same length as input, with String paths */ public static String[] getPaths(File[] files) { if ((null == files) || (0 == files.length)) { return new String[0]; } String[] result = new String[files.length]; for (int i = 0; i < result.length; i++) { if (null != files[i]) { result[i] = files[i].getPath(); } } return result; } /** @return array same length as input, with String paths */ public static String[] getPaths(List<File> files) { final int size = (null == files ? 0 : files.size()); if (0 == size) { return new String[0]; } String[] result = new String[size]; for (int i = 0; i < size; i++) { File file = files.get(i); if (null != file) { result[i] = file.getPath(); } } return result; } /** * Extract the name of a class from the path to its file. If the basedir is null, then the class is assumed to be in the default * package unless the classFile has one of the top-level suffixes { com, org, java, javax } as a parent directory. * * @param basedir the File of the base directory (prefix of classFile) * @param classFile the File of the class to extract the name for * @throws IllegalArgumentException if classFile is null or does not end with ".class" or a non-null basedir is not a prefix of * classFile */ public static String fileToClassName(File basedir, File classFile) { LangUtil.throwIaxIfNull(classFile, "classFile"); String classFilePath = normalizedPath(classFile); if (!classFilePath.endsWith(".class")) { String m = classFile + " does not end with .class"; throw new IllegalArgumentException(m); } classFilePath = classFilePath.substring(0, classFilePath.length() - 6); if (null != basedir) { String basePath = normalizedPath(basedir); if (!classFilePath.startsWith(basePath)) { String m = classFile + " does not start with " + basedir; throw new IllegalArgumentException(m); } classFilePath = classFilePath.substring(basePath.length() + 1); } else { final String[] suffixes = new String[] { "com", "org", "java", "javax" }; boolean found = false; for (int i = 0; !found && (i < suffixes.length); i++) { int loc = classFilePath.indexOf(suffixes[i] + "/"); if ((0 == loc) || ((-1 != loc) && ('/' == classFilePath.charAt(loc - 1)))) { classFilePath = classFilePath.substring(loc); found = true; } } if (!found) { int loc = classFilePath.lastIndexOf("/"); if (-1 != loc) { // treat as default package classFilePath = classFilePath.substring(loc + 1); } } } return classFilePath.replace('/', '.'); } /** * Normalize path for comparisons by rendering absolute, clipping basedir prefix, trimming and changing '\\' to '/' * * @param file the File with the path to normalize * @param basedir the File for the prefix of the file to normalize - ignored if null * @return "" if null or normalized path otherwise * @throws IllegalArgumentException if basedir is not a prefix of file */ public static String normalizedPath(File file, File basedir) { String filePath = normalizedPath(file); if (null != basedir) { String basePath = normalizedPath(basedir); if (filePath.startsWith(basePath)) { filePath = filePath.substring(basePath.length()); if (filePath.startsWith("/")) { filePath = filePath.substring(1); } } } return filePath; } /** * Render a set of files to String as a path by getting absolute paths of each and delimiting with infix. * * @param files the File[] to flatten - may be null or empty * @param infix the String delimiter internally between entries (if null, then use File.pathSeparator). (alias to * <code>flatten(getAbsolutePaths(files), infix)</code> * @return String with absolute paths to entries in order, delimited with infix */ public static String flatten(File[] files, String infix) { if (LangUtil.isEmpty(files)) { return ""; } return flatten(getPaths(files), infix); } /** * Flatten File[] to String. * * @param files the File[] of paths to flatten - null ignored * @param infix the String infix to use - null treated as File.pathSeparator */ public static String flatten(String[] paths, String infix) { if (null == infix) { infix = File.pathSeparator; } StringBuffer result = new StringBuffer(); boolean first = true; for (int i = 0; i < paths.length; i++) { String path = paths[i]; if (null == path) { continue; } if (first) { first = false; } else { result.append(infix); } result.append(path); } return result.toString(); } /** * Normalize path for comparisons by rendering absolute trimming and changing '\\' to '/' * * @return "" if null or normalized path otherwise */ public static String normalizedPath(File file) { return (null == file ? "" : weakNormalize(file.getAbsolutePath())); } /** * Weakly normalize path for comparisons by trimming and changing '\\' to '/' */ public static String weakNormalize(String path) { if (null != path) { path = path.replace('\\', '/').trim(); } return path; } /** * Get best File for the first-readable path in input paths, treating entries prefixed "sp:" as system property keys. Safe to * call in static initializers. * * @param paths the String[] of paths to check. * @return null if not found, or valid File otherwise */ public static File getBestFile(String[] paths) { if (null == paths) { return null; } File result = null; for (int i = 0; (null == result) && (i < paths.length); i++) { String path = paths[i]; if (null == path) { continue; } if (path.startsWith("sp:")) { try { path = System.getProperty(path.substring(3)); } catch (Throwable t) { path = null; } if (null == path) { continue; } } try { File f = new File(path); if (f.exists() && f.canRead()) { result = FileUtil.getBestFile(f); } } catch (Throwable t) { // swallow } } return result; } /** * Render as best file, canonical or absolute. * * @param file the File to get the best File for (not null) * @return File of the best-available path * @throws IllegalArgumentException if file is null */ public static File getBestFile(File file) { LangUtil.throwIaxIfNull(file, "file"); if (file.exists()) { try { return file.getCanonicalFile(); } catch (IOException e) { return file.getAbsoluteFile(); } } else { return file; } } /** * Render as best path, canonical or absolute. * * @param file the File to get the path for (not null) * @return String of the best-available path * @throws IllegalArgumentException if file is null */ public static String getBestPath(File file) { LangUtil.throwIaxIfNull(file, "file"); if (file.exists()) { try { return file.getCanonicalPath(); } catch (IOException e) { return file.getAbsolutePath(); } } else { return file.getPath(); } } /** @return array same length as input, with String absolute paths */ public static String[] getAbsolutePaths(File[] files) { if ((null == files) || (0 == files.length)) { return new String[0]; } String[] result = new String[files.length]; for (int i = 0; i < result.length; i++) { if (null != files[i]) { result[i] = files[i].getAbsolutePath(); } } return result; } /** * Recursively delete the contents of dir, but not the dir itself * * @return the total number of files deleted */ public static int deleteContents(File dir) { return deleteContents(dir, ALL); } /** * Recursively delete some contents of dir, but not the dir itself. This deletes any subdirectory which is empty after its files * are deleted. * * @return the total number of files deleted */ public static int deleteContents(File dir, FileFilter filter) { return deleteContents(dir, filter, true); } /** * Recursively delete some contents of dir, but not the dir itself. If deleteEmptyDirs is true, this deletes any subdirectory * which is empty after its files are deleted. * * @param dir the File directory (if a file, the the file is deleted) * @return the total number of files deleted */ public static int deleteContents(File dir, FileFilter filter, boolean deleteEmptyDirs) { if (null == dir) { throw new IllegalArgumentException("null dir"); } if ((!dir.exists()) || (!dir.canWrite())) { return 0; } if (!dir.isDirectory()) { dir.delete(); return 1; } String[] fromFiles = dir.list(); int result = 0; for (int i = 0; i < fromFiles.length; i++) { String string = fromFiles[i]; File file = new File(dir, string); if ((null == filter) || filter.accept(file)) { if (file.isDirectory()) { result += deleteContents(file, filter, deleteEmptyDirs); if (deleteEmptyDirs && (0 == file.list().length)) { file.delete(); } } else { /* boolean ret = */file.delete(); result++; } } } return result; } /** * Copy contents of fromDir into toDir * * @param fromDir must exist and be readable * @param toDir must exist or be creatable and be writable * @return the total number of files copied */ public static int copyDir(File fromDir, File toDir) throws IOException { return copyDir(fromDir, toDir, null, null); } /** * Recursively copy files in fromDir (with any fromSuffix) to toDir, replacing fromSuffix with toSuffix if any. This silently * ignores dirs and files that are not readable but throw IOException for directories that are not writable. This does not clean * out the original contents of toDir. (subdirectories are not renamed per directory rules) * * @param fromSuffix select files with this suffix - select all if null or empty * @param toSuffix replace fromSuffix with toSuffix in the destination file name - ignored if null or empty, appended to name if * fromSuffix is null or empty * @return the total number of files copied */ public static int copyDir(File fromDir, File toDir, final String fromSuffix, String toSuffix) throws IOException { return copyDir(fromDir, toDir, fromSuffix, toSuffix, (FileFilter) null); } // /** // * Recursively copy files in fromDir (with any fromSuffix) to toDir, // * replacing fromSuffix with toSuffix if any, and adding the destination // * file to any collector. This silently ignores dirs and files that are // not // * readable but throw IOException for directories that are not writable. // * This does not clean out the original contents of toDir. (subdirectories // * are not renamed per directory rules) This calls any delegate // * FilenameFilter to collect any selected file. // * // * @param fromSuffix select files with this suffix - select all if null or // * empty // * @param toSuffix replace fromSuffix with toSuffix in the destination // file // * name - ignored if null or empty, appended to name if // * fromSuffix is null or empty // * @param collector the List sink for destination files - ignored if null // * @return the total number of files copied // */ // public static int copyDir(File fromDir, File toDir, final String // fromSuffix, final String toSuffix, final List collector) // throws IOException { // // int before = collector.size(); // if (null == collector) { // return copyDir(fromDir, toDir, fromSuffix, toSuffix); // } else { // FileFilter collect = new FileFilter() { // public boolean accept(File pathname) { // return collector.add(pathname); // } // }; // return copyDir(fromDir, toDir, fromSuffix, toSuffix, collect); // } // } /** * Recursively copy files in fromDir (with any fromSuffix) to toDir, replacing fromSuffix with toSuffix if any. This silently * ignores dirs and files that are not readable but throw IOException for directories that are not writable. This does not clean * out the original contents of toDir. (subdirectories are not renamed per directory rules) This calls any delegate * FilenameFilter to collect any selected file. * * @param fromSuffix select files with this suffix - select all if null or empty * @param toSuffix replace fromSuffix with toSuffix in the destination file name - ignored if null or empty, appended to name if * fromSuffix is null or empty * @return the total number of files copied */ public static int copyDir(File fromDir, File toDir, final String fromSuffix, final String toSuffix, final FileFilter delegate) throws IOException { if ((null == fromDir) || (!fromDir.canRead())) { return 0; } final boolean haveSuffix = ((null != fromSuffix) && (0 < fromSuffix.length())); final int slen = (!haveSuffix ? 0 : fromSuffix.length()); if (!toDir.exists()) { toDir.mkdirs(); } final String[] fromFiles; if (!haveSuffix) { fromFiles = fromDir.list(); } else { FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { return (new File(dir, name).isDirectory() || (name.endsWith(fromSuffix))); } }; fromFiles = fromDir.list(filter); } int result = 0; final int MAX = (null == fromFiles ? 0 : fromFiles.length); for (int i = 0; i < MAX; i++) { String filename = fromFiles[i]; File fromFile = new File(fromDir, filename); if (fromFile.canRead()) { if (fromFile.isDirectory()) { result += copyDir(fromFile, new File(toDir, filename), fromSuffix, toSuffix, delegate); } else if (fromFile.isFile()) { if (haveSuffix) { filename = filename.substring(0, filename.length() - slen); } if (null != toSuffix) { filename = filename + toSuffix; } File targetFile = new File(toDir, filename); if ((null == delegate) || delegate.accept(targetFile)) { copyFile(fromFile, targetFile); } result++; } } } return result; } /** * Recursively list files in srcDir. * * @return ArrayList with String paths of File under srcDir (relative to srcDir) */ public static String[] listFiles(File srcDir) { ArrayList<String> result = new ArrayList<String>(); if ((null != srcDir) && srcDir.canRead()) { listFiles(srcDir, null, result); } return result.toArray(new String[0]); } public static final FileFilter aspectjSourceFileFilter = new FileFilter() { public boolean accept(File pathname) { String name = pathname.getName().toLowerCase(); return name.endsWith(".java") || name.endsWith(".aj"); } }; /** * Recursively list files in srcDir. * * @return ArrayList with String paths of File under srcDir (relative to srcDir) */ public static File[] listFiles(File srcDir, FileFilter fileFilter) { ArrayList<File> result = new ArrayList<File>(); if ((null != srcDir) && srcDir.canRead()) { listFiles(srcDir, result, fileFilter); } return result.toArray(new File[result.size()]); } /** * Recursively list .class files in specified directory * * @return List of File objects */ public static List<File> listClassFiles(File dir) { ArrayList<File> result = new ArrayList<File>(); if ((null != dir) && dir.canRead()) { listClassFiles(dir, result); } return result; } /** * Convert String[] paths to File[] as offset of base directory * * @param basedir the non-null File base directory for File to create with paths * @param paths the String[] of paths to create * @return File[] with same length as paths */ public static File[] getBaseDirFiles(File basedir, String[] paths) { return getBaseDirFiles(basedir, paths, (String[]) null); } /** * Convert String[] paths to File[] as offset of base directory * * @param basedir the non-null File base directory for File to create with paths * @param paths the String[] of paths to create * @param suffixes the String[] of suffixes to limit sources to - ignored if null * @return File[] with same length as paths */ public static File[] getBaseDirFiles(File basedir, String[] paths, String[] suffixes) { LangUtil.throwIaxIfNull(basedir, "basedir"); LangUtil.throwIaxIfNull(paths, "paths"); File[] result = null; if (!LangUtil.isEmpty(suffixes)) { ArrayList<File> list = new ArrayList<File>(); for (int i = 0; i < paths.length; i++) { String path = paths[i]; for (int j = 0; j < suffixes.length; j++) { if (path.endsWith(suffixes[j])) { list.add(new File(basedir, paths[i])); break; } } } result = list.toArray(new File[0]); } else { result = new File[paths.length]; for (int i = 0; i < result.length; i++) { result[i] = newFile(basedir, paths[i]); } } return result; } /** * Create a new File, resolving paths ".." and "." specially. * * @param dir the File for the parent directory of the file * @param path the path in the parent directory (filename only?) * @return File for the new file. */ private static File newFile(File dir, String path) { if (".".equals(path)) { return dir; } else if ("..".equals(path)) { File parentDir = dir.getParentFile(); if (null != parentDir) { return parentDir; } else { return new File(dir, ".."); } } else { return new File(dir, path); } } /** * Copy files from source dir into destination directory, creating any needed directories. This differs from copyDir in not * being recursive; each input with the source dir creates a full path. However, if the source is a directory, it is copied as * such. * * @param srcDir an existing, readable directory containing relativePaths files * @param relativePaths a set of paths relative to srcDir to readable File to copy * @param destDir an existing, writable directory to copy files to * @throws IllegalArgumentException if input invalid, IOException if operations fail */ public static File[] copyFiles(File srcDir, String[] relativePaths, File destDir) throws IllegalArgumentException, IOException { final String[] paths = relativePaths; throwIaxUnlessCanReadDir(srcDir, "srcDir"); throwIaxUnlessCanWriteDir(destDir, "destDir"); LangUtil.throwIaxIfNull(paths, "relativePaths"); File[] result = new File[paths.length]; for (int i = 0; i < paths.length; i++) { String path = paths[i]; LangUtil.throwIaxIfNull(path, "relativePaths-entry"); File src = newFile(srcDir, paths[i]); File dest = newFile(destDir, path); File destParent = dest.getParentFile(); if (!destParent.exists()) { destParent.mkdirs(); } LangUtil.throwIaxIfFalse(canWriteDir(destParent), "dest-entry-parent"); copyFile(src, dest); // both file-dir and dir-dir copies result[i] = dest; } return result; } /** * Copy fromFile to toFile, handling file-file, dir-dir, and file-dir copies. * * @param fromFile the File path of the file or directory to copy - must be readable * @param toFile the File path of the target file or directory - must be writable (will be created if it does not exist) */ public static void copyFile(File fromFile, File toFile) throws IOException { LangUtil.throwIaxIfNull(fromFile, "fromFile"); LangUtil.throwIaxIfNull(toFile, "toFile"); LangUtil.throwIaxIfFalse(!toFile.equals(fromFile), "same file"); if (toFile.isDirectory()) { // existing directory throwIaxUnlessCanWriteDir(toFile, "toFile"); if (fromFile.isFile()) { // file-dir File targFile = new File(toFile, fromFile.getName()); copyValidFiles(fromFile, targFile); } else if (fromFile.isDirectory()) { // dir-dir copyDir(fromFile, toFile); } else { LangUtil.throwIaxIfFalse(false, "not dir or file: " + fromFile); } } else if (toFile.isFile()) { // target file exists if (fromFile.isDirectory()) { LangUtil.throwIaxIfFalse(false, "can't copy to file dir: " + fromFile); } copyValidFiles(fromFile, toFile); // file-file } else { // target file is a non-existent path -- could be file or dir /* File toFileParent = */ensureParentWritable(toFile); if (fromFile.isFile()) { copyValidFiles(fromFile, toFile); } else if (fromFile.isDirectory()) { toFile.mkdirs(); throwIaxUnlessCanWriteDir(toFile, "toFile"); copyDir(fromFile, toFile); } else { LangUtil.throwIaxIfFalse(false, "not dir or file: " + fromFile); } } } /** * Ensure that the parent directory to path can be written. If the path has a null parent, DEFAULT_PARENT is tested. If the path * parent does not exist, this tries to create it. * * @param path the File path whose parent should be writable * @return the File path of the writable parent directory * @throws IllegalArgumentException if parent cannot be written or path is null. */ public static File ensureParentWritable(File path) { LangUtil.throwIaxIfNull(path, "path"); File pathParent = path.getParentFile(); if (null == pathParent) { pathParent = DEFAULT_PARENT; } if (!pathParent.canWrite()) { pathParent.mkdirs(); } throwIaxUnlessCanWriteDir(pathParent, "pathParent"); return pathParent; } /** * Copy file to file. * * @param fromFile the File to copy (readable, non-null file) * @param toFile the File to copy to (non-null, parent dir exists) * @throws IOException */ public static void copyValidFiles(File fromFile, File toFile) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(fromFile); out = new FileOutputStream(toFile); copyStream(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } } /** do line-based copying */ public static void copyStream(DataInputStream in, PrintStream out) throws IOException { LangUtil.throwIaxIfNull(in, "in"); LangUtil.throwIaxIfNull(in, "out"); String s; while (null != (s = in.readLine())) { out.println(s); } } public static void copyStream(InputStream in, OutputStream out) throws IOException { final int MAX = 4096; byte[] buf = new byte[MAX]; for (int bytesRead = in.read(buf, 0, MAX); bytesRead != -1; bytesRead = in.read(buf, 0, MAX)) { out.write(buf, 0, bytesRead); } } public static void copyStream(Reader in, Writer out) throws IOException { final int MAX = 4096; char[] buf = new char[MAX]; for (int bytesRead = in.read(buf, 0, MAX); bytesRead != -1; bytesRead = in.read(buf, 0, MAX)) { out.write(buf, 0, bytesRead); } } /** * Make a new child directory of parent * * @param parent a File for the parent (writable) * @param child a prefix for the child directory * @return a File dir that exists with parentDir as the parent file or null */ public static File makeNewChildDir(File parent, String child) { if (null == parent || !parent.canWrite() || !parent.isDirectory()) { throw new IllegalArgumentException("bad parent: " + parent); } else if (null == child) { child = "makeNewChildDir"; } else if (!isValidFileName(child)) { throw new IllegalArgumentException("bad child: " + child); } File result = new File(parent, child); int safety = 1000; for (String suffix = FileUtil.randomFileString(); ((0 < --safety) && result.exists()); suffix = FileUtil.randomFileString()) { result = new File(parent, child + suffix); } if (result.exists()) { System.err.println("exhausted files for child dir in " + parent); return null; } return ((result.mkdirs() && result.exists()) ? result : null); } /** * Make a new temporary directory in the same directory that the system uses for temporary files, or if that files, in the * current directory. * * @param name the preferred (simple) name of the directory - may be null. * @return File of an existing new temp dir, or null if unable to create */ public static File getTempDir(String name) { if (null == name) { name = "FileUtil_getTempDir"; } else if (!isValidFileName(name)) { throw new IllegalArgumentException(" invalid: " + name); } File result = null; File tempFile = null; try { tempFile = File.createTempFile("ignoreMe", ".txt"); File tempParent = tempFile.getParentFile(); result = makeNewChildDir(tempParent, name); } catch (IOException t) { result = makeNewChildDir(new File("."), name); } finally { if (null != tempFile) { tempFile.delete(); } } return result; } public static URL[] getFileURLs(File[] files) { if ((null == files) || (0 == files.length)) { return new URL[0]; } URL[] result = new URL[files.length]; // XXX dangerous non-copy... for (int i = 0; i < result.length; i++) { result[i] = getFileURL(files[i]); } return result; } /** * Get URL for a File. This appends "/" for directories. prints errors to System.err * * @param file the File to convert to URL (not null) */ public static URL getFileURL(File file) { LangUtil.throwIaxIfNull(file, "file"); URL result = null; try { result = file.toURL();// TODO AV - was toURI.toURL that does not // works on Java 1.3 if (null != result) { return result; } String url = "file:" + file.getAbsolutePath().replace('\\', '/'); result = new URL(url + (file.isDirectory() ? "/" : "")); } catch (MalformedURLException e) { String m = "Util.makeURL(\"" + file.getPath() + "\" MUE " + e.getMessage(); System.err.println(m); } return result; } /** * Write contents to file, returning null on success or error message otherwise. This tries to make any necessary parent * directories first. * * @param file the File to write (not null) * @param contents the String to write (use "" if null) * @return String null on no error, error otherwise */ public static String writeAsString(File file, String contents) { LangUtil.throwIaxIfNull(file, "file"); if (null == contents) { contents = ""; } Writer out = null; try { File parentDir = file.getParentFile(); if (!parentDir.exists() && !parentDir.mkdirs()) { return "unable to make parent dir for " + file; } Reader in = new StringReader(contents); out = new FileWriter(file); FileUtil.copyStream(in, out); return null; } catch (IOException e) { return LangUtil.unqualifiedClassName(e) + " writing " + file + ": " + e.getMessage(); } finally { if (null != out) { try { out.close(); } catch (IOException e) { } // ignored } } } /** * Reads a boolean array with our encoding */ public static boolean[] readBooleanArray(DataInputStream s) throws IOException { int len = s.readInt(); boolean[] ret = new boolean[len]; for (int i = 0; i < len; i++) { ret[i] = s.readBoolean(); } return ret; } /** * Writes a boolean array with our encoding */ public static void writeBooleanArray(boolean[] a, DataOutputStream s) throws IOException { int len = a.length; s.writeInt(len); for (int i = 0; i < len; i++) { s.writeBoolean(a[i]); } } /** * Reads an int array with our encoding */ public static int[] readIntArray(DataInputStream s) throws IOException { int len = s.readInt(); int[] ret = new int[len]; for (int i = 0; i < len; i++) { ret[i] = s.readInt(); } return ret; } /** * Writes an int array with our encoding */ public static void writeIntArray(int[] a, DataOutputStream s) throws IOException { int len = a.length; s.writeInt(len); for (int i = 0; i < len; i++) { s.writeInt(a[i]); } } /** * Reads an int array with our encoding */ public static String[] readStringArray(DataInputStream s) throws IOException { int len = s.readInt(); String[] ret = new String[len]; for (int i = 0; i < len; i++) { ret[i] = s.readUTF(); } return ret; } /** * Writes an int array with our encoding */ public static void writeStringArray(String[] a, DataOutputStream s) throws IOException { if (a == null) { s.writeInt(0); return; } int len = a.length; s.writeInt(len); for (int i = 0; i < len; i++) { s.writeUTF(a[i]); } } /** * Returns the contents of this file as a String */ public static String readAsString(File file) throws IOException { BufferedReader r = new BufferedReader(new FileReader(file)); StringBuffer b = new StringBuffer(); while (true) { int ch = r.read(); if (ch == -1) { break; } b.append((char) ch); } r.close(); return b.toString(); } // /** // * Returns the contents of this stream as a String // */ // public static String readAsString(InputStream in) throws IOException { // BufferedReader r = new BufferedReader(new InputStreamReader(in)); // StringBuffer b = new StringBuffer(); // while (true) { // int ch = r.read(); // if (ch == -1) // break; // b.append((char) ch); // } // in.close(); // r.close(); // return b.toString(); // } /** * Returns the contents of this file as a byte[] */ public static byte[] readAsByteArray(File file) throws IOException { FileInputStream in = new FileInputStream(file); byte[] ret = FileUtil.readAsByteArray(in); in.close(); return ret; } /** * Reads this input stream and returns contents as a byte[] */ public static byte[] readAsByteArray(InputStream inStream) throws IOException { int size = 1024; byte[] ba = new byte[size]; int readSoFar = 0; while (true) { int nRead = inStream.read(ba, readSoFar, size - readSoFar); if (nRead == -1) { break; } readSoFar += nRead; if (readSoFar == size) { int newSize = size * 2; byte[] newBa = new byte[newSize]; System.arraycopy(ba, 0, newBa, 0, size); ba = newBa; size = newSize; } } byte[] newBa = new byte[readSoFar]; System.arraycopy(ba, 0, newBa, 0, readSoFar); return newBa; } final static String FILECHARS = "abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; /** @return semi-random String of length 6 usable as filename suffix */ static String randomFileString() { final double FILECHARS_length = FILECHARS.length(); final int LEN = 6; final char[] result = new char[LEN]; int index = (int) (Math.random() * 6d); for (int i = 0; i < LEN; i++) { if (index >= LEN) { index = 0; } result[index++] = FILECHARS.charAt((int) (Math.random() * FILECHARS_length)); } return new String(result); } public static InputStream getStreamFromZip(String zipFile, String name) { try { ZipFile zf = new ZipFile(zipFile); try { ZipEntry entry = zf.getEntry(name); return zf.getInputStream(entry); } finally { // ??? is it safe not to close this zf.close(); } } catch (IOException ioe) { return null; } } // // public static void extractJar(String zipFile, String outDir) throws // IOException { // ZipInputStream zs = new ZipInputStream(new FileInputStream(zipFile)); // ZipEntry entry; // while ((entry = zs.getNextEntry()) != null) { // if (entry.isDirectory()) // continue; // byte[] in = readAsByteArray(zs); // // File outFile = new File(outDir + "/" + entry.getName()); // // if (!outFile.getParentFile().exists()) // // System.err.println("parent: " + outFile.getParentFile()); // // System.err.println("parent: " + outFile.getParentFile()); // outFile.getParentFile().mkdirs(); // FileOutputStream os = new FileOutputStream(outFile); // os.write(in); // os.close(); // zs.closeEntry(); // } // zs.close(); // } /** * Do line-based search for literal text in source files, returning file:line where found. * * @param sought the String text to seek in the file * @param sources the List of String paths to the source files * @param listAll if false, only list first match in file * @param errorSink the PrintStream to print any errors to (one per line) (use null to silently ignore errors) * @return List of String of the form file:line for each found entry (never null, might be empty) */ // OPTIMIZE only used by tests? move it out public static List<String> lineSeek(String sought, List<String> sources, boolean listAll, PrintStream errorSink) { if (LangUtil.isEmpty(sought) || LangUtil.isEmpty(sources)) { return Collections.emptyList(); } ArrayList<String> result = new ArrayList<String>(); for (Iterator<String> iter = sources.iterator(); iter.hasNext();) { String path = iter.next(); String error = lineSeek(sought, path, listAll, result); if ((null != error) && (null != errorSink)) { errorSink.println(error); } } return result; } /** * Do line-based search for literal text in source file, returning line where found as a String in the form * {sourcePath}:line:column submitted to the collecting parameter sink. Any error is rendered to String and returned as the * result. * * @param sought the String text to seek in the file * @param sources the List of String paths to the source files * @param listAll if false, only list first match in file * @param List sink the List for String entries of the form {sourcePath}:line:column * @return String error if any, or add String entries to sink */ public static String lineSeek(String sought, String sourcePath, boolean listAll, ArrayList<String> sink) { if (LangUtil.isEmpty(sought) || LangUtil.isEmpty(sourcePath)) { return "nothing sought"; } if (LangUtil.isEmpty(sourcePath)) { return "no sourcePath"; } final File file = new File(sourcePath); if (!file.canRead() || !file.isFile()) { return "sourcePath not a readable file"; } int lineNum = 0; FileReader fin = null; try { fin = new FileReader(file); BufferedReader reader = new BufferedReader(fin); String line; while (null != (line = reader.readLine())) { lineNum++; int loc = line.indexOf(sought); if (-1 != loc) { sink.add(sourcePath + ":" + lineNum + ":" + loc); if (!listAll) { break; } } } } catch (IOException e) { return LangUtil.unqualifiedClassName(e) + " reading " + sourcePath + ":" + lineNum; } finally { try { if (null != fin) { fin.close(); } } catch (IOException e) { } // ignore } return null; } public static BufferedOutputStream makeOutputStream(File file) throws FileNotFoundException { File parent = file.getParentFile(); if (parent != null) { parent.mkdirs(); } return new BufferedOutputStream(new FileOutputStream(file)); } /** * Sleep until after the last last-modified stamp from the files. * * @param files the File[] of files to inspect for last modified times (this ignores null or empty files array and null or * non-existing components of files array) * @return true if succeeded without 100 interrupts */ public static boolean sleepPastFinalModifiedTime(File[] files) { if ((null == files) || (0 == files.length)) { return true; } long delayUntil = System.currentTimeMillis(); for (int i = 0; i < files.length; i++) { File file = files[i]; if ((null == file) || !file.exists()) { continue; } long nextModTime = file.lastModified(); if (nextModTime > delayUntil) { delayUntil = nextModTime; } } return LangUtil.sleepUntil(++delayUntil); } private static void listClassFiles(final File baseDir, ArrayList<File> result) { File[] files = baseDir.listFiles(); for (int i = 0; i < files.length; i++) { File f = files[i]; if (f.isDirectory()) { listClassFiles(f, result); } else { if (f.getName().endsWith(".class")) { result.add(f); } } } } private static void listFiles(final File baseDir, ArrayList<File> result, FileFilter filter) { File[] files = baseDir.listFiles(); // hack https://bugs.eclipse.org/bugs/show_bug.cgi?id=48650 final boolean skipCVS = (!PERMIT_CVS && (filter == aspectjSourceFileFilter)); for (int i = 0; i < files.length; i++) { File f = files[i]; if (f.isDirectory()) { if (skipCVS) { String name = f.getName().toLowerCase(); if ("cvs".equals(name) || "sccs".equals(name)) { continue; } } listFiles(f, result, filter); } else { if (filter.accept(f)) { result.add(f); } } } } /** @return true if input is not null and contains no path separator */ private static boolean isValidFileName(String input) { return ((null != input) && (-1 == input.indexOf(File.pathSeparator))); } private static void listFiles(final File baseDir, String dir, ArrayList<String> result) { final String dirPrefix = (null == dir ? "" : dir + "/"); final File dirFile = (null == dir ? baseDir : new File(baseDir.getPath() + "/" + dir)); final String[] files = dirFile.list(); for (int i = 0; i < files.length; i++) { File f = new File(dirFile, files[i]); String path = dirPrefix + files[i]; if (f.isDirectory()) { listFiles(baseDir, path, result); } else { result.add(path); } } } private FileUtil() { } public static List<String> makeClasspath(URL[] urls) { List<String> ret = new LinkedList<String>(); if (urls != null) { for (int i = 0; i < urls.length; i++) { ret.add(urls[i].getPath()); } } return ret; } /** * A pipe when run reads from an input stream to an output stream, optionally sleeping between reads. * * @see #copyStream(InputStream, OutputStream) */ public static class Pipe implements Runnable { private final InputStream in; private final OutputStream out; private final long sleep; private ByteArrayOutputStream snoop; private long totalWritten; private Throwable thrown; private boolean halt; /** * Seem to be unable to detect erroroneous closing of System.out... */ private final boolean closeInput; private final boolean closeOutput; /** * If true, then continue processing stream until no characters are returned when halting. */ private boolean finishStream; private boolean done; // true after completing() completes /** * alias for <code>Pipe(in, out, 100l, false, false)</code> * * @param in the InputStream source to read * @param out the OutputStream sink to write */ Pipe(InputStream in, OutputStream out) { this(in, out, 100l, false, false); } /** * @param in the InputStream source to read * @param out the OutputStream sink to write * @param tryClosingStreams if true, then try closing both streams when done * @param sleep milliseconds to delay between reads (pinned to 0..1 minute) */ Pipe(InputStream in, OutputStream out, long sleep, boolean closeInput, boolean closeOutput) { LangUtil.throwIaxIfNull(in, "in"); LangUtil.throwIaxIfNull(out, "out"); this.in = in; this.out = out; this.closeInput = closeInput; this.closeOutput = closeOutput; this.sleep = Math.min(0l, Math.max(60l * 1000l, sleep)); } public void setSnoop(ByteArrayOutputStream snoop) { this.snoop = snoop; } /** * Run the pipe. This halts on the first Throwable thrown or when a read returns -1 (for end-of-file) or on demand. */ public void run() { totalWritten = 0; if (halt) { return; } try { final int MAX = 4096; byte[] buf = new byte[MAX]; // TODO this blocks, hanging the harness int count = in.read(buf, 0, MAX); ByteArrayOutputStream mySnoop; while ((halt && finishStream && (0 < count)) || (!halt && (-1 != count))) { out.write(buf, 0, count); mySnoop = snoop; if (null != mySnoop) { mySnoop.write(buf, 0, count); } totalWritten += count; if (halt && !finishStream) { break; } if (!halt && (0 < sleep)) { Thread.sleep(sleep); } if (halt && !finishStream) { break; } count = in.read(buf, 0, MAX); } } catch (Throwable e) { thrown = e; } finally { halt = true; if (closeInput) { try { in.close(); } catch (IOException e) { // ignore } } if (closeOutput) { try { out.close(); } catch (IOException e) { // ignore } } done = true; completing(totalWritten, thrown); } } /** * Tell the pipe to halt the next time it gains control. * * @param wait if true, this waits synchronously until pipe is done * @param finishStream if true, then continue until a read from the input stream returns no bytes, then halt. * @return true if <code>run()</code> will return the next time it gains control */ public boolean halt(boolean wait, boolean finishStream) { if (!halt) { halt = true; } if (wait) { while (!done) { synchronized (this) { notifyAll(); } if (!done) { try { Thread.sleep(5l); } catch (InterruptedException e) { break; } } } } return halt; } /** @return the total number of bytes written */ public long totalWritten() { return totalWritten; } /** @return any exception thrown when reading/writing */ public Throwable getThrown() { return thrown; } /** * This is called when the pipe is completing. This implementation does nothing. Subclasses implement this to get notice. * Note that halt(true, true) might or might not have completed before this method is called. */ protected void completing(long totalWritten, Throwable thrown) { } } }
336,997
Bug 336997 IllegalStateException for generic ITD usage
java.lang.IllegalStateException: Can't answer binding questions prior to resolving at org.aspectj.weaver.TypeVariable.canBeBoundTo(TypeVariable.java:175) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:496) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:399) at org.aspectj.weaver.ResolvedType.checkLegalOverride(ResolvedType.java:1999) at org.aspectj.weaver.ResolvedType.clashesWithExistingMember(ResolvedType.java:1843) at org.aspectj.weaver.ResolvedType.addInterTypeMunger(ResolvedType.java:1699) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:795) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:652) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.createBinaryTypeFrom(AjLookupEnvironment.java:1398) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.createBinaryTypeFrom(LookupEnvironment.java:599) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.accept(Compiler.java:276) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.askForType(LookupEnvironment.java:113) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.UnresolvedReferenceBinding.resolve(UnresolvedReferenceBinding.java:49) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding.resolveType(BinaryTypeBinding.java:99) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.getType(LookupEnvironment.java:971) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.lookupBinding(EclipseFactory.java:749) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeTypeBinding1(EclipseFactory.java:743) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeTypeBinding(EclipseFactory.java:605) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.addParent(AjLookupEnvironment.java:1314) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.doDeclareParents(AjLookupEnvironment.java:902) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:730) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveIntertypes(AjLookupEnvironment.java:418) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:255) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.internalBeginToCompile(Compiler.java:616) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:357) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:371) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:1021) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performBuild(AjBuildManager.java:268) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:181) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:112) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:371) at org.aspectj.tools.ajc.Main.runMain(Main.java:248) at org.codehaus.mojo.aspectj.AbstractAjcCompiler.execute(AbstractAjcCompiler.java:360) at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:490) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:694) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:556) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:535) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:387) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:348) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:180) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138) at org.apache.maven.cli.MavenCli.main(MavenCli.java:362) at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:60) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315) at org.codehaus.classworlds.Launcher.launch(Launcher.java:255) at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430) at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
resolved fixed
80785bf
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-02-11T19:03:13Z"
"2011-02-11T18:46:40Z"
org.aspectj.matcher/src/org/aspectj/weaver/TypeVariable.java
/* ******************************************************************* * Copyright (c) 2005-2010 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 * ******************************************************************/ package org.aspectj.weaver; import java.io.IOException; /** * Represents a type variable with possible bounds. * * @author Adrian Colyer * @author Andy Clement */ public class TypeVariable { public static final TypeVariable[] NONE = new TypeVariable[0]; // the name of the type variable as recorded in the generic signature private String name; // index private int rank; // computed as required: either ==superclass or ==superInterfaces[0] or is OBJECT private UnresolvedType firstbound; // the upper bound of the type variable. From the extends clause, eg. T extends Number private UnresolvedType superclass; // any additional upper (interface) bounds. from the extends clause, e.g. T extends Number & Comparable private UnresolvedType[] superInterfaces = UnresolvedType.NONE; // It would be nice to push this field onto the TypeVariableDeclaringElement // interface (a getKind()) but at the moment we don't always guarantee // to set the declaring element (eclipse seems to utilise the knowledge of // what declared the type variable, but we dont yet...) public static final int UNKNOWN = -1; public static final int METHOD = 1; public static final int TYPE = 2; // What kind of element declared this type variable? private int declaringElementKind = UNKNOWN; private TypeVariableDeclaringElement declaringElement; // whether or not the bounds of this type variable have been resolved private boolean isResolved = false; // Is this type variable in the process of being resolved (allows for something self-referential like Enum) private boolean beingResolved = false; /** * Constructor for an unbound type variable, eg. 'T' */ public TypeVariable(String name) { this.name = name; } public TypeVariable(String name, UnresolvedType anUpperBound) { this(name); this.superclass = anUpperBound; } public TypeVariable(String name, UnresolvedType anUpperBound, UnresolvedType[] superInterfaces) { this(name, anUpperBound); this.superInterfaces = superInterfaces; } /** * @return the first bound, either the superclass or if non is specified the first interface or if non are specified then OBJECT */ public UnresolvedType getFirstBound() { if (firstbound != null) { return firstbound; } if (superclass == null || superclass.getSignature().equals("Ljava/lang/Object;")) { if (superInterfaces.length > 0) { firstbound = superInterfaces[0]; } else { firstbound = UnresolvedType.OBJECT; } } else { firstbound = superclass; } return firstbound; } public UnresolvedType getUpperBound() { return superclass; } public UnresolvedType[] getSuperInterfaces() { return superInterfaces; } public String getName() { return name; } /** * resolve all the bounds of this type variable */ public TypeVariable resolve(World world) { if (isResolved) { return this; } if (beingResolved) { return this; } beingResolved = true; TypeVariable resolvedTVar = null; if (declaringElement != null) { // resolve by finding the real type var that we refer to... if (declaringElementKind == TYPE) { UnresolvedType declaring = (UnresolvedType) declaringElement; ReferenceType rd = (ReferenceType) declaring.resolve(world); TypeVariable[] tVars = rd.getTypeVariables(); for (int i = 0; i < tVars.length; i++) { if (tVars[i].getName().equals(getName())) { resolvedTVar = tVars[i]; break; } } } else { // look for type variable on method... ResolvedMember declaring = (ResolvedMember) declaringElement; TypeVariable[] tvrts = declaring.getTypeVariables(); for (int i = 0; i < tvrts.length; i++) { if (tvrts[i].getName().equals(getName())) { resolvedTVar = tvrts[i]; // if (tvrts[i].isTypeVariableReference()) { // TypeVariableReferenceType tvrt = (TypeVariableReferenceType) tvrts[i].resolve(inSomeWorld); // TypeVariable tv = tvrt.getTypeVariable(); // if (tv.getName().equals(getName())) resolvedTVar = tv; // } } } } if (resolvedTVar == null) { throw new IllegalStateException(); // well, this is bad... we didn't find the type variable on the member // could be a separate compilation issue... // should issue message, this is a workaround to get us going... // resolvedTVar = this; } } else { resolvedTVar = this; } superclass = resolvedTVar.superclass; superInterfaces = resolvedTVar.superInterfaces; if (superclass != null) { ResolvedType rt = superclass.resolve(world); // if (!superclass.isTypeVariableReference() && rt.isInterface()) { // throw new IllegalStateException("Why is the type an interface? " + rt); // } superclass = rt; } firstbound = getFirstBound().resolve(world); for (int i = 0; i < superInterfaces.length; i++) { superInterfaces[i] = superInterfaces[i].resolve(world); } isResolved = true; beingResolved = false; return this; } /** * answer true if the given type satisfies all of the bound constraints of this type variable. If type variable has not been * resolved then throws IllegalStateException */ public boolean canBeBoundTo(ResolvedType candidate) { if (!isResolved) { throw new IllegalStateException("Can't answer binding questions prior to resolving"); } // wildcard can accept any binding if (candidate.isGenericWildcard()) { return true; } // otherwise can be bound iff... // candidate is a subtype of upperBound if (superclass != null && !isASubtypeOf(superclass, candidate)) { return false; } // candidate is a subtype of all superInterfaces for (int i = 0; i < superInterfaces.length; i++) { if (!isASubtypeOf(superInterfaces[i], candidate)) { return false; } } return true; } private boolean isASubtypeOf(UnresolvedType candidateSuperType, UnresolvedType candidateSubType) { ResolvedType superType = (ResolvedType) candidateSuperType; ResolvedType subType = (ResolvedType) candidateSubType; return superType.isAssignableFrom(subType); } // only used when resolving public void setUpperBound(UnresolvedType superclass) { // if (isResolved) { // throw new IllegalStateException("Why set this late?"); // } this.firstbound = null; this.superclass = superclass; } // only used when resolving public void setAdditionalInterfaceBounds(UnresolvedType[] superInterfaces) { if (isResolved) { throw new IllegalStateException("Why set this late?"); } this.firstbound = null; this.superInterfaces = superInterfaces; } public String toDebugString() { return getDisplayName(); } public String getDisplayName() { StringBuffer ret = new StringBuffer(); ret.append(name); if (!getFirstBound().getName().equals("java.lang.Object")) { ret.append(" extends "); ret.append(getFirstBound().getName()); if (superInterfaces != null) { for (int i = 0; i < superInterfaces.length; i++) { if (!getFirstBound().equals(superInterfaces[i])) { ret.append(" & "); ret.append(superInterfaces[i].getName()); } } } } return ret.toString(); } @Override public String toString() { return "TypeVar " + getDisplayName(); } /** * Return complete signature, e.g. "T extends Number" would return "T:Ljava/lang/Number;" note: MAY INCLUDE P types if bounds * are parameterized types */ public String getSignature() { StringBuffer sb = new StringBuffer(); sb.append(name); sb.append(":"); sb.append(superclass.getSignature()); if (superInterfaces.length != 0) { sb.append(":"); for (int i = 0; i < superInterfaces.length; i++) { UnresolvedType iBound = superInterfaces[i]; sb.append(iBound.getSignature()); } } return sb.toString(); } /** * @return signature for inclusion in an attribute, there must be no 'P' in it signatures */ public String getSignatureForAttribute() { StringBuffer sb = new StringBuffer(); sb.append(name); sb.append(":"); if (superInterfaces.length == 0) { sb.append(((ResolvedType) superclass).getSignatureForAttribute()); } if (superInterfaces.length != 0) { sb.append(":"); for (int i = 0; i < superInterfaces.length; i++) { ResolvedType iBound = (ResolvedType) superInterfaces[i]; sb.append(iBound.getSignatureForAttribute()); } } return sb.toString(); } public void setRank(int rank) { this.rank = rank; } public int getRank() { return rank; } public void setDeclaringElement(TypeVariableDeclaringElement element) { this.declaringElement = element; if (element instanceof UnresolvedType) { this.declaringElementKind = TYPE; } else { this.declaringElementKind = METHOD; } } public TypeVariableDeclaringElement getDeclaringElement() { return declaringElement; } public void setDeclaringElementKind(int kind) { this.declaringElementKind = kind; } public int getDeclaringElementKind() { // if (declaringElementKind==UNKNOWN) throw new RuntimeException("Dont know declarer of this tvar : "+this); return declaringElementKind; } public void write(CompressingDataOutputStream s) throws IOException { // name, upperbound, additionalInterfaceBounds, lowerbound s.writeUTF(name); superclass.write(s); if (superInterfaces.length == 0) { s.writeInt(0); } else { s.writeInt(superInterfaces.length); for (int i = 0; i < superInterfaces.length; i++) { UnresolvedType ibound = superInterfaces[i]; ibound.write(s); } } } public static TypeVariable read(VersionedDataInputStream s) throws IOException { // if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) { String name = s.readUTF(); UnresolvedType ubound = UnresolvedType.read(s); int iboundcount = s.readInt(); UnresolvedType[] ibounds = UnresolvedType.NONE; if (iboundcount > 0) { ibounds = new UnresolvedType[iboundcount]; for (int i = 0; i < iboundcount; i++) { ibounds[i] = UnresolvedType.read(s); } } TypeVariable newVariable = new TypeVariable(name, ubound, ibounds); return newVariable; } public String getGenericSignature() { return "T" + name + ";"; } public String getErasureSignature() { return getFirstBound().getErasureSignature(); } public UnresolvedType getSuperclass() { return superclass; } public void setSuperclass(UnresolvedType superclass) { this.firstbound = null; this.superclass = superclass; } }
336,997
Bug 336997 IllegalStateException for generic ITD usage
java.lang.IllegalStateException: Can't answer binding questions prior to resolving at org.aspectj.weaver.TypeVariable.canBeBoundTo(TypeVariable.java:175) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:496) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:399) at org.aspectj.weaver.ResolvedType.checkLegalOverride(ResolvedType.java:1999) at org.aspectj.weaver.ResolvedType.clashesWithExistingMember(ResolvedType.java:1843) at org.aspectj.weaver.ResolvedType.addInterTypeMunger(ResolvedType.java:1699) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:795) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:652) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.createBinaryTypeFrom(AjLookupEnvironment.java:1398) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.createBinaryTypeFrom(LookupEnvironment.java:599) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.accept(Compiler.java:276) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.askForType(LookupEnvironment.java:113) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.UnresolvedReferenceBinding.resolve(UnresolvedReferenceBinding.java:49) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding.resolveType(BinaryTypeBinding.java:99) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.getType(LookupEnvironment.java:971) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.lookupBinding(EclipseFactory.java:749) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeTypeBinding1(EclipseFactory.java:743) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeTypeBinding(EclipseFactory.java:605) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.addParent(AjLookupEnvironment.java:1314) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.doDeclareParents(AjLookupEnvironment.java:902) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:730) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveIntertypes(AjLookupEnvironment.java:418) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:255) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.internalBeginToCompile(Compiler.java:616) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:357) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:371) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:1021) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performBuild(AjBuildManager.java:268) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:181) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:112) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:371) at org.aspectj.tools.ajc.Main.runMain(Main.java:248) at org.codehaus.mojo.aspectj.AbstractAjcCompiler.execute(AbstractAjcCompiler.java:360) at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:490) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:694) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:556) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:535) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:387) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:348) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:180) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138) at org.apache.maven.cli.MavenCli.main(MavenCli.java:362) at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:60) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315) at org.codehaus.classworlds.Launcher.launch(Launcher.java:255) at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430) at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
resolved fixed
80785bf
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-02-11T19:03:13Z"
"2011-02-11T18:46:40Z"
org.aspectj.matcher/src/org/aspectj/weaver/TypeVariableReferenceType.java
/* ******************************************************************* * Copyright (c) 2005-2010 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 * ******************************************************************/ package org.aspectj.weaver; import java.util.Map; /** * ReferenceType representing a type variable. The delegate for this reference type is the upperbound on the type variable (so * Object if not otherwise specified). * * @author Adrian Colyer * @author Andy Clement */ public class TypeVariableReferenceType extends ReferenceType implements TypeVariableReference { private TypeVariable typeVariable; // If 'fixedUp' then the type variable in here is a reference to the real one that may // exist either on a member or a type. Not fixedUp means that we unpacked a generic // signature and weren't able to fix it up during resolution (didn't quite know enough // at the right time). Wonder if we can fix it up late? boolean fixedUp = false; public TypeVariableReferenceType(TypeVariable typeVariable, World world) { super(typeVariable.getGenericSignature(), typeVariable.getErasureSignature(), world); this.typeVariable = typeVariable; // setDelegate(new BoundedReferenceTypeDelegate(backing)); // this.isExtends = false; // this.isSuper = false; } /** * For a TypeVariableReferenceType the delegate is the delegate for the first bound. */ @Override public ReferenceTypeDelegate getDelegate() { if (this.delegate == null) { ResolvedType resolvedFirstBound = typeVariable.getFirstBound().resolve(world); BoundedReferenceTypeDelegate brtd = null; if (resolvedFirstBound.isMissing()) { brtd = new BoundedReferenceTypeDelegate((ReferenceType) world.resolve(UnresolvedType.OBJECT)); setDelegate(brtd); // set now because getSourceLocation() below will cause a recursive step to discover the delegate world.getLint().cantFindType.signal( "Unable to find type for generic bound. Missing type is " + resolvedFirstBound.getName(), getSourceLocation()); } else { brtd = new BoundedReferenceTypeDelegate((ReferenceType) resolvedFirstBound); setDelegate(brtd); } } return this.delegate; } @Override public UnresolvedType parameterize(Map<String, UnresolvedType> typeBindings) { UnresolvedType ut = typeBindings.get(getName()); if (ut != null) { return world.resolve(ut); } return this; } public TypeVariable getTypeVariable() { // if (!fixedUp) throw new BCException("ARGH"); // fix it up now? return typeVariable; } @Override public boolean isTypeVariableReference() { return true; } @Override public String toString() { return typeVariable.getName(); } @Override public boolean isGenericWildcard() { return false; } @Override public boolean isAnnotation() { ReferenceType upper = (ReferenceType) typeVariable.getUpperBound(); if (upper.isAnnotation()) { return true; } World world = upper.getWorld(); typeVariable.resolve(world); ResolvedType annotationType = ResolvedType.ANNOTATION.resolve(world); UnresolvedType[] ifBounds = typeVariable.getSuperInterfaces();// AdditionalBounds(); for (int i = 0; i < ifBounds.length; i++) { if (((ReferenceType) ifBounds[i]).isAnnotation()) { return true; } if (ifBounds[i].equals(annotationType)) { return true; // annotation itself does not have the annotation flag set in Java! } } return false; } /** * return the signature for a *REFERENCE* to a type variable, which is simply: Tname; there is no bounds info included, that is * in the signature of the type variable itself */ @Override public String getSignature() { StringBuffer sb = new StringBuffer(); sb.append("T"); sb.append(typeVariable.getName()); sb.append(";"); return sb.toString(); } /** * @return the name of the type variable */ public String getTypeVariableName() { return typeVariable.getName(); } public ReferenceType getUpperBound() { return (ReferenceType) typeVariable.resolve(world).getUpperBound(); } }
336,997
Bug 336997 IllegalStateException for generic ITD usage
java.lang.IllegalStateException: Can't answer binding questions prior to resolving at org.aspectj.weaver.TypeVariable.canBeBoundTo(TypeVariable.java:175) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:496) at org.aspectj.weaver.ReferenceType.isAssignableFrom(ReferenceType.java:399) at org.aspectj.weaver.ResolvedType.checkLegalOverride(ResolvedType.java:1999) at org.aspectj.weaver.ResolvedType.clashesWithExistingMember(ResolvedType.java:1843) at org.aspectj.weaver.ResolvedType.addInterTypeMunger(ResolvedType.java:1699) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:795) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:652) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.createBinaryTypeFrom(AjLookupEnvironment.java:1398) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.createBinaryTypeFrom(LookupEnvironment.java:599) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.accept(Compiler.java:276) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.askForType(LookupEnvironment.java:113) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.UnresolvedReferenceBinding.resolve(UnresolvedReferenceBinding.java:49) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding.resolveType(BinaryTypeBinding.java:99) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.getType(LookupEnvironment.java:971) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.lookupBinding(EclipseFactory.java:749) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeTypeBinding1(EclipseFactory.java:743) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeTypeBinding(EclipseFactory.java:605) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.addParent(AjLookupEnvironment.java:1314) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.doDeclareParents(AjLookupEnvironment.java:902) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:730) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveIntertypes(AjLookupEnvironment.java:418) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:255) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.internalBeginToCompile(Compiler.java:616) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:357) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:371) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:1021) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performBuild(AjBuildManager.java:268) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:181) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:112) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:371) at org.aspectj.tools.ajc.Main.runMain(Main.java:248) at org.codehaus.mojo.aspectj.AbstractAjcCompiler.execute(AbstractAjcCompiler.java:360) at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:490) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:694) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:556) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:535) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:387) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:348) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:180) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138) at org.apache.maven.cli.MavenCli.main(MavenCli.java:362) at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:60) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315) at org.codehaus.classworlds.Launcher.launch(Launcher.java:255) at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430) at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
resolved fixed
80785bf
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-02-11T19:03:13Z"
"2011-02-11T18:46: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, Abraham Nevado * ******************************************************************/ package org.aspectj.weaver; import java.lang.ref.Reference; 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.IMessage; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.context.PinpointingMessageHandler; import org.aspectj.util.IStructureModel; import org.aspectj.weaver.UnresolvedType.TypeKind; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.DeclareSoft; import org.aspectj.weaver.patterns.DeclareTypeErrorOrWarning; 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<PointcutDesignatorHandler> 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; /** Should timing information be reported (as info messages)? */ private boolean timing = false; private boolean timingPeriodically = true; /** 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 runMinimalMemorySet = false; private boolean shouldPipelineCompilation = true; private boolean shouldGenerateStackMaps = false; protected boolean bcelRepositoryCaching = xsetBCEL_REPOSITORY_CACHING_DEFAULT.equalsIgnoreCase("true"); private boolean fastMethodPacking = false; private int itdVersion = 2; // defaults to 2nd generation itds // Minimal Model controls whether model entities that are not involved in relationships are deleted post-build private boolean minimalModel = false; private boolean targettingRuntime1_6_10 = false; private boolean completeBinaryTypes = false; private boolean overWeaving = false; public boolean forDEBUG_structuralChangesCode = false; public boolean forDEBUG_bridgingCode = false; public boolean optimizedMatching = true; protected long timersPerJoinpoint = 25000; protected long timersPerType = 250; public int infoMessagesEnabled = 0; // 0=uninitialized, 1=no, 2=yes 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<RuntimeException> 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 ResolvedType.NONE; } 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 = getWildcard(); 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 ResolvedType result = typeMap.get(signature); if (result == null && !ret.isMissing()) { ret = ensureRawTypeIfNecessary(ret); typeMap.put(signature, ret); return ret; } if (result == null) { return ret; } else { return result; } } // Only need one representation of '?' in a world - can be shared private BoundedReferenceType wildcard; private BoundedReferenceType getWildcard() { if (wildcard == null) { wildcard = new BoundedReferenceType(this); } return wildcard; } /** * 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<RuntimeException>(); } 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) { resolved = ensureRawTypeIfNecessary(ty); typeMap.put(ty.getSignature(), resolved); resolved = ty; } resolved.world = this; return resolved; } /** * When the world is operating in 1.5 mode, the TypeMap should only contain RAW types and never directly generic types. The RAW * type will contain a reference to the generic type. * * @param type a possibly generic type for which the raw needs creating as it is not currently in the world * @return a type suitable for putting into the world */ private ResolvedType ensureRawTypeIfNecessary(ResolvedType type) { if (!isInJava5Mode() || type.isRawType()) { return type; } // Key requirement here is if it is generic, create a RAW entry to be put in the map that points to it if (type instanceof ReferenceType && ((ReferenceType) type).getDelegate() != null && type.isGenericType()) { ReferenceType rawType = new ReferenceType(type.getSignature(), this); rawType.typeKind = UnresolvedType.TypeKind.RAW; ReferenceTypeDelegate delegate = ((ReferenceType) type).getDelegate(); rawType.setDelegate(delegate); rawType.setGenericType((ReferenceType) type); return rawType; } // probably parameterized... return type; } /** * 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 ReferenceType resolveToReferenceType(String name) { return (ReferenceType) resolve(name); } 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 ====================== ResolvedType rt = resolveGenericTypeFor(ty, false); ReferenceType genericType = (ReferenceType) rt; 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 = getWildcard(); } 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); } private boolean allLintIgnored = false; public void setAllLintIgnored() { allLintIgnored = true; } public boolean areAllLintIgnored() { return allLintIgnored; } 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, ResolvedType declaringAspect) { AjAttribute.AdviceAttribute attribute = new AjAttribute.AdviceAttribute(kind, p, extraParameterFlags, loc.getStart(), loc.getEnd(), loc.getSourceContext()); return getWeavingSupport().createAdviceMunger(attribute, p, signature, declaringAspect); } /** * 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<DeclareParents> getDeclareParents() { return crosscuttingMembersSet.getDeclareParents(); } public List<DeclareAnnotation> getDeclareAnnotationOnTypes() { return crosscuttingMembersSet.getDeclareAnnotationOnTypes(); } public List<DeclareAnnotation> getDeclareAnnotationOnFields() { return crosscuttingMembersSet.getDeclareAnnotationOnFields(); } public List<DeclareAnnotation> getDeclareAnnotationOnMethods() { return crosscuttingMembersSet.getDeclareAnnotationOnMethods(); } public List<DeclareTypeErrorOrWarning> getDeclareTypeEows() { return crosscuttingMembersSet.getDeclareTypeEows(); } public List<DeclareSoft> 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 boolean isMinimalModel() { ensureAdvancedConfigurationProcessed(); return minimalModel; } public boolean isTargettingRuntime1_6_10() { ensureAdvancedConfigurationProcessed(); return targettingRuntime1_6_10; } public void setBehaveInJava5Way(boolean b) { behaveInJava5Way = b; } /** * Set the timing option (whether to collect timing info), this will also need INFO messages turned on for the message handler * being used. The reportPeriodically flag should be set to false under AJDT so numbers just come out at the end. */ public void setTiming(boolean timersOn, boolean reportPeriodically) { timing = timersOn; timingPeriodically = reportPeriodically; } /** * 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(); } public boolean areInfoMessagesEnabled() { if (infoMessagesEnabled == 0) { infoMessagesEnabled = (messageHandler.isIgnoring(IMessage.INFO) ? 1 : 2); } return infoMessagesEnabled == 2; } /** * 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 final static String xsetOVERWEAVING = "overWeaving"; public final static String xsetOPTIMIZED_MATCHING = "optimizedMatching"; public final static String xsetTIMERS_PER_JOINPOINT = "timersPerJoinpoint"; public final static String xsetTIMERS_PER_FASTMATCH_CALL = "timersPerFastMatchCall"; public final static String xsetITD_VERSION = "itdVersion"; public final static String xsetITD_VERSION_ORIGINAL = "1"; public final static String xsetITD_VERSION_2NDGEN = "2"; public final static String xsetITD_VERSION_DEFAULT = xsetITD_VERSION_2NDGEN; public final static String xsetMINIMAL_MODEL = "minimalModel"; public final static String xsetTARGETING_RUNTIME_1610 = "targetRuntime1_6_10"; public boolean isInJava5Mode() { return behaveInJava5Way; } public boolean isTimingEnabled() { return timing; } 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). */ public static class TypeMap { // 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 public List<String> addedSinceLastDemote; public List<String> writtenClasses; private static boolean debug = false; public static boolean useExpendableMap = true; // configurable for reliable testing private boolean demotionSystemActive; private boolean debugDemotion = false; public int policy = USE_WEAK_REFS; // Map of types that never get thrown away final Map<String, ResolvedType> tMap = new HashMap<String, ResolvedType>(); // Map of types that may be ejected from the cache if we need space final Map<String, Reference<ResolvedType>> expendableMap = Collections .synchronizedMap(new WeakHashMap<String, Reference<ResolvedType>>()); private final World w; // profiling tools... private boolean memoryProfiling = false; private int maxExpendableMapSize = -1; private int collectedTypes = 0; private final ReferenceQueue<ResolvedType> rq = new ReferenceQueue<ResolvedType>(); // private static Trace trace = TraceFactory.getTraceFactory().getTrace(World.TypeMap.class); TypeMap(World w) { // Demotion activated when switched on and loadtime weaving or in AJDT demotionSystemActive = w.isDemotionActive() && (w.isLoadtimeWeaving() || w.couldIncrementalCompileFollow()); addedSinceLastDemote = new ArrayList<String>(); writtenClasses = new ArrayList<String>(); this.w = w; memoryProfiling = false;// !w.getMessageHandler().isIgnoring(Message. // INFO); } // For testing public Map<String, Reference<ResolvedType>> getExpendableMap() { return expendableMap; } // For testing public Map<String, ResolvedType> getMainMap() { return tMap; } public int demote() { return demote(false); } /** * 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(boolean atEndOfCompile) { if (!demotionSystemActive) { return 0; } if (debugDemotion) { System.out.println("Demotion running " + addedSinceLastDemote); } boolean isLtw = w.isLoadtimeWeaving(); int demotionCounter = 0; if (isLtw) { // Loadtime weaving demotion strategy for (String key : addedSinceLastDemote) { ResolvedType type = tMap.get(key); if (type != null && !type.isAspect() && !type.equals(UnresolvedType.OBJECT) && !type.isPrimitiveType()) { List<ConcreteTypeMunger> typeMungers = type.getInterTypeMungers(); if (typeMungers == null || typeMungers.size() == 0) { tMap.remove(key); insertInExpendableMap(key, type); demotionCounter++; } } } addedSinceLastDemote.clear(); } else { // Compile time demotion strategy List<String> forRemoval = new ArrayList<String>(); for (String key : addedSinceLastDemote) { ResolvedType type = tMap.get(key); if (type == null) { // TODO not 100% sure why it is not there, where did it go? forRemoval.add(key); continue; } if (!writtenClasses.contains(type.getName())) { // COSTLY continue; } if (type != null && !type.isAspect() && !type.equals(UnresolvedType.OBJECT) && !type.isPrimitiveType()) { List<ConcreteTypeMunger> typeMungers = type.getInterTypeMungers(); if (typeMungers == null || typeMungers.size() == 0) { /* * if (type.isNested()) { try { ReferenceType rt = (ReferenceType) w.resolve(type.getOutermostType()); * if (!rt.isMissing()) { ReferenceTypeDelegate delegate = ((ReferenceType) type).getDelegate(); boolean * isWeavable = delegate == null ? false : delegate.isExposedToWeaver(); boolean hasBeenWoven = delegate * == null ? false : delegate.hasBeenWoven(); if (isWeavable && !hasBeenWoven) { // skip demotion of * this inner type for now continue; } } } catch (ClassCastException cce) { cce.printStackTrace(); * System.out.println("outer of " + key + " is not a reftype? " + type.getOutermostType()); // throw new * IllegalStateException(cce); } } */ ReferenceTypeDelegate delegate = ((ReferenceType) type).getDelegate(); boolean isWeavable = delegate == null ? false : delegate.isExposedToWeaver(); boolean hasBeenWoven = delegate == null ? false : delegate.hasBeenWoven(); if (!isWeavable || hasBeenWoven) { if (debugDemotion) { System.out.println("Demoting " + key); } forRemoval.add(key); tMap.remove(key); insertInExpendableMap(key, type); demotionCounter++; } } else { // no need to try this again, it will never be demoted writtenClasses.remove(type.getName()); forRemoval.add(key); } } else { writtenClasses.remove(type.getName()); // no need to try this again, it will never be demoted forRemoval.add(key); } } addedSinceLastDemote.removeAll(forRemoval); } if (debugDemotion) { System.out.println("Demoted " + demotionCounter + " types. Types remaining in fixed set #" + tMap.keySet().size() + ". addedSinceLastDemote size is " + addedSinceLastDemote.size()); System.out.println("writtenClasses.size() = " + writtenClasses.size() + ": " + writtenClasses); } if (atEndOfCompile) { if (debugDemotion) { System.out.println("Clearing writtenClasses"); } writtenClasses.clear(); } return demotionCounter; } private void insertInExpendableMap(String key, ResolvedType type) { if (useExpendableMap) { if (!expendableMap.containsKey(key)) { if (policy == USE_SOFT_REFS) { expendableMap.put(key, new SoftReference<ResolvedType>(type)); } else { expendableMap.put(key, new WeakReference<ResolvedType>(type)); } } } } /** * 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.isCacheable()) { return 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; } // TODO should this be in as a permanent assertion? /* * if ((type instanceof ReferenceType) && type.getWorld().isInJava5Mode() && (((ReferenceType) type).getDelegate() != * null) && type.isGenericType()) { throw new BCException("Attempt to add generic type to typemap " + type.toString() + * " (should be raw)"); } */ if (w.isExpendable(type)) { if (useExpendableMap) { // Dont use reference queue for tracking if not profiling... if (policy == USE_WEAK_REFS) { if (memoryProfiling) { expendableMap.put(key, new WeakReference<ResolvedType>(type, rq)); } else { expendableMap.put(key, new WeakReference<ResolvedType>(type)); } } else if (policy == USE_SOFT_REFS) { if (memoryProfiling) { expendableMap.put(key, new SoftReference<ResolvedType>(type, rq)); } else { expendableMap.put(key, new SoftReference<ResolvedType>(type)); } // } else { // expendableMap.put(key, type); } } if (memoryProfiling && expendableMap.size() > maxExpendableMapSize) { maxExpendableMapSize = expendableMap.size(); } return type; } else { if (demotionSystemActive) { // System.out.println("Added since last demote " + key); addedSinceLastDemote.add(key); } return 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 = tMap.get(key); if (ret == null) { if (policy == USE_WEAK_REFS) { WeakReference<ResolvedType> ref = (WeakReference<ResolvedType>) expendableMap.get(key); if (ref != null) { ret = ref.get(); } } else if (policy == USE_SOFT_REFS) { SoftReference<ResolvedType> ref = (SoftReference<ResolvedType>) expendableMap.get(key); if (ref != null) { ret = ref.get(); } // } else { // return (ResolvedType) expendableMap.get(key); } } return ret; } /** Remove a type from the map */ public ResolvedType remove(String key) { ResolvedType ret = tMap.remove(key); if (ret == null) { if (policy == USE_WEAK_REFS) { WeakReference<ResolvedType> wref = (WeakReference<ResolvedType>) expendableMap.remove(key); if (wref != null) { ret = wref.get(); } } else if (policy == USE_SOFT_REFS) { SoftReference<ResolvedType> wref = (SoftReference<ResolvedType>) expendableMap.remove(key); if (wref != null) { ret = wref.get(); } // } else { // ret = (ResolvedType) expendableMap.remove(key); } } return ret; } public void classWriteEvent(String classname) { // that is a name com.Foo and not a signature Lcom/Foo; boooooooooo! if (demotionSystemActive) { writtenClasses.add(classname); } if (debugDemotion) { System.out.println("Class write event for " + classname); } } // 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<PrecedenceCacheKey, Integer> cachedResults; public AspectPrecedenceCalculator(World forSomeWorld) { world = forSomeWorld; cachedResults = new HashMap<PrecedenceCacheKey, Integer>(); } /** * 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 (cachedResults.get(key)).intValue(); } else { int order = 0; DeclarePrecedence orderer = null; // Records the declare // precedence statement that // gives the first ordering for (Iterator<Declare> 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 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; } @Override public boolean equals(Object obj) { if (!(obj instanceof PrecedenceCacheKey)) { return false; } PrecedenceCacheKey other = (PrecedenceCacheKey) obj; return (aspect1 == other.aspect1 && aspect2 == other.aspect2); } @Override 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) --- public boolean isDemotionActive() { return false; } // --- 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<Class<?>, TypeVariable[]> workInProgress1 = new HashMap<Class<?>, TypeVariable[]>(); public TypeVariable[] getTypeVariablesCurrentlyBeingProcessed(Class<?> baseClass) { return 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")); } // ITD Versions // 1 is the first version in use up to AspectJ 1.6.8 // 2 is from 1.6.9 onwards s = p.getProperty(xsetITD_VERSION, xsetITD_VERSION_DEFAULT); if (s.equals(xsetITD_VERSION_ORIGINAL)) { itdVersion = 1; } s = p.getProperty(xsetMINIMAL_MODEL, "false"); if (s.equalsIgnoreCase("true")) { minimalModel = true; } s = p.getProperty(xsetTARGETING_RUNTIME_1610, "false"); if (s.equalsIgnoreCase("true")) { targettingRuntime1_6_10 = true; } 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); // default is: ON (for ltw) OFF (for ctw) if (s != null) { boolean b = typeMap.demotionSystemActive; if (b && s.equalsIgnoreCase("false")) { System.out.println("typeDemotion=false: type demotion switched OFF"); typeMap.demotionSystemActive = false; } else if (!b && s.equalsIgnoreCase("true")) { System.out.println("typeDemotion=true: type demotion switched ON"); typeMap.demotionSystemActive = true; } } s = p.getProperty(xsetOVERWEAVING, "false"); if (s.equalsIgnoreCase("true")) { overWeaving = true; } s = p.getProperty(xsetTYPE_DEMOTION_DEBUG, "false"); if (s.equalsIgnoreCase("true")) { typeMap.debugDemotion = true; } s = p.getProperty(xsetTYPE_REFS, "true"); if (s.equalsIgnoreCase("false")) { typeMap.policy = TypeMap.USE_SOFT_REFS; } runMinimalMemorySet = p.getProperty(xsetRUN_MINIMAL_MEMORY) != null; 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"); s = p.getProperty(xsetOPTIMIZED_MATCHING, "true"); optimizedMatching = s.equalsIgnoreCase("true"); if (!optimizedMatching) { getMessageHandler().handleMessage(MessageUtil.info("[optimizedMatching=false] optimized matching turned off")); } s = p.getProperty(xsetTIMERS_PER_JOINPOINT, "25000"); try { timersPerJoinpoint = Integer.parseInt(s); } catch (Exception e) { getMessageHandler().handleMessage(MessageUtil.error("unable to process timersPerJoinpoint value of " + s)); timersPerJoinpoint = 25000; } s = p.getProperty(xsetTIMERS_PER_FASTMATCH_CALL, "250"); try { timersPerType = Integer.parseInt(s); } catch (Exception e) { getMessageHandler().handleMessage(MessageUtil.error("unable to process timersPerType value of " + s)); timersPerType = 250; } } try { String value = System.getProperty("aspectj.overweaving", "false"); if (value.equalsIgnoreCase("true")) { System.out.println("ASPECTJ: aspectj.overweaving=true: overweaving switched ON"); overWeaving = true; } value = System.getProperty("aspectj.typeDemotion", "false"); if (value.equalsIgnoreCase("true")) { System.out.println("ASPECTJ: aspectj.typeDemotion=true: type demotion switched ON"); typeMap.demotionSystemActive = true; } value = System.getProperty("aspectj.minimalModel", "false"); if (value.equalsIgnoreCase("true")) { System.out.println("ASPECTJ: aspectj.minimalModel=true: minimal model switched ON"); minimalModel = true; } } catch (Throwable t) { System.err.println("ASPECTJ: Unable to read system properties"); t.printStackTrace(); } checkedAdvancedConfiguration = true; } } public boolean isRunMinimalMemory() { ensureAdvancedConfigurationProcessed(); return runMinimalMemory; } public boolean isRunMinimalMemorySet() { ensureAdvancedConfigurationProcessed(); return runMinimalMemorySet; } 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<PointcutDesignatorHandler>(); } pointcutDesignators.add(designatorHandler); } public Set<PointcutDesignatorHandler> getRegisteredPointcutHandlers() { if (pointcutDesignators == null) { return Collections.emptySet(); } return pointcutDesignators; } public void reportMatch(ShadowMunger munger, Shadow shadow) { } public boolean isOverWeaving() { return overWeaving; } 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; } /** * Determine if the named aspect requires a particular type around in order to be useful. The type is named in the aop.xml file * against the aspect. * * @return true if there is a type missing that this aspect really needed around */ public boolean hasUnsatisfiedDependency(ResolvedType aspectType) { return false; } public TypePattern getAspectScope(ResolvedType declaringType) { return null; } public Map<String, ResolvedType> getFixed() { return typeMap.tMap; } public Map<String, Reference<ResolvedType>> 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())); } // map from aspect > excluded types // memory issue here? private Map<ResolvedType, Set<ResolvedType>> exclusionMap = new HashMap<ResolvedType, Set<ResolvedType>>(); public Map<ResolvedType, Set<ResolvedType>> getExclusionMap() { return exclusionMap; } private TimeCollector timeCollector = null; /** * Record the time spent matching a pointcut - this will accumulate over the lifetime of this world/weaver and be reported every * 25000 join points. */ public void record(Pointcut pointcut, long timetaken) { if (timeCollector == null) { ensureAdvancedConfigurationProcessed(); timeCollector = new TimeCollector(this); } timeCollector.record(pointcut, timetaken); } /** * Record the time spent fastmatching a pointcut - this will accumulate over the lifetime of this world/weaver and be reported * every 250 types. */ public void recordFastMatch(Pointcut pointcut, long timetaken) { if (timeCollector == null) { ensureAdvancedConfigurationProcessed(); timeCollector = new TimeCollector(this); } timeCollector.recordFastMatch(pointcut, timetaken); } public void reportTimers() { if (timeCollector != null && !timingPeriodically) { timeCollector.report(); timeCollector = new TimeCollector(this); } } private static class TimeCollector { private World world; long joinpointCount; long typeCount; long perJoinpointCount; long perTypes; Map<String, Long> joinpointsPerPointcut = new HashMap<String, Long>(); Map<String, Long> timePerPointcut = new HashMap<String, Long>(); Map<String, Long> fastMatchTimesPerPointcut = new HashMap<String, Long>(); Map<String, Long> fastMatchTypesPerPointcut = new HashMap<String, Long>(); TimeCollector(World world) { this.perJoinpointCount = world.timersPerJoinpoint; this.perTypes = world.timersPerType; this.world = world; this.joinpointCount = 0; this.typeCount = 0; this.joinpointsPerPointcut = new HashMap<String, Long>(); this.timePerPointcut = new HashMap<String, Long>(); } public void report() { long totalTime = 0L; for (String p : joinpointsPerPointcut.keySet()) { totalTime += timePerPointcut.get(p); } world.getMessageHandler().handleMessage( MessageUtil.info("Pointcut matching cost (total=" + (totalTime / 1000000) + "ms for " + joinpointCount + " joinpoint match calls):")); for (String p : joinpointsPerPointcut.keySet()) { StringBuffer sb = new StringBuffer(); sb.append("Time:" + (timePerPointcut.get(p) / 1000000) + "ms (jps:#" + joinpointsPerPointcut.get(p) + ") matching against " + p); world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString())); } world.getMessageHandler().handleMessage(MessageUtil.info("---")); totalTime = 0L; for (String p : fastMatchTimesPerPointcut.keySet()) { totalTime += fastMatchTimesPerPointcut.get(p); } world.getMessageHandler().handleMessage( MessageUtil.info("Pointcut fast matching cost (total=" + (totalTime / 1000000) + "ms for " + typeCount + " fast match calls):")); for (String p : fastMatchTimesPerPointcut.keySet()) { StringBuffer sb = new StringBuffer(); sb.append("Time:" + (fastMatchTimesPerPointcut.get(p) / 1000000) + "ms (types:#" + fastMatchTypesPerPointcut.get(p) + ") fast matching against " + p); world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString())); } world.getMessageHandler().handleMessage(MessageUtil.info("---")); } void record(Pointcut pointcut, long timetakenInNs) { joinpointCount++; String pointcutText = pointcut.toString(); Long jpcounter = joinpointsPerPointcut.get(pointcutText); if (jpcounter == null) { jpcounter = 1L; } else { jpcounter++; } joinpointsPerPointcut.put(pointcutText, jpcounter); Long time = timePerPointcut.get(pointcutText); if (time == null) { time = timetakenInNs; } else { time += timetakenInNs; } timePerPointcut.put(pointcutText, time); if (world.timingPeriodically) { if ((joinpointCount % perJoinpointCount) == 0) { long totalTime = 0L; for (String p : joinpointsPerPointcut.keySet()) { totalTime += timePerPointcut.get(p); } world.getMessageHandler().handleMessage( MessageUtil.info("Pointcut matching cost (total=" + (totalTime / 1000000) + "ms for " + joinpointCount + " joinpoint match calls):")); for (String p : joinpointsPerPointcut.keySet()) { StringBuffer sb = new StringBuffer(); sb.append("Time:" + (timePerPointcut.get(p) / 1000000) + "ms (jps:#" + joinpointsPerPointcut.get(p) + ") matching against " + p); world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString())); } world.getMessageHandler().handleMessage(MessageUtil.info("---")); } } } void recordFastMatch(Pointcut pointcut, long timetakenInNs) { typeCount++; String pointcutText = pointcut.toString(); Long typecounter = fastMatchTypesPerPointcut.get(pointcutText); if (typecounter == null) { typecounter = 1L; } else { typecounter++; } fastMatchTypesPerPointcut.put(pointcutText, typecounter); Long time = fastMatchTimesPerPointcut.get(pointcutText); if (time == null) { time = timetakenInNs; } else { time += timetakenInNs; } fastMatchTimesPerPointcut.put(pointcutText, time); if (world.timingPeriodically) { if ((typeCount % perTypes) == 0) { long totalTime = 0L; for (String p : fastMatchTimesPerPointcut.keySet()) { totalTime += fastMatchTimesPerPointcut.get(p); } world.getMessageHandler().handleMessage( MessageUtil.info("Pointcut fast matching cost (total=" + (totalTime / 1000000) + "ms for " + typeCount + " fast match calls):")); for (String p : fastMatchTimesPerPointcut.keySet()) { StringBuffer sb = new StringBuffer(); sb.append("Time:" + (fastMatchTimesPerPointcut.get(p) / 1000000) + "ms (types:#" + fastMatchTypesPerPointcut.get(p) + ") fast matching against " + p); world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString())); } world.getMessageHandler().handleMessage(MessageUtil.info("---")); } } } } public TypeMap getTypeMap() { return typeMap; } public static void reset() { ResolvedType.resetPrimitives(); } /** * Returns the version of ITD that this world wants to create. The default is the new style (2) but in some cases where there * might be a clash, the old style can be used. It is set through the option -Xset:itdVersion=1 * * @return the ITD version this world wants to create - 1=oldstyle 2=new, transparent style */ public int getItdVersion() { return itdVersion; } // if not loadtime weaving then we are compile time weaving or post-compile time weaving public abstract boolean isLoadtimeWeaving(); public void classWriteEvent(char[][] compoundName) { // override if interested in write events } }
339,300
Bug 339300 problem weaving anonymous inner (member owned) classes in scala library
Reported by Ramnivas. Due to the use of numerous $ chars in scala classnames, some of the AspectJ handling of inner classes breaks down. It should be possible to correctly use the available class attributes rather than mess around with attributes. A while back one use did contribute a change to enable scala weaving which tried to use the InnerClasses attribute before falling back on string chopping. However we have now hit another case. In the scenario we are dealing with the class scala.Predef$$anon$3 in the scala library (a 2.9.0-SNAPSHOT version). What we normally do here is in that type we discover the InnerClass attribute and refer to the outerclass index it holds. Unfortunately, due to it being an anonymous inner inside a method, the index is 0. So we fail to process the attribute and with string chopping come up with a stupid guessed name for the outer. The solution is to use the EnclosingMethod attribute in these situations. The EnclosingMethod attribute is an optional attribute. A class must have an EnclosingMethod attribute if and only if it is a local class or an anonymous class. A class may have no more than one EnclosingMethod attribute. The EnclosingMethod attribute includes a pointer to the containing outerclass (that had the method in which encloses this inner type).
resolved fixed
945402f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-03-09T01:14:39Z"
"2011-03-09T00:20: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.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.asm.AsmManager; 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); ReferenceType type = getResolvedTypeX(); AsmManager asmManager = ((BcelWorld) type.getWorld()).getModelAsAsmManager(); l = AtAjAttributes.readAj5ClassAttributes(asmManager, javaClass, type, type.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) { // Set the weaver version used to build this type wvInfo = (AjAttribute.WeaverVersionInfo) a; } 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()); // Can be null if unpacking whilst building the bcel delegate (in call hierarchy from BcelWorld.addSourceObjectType() // line 453) - see 317139 if (genericType != null) { 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(); } public boolean isWeavable() { return true; } }
340,323
Bug 340323 NPE when weaving java.lang.Object at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1251)
null
resolved fixed
a8e6797
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-03-28T19:37:01Z"
"2011-03-17T13: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.ArrayList; 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.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.asm.AsmManager; import org.aspectj.asm.IProgramElement; 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.MemberUtils; import org.aspectj.weaver.MethodDelegateTypeMunger; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMemberClassTypeMunger; 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; public class BcelTypeMunger extends ConcreteTypeMunger { public BcelTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType) { super(munger, aspectType); } @Override public String toString() { return "(BcelTypeMunger " + getMunger() + ")"; } @Override 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 (weaver.getWorld().isOverWeaving()) { WeaverStateInfo typeWeaverState = weaver.getLazyClassGen().getType().getWeaverState(); if (typeWeaverState != null && typeWeaverState.isAspectAlreadyApplied(getAspectType())) { return false; } } 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.InnerClass) { changed = mungeNewMemberType(weaver, (NewMemberClassTypeMunger) 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) { ResolvedType declaringAspect = null; AsmManager model = ((BcelWorld) getWorld()).getModelAsAsmManager(); if (model != null) { if (munger instanceof NewParentTypeMunger) { NewParentTypeMunger nptMunger = (NewParentTypeMunger) munger; declaringAspect = nptMunger.getDeclaringType(); if (declaringAspect.isParameterizedOrGenericType()) { declaringAspect = declaringAspect.getRawType(); } ResolvedType thisAspect = getAspectType(); AsmRelationshipProvider.addRelationship(model, weaver.getLazyClassGen().getType(), munger, thisAspect); // Add a relationship on the actual declaring aspect too if (!thisAspect.equals(declaringAspect)) { // Might be the case the declaring aspect is generic and thisAspect is parameterizing it. In that case // record the actual parameterizations ResolvedType target = weaver.getLazyClassGen().getType(); ResolvedType newParent = nptMunger.getNewParent(); IProgramElement thisAspectNode = model.getHierarchy().findElementForType(thisAspect.getPackageName(), thisAspect.getClassName()); Map<String, List<String>> declareParentsMap = thisAspectNode.getDeclareParentsMap(); if (declareParentsMap == null) { declareParentsMap = new HashMap<String, List<String>>(); thisAspectNode.setDeclareParentsMap(declareParentsMap); } String tname = target.getName(); String pname = newParent.getName(); List<String> newparents = declareParentsMap.get(tname); if (newparents == null) { newparents = new ArrayList<String>(); declareParentsMap.put(tname, newparents); } newparents.add(pname); AsmRelationshipProvider.addRelationship(model, weaver.getLazyClassGen().getType(), munger, declaringAspect); } } else { declaringAspect = getAspectType(); AsmRelationshipProvider.addRelationship(model, weaver.getLazyClassGen().getType(), munger, declaringAspect); } } } // 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.isMixin()) { weaver.getWorld() .getMessageHandler() .handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_MIXIN, new String[] { parentTM.getNewParent().getName(), fName, weaver.getLazyClassGen().getType().getName(), tName }, weaver.getLazyClassGen().getClassName(), getAspectType().getName())); } else { 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(); String fromString = fName + ":'" + declaredSig + "'"; // if (declaredSig==null) declaredSig= munger.getSignature(); String kindString = munger.getKind().toString().toLowerCase(); if (kindString.equals("innerclass")) { kindString = "member class"; fromString = fName; } weaver.getWorld() .getMessageHandler() .handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ITD, new String[] { weaver.getLazyClassGen().getType().getName(), tName, kindString, getAspectType().getName(), fromString }, 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 typeTransformer) { LazyClassGen newParentTarget = weaver.getLazyClassGen(); ResolvedType newParent = typeTransformer.getNewParent(); boolean performChange = true; performChange = enforceDecpRule1_abstractMethodsImplemented(weaver, typeTransformer.getSourceLocation(), newParentTarget, newParent); performChange = enforceDecpRule2_cantExtendFinalClass(weaver, typeTransformer.getSourceLocation(), newParentTarget, newParent) && performChange; List<ResolvedMember> methods = newParent.getMethodsWithoutIterator(false, true, false); for (ResolvedMember method : methods) { if (!method.getName().equals("<init>")) { LazyMethodGen subMethod = findMatchingMethod(newParentTarget, method); // FIXME asc is this safe for all bridge methods? if (subMethod != null && !subMethod.isBridgeMethod()) { if (!(subMethod.isSynthetic() && method.isSynthetic())) { if (!(subMethod.isStatic() && subMethod.getName().startsWith("access$"))) { // ignore generated accessors performChange = enforceDecpRule3_visibilityChanges(weaver, newParent, method, subMethod) && performChange; performChange = enforceDecpRule4_compatibleReturnTypes(weaver, method, subMethod) && performChange; performChange = enforceDecpRule5_cantChangeFromStaticToNonstatic(weaver, typeTransformer.getSourceLocation(), method, subMethod) && performChange; } } } } } if (!performChange) { // A rule was violated and an error message already reported return false; } if (newParent.isClass()) { // Changing the supertype if (!attemptToModifySuperCalls(weaver, newParentTarget, newParent)) { return false; } newParentTarget.setSuperClass(newParent); } else { // Add 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) { // Ignore abstract classes or interfaces if (newParentTarget.isAbstract() || newParentTarget.isInterface()) { return true; } boolean ruleCheckingSucceeded = true; List<ResolvedMember> newParentMethods = newParent.getMethodsWithoutIterator(false, true, false); for (ResolvedMember newParentMethod : newParentMethods) { String newParentMethodName = newParentMethod.getName(); // Ignore abstract ajc$interField prefixed methods if (newParentMethod.isAbstract() && !newParentMethodName.startsWith("ajc$interField")) { ResolvedMember discoveredImpl = null; List<ResolvedMember> targetMethods = newParentTarget.getType().getMethodsWithoutIterator(false, true, false); for (ResolvedMember targetMethod : targetMethods) { if (!targetMethod.isAbstract() && targetMethod.getName().equals(newParentMethodName)) { String newParentMethodSig = newParentMethod.getParameterSignature(); // ([TT;) String targetMethodSignature = targetMethod.getParameterSignature(); // ([Ljava/lang/Object;) // could be a match if (targetMethodSignature.equals(newParentMethodSig)) { discoveredImpl = targetMethod; } else { // Does the erasure match? In which case a bridge method will be created later to // satisfy the abstract method if (targetMethod.hasBackingGenericMember() && targetMethod.getBackingGenericMember().getParameterSignature().equals(newParentMethodSig)) { discoveredImpl = targetMethod; } else if (newParentMethod.hasBackingGenericMember()) { if (newParentMethod.getBackingGenericMember().getParameterSignature().equals(targetMethodSignature)) { discoveredImpl = targetMethod; } } } if (discoveredImpl != null) { break; } } } 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 (ConcreteTypeMunger m : newParentTarget.getType().getInterTypeMungersIncludingSupers()) { 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)); // possible sig change when type parameters filled in sig = m.getSignature(); } if (ResolvedType.matches( AjcMemberMaker.interMethod(sig, m.getAspectType(), sig.getDeclaringType().resolve(weaver.getWorld()).isInterface()), newParentMethod)) { satisfiedByITD = true; } } } else if (m.getMunger() != null && m.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate2) { // AV - that should be enough, no need to check more satisfiedByITD = true; } } if (!satisfiedByITD) { error(weaver, "The type " + newParentTarget.getName() + " must implement the inherited abstract method " + newParentMethod.getDeclaringType() + "." + newParentMethodName + newParentMethod.getParameterSignature(), newParentTarget.getType().getSourceLocation(), new ISourceLocation[] { newParentMethod.getSourceLocation(), mungerLoc }); ruleCheckingSucceeded = false; } } } } return ruleCheckingSucceeded; } /** * Rule 2. Can't extend final types */ private boolean enforceDecpRule2_cantExtendFinalClass(BcelClassWeaver weaver, ISourceLocation transformerLoc, LazyClassGen targetType, ResolvedType newParent) { if (newParent.isFinal()) { error(weaver, "Cannot make type " + targetType.getName() + " extend final class " + newParent.getName(), targetType .getType().getSourceLocation(), new ISourceLocation[] { transformerLoc }); 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 (Modifier.isPublic(superMethod.getModifiers())) { 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 (Modifier.isProtected(superMethod.getModifiers())) { 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) { boolean superMethodStatic = Modifier.isStatic(superMethod.getModifiers()); if (superMethodStatic && !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 (!superMethodStatic && 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 type, ResolvedMember searchMethod) { String searchName = searchMethod.getName(); String searchSig = searchMethod.getParameterSignature(); for (LazyMethodGen method : type.getMethodGens()) { if (method.getName().equals(searchName) && method.getParameterSignature().equals(searchSig)) { return method; } } return null; } /** * 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) { ResolvedType currentParentType = newParentTarget.getSuperClass(); if (currentParentType.getGenericType() != null) { currentParentType = currentParentType.getGenericType(); } String currentParent = currentParentType.getName(); if (newParent.getGenericType() != null) { newParent = newParent.getGenericType(); // target new super calls at } // the generic type if its raw or parameterized List<LazyMethodGen> mgs = newParentTarget.getMethodGens(); // Look for ctors to modify for (LazyMethodGen aMethod : mgs) { if (LazyMethodGen.isConstructor(aMethod)) { 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>" + invokeSpecial.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<ConcreteTypeMunger> ii = newParentTarget.getType() .getInterTypeMungersIncludingSupers().iterator(); ii.hasNext() && !satisfiedByITDC;) { ConcreteTypeMunger m = 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 type, String searchSig) { for (ResolvedMember method : type.getDeclaredJavaMethods()) { if (MemberUtils.isConstructor(method)) { if (method.getSignature().equals(searchSig)) { return method; } } } 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, munger.shortSyntax)); addFieldSetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldSet(aspectType, member, munger.shortSyntax)); 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<LazyMethodGen> i = gen.getMethodGens().iterator(); i.hasNext();) { LazyMethodGen m = 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 (Modifier.isStatic(field.getModifiers())) { 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 (Modifier.isStatic(field.getModifiers())) { 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 (!Modifier.isStatic(method.getModifiers())) { 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 mungeNewMemberType(BcelClassWeaver classWeaver, NewMemberClassTypeMunger munger) { World world = classWeaver.getWorld(); ResolvedType onType = world.resolve(munger.getTargetType()); if (onType.isRawType()) { onType = onType.getGenericType(); } return onType.equals(classWeaver.getLazyClassGen().getType()); } private boolean mungeNewMethod(BcelClassWeaver classWeaver, NewMethodTypeMunger munger) { World world = classWeaver.getWorld(); // Resolving it will sort out the tvars ResolvedMember unMangledInterMethod = munger.getSignature().resolve(world); // do matching on the unMangled one, but actually add them to the mangled method ResolvedMember interMethodBody = munger.getDeclaredInterMethodBody(aspectType, world); ResolvedMember interMethodDispatcher = munger.getDeclaredInterMethodDispatcher(aspectType, world); ResolvedMember memberHoldingAnyAnnotations = interMethodDispatcher; LazyClassGen classGen = classWeaver.getLazyClassGen(); ResolvedType onType = world.resolve(unMangledInterMethod.getDeclaringType(), munger.getSourceLocation()); if (onType.isRawType()) { onType = onType.getGenericType(); } // Simple checks, can't ITD on annotations or enums if (onType.isAnnotation()) { signalError(WeaverMessages.ITDM_ON_ANNOTATION_NOT_ALLOWED, classWeaver, onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDM_ON_ENUM_NOT_ALLOWED, classWeaver, onType); return false; } boolean mungingInterface = classGen.isInterface(); boolean onInterface = onType.isInterface(); if (onInterface && classGen.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(classGen.getType())) { ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, onInterface); LazyMethodGen newMethod = makeMethodGen(classGen, 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 (classWeaver.getWorld().isInJava5Mode()) { AnnotationAJ annotationsOnRealMember[] = null; ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) { toLookOn = aspectType.getGenericType(); } ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn, memberHoldingAnyAnnotations, false); // 266602 - consider it missing to mean that the corresponding aspect had errors if (realMember == null) { // signalWarning("Unable to apply any annotations attached to " + munger.getSignature(), weaver); // throw new BCException("Couldn't find ITD init member '" + interMethodBody + "' on aspect " + aspectType); } else { annotationsOnRealMember = realMember.getAnnotations(); } Set<ResolvedType> addedAnnotations = new HashSet<ResolvedType>(); if (annotationsOnRealMember != null) { for (AnnotationAJ anno : annotationsOnRealMember) { AnnotationGen a = ((BcelAnnotation) anno).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, classGen.getConstantPool(), true); newMethod.addAnnotation(new BcelAnnotation(ag, classWeaver.getWorld())); addedAnnotations.add(anno.getType()); } } if (realMember != null) { copyOverParameterAnnotations(newMethod, realMember); } // the code below was originally added to cope with the case where an aspect declares an annotation on an ITD // declared within itself (an unusual situation). However, it also addresses the case where we may not find the // annotation on the real representation of the ITD. This can happen in a load-time weaving situation where // we couldn't add the annotation in time - and so here we recheck the declare annotations. Not quite ideal but // works. pr288635 List<DeclareAnnotation> allDecams = world.getDeclareAnnotationOnMethods(); for (DeclareAnnotation declareAnnotationMC : allDecams) { if (declareAnnotationMC.matches(unMangledInterMethod, world)) { // && newMethod.getEnclosingClass().getType() == aspectType) { AnnotationAJ annotation = declareAnnotationMC.getAnnotation(); if (!addedAnnotations.contains(annotation.getType())) { newMethod.addAnnotation(annotation); } } } } // 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 = classGen.getFactory(); int pos = 0; if (!Modifier.isStatic(unMangledInterMethod.getModifiers())) { 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, classWeaver.getWorld(), interMethodBody)); body.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(mangledInterMethod.getReturnType()))); if (classWeaver.getWorld().isInJava5Mode()) { // Don't need bridge // methods if not in // 1.5 mode. createAnyBridgeMethodsForCovariance(classWeaver, munger, unMangledInterMethod, onType, classGen, paramTypes); } } else { // ??? this is okay // if (!(mg.getBody() == null)) throw new // RuntimeException("bas"); } if (world.isInJava5Mode()) { String basicSignature = mangledInterMethod.getSignature(); String genericSignature = ((ResolvedMemberImpl) mangledInterMethod).getSignatureForAttribute(); if (!basicSignature.equals(genericSignature)) { // Add a signature attribute to it newMethod.addAttribute(createSignatureAttribute(classGen.getConstantPool(), genericSignature)); } } // XXX make sure to check that we set exceptions properly on this // guy. classWeaver.addLazyMethodGen(newMethod); classWeaver.getLazyClassGen().warnOnAddedMethod(newMethod.getMethod(), getSignature().getSourceLocation()); addNeededSuperCallMethods(classWeaver, 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 (!classGen.getType().isTopmostImplementor(onType)) { ResolvedType rtx = classGen.getType().getTopmostImplementor(onType); if (rtx == null) { // pr302460 // null means there is something wrong with what we are looking at ResolvedType rt = classGen.getType(); if (rt.isInterface()) { ISourceLocation sloc = munger.getSourceLocation(); classWeaver .getWorld() .getMessageHandler() .handleMessage( MessageUtil.error( "ITD target " + rt.getName() + " is an interface but has been incorrectly determined to be the topmost implementor of " + onType.getName() + ". ITD is " + this.getSignature(), sloc)); } if (!onType.isAssignableFrom(rt)) { ISourceLocation sloc = munger.getSourceLocation(); classWeaver .getWorld() .getMessageHandler() .handleMessage( MessageUtil.error( "ITD target " + rt.getName() + " doesn't appear to implement " + onType.getName() + " why did we consider it the top most implementor? ITD is " + this.getSignature(), sloc)); } } else if (!rtx.isExposedToWeaver()) { ISourceLocation sLoc = munger.getSourceLocation(); classWeaver .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(classGen, mangledInterMethod); // From 98901#29 - need to copy annotations across if (classWeaver.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 (AnnotationAJ annotationX : annotationsOnRealMember) { AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, classWeaver.getLazyClassGen().getConstantPool(), true); mg.addAnnotation(new BcelAnnotation(ag, classWeaver.getWorld())); } } copyOverParameterAnnotations(mg, realMember); } 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 = classGen.getFactory(); int pos = 0; if (!Modifier.isStatic(mangledInterMethod.getModifiers())) { 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, classWeaver.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 (world.isInJava5Mode()) { String basicSignature = mangledInterMethod.getSignature(); String genericSignature = ((ResolvedMemberImpl) mangledInterMethod).getSignatureForAttribute(); if (!basicSignature.equals(genericSignature)) { // Add a signature attribute to it mg.addAttribute(createSignatureAttribute(classGen.getConstantPool(), genericSignature)); } } classWeaver.addOrReplaceLazyMethodGen(mg); addNeededSuperCallMethods(classWeaver, onType, munger.getSuperMethodsCalled()); // Work out if we need a bridge method for the new method added to the topmostimplementor. // Check if the munger being processed is a parameterized form of the original munger createBridgeIfNecessary(classWeaver, munger, unMangledInterMethod, classGen); return true; } } else { return false; } } private void createBridgeIfNecessary(BcelClassWeaver classWeaver, NewMethodTypeMunger munger, ResolvedMember unMangledInterMethod, LazyClassGen classGen) { if (munger.getDeclaredSignature() != null) { boolean needsbridging = false; ResolvedMember mungerSignature = munger.getSignature(); ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null, mungerSignature.getDeclaringType().resolve(getWorld()), false, munger.getTypeVariableAliases()); if (!toBridgeTo.getReturnType().getErasureSignature().equals(mungerSignature.getReturnType().getErasureSignature())) { needsbridging = true; } UnresolvedType[] originalParams = toBridgeTo.getParameterTypes(); UnresolvedType[] newParams = mungerSignature.getParameterTypes(); for (int ii = 0; ii < originalParams.length; ii++) { if (!originalParams[ii].getErasureSignature().equals(newParams[ii].getErasureSignature())) { needsbridging = true; } } if (needsbridging) { createBridge(classWeaver, unMangledInterMethod, classGen, toBridgeTo); } } } private void copyOverParameterAnnotations(LazyMethodGen receiverMethod, ResolvedMember donorMethod) { AnnotationAJ[][] pAnnos = donorMethod.getParameterAnnotations(); if (pAnnos != null) { int offset = receiverMethod.isStatic() ? 0 : 1; int param = 0; for (int i = offset; i < pAnnos.length; i++) { AnnotationAJ[] annosOnParam = pAnnos[i]; if (annosOnParam != null) { for (AnnotationAJ anno : annosOnParam) { receiverMethod.addParameterAnnotation(param, anno); } } param++; } } } private void createBridge(BcelClassWeaver weaver, ResolvedMember unMangledInterMethod, LazyClassGen classGen, ResolvedMember toBridgeTo) { Type[] paramTypes; Type returnType; InstructionList body; InstructionFactory fact; int pos; ResolvedMember bridgerMethod = AjcMemberMaker.bridgerToInterMethod(unMangledInterMethod, classGen.getType()); ResolvedMember bridgingSetter = AjcMemberMaker.interMethodBridger(toBridgeTo, aspectType, false); // pr250493 LazyMethodGen bridgeMethod = makeMethodGen(classGen, bridgingSetter); paramTypes = BcelWorld.makeBcelTypes(bridgingSetter.getParameterTypes()); Type[] bridgingToParms = BcelWorld.makeBcelTypes(unMangledInterMethod.getParameterTypes()); returnType = BcelWorld.makeBcelType(bridgingSetter.getReturnType()); body = bridgeMethod.getBody(); fact = classGen.getFactory(); pos = 0; if (!Modifier.isStatic(bridgingSetter.getModifiers())) { 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)); classGen.addMethodGen(bridgeMethod); // mg.definingType = onType; } /** * 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<ResolvedMember> iter = onType.getSuperclass().getMethods(true, true); iter.hasNext() && !quitRightNow;) { ResolvedMember aMethod = 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 (!Modifier.isStatic(unMangledInterMethod.getModifiers())) { 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) { World world = weaver.getWorld(); 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; } ResolvedMember introduced = munger.getSignature(); ResolvedType fromType = world.resolve(introduced.getDeclaringType(), munger.getSourceLocation()); if (fromType.isRawType()) { fromType = fromType.getGenericType(); } boolean shouldApply = munger.matches(weaver.getLazyClassGen().getType(), aspectType); if (shouldApply) { Type bcelReturnType = BcelWorld.makeBcelType(introduced.getReturnType()); // 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 && !munger.specifiesDelegateFactoryMethod()) { boolean isOK = false; List<LazyMethodGen> existingMethods = gen.getMethodGens(); for (LazyMethodGen m : existingMethods) { if (m.getName().equals(introduced.getName()) && m.getParameterSignature().equals(introduced.getParameterSignature()) && m.getReturnType().equals(bcelReturnType)) { 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, bcelReturnType, 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 (ResolvedMember m : ms) { if (introduced.getName().equals(m.getName()) && introduced.getSignature().equals(m.getSignature())) { annotationsOnRealMember = m.getAnnotations(); break; } } if (annotationsOnRealMember != null) { for (AnnotationAJ anno : annotationsOnRealMember) { AnnotationGen a = ((BcelAnnotation) anno).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); // 'this' is where we'll store the field value // TODO for non-static case, call aspectOf() then call the factory method on the retval // TODO decide whether the value can really be cached // locate the aspect and call the static method in it if (munger.specifiesDelegateFactoryMethod()) { ResolvedMember rm = munger.getDelegateFactoryMethod(weaver.getWorld()); // Check the method parameter is compatible with the type of the instance to be passed if (rm.getArity() != 0) { ResolvedType parameterType = rm.getParameterTypes()[0].resolve(weaver.getWorld()); if (!parameterType.isAssignableFrom(weaver.getLazyClassGen().getType())) { signalError("For mixin factory method '" + rm + "': Instance type '" + weaver.getLazyClassGen().getType() + "' is not compatible with factory parameter type '" + parameterType + "'", weaver); return false; } } if (Modifier.isStatic(rm.getModifiers())) { if (rm.getArity() != 0) { body.append(InstructionConstants.ALOAD_0); } body.append(fact.createInvoke(rm.getDeclaringType().getName(), rm.getName(), rm.getSignature(), Constants.INVOKESTATIC)); body.append(Utility.createSet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); } else { // Need to call aspectOf() to obtain the aspect instance then call the factory method upon that UnresolvedType theAspect = munger.getAspect(); body.append(fact.createInvoke(theAspect.getName(), "aspectOf", "()" + theAspect.getSignature(), Constants.INVOKESTATIC)); if (rm.getArity() != 0) { body.append(InstructionConstants.ALOAD_0); } body.append(fact.createInvoke(rm.getDeclaringType().getName(), rm.getName(), rm.getSignature(), Constants.INVOKEVIRTUAL)); body.append(Utility.createSet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); } } else { 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 (!Modifier.isStatic(introduced.getModifiers())) { // 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(bcelReturnType)); 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); FieldGen field = makeFieldGen(weaver.getLazyClassGen(), host); field.setModifiers(field.getModifiers() | BcelField.AccSynthetic); weaver.getLazyClassGen().addField(field, 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<ResolvedMember> neededSuperCalls) { LazyClassGen gen = weaver.getLazyClassGen(); for (Iterator<ResolvedMember> iter = neededSuperCalls.iterator(); iter.hasNext();) { ResolvedMember superMethod = 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 void signalWarning(String msgString, BcelClassWeaver weaver) { // IMessage msg = MessageUtil.warn(msgString, getSourceLocation()); // weaver.getWorld().getMessageHandler().handleMessage(msg); // } private void signalError(String msgString, BcelClassWeaver weaver) { IMessage msg = MessageUtil.error(msgString, 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); // 266602 - consider it missing to mean that the corresponding aspect had errors if (realMember == null) { // signalWarning("Unable to apply any annotations attached to " + munger.getSignature(), weaver); // throw new BCException("Couldn't find ITD init member '" + interMethodBody + "' on aspect " + aspectType); } else { 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<DeclareAnnotation> allDecams = weaver.getWorld().getDeclareAnnotationOnMethods(); for (Iterator<DeclareAnnotation> i = allDecams.iterator(); i.hasNext();) { DeclareAnnotation decaMC = i.next(); if (decaMC.matches(explicitConstructor, weaver.getWorld()) && mg.getEnclosingClass().getType() == aspectType) { mg.addAnnotation(decaMC.getAnnotation()); } } } // Might have to remove the default constructor - b275032 // TODO could have tagged the type munger when the fact we needed to do this was detected earlier if (mg.getArgumentTypes().length == 0) { LazyMethodGen toRemove = null; for (LazyMethodGen object : currentClass.getMethodGens()) { if (object.getName().equals("<init>") && object.getArgumentTypes().length == 0) { toRemove = object; } } if (toRemove != null) { currentClass.removeMethodGen(toRemove); } } 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) { // signalWarning("Unable to apply any annotations attached to " + munger.getSignature(), weaver); // throw new BCException("Couldn't find ITD init member '" + interMethodBody + "' on aspect " + aspectType); } else { 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); ResolvedMember newField = AjcMemberMaker.interFieldClassField(field, aspectType, munger.version == NewFieldTypeMunger.VersionTwo); FieldGen fg = makeFieldGen(gen, newField); 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 (Modifier.isStatic(field.getModifiers())) { 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 (Modifier.isStatic(field.getModifiers())) { 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 (Modifier.isStatic(field.getModifiers())) { 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 (!Modifier.isStatic(bridgingSetter.getModifiers())) { 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); } @Override public ConcreteTypeMunger parameterizedFor(ResolvedType target) { return new BcelTypeMunger(munger.parameterizedFor(target), aspectType); } @Override public ConcreteTypeMunger parameterizeWith(Map<String, UnresolvedType> 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(); } @Override 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; @Override 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; } }
341,446
Bug 341446 java.lang.UnsupportedClassVersionError when running Java 1.5
null
resolved fixed
293a075
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-04-01T03:46:11Z"
"2011-03-31T05:40:00Z"
org.aspectj.matcher/testdata/AnnotatedClass.java
package testdata; @SomeAnnotation public class AnnotatedClass { @MethodLevelAnnotation public void annotatedMethod() { } public void nonAnnotatedMethod() { } }
341,446
Bug 341446 java.lang.UnsupportedClassVersionError when running Java 1.5
null
resolved fixed
293a075
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-04-01T03:46:11Z"
"2011-03-31T05:40:00Z"
org.aspectj.matcher/testdata/MethodLevelAnnotation.java
package testdata; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @interface MethodLevelAnnotation {}
341,446
Bug 341446 java.lang.UnsupportedClassVersionError when running Java 1.5
null
resolved fixed
293a075
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-04-01T03:46:11Z"
"2011-03-31T05:40:00Z"
org.aspectj.matcher/testdata/SomeAnnotation.java
package testdata; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @interface SomeAnnotation {}
341,446
Bug 341446 java.lang.UnsupportedClassVersionError when running Java 1.5
null
resolved fixed
293a075
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-04-01T03:46:11Z"
"2011-03-31T05:40:00Z"
org.aspectj.matcher/testsrc/org/aspectj/matcher/tools/CommonAdvancedPointcutExpressionTests.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 *******************************************************************************/ package org.aspectj.matcher.tools; import junit.framework.TestCase; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.tools.StandardPointcutExpression; import org.aspectj.weaver.tools.StandardPointcutParser; /** * Test the use of the pointcut parser and matching infrastructure. The org.aspectj.matcher.tools infrastructure used should not be * aware of what kind of World it is working with and only operate in terms of the type abstraction expressed in the * org.aspectj.matcher project (so Members, etc). These tests require some testdata types. * * This is based on the Reflection oriented PointcutExpressionTest in the weaver project. * * TESTDATA. The testdata for these tests is kept in org.aspectj.matcher/testdata. It is a series of .java files that need to be * compiled and available at runtime. Since they are java5 (they include annotations) they cannot be in a source folder for the * project, so they are compiled separately and then jar'd into a testdata.jar file in that folder. This folder is defined to be on * the classpath for org.aspectj.matcher, this enables them to be seen by a simple world that uses the classpath of the matcher * project as the definition of what it can see. Other worlds, for example JDT World, will need to have those types defined in a * project that is accessible in the JDT World instance. Because these tests exercise Java5 matching, the concrete ReflectionWorld * subtype is not defined in here, it is defined in weaver5 (messy, but works well). * * @author Andy Clement */ public abstract class CommonAdvancedPointcutExpressionTests extends TestCase { private World world; private StandardPointcutParser pointcutParser; protected abstract World getWorld(); protected void setUp() throws Exception { super.setUp(); world = getWorld(); pointcutParser = StandardPointcutParser.getPointcutParserSupportingAllPrimitives(world); } public void testResolvingOneType() { assertFalse(world.resolve("testdata.SomeAnnotation").isMissing()); assertFalse(world.resolve("testdata.MethodLevelAnnotation").isMissing()); assertFalse(world.resolve("testdata.AnnotatedClass").isMissing()); } public void testTypeLevelAnnotationMatchingWithStaticInitialization01() { StandardPointcutExpression ex = pointcutParser.parsePointcutExpression("staticinitialization(@testdata.SomeAnnotation *)"); ResolvedType jlString = world.resolve("java.lang.String"); ResolvedType tAnnotatedClass = world.resolve("testdata.AnnotatedClass"); assertTrue(ex.matchesStaticInitialization(tAnnotatedClass).alwaysMatches()); assertTrue(ex.matchesStaticInitialization(jlString).neverMatches()); } public void testTypeLevelAnnotationMatchingWithExecution01() { StandardPointcutExpression ex = pointcutParser.parsePointcutExpression("execution(* (@testdata.SomeAnnotation *).*(..))"); ResolvedType jlString = world.resolve("java.lang.String"); ResolvedType tAnnotatedClass = world.resolve("testdata.AnnotatedClass"); assertTrue(ex.matchesMethodExecution(getMethod(tAnnotatedClass, "annotatedMethod", "()V")).alwaysMatches()); assertTrue(ex.matchesMethodExecution(getMethod(jlString, "valueOf", "(Z)Ljava/lang/String;")).neverMatches()); } public void testMethodLevelAnnotationMatchingWithExecution01() { StandardPointcutExpression ex = pointcutParser .parsePointcutExpression("execution(@testdata.MethodLevelAnnotation * *(..))"); ResolvedType jlString = world.resolve("java.lang.String"); ResolvedType tAnnotatedClass = world.resolve("testdata.AnnotatedClass"); assertTrue(ex.matchesMethodExecution(getMethod(tAnnotatedClass, "annotatedMethod", "()V")).alwaysMatches()); assertTrue(ex.matchesMethodExecution(getMethod(tAnnotatedClass, "nonAnnotatedMethod", "()V")).neverMatches()); assertTrue(ex.matchesMethodExecution(getMethod(jlString, "valueOf", "(Z)Ljava/lang/String;")).neverMatches()); } // // ResolvedMember stringSplitMethod = getMethod(jlString, "split", "(Ljava/lang/String;I)[Ljava/lang/String;"); // ResolvedMember stringValueOfIntMethod = getMethod(jlString, "valueOf", "(I)Ljava/lang/String;"); // ResolvedMember listAddMethod = getMethod(juList, "add", "(Ljava/lang/Object;)Z"); // public void testResolveTypeAndRetrieveMethod() { // ResolvedType type = world.resolve("java.lang.String"); // assertNotNull(type); // ResolvedMember method = getMethod(type, "valueOf", "(Z)Ljava/lang/String;"); // grab the method 'String valueOf()' // assertNotNull(method); // } // // public void testMethodExecutionMatching01() { // checkAlwaysMatches("execution(String valueOf(boolean))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); // } // // public void testMethodExecutionMatching02() { // checkAlwaysMatches("execution(* *val*(..))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); // checkAlwaysMatches("execution(String *(..))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); // checkAlwaysMatches("execution(* *(boolean))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); // checkAlwaysMatches("execution(* j*..*.valueOf(..))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); // checkAlwaysMatches("execution(* *(*))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); // // checkNeverMatches("execution(* vulueOf(..))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); // checkNeverMatches("execution(int *(..))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); // checkNeverMatches("execution(* valueOf(String))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); // checkNeverMatches("execution(private * valueOf(..))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); // } // // public void testMethodExecutionMatching03() { // checkAlwaysMatches("execution(* *())", "java.util.List", "toArray", "()[Ljava/lang/Object;"); // checkAlwaysMatches("execution(*[] *())", "java.util.List", "toArray", "()[Ljava/lang/Object;"); // checkAlwaysMatches("execution(*b*[] *())", "java.util.List", "toArray", "()[Ljava/lang/Object;"); // } // // public void testMethodMatchesStaticInitialization() { // StandardPointcutExpression ex = pointcutParser.parsePointcutExpression("staticinitialization(java.lang.String)"); // assertNotNull(ex); // // ResolvedType jlString = world.resolve("java.lang.String"); // // boolean b = ex.matchesStaticInitialization(jlString).alwaysMatches(); // assertTrue(b); // } // public void testMethodExecutionMatching04() { // was execution((* *..A.aa(..)) // assertTrue("Should match execution of A.aa", ex.matchesMethodExecution(aa).alwaysMatches()); // assertTrue("Should match execution of B.aa", ex.matchesMethodExecution(bsaa).alwaysMatches()); // assertTrue("Should not match execution of A.a", ex.matchesMethodExecution(a).neverMatches()); // ex = p.parsePointcutExpression("call(* *..A.a*(int))"); // assertTrue("Should not match execution of A.a", ex.matchesMethodExecution(a).neverMatches()); // // // test this // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); // assertTrue("Should match A", ex.matchesMethodExecution(a).alwaysMatches()); // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); // assertTrue("Maybe matches B", ex.matchesMethodExecution(a).maybeMatches()); // assertFalse("Maybe matches B", ex.matchesMethodExecution(a).alwaysMatches()); // // // test target // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); // assertTrue("Should match A", ex.matchesMethodExecution(a).alwaysMatches()); // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); // assertTrue("Maybe matches B", ex.matchesMethodExecution(a).maybeMatches()); // assertFalse("Maybe matches B", ex.matchesMethodExecution(a).alwaysMatches()); // // // test args // ex = p.parsePointcutExpression("args(..,int)"); // assertTrue("Should match A.aa", ex.matchesMethodExecution(aa).alwaysMatches()); // assertTrue("Should match A.aaa", ex.matchesMethodExecution(aaa).alwaysMatches()); // assertTrue("Should not match A.a", ex.matchesMethodExecution(a).neverMatches()); // // // within // ex = p.parsePointcutExpression("within(*..A)"); // assertTrue("Matches in class A", ex.matchesMethodExecution(a).alwaysMatches()); // assertTrue("Does not match in class B", ex.matchesMethodExecution(bsaa).neverMatches()); // // // withincode // ex = p.parsePointcutExpression("withincode(* a*(..))"); // assertTrue("Should not match", ex.matchesMethodExecution(a).neverMatches()); // public void testMatchesMethodCall() { // PointcutExpression ex = p.parsePointcutExpression("call(* *..A.a*(..))"); // assertTrue("Should match call to A.a()", ex.matchesMethodCall(a, a).alwaysMatches()); // assertTrue("Should match call to A.aaa()", ex.matchesMethodCall(aaa, a).alwaysMatches()); // assertTrue("Should match call to B.aa()", ex.matchesMethodCall(bsaa, a).alwaysMatches()); // assertTrue("Should not match call to B.b()", ex.matchesMethodCall(b, a).neverMatches()); // ex = p.parsePointcutExpression("call(* *..A.a*(int))"); // assertTrue("Should match call to A.aa()", ex.matchesMethodCall(aa, a).alwaysMatches()); // assertTrue("Should not match call to A.a()", ex.matchesMethodCall(a, a).neverMatches()); // ex = p.parsePointcutExpression("call(void aaa(..)) && this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); // assertTrue("Should match call to A.aaa() from Client", ex.matchesMethodCall(aaa, foo).alwaysMatches()); // ex = p.parsePointcutExpression("call(void aaa(..)) && this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); // assertTrue("Should match call to A.aaa() from B", ex.matchesMethodCall(aaa, b).alwaysMatches()); // assertTrue("May match call to A.aaa() from A", ex.matchesMethodCall(aaa, a).maybeMatches()); // assertFalse("May match call to A.aaa() from A", ex.matchesMethodCall(aaa, a).alwaysMatches()); // ex = p.parsePointcutExpression("execution(* *.*(..))"); // assertTrue("Should not match call to A.aa", ex.matchesMethodCall(aa, a).neverMatches()); // // this // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); // assertTrue("Should match Client", ex.matchesMethodCall(a, foo).alwaysMatches()); // assertTrue("Should not match A", ex.matchesMethodCall(a, a).neverMatches()); // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); // assertTrue("Should maybe match B", ex.matchesMethodCall(bsaa, a).maybeMatches()); // assertFalse("Should maybe match B", ex.matchesMethodCall(bsaa, a).alwaysMatches()); // // target // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); // assertTrue("Should not match Client", ex.matchesMethodCall(a, a).neverMatches()); // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); // assertTrue("Should match A", ex.matchesMethodCall(a, a).alwaysMatches()); // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); // assertTrue("Should maybe match A", ex.matchesMethodCall(aa, a).maybeMatches()); // assertFalse("Should maybe match A", ex.matchesMethodCall(aa, a).alwaysMatches()); // // test args // ex = p.parsePointcutExpression("args(..,int)"); // assertTrue("Should match A.aa", ex.matchesMethodCall(aa, a).alwaysMatches()); // assertTrue("Should match A.aaa", ex.matchesMethodCall(aaa, a).alwaysMatches()); // assertTrue("Should not match A.a", ex.matchesMethodCall(a, a).neverMatches()); // // within // ex = p.parsePointcutExpression("within(*..A)"); // assertTrue("Matches in class A", ex.matchesMethodCall(a, a).alwaysMatches()); // assertTrue("Does not match in class B", ex.matchesMethodCall(a, b).neverMatches()); // assertTrue("Matches in class A", ex.matchesMethodCall(a, A.class).alwaysMatches()); // assertTrue("Does not match in class B", ex.matchesMethodCall(a, B.class).neverMatches()); // // withincode // ex = p.parsePointcutExpression("withincode(* a*(..))"); // assertTrue("Should match", ex.matchesMethodCall(b, bsaa).alwaysMatches()); // assertTrue("Should not match", ex.matchesMethodCall(b, b).neverMatches()); // } // public void testMatchesConstructorCall() { // PointcutExpression ex = p.parsePointcutExpression("call(new(String))"); // assertTrue("Should match A(String)", ex.matchesConstructorCall(asCons, b).alwaysMatches()); // assertTrue("Should match B(String)", ex.matchesConstructorCall(bsStringCons, b).alwaysMatches()); // assertTrue("Should not match B()", ex.matchesConstructorCall(bsCons, foo).neverMatches()); // ex = p.parsePointcutExpression("call(*..A.new(String))"); // assertTrue("Should match A(String)", ex.matchesConstructorCall(asCons, b).alwaysMatches()); // assertTrue("Should not match B(String)", ex.matchesConstructorCall(bsStringCons, foo).neverMatches()); // // this // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); // assertTrue("Should match Client", ex.matchesConstructorCall(asCons, foo).alwaysMatches()); // assertTrue("Should not match A", ex.matchesConstructorCall(asCons, a).neverMatches()); // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); // assertTrue("Should maybe match B", ex.matchesConstructorCall(asCons, a).maybeMatches()); // assertFalse("Should maybe match B", ex.matchesConstructorCall(asCons, a).alwaysMatches()); // // target // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); // assertTrue("Should not match Client", ex.matchesConstructorCall(asCons, foo).neverMatches()); // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); // assertTrue("Should not match A (no target)", ex.matchesConstructorCall(asCons, a).neverMatches()); // // args // ex = p.parsePointcutExpression("args(String)"); // assertTrue("Should match A(String)", ex.matchesConstructorCall(asCons, b).alwaysMatches()); // assertTrue("Should match B(String)", ex.matchesConstructorCall(bsStringCons, foo).alwaysMatches()); // assertTrue("Should not match B()", ex.matchesConstructorCall(bsCons, foo).neverMatches()); // // within // ex = p.parsePointcutExpression("within(*..A)"); // assertTrue("Matches in class A", ex.matchesConstructorCall(asCons, a).alwaysMatches()); // assertTrue("Does not match in class B", ex.matchesConstructorCall(asCons, b).neverMatches()); // // withincode // ex = p.parsePointcutExpression("withincode(* a*(..))"); // assertTrue("Should match", ex.matchesConstructorCall(bsCons, aa).alwaysMatches()); // assertTrue("Should not match", ex.matchesConstructorCall(bsCons, b).neverMatches()); // } // // public void testMatchesConstructorExecution() { // PointcutExpression ex = p.parsePointcutExpression("execution(new(String))"); // assertTrue("Should match A(String)", ex.matchesConstructorExecution(asCons).alwaysMatches()); // assertTrue("Should match B(String)", ex.matchesConstructorExecution(bsStringCons).alwaysMatches()); // assertTrue("Should not match B()", ex.matchesConstructorExecution(bsCons).neverMatches()); // ex = p.parsePointcutExpression("execution(*..A.new(String))"); // assertTrue("Should match A(String)", ex.matchesConstructorExecution(asCons).alwaysMatches()); // assertTrue("Should not match B(String)", ex.matchesConstructorExecution(bsStringCons).neverMatches()); // // // test this // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); // assertTrue("Should match A", ex.matchesConstructorExecution(asCons).alwaysMatches()); // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); // assertTrue("Maybe matches B", ex.matchesConstructorExecution(asCons).maybeMatches()); // assertFalse("Maybe matches B", ex.matchesConstructorExecution(asCons).alwaysMatches()); // assertTrue("Should match B", ex.matchesConstructorExecution(bsCons).alwaysMatches()); // assertTrue("Does not match client", ex.matchesConstructorExecution(clientCons).neverMatches()); // // // test target // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); // assertTrue("Should match A", ex.matchesConstructorExecution(asCons).alwaysMatches()); // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); // assertTrue("Maybe matches B", ex.matchesConstructorExecution(asCons).maybeMatches()); // assertFalse("Maybe matches B", ex.matchesConstructorExecution(asCons).alwaysMatches()); // assertTrue("Should match B", ex.matchesConstructorExecution(bsCons).alwaysMatches()); // assertTrue("Does not match client", ex.matchesConstructorExecution(clientCons).neverMatches()); // // // within // ex = p.parsePointcutExpression("within(*..A)"); // assertTrue("Matches in class A", ex.matchesConstructorExecution(asCons).alwaysMatches()); // assertTrue("Does not match in class B", ex.matchesConstructorExecution(bsCons).neverMatches()); // // // withincode // ex = p.parsePointcutExpression("withincode(* a*(..))"); // assertTrue("Does not match", ex.matchesConstructorExecution(bsCons).neverMatches()); // // // args // ex = p.parsePointcutExpression("args(String)"); // assertTrue("Should match A(String)", ex.matchesConstructorExecution(asCons).alwaysMatches()); // assertTrue("Should match B(String)", ex.matchesConstructorExecution(bsStringCons).alwaysMatches()); // assertTrue("Should not match B()", ex.matchesConstructorExecution(bsCons).neverMatches()); // } // // public void testMatchesAdviceExecution() { // PointcutExpression ex = p.parsePointcutExpression("adviceexecution()"); // assertTrue("Should match (advice) A.a", ex.matchesAdviceExecution(a).alwaysMatches()); // // test this // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); // assertTrue("Should match Client", ex.matchesAdviceExecution(foo).alwaysMatches()); // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); // assertTrue("Maybe matches B", ex.matchesAdviceExecution(a).maybeMatches()); // assertFalse("Maybe matches B", ex.matchesAdviceExecution(a).alwaysMatches()); // assertTrue("Does not match client", ex.matchesAdviceExecution(foo).neverMatches()); // // // test target // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); // assertTrue("Should match Client", ex.matchesAdviceExecution(foo).alwaysMatches()); // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); // assertTrue("Maybe matches B", ex.matchesAdviceExecution(a).maybeMatches()); // assertFalse("Maybe matches B", ex.matchesAdviceExecution(a).alwaysMatches()); // assertTrue("Does not match client", ex.matchesAdviceExecution(foo).neverMatches()); // // // test within // ex = p.parsePointcutExpression("within(*..A)"); // assertTrue("Matches in class A", ex.matchesAdviceExecution(a).alwaysMatches()); // assertTrue("Does not match in class B", ex.matchesAdviceExecution(b).neverMatches()); // // // withincode // ex = p.parsePointcutExpression("withincode(* a*(..))"); // assertTrue("Does not match", ex.matchesAdviceExecution(a).neverMatches()); // // // test args // ex = p.parsePointcutExpression("args(..,int)"); // assertTrue("Should match A.aa", ex.matchesAdviceExecution(aa).alwaysMatches()); // assertTrue("Should match A.aaa", ex.matchesAdviceExecution(aaa).alwaysMatches()); // assertTrue("Should not match A.a", ex.matchesAdviceExecution(a).neverMatches()); // } // // public void testMatchesHandler() { // PointcutExpression ex = p.parsePointcutExpression("handler(Exception)"); // assertTrue("Should match catch(Exception)", ex.matchesHandler(Exception.class, Client.class).alwaysMatches()); // assertTrue("Should not match catch(Throwable)", ex.matchesHandler(Throwable.class, Client.class).neverMatches()); // // test this // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); // assertTrue("Should match Client", ex.matchesHandler(Exception.class, foo).alwaysMatches()); // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); // assertTrue("Maybe matches B", ex.matchesHandler(Exception.class, a).maybeMatches()); // assertFalse("Maybe matches B", ex.matchesHandler(Exception.class, a).alwaysMatches()); // assertTrue("Does not match client", ex.matchesHandler(Exception.class, foo).neverMatches()); // // target - no target for exception handlers // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); // assertTrue("Should match Client", ex.matchesHandler(Exception.class, foo).neverMatches()); // // args // ex = p.parsePointcutExpression("args(Exception)"); // assertTrue("Should match Exception", ex.matchesHandler(Exception.class, foo).alwaysMatches()); // assertTrue("Should match RuntimeException", ex.matchesHandler(RuntimeException.class, foo).alwaysMatches()); // assertTrue("Should not match String", ex.matchesHandler(String.class, foo).neverMatches()); // assertTrue("Maybe matches Throwable", ex.matchesHandler(Throwable.class, foo).maybeMatches()); // assertFalse("Maybe matches Throwable", ex.matchesHandler(Throwable.class, foo).alwaysMatches()); // // within // ex = p.parsePointcutExpression("within(*..Client)"); // assertTrue("Matches in class Client", ex.matchesHandler(Exception.class, foo).alwaysMatches()); // assertTrue("Does not match in class B", ex.matchesHandler(Exception.class, b).neverMatches()); // // withincode // ex = p.parsePointcutExpression("withincode(* a*(..))"); // assertTrue("Matches within aa", ex.matchesHandler(Exception.class, aa).alwaysMatches()); // assertTrue("Does not match within b", ex.matchesHandler(Exception.class, b).neverMatches()); // } // // public void testMatchesInitialization() { // PointcutExpression ex = p.parsePointcutExpression("initialization(new(String))"); // assertTrue("Should match A(String)", ex.matchesInitialization(asCons).alwaysMatches()); // assertTrue("Should match B(String)", ex.matchesInitialization(bsStringCons).alwaysMatches()); // assertTrue("Should not match B()", ex.matchesInitialization(bsCons).neverMatches()); // ex = p.parsePointcutExpression("initialization(*..A.new(String))"); // assertTrue("Should match A(String)", ex.matchesInitialization(asCons).alwaysMatches()); // assertTrue("Should not match B(String)", ex.matchesInitialization(bsStringCons).neverMatches()); // // test this // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); // assertTrue("Should match A", ex.matchesInitialization(asCons).alwaysMatches()); // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); // assertTrue("Maybe matches B", ex.matchesInitialization(asCons).maybeMatches()); // assertFalse("Maybe matches B", ex.matchesInitialization(asCons).alwaysMatches()); // // // test target // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); // assertTrue("Should match A", ex.matchesInitialization(asCons).alwaysMatches()); // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); // assertTrue("Maybe matches B", ex.matchesInitialization(asCons).maybeMatches()); // assertFalse("Maybe matches B", ex.matchesInitialization(asCons).alwaysMatches()); // // within // ex = p.parsePointcutExpression("within(*..A)"); // assertTrue("Matches in class A", ex.matchesInitialization(asCons).alwaysMatches()); // assertTrue("Does not match in class B", ex.matchesInitialization(bsCons).neverMatches()); // // withincode // ex = p.parsePointcutExpression("withincode(* a*(..))"); // assertTrue("Does not match", ex.matchesInitialization(bsCons).neverMatches()); // // args // ex = p.parsePointcutExpression("args(String)"); // assertTrue("Should match A(String)", ex.matchesInitialization(asCons).alwaysMatches()); // assertTrue("Should match B(String)", ex.matchesInitialization(bsStringCons).alwaysMatches()); // assertTrue("Should not match B()", ex.matchesInitialization(bsCons).neverMatches()); // } // // public void testMatchesPreInitialization() { // PointcutExpression ex = p.parsePointcutExpression("preinitialization(new(String))"); // assertTrue("Should match A(String)", ex.matchesPreInitialization(asCons).alwaysMatches()); // assertTrue("Should match B(String)", ex.matchesPreInitialization(bsStringCons).alwaysMatches()); // assertTrue("Should not match B()", ex.matchesPreInitialization(bsCons).neverMatches()); // ex = p.parsePointcutExpression("preinitialization(*..A.new(String))"); // assertTrue("Should match A(String)", ex.matchesPreInitialization(asCons).alwaysMatches()); // assertTrue("Should not match B(String)", ex.matchesPreInitialization(bsStringCons).neverMatches()); // // test this // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); // assertTrue("No match, no this at preinit", ex.matchesPreInitialization(asCons).neverMatches()); // // // test target // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); // assertTrue("No match, no target at preinit", ex.matchesPreInitialization(asCons).neverMatches()); // // // within // ex = p.parsePointcutExpression("within(*..A)"); // assertTrue("Matches in class A", ex.matchesPreInitialization(asCons).alwaysMatches()); // assertTrue("Does not match in class B", ex.matchesPreInitialization(bsCons).neverMatches()); // // withincode // ex = p.parsePointcutExpression("withincode(* a*(..))"); // assertTrue("Does not match", ex.matchesPreInitialization(bsCons).neverMatches()); // // args // ex = p.parsePointcutExpression("args(String)"); // assertTrue("Should match A(String)", ex.matchesPreInitialization(asCons).alwaysMatches()); // assertTrue("Should match B(String)", ex.matchesPreInitialization(bsStringCons).alwaysMatches()); // assertTrue("Should not match B()", ex.matchesPreInitialization(bsCons).neverMatches()); // } // // public void testMatchesStaticInitialization() { // // staticinit // PointcutExpression ex = p.parsePointcutExpression("staticinitialization(*..A+)"); // assertTrue("Matches A", ex.matchesStaticInitialization(A.class).alwaysMatches()); // assertTrue("Matches B", ex.matchesStaticInitialization(B.class).alwaysMatches()); // assertTrue("Doesn't match Client", ex.matchesStaticInitialization(Client.class).neverMatches()); // // this // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); // assertTrue("No this", ex.matchesStaticInitialization(A.class).neverMatches()); // // target // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); // assertTrue("No target", ex.matchesStaticInitialization(A.class).neverMatches()); // // // args // ex = p.parsePointcutExpression("args()"); // assertTrue("No args", ex.matchesStaticInitialization(A.class).alwaysMatches()); // ex = p.parsePointcutExpression("args(String)"); // assertTrue("No args", ex.matchesStaticInitialization(A.class).neverMatches()); // // // within // ex = p.parsePointcutExpression("within(*..A)"); // assertTrue("Matches in class A", ex.matchesStaticInitialization(A.class).alwaysMatches()); // assertTrue("Does not match in class B", ex.matchesStaticInitialization(B.class).neverMatches()); // // // withincode // ex = p.parsePointcutExpression("withincode(* a*(..))"); // assertTrue("Does not match", ex.matchesStaticInitialization(A.class).neverMatches()); // } // // public void testMatchesFieldSet() { // PointcutExpression ex = p.parsePointcutExpression("set(* *..A+.*)"); // assertTrue("matches x", ex.matchesFieldSet(x, a).alwaysMatches()); // assertTrue("matches y", ex.matchesFieldSet(y, foo).alwaysMatches()); // assertTrue("does not match n", ex.matchesFieldSet(n, foo).neverMatches()); // // this // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); // assertTrue("matches Client", ex.matchesFieldSet(x, foo).alwaysMatches()); // assertTrue("does not match A", ex.matchesFieldSet(n, a).neverMatches()); // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); // assertTrue("maybe matches A", ex.matchesFieldSet(x, a).maybeMatches()); // assertFalse("maybe matches A", ex.matchesFieldSet(x, a).alwaysMatches()); // // target // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); // assertTrue("matches B", ex.matchesFieldSet(y, foo).alwaysMatches()); // assertTrue("maybe matches A", ex.matchesFieldSet(x, foo).maybeMatches()); // assertFalse("maybe matches A", ex.matchesFieldSet(x, foo).alwaysMatches()); // // args // ex = p.parsePointcutExpression("args(int)"); // assertTrue("matches x", ex.matchesFieldSet(x, a).alwaysMatches()); // assertTrue("matches y", ex.matchesFieldSet(y, a).alwaysMatches()); // assertTrue("does not match n", ex.matchesFieldSet(n, a).neverMatches()); // // within // ex = p.parsePointcutExpression("within(*..A)"); // assertTrue("Matches in class A", ex.matchesFieldSet(x, a).alwaysMatches()); // assertTrue("Does not match in class B", ex.matchesFieldSet(x, b).neverMatches()); // // withincode // ex = p.parsePointcutExpression("withincode(* a*(..))"); // assertTrue("Should match", ex.matchesFieldSet(x, aa).alwaysMatches()); // assertTrue("Should not match", ex.matchesFieldSet(x, b).neverMatches()); // } // // public void testMatchesFieldGet() { // PointcutExpression ex = p.parsePointcutExpression("get(* *..A+.*)"); // assertTrue("matches x", ex.matchesFieldGet(x, a).alwaysMatches()); // assertTrue("matches y", ex.matchesFieldGet(y, foo).alwaysMatches()); // assertTrue("does not match n", ex.matchesFieldGet(n, foo).neverMatches()); // // this // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); // assertTrue("matches Client", ex.matchesFieldGet(x, foo).alwaysMatches()); // assertTrue("does not match A", ex.matchesFieldGet(n, a).neverMatches()); // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); // assertTrue("maybe matches A", ex.matchesFieldGet(x, a).maybeMatches()); // assertFalse("maybe matches A", ex.matchesFieldGet(x, a).alwaysMatches()); // // target // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); // assertTrue("matches B", ex.matchesFieldGet(y, foo).alwaysMatches()); // assertTrue("maybe matches A", ex.matchesFieldGet(x, foo).maybeMatches()); // assertFalse("maybe matches A", ex.matchesFieldGet(x, foo).alwaysMatches()); // // args - no args at get join point // ex = p.parsePointcutExpression("args(int)"); // assertTrue("matches x", ex.matchesFieldGet(x, a).neverMatches()); // // within // ex = p.parsePointcutExpression("within(*..A)"); // assertTrue("Matches in class A", ex.matchesFieldGet(x, a).alwaysMatches()); // assertTrue("Does not match in class B", ex.matchesFieldGet(x, b).neverMatches()); // // withincode // ex = p.parsePointcutExpression("withincode(* a*(..))"); // assertTrue("Should match", ex.matchesFieldGet(x, aa).alwaysMatches()); // assertTrue("Should not match", ex.matchesFieldGet(x, b).neverMatches()); // } // // public void testArgsMatching() { // // too few args // PointcutExpression ex = p.parsePointcutExpression("args(*,*,*,*)"); // assertTrue("Too few args", ex.matchesMethodExecution(foo).neverMatches()); // assertTrue("Matching #args", ex.matchesMethodExecution(bar).alwaysMatches()); // // one too few + ellipsis // ex = p.parsePointcutExpression("args(*,*,*,..)"); // assertTrue("Matches with ellipsis", ex.matchesMethodExecution(foo).alwaysMatches()); // // exact number + ellipsis // assertTrue("Matches with ellipsis", ex.matchesMethodExecution(bar).alwaysMatches()); // assertTrue("Does not match with ellipsis", ex.matchesMethodExecution(a).neverMatches()); // // too many + ellipsis // ex = p.parsePointcutExpression("args(*,..,*)"); // assertTrue("Matches with ellipsis", ex.matchesMethodExecution(bar).alwaysMatches()); // assertTrue("Does not match with ellipsis", ex.matchesMethodExecution(a).neverMatches()); // assertTrue("Matches with ellipsis", ex.matchesMethodExecution(aaa).alwaysMatches()); // // exact match // ex = p.parsePointcutExpression("args(String,int,Number)"); // assertTrue("Matches exactly", ex.matchesMethodExecution(foo).alwaysMatches()); // // maybe match // ex = p.parsePointcutExpression("args(String,int,Double)"); // assertTrue("Matches maybe", ex.matchesMethodExecution(foo).maybeMatches()); // assertFalse("Matches maybe", ex.matchesMethodExecution(foo).alwaysMatches()); // // never match // ex = p.parsePointcutExpression("args(String,Integer,Number)"); // if (LangUtil.is15VMOrGreater()) { // assertTrue("matches", ex.matchesMethodExecution(foo).alwaysMatches()); // } else { // assertTrue("Does not match", ex.matchesMethodExecution(foo).neverMatches()); // } // } // // // public void testMatchesDynamically() { // // // everything other than this,target,args should just return true // // PointcutExpression ex = p.parsePointcutExpression("call(* *.*(..)) && execution(* *.*(..)) &&" + // // "get(* *) && set(* *) && initialization(new(..)) && preinitialization(new(..)) &&" + // // "staticinitialization(X) && adviceexecution() && within(Y) && withincode(* *.*(..)))"); // // assertTrue("Matches dynamically",ex.matchesDynamically(a,b,new Object[0])); // // // this // // ex = p.parsePointcutExpression("this(String)"); // // assertTrue("String matches",ex.matchesDynamically("",this,new Object[0])); // // assertFalse("Object doesn't match",ex.matchesDynamically(new Object(),this,new Object[0])); // // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); // // assertTrue("A matches",ex.matchesDynamically(new A(""),this,new Object[0])); // // assertTrue("B matches",ex.matchesDynamically(new B(""),this,new Object[0])); // // // target // // ex = p.parsePointcutExpression("target(String)"); // // assertTrue("String matches",ex.matchesDynamically(this,"",new Object[0])); // // assertFalse("Object doesn't match",ex.matchesDynamically(this,new Object(),new Object[0])); // // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); // // assertTrue("A matches",ex.matchesDynamically(this,new A(""),new Object[0])); // // assertTrue("B matches",ex.matchesDynamically(this,new B(""),new Object[0])); // // // args // // ex = p.parsePointcutExpression("args(*,*,*,*)"); // // assertFalse("Too few args",ex.matchesDynamically(null,null,new Object[]{a,b})); // // assertTrue("Matching #args",ex.matchesDynamically(null,null,new Object[]{a,b,aa,aaa})); // // // one too few + ellipsis // // ex = p.parsePointcutExpression("args(*,*,*,..)"); // // assertTrue("Matches with ellipsis",ex.matchesDynamically(null,null,new Object[]{a,b,aa,aaa})); // // // exact number + ellipsis // // assertTrue("Matches with ellipsis",ex.matchesDynamically(null,null,new Object[]{a,b,aa})); // // assertFalse("Does not match with ellipsis",ex.matchesDynamically(null,null,new Object[]{a,b})); // // // too many + ellipsis // // ex = p.parsePointcutExpression("args(*,..,*)"); // // assertTrue("Matches with ellipsis",ex.matchesDynamically(null,null,new Object[]{a,b,aa,aaa})); // // assertFalse("Does not match with ellipsis",ex.matchesDynamically(null,null,new Object[]{a})); // // assertTrue("Matches with ellipsis",ex.matchesDynamically(null,null,new Object[]{a,b})); // // // exact match // // ex = p.parsePointcutExpression("args(String,int,Number)"); // // assertTrue("Matches exactly",ex.matchesDynamically(null,null,new Object[]{"",new Integer(5),new Double(5.0)})); // // ex = p.parsePointcutExpression("args(String,Integer,Number)"); // // assertTrue("Matches exactly",ex.matchesDynamically(null,null,new Object[]{"",new Integer(5),new Double(5.0)})); // // // never match // // ex = p.parsePointcutExpression("args(String,Integer,Number)"); // // assertFalse("Does not match",ex.matchesDynamically(null,null,new Object[]{a,b,aa})); // // } // // public void testGetPointcutExpression() { // PointcutExpression ex = p.parsePointcutExpression("staticinitialization(*..A+)"); // assertEquals("staticinitialization(*..A+)", ex.getPointcutExpression()); // } // // public void testCouldMatchJoinPointsInType() { // PointcutExpression ex = p.parsePointcutExpression("execution(* org.aspectj.weaver.tools.PointcutExpressionTest.B.*(..))"); // assertTrue("Could maybe match String (as best we know at this point)", ex.couldMatchJoinPointsInType(String.class)); // assertTrue("Will always match B", ex.couldMatchJoinPointsInType(B.class)); // ex = p.parsePointcutExpression("within(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); // assertFalse("Will never match String", ex.couldMatchJoinPointsInType(String.class)); // assertTrue("Will always match B", ex.couldMatchJoinPointsInType(B.class)); // } // // public void testMayNeedDynamicTest() { // PointcutExpression ex = p.parsePointcutExpression("execution(* org.aspectj.weaver.tools.PointcutExpressionTest.B.*(..))"); // assertFalse("No dynamic test needed", ex.mayNeedDynamicTest()); // ex = p // .parsePointcutExpression("execution(* org.aspectj.weaver.tools.PointcutExpressionTest.B.*(..)) && args(org.aspectj.weaver.tools.PointcutExpressionTest.X)"); // assertTrue("Dynamic test needed", ex.mayNeedDynamicTest()); // } // static class A { // public A(String s) { // } // // public void a() { // } // // public void aa(int i) { // } // // public void aaa(String s, int i) { // } // // int x; // } // // static class B extends A { // public B() { // super(""); // } // // public B(String s) { // super(s); // } // // public String b() { // return null; // } // // public void aa(int i) { // } // // int y; // } // // static class Client { // public Client() { // } // // Number n; // // public void foo(String s, int i, Number n) { // } // // public void bar(String s, int i, Integer i2, Number n) { // } // } // // static class X { // } private ResolvedMember getMethod(ResolvedType type, String methodName, String methodSignature) { ResolvedMember[] methods = type.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { if (methods[i].getName().equals(methodName) && (methodSignature == null || methodSignature.equals(methods[i].getSignature()))) { return methods[i]; } } return null; } private void checkAlwaysMatches(String pointcutExpression, String type, String methodName, String methodSignature) { StandardPointcutExpression ex = pointcutParser.parsePointcutExpression(pointcutExpression); assertNotNull(ex); ResolvedType resolvedType = world.resolve(type); ResolvedMember method = getMethod(resolvedType, methodName, methodSignature); assertNotNull(method); boolean b = ex.matchesMethodExecution(method).alwaysMatches(); assertTrue(b); } private void checkNeverMatches(String pointcutExpression, String type, String methodName, String methodSignature) { StandardPointcutExpression ex = pointcutParser.parsePointcutExpression(pointcutExpression); assertNotNull(ex); ResolvedType resolvedType = world.resolve(type); ResolvedMember method = getMethod(resolvedType, methodName, methodSignature); assertNotNull(method); boolean b = ex.matchesMethodExecution(method).neverMatches(); assertTrue(b); } }
341,446
Bug 341446 java.lang.UnsupportedClassVersionError when running Java 1.5
null
resolved fixed
293a075
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-04-01T03:46:11Z"
"2011-03-31T05:40:00Z"
org.aspectj.matcher/testsrc/testdata/AnnotatedClass.java
341,446
Bug 341446 java.lang.UnsupportedClassVersionError when running Java 1.5
null
resolved fixed
293a075
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-04-01T03:46:11Z"
"2011-03-31T05:40:00Z"
org.aspectj.matcher/testsrc/testdata/MethodLevelAnnotation.java
341,446
Bug 341446 java.lang.UnsupportedClassVersionError when running Java 1.5
null
resolved fixed
293a075
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-04-01T03:46:11Z"
"2011-03-31T05:40:00Z"
org.aspectj.matcher/testsrc/testdata/SomeAnnotation.java
339,974
Bug 339974 NPE when accessing static class inside of an ITIT
This code: public class City { private String name; private Country country; } And separate file: public aspect TrafficCalculator { public static class City.TrafficCalculator { Function<City, Time> EXTREME = createExtremeTraffic(); Function<City, Time> BASIC = createBasicTraffic(); } private static Function<City, Time> createExtremeTraffic() { return null; } private static Function<City, Time> createBasicTraffic() { return null; } public static class Time { } } Try full build and the following exception: java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.ast.IntertypeMemberClassDeclaration.resolveOnType(IntertypeMemberClassDeclaration.java:238) at org.aspectj.ajdt.internal.compiler.ast.IntertypeMemberClassDeclaration.build(IntertypeMemberClassDeclaration.java:246) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.processIntertypeMemberTypes(AspectDeclaration.java:1039) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.processInterTypeMemberTypes(AjLookupEnvironment.java:523) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:197) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.internalBeginToCompile(Compiler.java:616) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:357) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:371) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:1021) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performBuild(AjBuildManager.java:305) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:185) at org.aspectj.ajde.core.internal.AjdeCoreBuildManager.performBuild(AjdeCoreBuildManager.java:127) at org.aspectj.ajde.core.AjCompiler.build(AjCompiler.java:91) at org.eclipse.ajdt.core.builder.AJBuilder.build(AJBuilder.java:257) at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:629) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:172) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:203) at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:255) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:258) at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:311) at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:343) at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:144) at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:242) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
resolved fixed
249f832
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-04-21T15:25:09Z"
"2011-03-15T03:33:20Z"
tests/bugs1612/pr339974/City.java
339,974
Bug 339974 NPE when accessing static class inside of an ITIT
This code: public class City { private String name; private Country country; } And separate file: public aspect TrafficCalculator { public static class City.TrafficCalculator { Function<City, Time> EXTREME = createExtremeTraffic(); Function<City, Time> BASIC = createBasicTraffic(); } private static Function<City, Time> createExtremeTraffic() { return null; } private static Function<City, Time> createBasicTraffic() { return null; } public static class Time { } } Try full build and the following exception: java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.ast.IntertypeMemberClassDeclaration.resolveOnType(IntertypeMemberClassDeclaration.java:238) at org.aspectj.ajdt.internal.compiler.ast.IntertypeMemberClassDeclaration.build(IntertypeMemberClassDeclaration.java:246) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.processIntertypeMemberTypes(AspectDeclaration.java:1039) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.processInterTypeMemberTypes(AjLookupEnvironment.java:523) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:197) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.internalBeginToCompile(Compiler.java:616) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:357) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:371) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:1021) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performBuild(AjBuildManager.java:305) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:185) at org.aspectj.ajde.core.internal.AjdeCoreBuildManager.performBuild(AjdeCoreBuildManager.java:127) at org.aspectj.ajde.core.AjCompiler.build(AjCompiler.java:91) at org.eclipse.ajdt.core.builder.AJBuilder.build(AJBuilder.java:257) at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:629) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:172) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:203) at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:255) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:258) at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:311) at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:343) at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:144) at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:242) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
resolved fixed
249f832
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-04-21T15:25:09Z"
"2011-03-15T03:33:20Z"
tests/bugs1612/pr339974/TrafficCalculator.java
339,974
Bug 339974 NPE when accessing static class inside of an ITIT
This code: public class City { private String name; private Country country; } And separate file: public aspect TrafficCalculator { public static class City.TrafficCalculator { Function<City, Time> EXTREME = createExtremeTraffic(); Function<City, Time> BASIC = createBasicTraffic(); } private static Function<City, Time> createExtremeTraffic() { return null; } private static Function<City, Time> createBasicTraffic() { return null; } public static class Time { } } Try full build and the following exception: java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.ast.IntertypeMemberClassDeclaration.resolveOnType(IntertypeMemberClassDeclaration.java:238) at org.aspectj.ajdt.internal.compiler.ast.IntertypeMemberClassDeclaration.build(IntertypeMemberClassDeclaration.java:246) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.processIntertypeMemberTypes(AspectDeclaration.java:1039) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.processInterTypeMemberTypes(AjLookupEnvironment.java:523) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:197) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.internalBeginToCompile(Compiler.java:616) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:357) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:371) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:1021) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performBuild(AjBuildManager.java:305) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:185) at org.aspectj.ajde.core.internal.AjdeCoreBuildManager.performBuild(AjdeCoreBuildManager.java:127) at org.aspectj.ajde.core.AjCompiler.build(AjCompiler.java:91) at org.eclipse.ajdt.core.builder.AJBuilder.build(AJBuilder.java:257) at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:629) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:172) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:203) at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:255) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:258) at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:311) at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:343) at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:144) at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:242) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
resolved fixed
249f832
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-04-21T15:25:09Z"
"2011-03-15T03:33:20Z"
tests/bugs1612/pr342605/Code.java
339,974
Bug 339974 NPE when accessing static class inside of an ITIT
This code: public class City { private String name; private Country country; } And separate file: public aspect TrafficCalculator { public static class City.TrafficCalculator { Function<City, Time> EXTREME = createExtremeTraffic(); Function<City, Time> BASIC = createBasicTraffic(); } private static Function<City, Time> createExtremeTraffic() { return null; } private static Function<City, Time> createBasicTraffic() { return null; } public static class Time { } } Try full build and the following exception: java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.ast.IntertypeMemberClassDeclaration.resolveOnType(IntertypeMemberClassDeclaration.java:238) at org.aspectj.ajdt.internal.compiler.ast.IntertypeMemberClassDeclaration.build(IntertypeMemberClassDeclaration.java:246) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.processIntertypeMemberTypes(AspectDeclaration.java:1039) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.processInterTypeMemberTypes(AjLookupEnvironment.java:523) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:197) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.internalBeginToCompile(Compiler.java:616) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:357) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:371) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:1021) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performBuild(AjBuildManager.java:305) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:185) at org.aspectj.ajde.core.internal.AjdeCoreBuildManager.performBuild(AjdeCoreBuildManager.java:127) at org.aspectj.ajde.core.AjCompiler.build(AjCompiler.java:91) at org.eclipse.ajdt.core.builder.AJBuilder.build(AJBuilder.java:257) at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:629) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:172) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:203) at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:255) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:258) at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:311) at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:343) at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:144) at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:242) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
resolved fixed
249f832
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-04-21T15:25:09Z"
"2011-03-15T03:33:20Z"
tests/src/org/aspectj/systemtest/ajc1612/Ajc1612Tests.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.ajc1612; import java.io.File; import junit.framework.Test; import org.aspectj.testing.XMLBasedAjcTestCase; /** * @author Andy Clement */ public class Ajc1612Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testClashingLocalTypes_342323() { runTest("clashing local types"); } public void testITIT_338175() { runTest("itit"); } public void testThrowsClause_292239() { runTest("throws clause"); } public void testThrowsClause_292239_2() { runTest("throws clause - 2"); } // --- public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc1612Tests.class); } @Override protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc1612/ajc1612.xml"); } }
327,134
Bug 327134 Cant suppress raw types warning in a pointcut
Build Identifier: I20100608-0911 Generic type used in a pointcut and bound to target() or this() must omit actual type name and thus causes 'raw type must be parametrized' compiler warning. @SuppressAJWarning or @SuppressWarning annotations does not turn it off Reproducible: Always Steps to Reproduce: Code snippets: pointcut IVOListUpdate(IVOList list): && target(list) && call(void updateList(*)); public interface IVOList<T extends IValueObject> extends List<T>, Externalizable, Serializable { void updateList(List<T> newList); } public interface IValueObject extends Comparable<IValueObject>, Serializable { }
resolved fixed
199299c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-04-28T15:36:50Z"
"2010-10-06T15:46:40Z"
tests/bugs1612/pr327134/Code.java
327,134
Bug 327134 Cant suppress raw types warning in a pointcut
Build Identifier: I20100608-0911 Generic type used in a pointcut and bound to target() or this() must omit actual type name and thus causes 'raw type must be parametrized' compiler warning. @SuppressAJWarning or @SuppressWarning annotations does not turn it off Reproducible: Always Steps to Reproduce: Code snippets: pointcut IVOListUpdate(IVOList list): && target(list) && call(void updateList(*)); public interface IVOList<T extends IValueObject> extends List<T>, Externalizable, Serializable { void updateList(List<T> newList); } public interface IValueObject extends Comparable<IValueObject>, Serializable { }
resolved fixed
199299c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-04-28T15:36:50Z"
"2010-10-06T15:46:40Z"
tests/src/org/aspectj/systemtest/ajc1612/Ajc1612Tests.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.ajc1612; import java.io.File; import junit.framework.Test; import org.aspectj.testing.XMLBasedAjcTestCase; /** * @author Andy Clement */ public class Ajc1612Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testRawTypeWarning_335810() { runTest("rawtype warning"); } // public void testDecpGenerics_344005() { // runTest("decp generics"); // } public void testIllegalAccessError_343051() { runTest("illegalaccesserror"); } public void testItitNpe_339974() { runTest("itit npe"); } // public void testNoImportError_342605() { // runTest("noimporterror"); // } public void testClashingLocalTypes_342323() { runTest("clashing local types"); } public void testITIT_338175() { runTest("itit"); } public void testThrowsClause_292239() { runTest("throws clause"); } public void testThrowsClause_292239_2() { runTest("throws clause - 2"); } // --- public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc1612Tests.class); } @Override protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc1612/ajc1612.xml"); } }
348,488
Bug 348488 "register definition failed" with NullPointerException
null
resolved fixed
95e70d2
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-06-07T16:46:19Z"
"2011-06-07T01: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.io.ByteArrayInputStream; import java.io.IOException; 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.Unknown; 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.AjAttribute.WeaverVersionInfo; 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.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; 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<AjAttribute> 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; WeaverVersionInfo wvinfo = null; 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; } } for (int i = attributes.length - 1; i >= 0; i--) { Attribute attribute = attributes[i]; if (attribute.getName().equals(WeaverVersionInfo.AttributeName)) { try { VersionedDataInputStream s = new VersionedDataInputStream(new ByteArrayInputStream( ((Unknown) attribute).getBytes()), null); wvinfo = WeaverVersionInfo.read(s); struct.ajAttributes.add(0, wvinfo); } catch (IOException ioe) { ioe.printStackTrace(); } } } if (wvinfo == null) { // If we are in here due to a resetState() call (presumably because of reweavable state processing), the // original type delegate will have been set with a version but that version will be missing from // the new set of attributes (looks like a bug where the version attribute was not included in the // data compressed into the attribute). So rather than 'defaulting' to current, we should use one // if it set on the delegate for the type. ReferenceTypeDelegate delegate = type.getDelegate(); if (delegate instanceof BcelObjectType) { wvinfo = ((BcelObjectType) delegate).getWeaverVersionAttribute(); if (wvinfo != null) { if (wvinfo.getMajorVersion() != WeaverVersionInfo.WEAVER_VERSION_MAJOR_UNKNOWN) { // use this one struct.ajAttributes.add(0, wvinfo); } else { wvinfo = null; } } } if (wvinfo == null) { struct.ajAttributes.add(0, wvinfo = new AjAttribute.WeaverVersionInfo()); } } // 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) { 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<AjAttribute> 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.emptyList(); } /** * 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 // Not setting version here // 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<TypePattern> parents = new ArrayList<TypePattern>(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; Iterator<ResolvedMember> methodIterator = fieldType.getMethodsIncludingIntertypeDeclarations(false, true); while (methodIterator.hasNext()) { ResolvedMember method = methodIterator.next(); // ResolvedMember[] methods = fieldType.getMethodsWithoutIterator(true, false, 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<ResolvedType> iterator = newInterfaceTypes.iterator(); iterator.hasNext();) { ResolvedType typeForDelegation = 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, false).toArray( new ResolvedMember[0]); for (int i = 0; i < methods.length; i++) { ResolvedMember method = methods[i]; if (method.isAbstract()) { hasAtLeastOneMethod = true; if (method.hasBackingGenericMember()) { method = method.getBackingGenericMember(); } 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 (AnnotationGen rv : rvs.getAnnotations()) { 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 (NameValuePair element : annotation.getValues()) { 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) { LocalVariable[] lvt = lt.getLocalVariableTable(); for (int j = 0; j < lvt.length; j++) { LocalVariable localVariable = lvt[j]; if (localVariable.getStartPC() == 0) { if (localVariable.getIndex() >= startAtStackIndex) { arguments.add(new MethodArgument(localVariable.getName(), localVariable.getIndex())); } } } if (arguments.size() == 0) { // could be cobertura code where some extra bytecode has been stuffed in at the start of the method // but the local variable table hasn't been repaired - for example: // LocalVariable(start_pc = 6, length = 40, index = 0:com.example.ExampleAspect this) // LocalVariable(start_pc = 6, length = 40, index = 1:org.aspectj.lang.ProceedingJoinPoint pjp) // LocalVariable(start_pc = 6, length = 40, index = 2:int __cobertura__line__number__) // LocalVariable(start_pc = 6, length = 40, index = 3:int __cobertura__branch__number__) LocalVariable localVariable = lvt[0]; if (localVariable.getStartPC() != 0) { // looks suspicious so let's use this information for (int j = 0; j < lvt.length && arguments.size() < method.getArgumentTypes().length; j++) { localVariable = lvt[j]; 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<MethodArgument>() { public int compare(MethodArgument mo, MethodArgument mo1) { 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<String> ignores = new ArrayList<String>(); for (int i = 0; i < bindings.length; i++) { FormalBinding formalBinding = bindings[i]; if (formalBinding instanceof FormalBinding.ImplicitFormalBinding) { ignores.add(formalBinding.getName()); } } pointcut.m_ignoreUnboundBindingForNames = 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; } } }
348,979
Bug 348979 world type map fixed/expendable problems
Discovered whilst working with Steve Ash on a build of a few projects that was consuming more than 2Gigs of heap. To recover memory Steve activated type demotion. This didn't appear to help much. This was due to Steve's projects using aspectpath. The aspectpath scanning to discover aspects was inadvertently making any types discovered on the aspectpath permanent types (not expendable) and they'd never be demoted/evicted. The types were all being made permanent in case they were an aspect but never being demoted if it turns out they were not. In a Roo petclinic I added spel as a dependency (on the aspectpath) and parsed a simple expression (just to further exaggerate the problem). This was leaving 213 types in the fixed area of the typemap. By correctly scanning aspectpath and demoting non-aspects this was reduced to 90.
resolved fixed
2edb246
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-06-10T20:36:55Z"
"2011-06-09T22:53:20Z"
tests/multiIncremental/PR278496_10/base/com/Asp.java
348,979
Bug 348979 world type map fixed/expendable problems
Discovered whilst working with Steve Ash on a build of a few projects that was consuming more than 2Gigs of heap. To recover memory Steve activated type demotion. This didn't appear to help much. This was due to Steve's projects using aspectpath. The aspectpath scanning to discover aspects was inadvertently making any types discovered on the aspectpath permanent types (not expendable) and they'd never be demoted/evicted. The types were all being made permanent in case they were an aspect but never being demoted if it turns out they were not. In a Roo petclinic I added spel as a dependency (on the aspectpath) and parsed a simple expression (just to further exaggerate the problem). This was leaving 213 types in the fixed area of the typemap. By correctly scanning aspectpath and demoting non-aspects this was reduced to 90.
resolved fixed
2edb246
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-06-10T20:36:55Z"
"2011-06-09T22:53:20Z"
tests/multiIncremental/PR278496_10/base/com/Foo.java
348,979
Bug 348979 world type map fixed/expendable problems
Discovered whilst working with Steve Ash on a build of a few projects that was consuming more than 2Gigs of heap. To recover memory Steve activated type demotion. This didn't appear to help much. This was due to Steve's projects using aspectpath. The aspectpath scanning to discover aspects was inadvertently making any types discovered on the aspectpath permanent types (not expendable) and they'd never be demoted/evicted. The types were all being made permanent in case they were an aspect but never being demoted if it turns out they were not. In a Roo petclinic I added spel as a dependency (on the aspectpath) and parsed a simple expression (just to further exaggerate the problem). This was leaving 213 types in the fixed area of the typemap. By correctly scanning aspectpath and demoting non-aspects this was reduced to 90.
resolved fixed
2edb246
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-06-10T20:36:55Z"
"2011-06-09T22:53:20Z"
tests/multiIncremental/PR278496_11/base/com/Foo.java
348,979
Bug 348979 world type map fixed/expendable problems
Discovered whilst working with Steve Ash on a build of a few projects that was consuming more than 2Gigs of heap. To recover memory Steve activated type demotion. This didn't appear to help much. This was due to Steve's projects using aspectpath. The aspectpath scanning to discover aspects was inadvertently making any types discovered on the aspectpath permanent types (not expendable) and they'd never be demoted/evicted. The types were all being made permanent in case they were an aspect but never being demoted if it turns out they were not. In a Roo petclinic I added spel as a dependency (on the aspectpath) and parsed a simple expression (just to further exaggerate the problem). This was leaving 213 types in the fixed area of the typemap. By correctly scanning aspectpath and demoting non-aspects this was reduced to 90.
resolved fixed
2edb246
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-06-10T20:36:55Z"
"2011-06-09T22:53:20Z"
tests/multiIncremental/PR278496_11_a/base/com/Asp.java
348,979
Bug 348979 world type map fixed/expendable problems
Discovered whilst working with Steve Ash on a build of a few projects that was consuming more than 2Gigs of heap. To recover memory Steve activated type demotion. This didn't appear to help much. This was due to Steve's projects using aspectpath. The aspectpath scanning to discover aspects was inadvertently making any types discovered on the aspectpath permanent types (not expendable) and they'd never be demoted/evicted. The types were all being made permanent in case they were an aspect but never being demoted if it turns out they were not. In a Roo petclinic I added spel as a dependency (on the aspectpath) and parsed a simple expression (just to further exaggerate the problem). This was leaving 213 types in the fixed area of the typemap. By correctly scanning aspectpath and demoting non-aspects this was reduced to 90.
resolved fixed
2edb246
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-06-10T20:36:55Z"
"2011-06-09T22:53:20Z"
tests/multiIncremental/PR278496_11_a/base/com/Dibble.java
349,636
Bug 349636 AspectJ reports "abort trouble" while instrumenting a class on startup
Build Identifier: 20110218-0911 java.lang.NullPointerException at org.aspectj.weaver.bcel.Utility.appendConversion(Utility.java:272) at org.aspectj.weaver.bcel.BcelVar.appendConvertableArrayLoad(BcelVar.java:81) at org.aspectj.weaver.bcel.BcelVar.createConvertableArrayLoad(BcelVar.java:101) at org.aspectj.weaver.bcel.BcelShadow.makeClosureClassAndReturnConstructor(BcelShadow.java:3066) at org.aspectj.weaver.bcel.BcelShadow.weaveAroundClosure(BcelShadow.java:2830) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:342) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:630) at org.aspectj.weaver.Shadow.implement(Shadow.java:544) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:3147) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:490) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:100) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1687) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1631) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1394) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1180) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:467) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:318) at org.eclipse.equinox.weaving.aspectj.loadtime.OSGiWeavingAdaptor.weaveClass(Unknown Source) at org.eclipse.equinox.weaving.aspectj.AspectJWeavingService.preProcess(Unknown Source) at org.eclipse.equinox.weaving.adaptors.WeavingAdaptor.weaveClass(Unknown Source) at org.eclipse.equinox.weaving.hooks.WeavingHook.processClass(Unknown Source) at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.defineClass(ClasspathManager.java:575) at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findClassImpl(ClasspathManager.java:550) at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClassImpl(ClasspathManager.java:481) at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClass_LockClassLoader(ClasspathManager.java:469) at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClass(ClasspathManager.java:449) at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.findLocalClass(DefaultClassLoader.java:216) at org.eclipse.osgi.internal.loader.BundleLoader.findLocalClass(BundleLoader.java:393) at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:469) at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:422) at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:410) at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107) at java.lang.ClassLoader.loadClass(ClassLoader.java:247) at org.eclipse.osgi.internal.loader.BundleLoader.loadClass(BundleLoader.java:338) at org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:232) at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadClass(AbstractBundle.java:1197) at org.springframework.osgi.util.BundleDelegatingClassLoader.findClass(BundleDelegatingClassLoader.java:99) at org.springframework.osgi.util.BundleDelegatingClassLoader.loadClass(BundleDelegatingClassLoader.java:157) at java.lang.ClassLoader.loadClass(ClassLoader.java:247) at org.springframework.util.ClassUtils.forName(ClassUtils.java:257) at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:408) at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1271) at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1242) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:576) at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1319) at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:315) at org.springframework.osgi.context.support.AbstractDelegatedExecutionApplicationContext.invokeBeanFactoryPostProcessors(AbstractDelegatedExecutionApplicationContext.java:391) at org.springframework.osgi.context.support.AbstractDelegatedExecutionApplicationContext.invokeBeanFactoryPostProcessors(AbstractDelegatedExecutionApplicationContext.java:364) at org.springframework.osgi.context.support.AbstractDelegatedExecutionApplicationContext$3.run(AbstractDelegatedExecutionApplicationContext.java:256) at org.springframework.osgi.util.internal.PrivilegedUtils.executeWithCustomTCCL(PrivilegedUtils.java:87) at org.springframework.osgi.context.support.AbstractDelegatedExecutionApplicationContext.startRefresh(AbstractDelegatedExecutionApplicationContext.java:222) at org.springframework.osgi.extender.internal.dependencies.startup.DependencyWaiterApplicationContextExecutor.stageOne(DependencyWaiterApplicationContextExecutor.java:225) at org.springframework.osgi.extender.internal.dependencies.startup.DependencyWaiterApplicationContextExecutor.refresh(DependencyWaiterApplicationContextExecutor.java:178) at org.springframework.osgi.context.support.AbstractDelegatedExecutionApplicationContext.refresh(AbstractDelegatedExecutionApplicationContext.java:159) at org.springframework.osgi.extender.internal.activator.LifecycleManager$1.run(LifecycleManager.java:223) at java.lang.Thread.run(Thread.java:662) Reproducible: Sometimes
resolved fixed
f7b1193
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-06-17T22:39:42Z"
"2011-06-17T00:20:00Z"
weaver/src/org/aspectj/weaver/bcel/Utility.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.ByteArrayInputStream; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Attribute; 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.classfile.Unknown; import org.aspectj.apache.bcel.classfile.annotation.ArrayElementValue; import org.aspectj.apache.bcel.classfile.annotation.ElementValue; import org.aspectj.apache.bcel.classfile.annotation.NameValuePair; import org.aspectj.apache.bcel.classfile.annotation.SimpleElementValue; import org.aspectj.apache.bcel.generic.ArrayType; import org.aspectj.apache.bcel.generic.BasicType; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionByte; 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.InstructionList; import org.aspectj.apache.bcel.generic.InstructionSelect; import org.aspectj.apache.bcel.generic.InstructionShort; import org.aspectj.apache.bcel.generic.InstructionTargeter; import org.aspectj.apache.bcel.generic.LineNumberTag; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.ReferenceType; import org.aspectj.apache.bcel.generic.SwitchBuilder; import org.aspectj.apache.bcel.generic.TargetLostException; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjAttribute.WeaverVersionInfo; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConstantPoolReader; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.Lint; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.Utils; import org.aspectj.weaver.World; public class Utility { public static List<AjAttribute> readAjAttributes(String classname, Attribute[] as, ISourceContext context, World w, AjAttribute.WeaverVersionInfo version, ConstantPoolReader dataDecompressor) { List<AjAttribute> attributes = new ArrayList<AjAttribute>(); // first pass, look for version List<Unknown> forSecondPass = new ArrayList<Unknown>(); for (int i = as.length - 1; i >= 0; i--) { Attribute a = as[i]; if (a instanceof Unknown) { Unknown u = (Unknown) a; String name = u.getName(); if (name.charAt(0) == 'o') { // 'o'rg.aspectj if (name.startsWith(AjAttribute.AttributePrefix)) { if (name.endsWith(WeaverVersionInfo.AttributeName)) { version = (AjAttribute.WeaverVersionInfo) AjAttribute.read(version, name, u.getBytes(), context, w, dataDecompressor); if (version.getMajorVersion() > WeaverVersionInfo.getCurrentWeaverMajorVersion()) { throw new BCException( "Unable to continue, this version of AspectJ supports classes built with weaver version " + WeaverVersionInfo.toCurrentVersionString() + " but the class " + classname + " is version " + version.toString() + ". Please update your AspectJ."); } } forSecondPass.add(u); } } } } // FIXASC why going backwards? is it important for (int i = forSecondPass.size() - 1; i >= 0; i--) { Unknown a = forSecondPass.get(i); String name = a.getName(); AjAttribute attr = AjAttribute.read(version, name, a.getBytes(), context, w, dataDecompressor); if (attr != null) { attributes.add(attr); } } return attributes; } /* * Ensure we report a nice source location - particular in the case where the source info is missing (binary weave). */ public static 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('\\'); } nice.append(isl.getSourceFile().getPath().substring(takeFrom + 1)); if (isl.getLine() != 0) { nice.append(":").append(isl.getLine()); } } return nice.toString(); } public static Instruction createSuperInvoke(InstructionFactory fact, BcelWorld world, Member signature) { short kind; if (Modifier.isInterface(signature.getModifiers())) { throw new RuntimeException("bad"); } else if (Modifier.isPrivate(signature.getModifiers()) || signature.getName().equals("<init>")) { throw new RuntimeException("unimplemented, possibly bad"); } else if (Modifier.isStatic(signature.getModifiers())) { throw new RuntimeException("bad"); } else { kind = Constants.INVOKESPECIAL; } return fact.createInvoke(signature.getDeclaringType().getName(), signature.getName(), BcelWorld.makeBcelType(signature.getReturnType()), BcelWorld.makeBcelTypes(signature.getParameterTypes()), kind); } // XXX don't need the world now public static Instruction createInvoke(InstructionFactory fact, BcelWorld world, Member signature) { short kind; int signatureModifiers = signature.getModifiers(); if (Modifier.isInterface(signatureModifiers)) { kind = Constants.INVOKEINTERFACE; } else if (Modifier.isStatic(signatureModifiers)) { kind = Constants.INVOKESTATIC; } else if (Modifier.isPrivate(signatureModifiers) || signature.getName().equals("<init>")) { kind = Constants.INVOKESPECIAL; } else { kind = Constants.INVOKEVIRTUAL; } UnresolvedType targetType = signature.getDeclaringType(); if (targetType.isParameterizedType()) { targetType = targetType.resolve(world).getGenericType(); } return fact.createInvoke(targetType.getName(), signature.getName(), BcelWorld.makeBcelType(signature.getReturnType()), BcelWorld.makeBcelTypes(signature.getParameterTypes()), kind); } public static Instruction createGet(InstructionFactory fact, Member signature) { short kind; if (Modifier.isStatic(signature.getModifiers())) { kind = Constants.GETSTATIC; } else { kind = Constants.GETFIELD; } return fact.createFieldAccess(signature.getDeclaringType().getName(), signature.getName(), BcelWorld.makeBcelType(signature.getReturnType()), kind); } public static Instruction createSet(InstructionFactory fact, Member signature) { short kind; if (Modifier.isStatic(signature.getModifiers())) { kind = Constants.PUTSTATIC; } else { kind = Constants.PUTFIELD; } return fact.createFieldAccess(signature.getDeclaringType().getName(), signature.getName(), BcelWorld.makeBcelType(signature.getReturnType()), kind); } public static Instruction createInstanceof(InstructionFactory fact, ReferenceType t) { int cpoolEntry = (t instanceof ArrayType) ? fact.getConstantPool().addArrayClass((ArrayType) t) : fact.getConstantPool() .addClass((ObjectType) t); return new InstructionCP(Constants.INSTANCEOF, cpoolEntry); } public static Instruction createInvoke(InstructionFactory fact, LazyMethodGen m) { short kind; if (m.getEnclosingClass().isInterface()) { kind = Constants.INVOKEINTERFACE; } else if (m.isStatic()) { kind = Constants.INVOKESTATIC; } else if (m.isPrivate() || m.getName().equals("<init>")) { kind = Constants.INVOKESPECIAL; } else { kind = Constants.INVOKEVIRTUAL; } return fact.createInvoke(m.getClassName(), m.getName(), m.getReturnType(), m.getArgumentTypes(), kind); } /** * Create an invoke instruction * * @param fact * @param kind INVOKEINTERFACE, INVOKEVIRTUAL.. * @param member * @return */ public static Instruction createInvoke(InstructionFactory fact, short kind, Member member) { return fact.createInvoke(member.getDeclaringType().getName(), member.getName(), BcelWorld.makeBcelType(member.getReturnType()), BcelWorld.makeBcelTypes(member.getParameterTypes()), kind); } private static String[] argNames = new String[] { "arg0", "arg1", "arg2", "arg3", "arg4" }; // ??? these should perhaps be cached. Remember to profile this to see if // it's a problem. public static String[] makeArgNames(int n) { String[] ret = new String[n]; for (int i = 0; i < n; i++) { if (i < 5) { ret[i] = argNames[i]; } else { ret[i] = "arg" + i; } } return ret; } // Lookup table, for converting between pairs of types, it gives // us the method name in the Conversions class private static Hashtable<String, String> validBoxing = new Hashtable<String, String>(); static { validBoxing.put("Ljava/lang/Byte;B", "byteObject"); validBoxing.put("Ljava/lang/Character;C", "charObject"); validBoxing.put("Ljava/lang/Double;D", "doubleObject"); validBoxing.put("Ljava/lang/Float;F", "floatObject"); validBoxing.put("Ljava/lang/Integer;I", "intObject"); validBoxing.put("Ljava/lang/Long;J", "longObject"); validBoxing.put("Ljava/lang/Short;S", "shortObject"); validBoxing.put("Ljava/lang/Boolean;Z", "booleanObject"); validBoxing.put("BLjava/lang/Byte;", "byteValue"); validBoxing.put("CLjava/lang/Character;", "charValue"); validBoxing.put("DLjava/lang/Double;", "doubleValue"); validBoxing.put("FLjava/lang/Float;", "floatValue"); validBoxing.put("ILjava/lang/Integer;", "intValue"); validBoxing.put("JLjava/lang/Long;", "longValue"); validBoxing.put("SLjava/lang/Short;", "shortValue"); validBoxing.put("ZLjava/lang/Boolean;", "booleanValue"); } public static void appendConversion(InstructionList il, InstructionFactory fact, ResolvedType fromType, ResolvedType toType) { if (!toType.isConvertableFrom(fromType) && !fromType.isConvertableFrom(toType)) { throw new BCException("can't convert from " + fromType + " to " + toType); } // XXX I'm sure this test can be simpler but my brain hurts and this // works if (!toType.getWorld().isInJava5Mode()) { if (toType.needsNoConversionFrom(fromType)) { return; } } else { if (toType.needsNoConversionFrom(fromType) && !(toType.isPrimitiveType() ^ fromType.isPrimitiveType())) { return; } } if (toType.equals(ResolvedType.VOID)) { // assert fromType.equals(UnresolvedType.OBJECT) il.append(InstructionFactory.createPop(fromType.getSize())); } else if (fromType.equals(ResolvedType.VOID)) { // assert toType.equals(UnresolvedType.OBJECT) il.append(InstructionFactory.createNull(Type.OBJECT)); return; } else if (fromType.equals(UnresolvedType.OBJECT)) { Type to = BcelWorld.makeBcelType(toType); if (toType.isPrimitiveType()) { String name = toType.toString() + "Value"; il.append(fact.createInvoke("org.aspectj.runtime.internal.Conversions", name, to, new Type[] { Type.OBJECT }, Constants.INVOKESTATIC)); } else { il.append(fact.createCheckCast((ReferenceType) to)); } } else if (toType.equals(UnresolvedType.OBJECT)) { // assert fromType.isPrimitive() Type from = BcelWorld.makeBcelType(fromType); String name = fromType.toString() + "Object"; il.append(fact.createInvoke("org.aspectj.runtime.internal.Conversions", name, Type.OBJECT, new Type[] { from }, Constants.INVOKESTATIC)); } else if (toType.getWorld().isInJava5Mode() && validBoxing.get(toType.getSignature() + fromType.getSignature()) != null) { // XXX could optimize by using any java boxing code that may be just // before the call... Type from = BcelWorld.makeBcelType(fromType); Type to = BcelWorld.makeBcelType(toType); String name = validBoxing.get(toType.getSignature() + fromType.getSignature()); if (toType.isPrimitiveType()) { il.append(fact.createInvoke("org.aspectj.runtime.internal.Conversions", name, to, new Type[] { Type.OBJECT }, Constants.INVOKESTATIC)); } else { il.append(fact.createInvoke("org.aspectj.runtime.internal.Conversions", name, Type.OBJECT, new Type[] { from }, Constants.INVOKESTATIC)); il.append(fact.createCheckCast((ReferenceType) to)); } } else if (fromType.isPrimitiveType()) { // assert toType.isPrimitive() Type from = BcelWorld.makeBcelType(fromType); Type to = BcelWorld.makeBcelType(toType); try { Instruction i = fact.createCast(from, to); if (i != null) { il.append(i); } else { il.append(fact.createCast(from, Type.INT)); il.append(fact.createCast(Type.INT, to)); } } catch (RuntimeException e) { il.append(fact.createCast(from, Type.INT)); il.append(fact.createCast(Type.INT, to)); } } else { Type to = BcelWorld.makeBcelType(toType); // assert ! fromType.isPrimitive() && ! toType.isPrimitive() il.append(fact.createCheckCast((ReferenceType) to)); } } public static InstructionList createConversion(InstructionFactory factory, Type fromType, Type toType) { return createConversion(factory, fromType, toType, false); } public static InstructionList createConversion(InstructionFactory fact, Type fromType, Type toType, boolean allowAutoboxing) { // System.out.println("cast to: " + toType); InstructionList il = new InstructionList(); // PR71273 if ((fromType.equals(Type.BYTE) || fromType.equals(Type.CHAR) || fromType.equals(Type.SHORT)) && (toType.equals(Type.INT))) { return il; } if (fromType.equals(toType)) { return il; } if (toType.equals(Type.VOID)) { il.append(InstructionFactory.createPop(fromType.getSize())); return il; } if (fromType.equals(Type.VOID)) { if (toType instanceof BasicType) { throw new BCException("attempting to cast from void to basic type"); } il.append(InstructionFactory.createNull(Type.OBJECT)); return il; } if (fromType.equals(Type.OBJECT)) { if (toType instanceof BasicType) { String name = toType.toString() + "Value"; il.append(fact.createInvoke("org.aspectj.runtime.internal.Conversions", name, toType, new Type[] { Type.OBJECT }, Constants.INVOKESTATIC)); return il; } } if (toType.equals(Type.OBJECT)) { if (fromType instanceof BasicType) { String name = fromType.toString() + "Object"; il.append(fact.createInvoke("org.aspectj.runtime.internal.Conversions", name, Type.OBJECT, new Type[] { fromType }, Constants.INVOKESTATIC)); return il; } else if (fromType instanceof ReferenceType) { return il; } else { throw new RuntimeException(); } } if (fromType instanceof ReferenceType && ((ReferenceType) fromType).isAssignmentCompatibleWith(toType)) { return il; } if (allowAutoboxing) { if (toType instanceof BasicType && fromType instanceof ReferenceType) { // unboxing String name = toType.toString() + "Value"; il.append(fact.createInvoke("org.aspectj.runtime.internal.Conversions", name, toType, new Type[] { Type.OBJECT }, Constants.INVOKESTATIC)); return il; } if (fromType instanceof BasicType && toType instanceof ReferenceType) { // boxing String name = fromType.toString() + "Object"; il.append(fact.createInvoke("org.aspectj.runtime.internal.Conversions", name, Type.OBJECT, new Type[] { fromType }, Constants.INVOKESTATIC)); il.append(fact.createCast(Type.OBJECT, toType)); return il; } } il.append(fact.createCast(fromType, toType)); return il; } public static Instruction createConstant(InstructionFactory fact, int value) { Instruction inst; switch (value) { case -1: inst = InstructionConstants.ICONST_M1; break; case 0: inst = InstructionConstants.ICONST_0; break; case 1: inst = InstructionConstants.ICONST_1; break; case 2: inst = InstructionConstants.ICONST_2; break; case 3: inst = InstructionConstants.ICONST_3; break; case 4: inst = InstructionConstants.ICONST_4; break; case 5: inst = InstructionConstants.ICONST_5; break; default: if (value <= Byte.MAX_VALUE && value >= Byte.MIN_VALUE) { inst = new InstructionByte(Constants.BIPUSH, (byte) value); } else if (value <= Short.MAX_VALUE && value >= Short.MIN_VALUE) { inst = new InstructionShort(Constants.SIPUSH, (short) value); } else { int ii = fact.getClassGen().getConstantPool().addInteger(value); inst = new InstructionCP(value <= Constants.MAX_BYTE ? Constants.LDC : Constants.LDC_W, ii); } break; } return inst; } /** For testing purposes: bit clunky but does work */ public static int testingParseCounter = 0; public static JavaClass makeJavaClass(String filename, byte[] bytes) { try { testingParseCounter++; ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes), filename); return parser.parse(); } catch (IOException e) { throw new BCException("malformed class file"); } } /** * replace an instruction handle with another instruction, in this case, a branch instruction. * * @param ih the instruction handle to replace. * @param branchInstruction the branch instruction to replace ih with * @param enclosingMethod where to find ih's instruction list. */ public static void replaceInstruction(InstructionHandle ih, InstructionList replacementInstructions, LazyMethodGen enclosingMethod) { InstructionList il = enclosingMethod.getBody(); InstructionHandle fresh = il.append(ih, replacementInstructions); deleteInstruction(ih, fresh, enclosingMethod); } /** * delete an instruction handle and retarget all targeters of the deleted instruction to the next instruction. Obviously, this * should not be used to delete a control transfer instruction unless you know what you're doing. * * @param ih the instruction handle to delete. * @param enclosingMethod where to find ih's instruction list. */ public static void deleteInstruction(InstructionHandle ih, LazyMethodGen enclosingMethod) { deleteInstruction(ih, ih.getNext(), enclosingMethod); } /** * delete an instruction handle and retarget all targeters of the deleted instruction to the provided target. * * @param ih the instruction handle to delete * @param retargetTo the instruction handle to retarget targeters of ih to. * @param enclosingMethod where to find ih's instruction list. */ public static void deleteInstruction(InstructionHandle ih, InstructionHandle retargetTo, LazyMethodGen enclosingMethod) { InstructionList il = enclosingMethod.getBody(); for (InstructionTargeter targeter : ih.getTargetersCopy()) { targeter.updateTarget(ih, retargetTo); } ih.removeAllTargeters(); try { il.delete(ih); } catch (TargetLostException e) { throw new BCException("this really can't happen"); } } /** * Fix for Bugzilla #39479, #40109 patch contributed by Andy Clement * * Need to manually copy Select instructions - if we rely on the the 'fresh' object created by copy(), the InstructionHandle * array 'targets' inside the Select object will not have been deep copied, so modifying targets in fresh will modify the * original Select - not what we want ! (It is a bug in BCEL to do with cloning Select objects). * * <pre> * declare error: * call(* Instruction.copy()) &amp;&amp; within(org.aspectj.weaver) * &amp;&amp; !withincode(* Utility.copyInstruction(Instruction)): * &quot;use Utility.copyInstruction to work-around bug in Select.copy()&quot;; * </pre> */ public static Instruction copyInstruction(Instruction i) { if (i instanceof InstructionSelect) { InstructionSelect freshSelect = (InstructionSelect) i; // Create a new targets array that looks just like the existing one InstructionHandle[] targets = new InstructionHandle[freshSelect.getTargets().length]; for (int ii = 0; ii < targets.length; ii++) { targets[ii] = freshSelect.getTargets()[ii]; } // Create a new select statement with the new targets array return new SwitchBuilder(freshSelect.getMatchs(), targets, freshSelect.getTarget()).getInstruction(); } else { return i.copy(); // Use clone for shallow copy... } } /** returns -1 if no source line attribute */ // this naive version overruns the JVM stack size, if only Java understood // tail recursion... // public static int getSourceLine(InstructionHandle ih) { // if (ih == null) return -1; // // InstructionTargeter[] ts = ih.getTargeters(); // if (ts != null) { // for (int j = ts.length - 1; j >= 0; j--) { // InstructionTargeter t = ts[j]; // if (t instanceof LineNumberTag) { // return ((LineNumberTag)t).getLineNumber(); // } // } // } // return getSourceLine(ih.getNext()); // } public static int getSourceLine(InstructionHandle ih) {// ,boolean // goforwards) { int lookahead = 0; // arbitrary rule that we will never lookahead more than 100 // instructions for a line # while (lookahead++ < 100) { if (ih == null) { return -1; } Iterator<InstructionTargeter> tIter = ih.getTargeters().iterator(); while (tIter.hasNext()) { InstructionTargeter t = tIter.next(); if (t instanceof LineNumberTag) { return ((LineNumberTag) t).getLineNumber(); } } // if (goforwards) ih=ih.getNext(); else ih = ih.getPrev(); } // System.err.println("no line information available for: " + ih); return -1; } // public static int getSourceLine(InstructionHandle ih) { // return getSourceLine(ih,false); // } // assumes that there is no already extant source line tag. Otherwise we'll // have to be better. public static void setSourceLine(InstructionHandle ih, int lineNumber) { // OPTIMIZE LineNumberTag instances for the same line could be shared // throughout a method... ih.addTargeter(new LineNumberTag(lineNumber)); } public static int makePublic(int i) { return i & ~(Modifier.PROTECTED | Modifier.PRIVATE) | Modifier.PUBLIC; } public static BcelVar[] pushAndReturnArrayOfVars(ResolvedType[] proceedParamTypes, InstructionList il, InstructionFactory fact, LazyMethodGen enclosingMethod) { int len = proceedParamTypes.length; BcelVar[] ret = new BcelVar[len]; for (int i = len - 1; i >= 0; i--) { ResolvedType typeX = proceedParamTypes[i]; Type type = BcelWorld.makeBcelType(typeX); int local = enclosingMethod.allocateLocal(type); il.append(InstructionFactory.createStore(type, local)); ret[i] = new BcelVar(typeX, local); } return ret; } public static boolean isConstantPushInstruction(Instruction i) { long ii = Constants.instFlags[i.opcode]; return ((ii & Constants.PUSH_INST) != 0 && (ii & Constants.CONSTANT_INST) != 0); } /** * Checks for suppression specified on the member or on the declaring type of that member */ public static boolean isSuppressing(Member member, String lintkey) { boolean isSuppressing = Utils.isSuppressing(member.getAnnotations(), lintkey); if (isSuppressing) { return true; } UnresolvedType type = member.getDeclaringType(); if (type instanceof ResolvedType) { return Utils.isSuppressing(((ResolvedType) type).getAnnotations(), lintkey); } return false; } public static List<Lint.Kind> getSuppressedWarnings(AnnotationAJ[] anns, Lint lint) { if (anns == null) { return Collections.emptyList(); } // Go through the annotation types List<Lint.Kind> suppressedWarnings = new ArrayList<Lint.Kind>(); boolean found = false; for (int i = 0; !found && i < anns.length; i++) { // Check for the SuppressAjWarnings annotation if (UnresolvedType.SUPPRESS_AJ_WARNINGS.getSignature().equals( ((BcelAnnotation) anns[i]).getBcelAnnotation().getTypeSignature())) { found = true; // Two possibilities: // 1. there are no values specified (i.e. @SuppressAjWarnings) // 2. there are values specified (i.e. @SuppressAjWarnings("A") // or @SuppressAjWarnings({"A","B"}) List<NameValuePair> vals = ((BcelAnnotation) anns[i]).getBcelAnnotation().getValues(); if (vals == null || vals.isEmpty()) { // (1) suppressedWarnings.addAll(lint.allKinds()); } else { // (2) // We know the value is an array value ArrayElementValue array = (ArrayElementValue) (vals.get(0)).getValue(); ElementValue[] values = array.getElementValuesArray(); for (int j = 0; j < values.length; j++) { // We know values in the array are strings SimpleElementValue value = (SimpleElementValue) values[j]; Lint.Kind lintKind = lint.getLintKind(value.getValueString()); if (lintKind != null) { suppressedWarnings.add(lintKind); } } } } } return suppressedWarnings; } // not yet used... // public static boolean isSimple(Method method) { // if (method.getCode()==null) return true; // if (method.getCode().getCode().length>10) return false; // InstructionList instrucs = new // InstructionList(method.getCode().getCode()); // expensive! // InstructionHandle InstrHandle = instrucs.getStart(); // while (InstrHandle != null) { // Instruction Instr = InstrHandle.getInstruction(); // int opCode = Instr.opcode; // // if current instruction is a branch instruction, see if it's a backward // branch. // // if it is return immediately (can't be trivial) // if (Instr instanceof InstructionBranch) { // // InstructionBranch BI = (InstructionBranch) Instr; // if (Instr.getIndex() < 0) return false; // } else if (Instr instanceof InvokeInstruction) { // // if current instruction is an invocation, indicate that it can't be // trivial // return false; // } // InstrHandle = InstrHandle.getNext(); // } // return true; // } public static Attribute bcelAttribute(AjAttribute a, ConstantPool pool) { int nameIndex = pool.addUtf8(a.getNameString()); byte[] bytes = a.getBytes(new BcelConstantPoolWriter(pool)); int length = bytes.length; return new Unknown(nameIndex, length, bytes, pool); } }
349,764
Bug 349764 Repeated output of ASPECTJ: aspectj.overweaving=true: overweaving switched ON
Build Identifier: 1.6.11 The message is repeated every time a new class loader is being use to load weaving configuration (using -Dorg.aspectj.tracing.factory=default). Since this value is a system (!) property there is no need to display its value more than once (or even check it more than once - it could be lazily initialized and cached...) Reproducible: Always Steps to Reproduce: 1. use -Dorg.aspectj.tracing.factory=default -Daspectj.overweaving=true properties 2. place some JAR that contains aop.xml with some aspects and weaving options where it can be loaded/visible from several class loaders 3. runt the application and check the STDOUT output
resolved fixed
bb2aea4
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-06-20T17:10:01Z"
"2011-06-19T10:40:00Z"
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, Abraham Nevado * ******************************************************************/ package org.aspectj.weaver; import java.lang.ref.Reference; 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.IMessage; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.context.PinpointingMessageHandler; import org.aspectj.util.IStructureModel; import org.aspectj.weaver.UnresolvedType.TypeKind; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.DeclareSoft; import org.aspectj.weaver.patterns.DeclareTypeErrorOrWarning; 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<PointcutDesignatorHandler> 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; /** Should timing information be reported (as info messages)? */ private boolean timing = false; private boolean timingPeriodically = true; /** 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 runMinimalMemorySet = false; private boolean shouldPipelineCompilation = true; private boolean shouldGenerateStackMaps = false; protected boolean bcelRepositoryCaching = xsetBCEL_REPOSITORY_CACHING_DEFAULT.equalsIgnoreCase("true"); private boolean fastMethodPacking = false; private int itdVersion = 2; // defaults to 2nd generation itds // Minimal Model controls whether model entities that are not involved in relationships are deleted post-build private boolean minimalModel = false; private boolean useFinal = true; private boolean targettingRuntime1_6_10 = false; private boolean completeBinaryTypes = false; private boolean overWeaving = false; public boolean forDEBUG_structuralChangesCode = false; public boolean forDEBUG_bridgingCode = false; public boolean optimizedMatching = true; protected long timersPerJoinpoint = 25000; protected long timersPerType = 250; public int infoMessagesEnabled = 0; // 0=uninitialized, 1=no, 2=yes 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<RuntimeException> 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 ResolvedType.NONE; } 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); // A TypeVariableReferenceType may look like it is resolved (it extends ResolvedType) but the internal // type variable may not yet have been resolved if (!rty.isTypeVariableReference() || ((TypeVariableReferenceType) rty).isTypeVariableResolved()) { 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 = getWildcard(); typeMap.put("?", something); return something; } // no existing resolved type, create one synchronized (buildingTypeLock) { if (ty.isArray()) { ResolvedType componentType = resolve(ty.getComponentType(), allowMissing); 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 ResolvedType result = typeMap.get(signature); if (result == null && !ret.isMissing()) { ret = ensureRawTypeIfNecessary(ret); typeMap.put(signature, ret); return ret; } if (result == null) { return ret; } else { return result; } } private Object buildingTypeLock = new Object(); // Only need one representation of '?' in a world - can be shared private BoundedReferenceType wildcard; private BoundedReferenceType getWildcard() { if (wildcard == null) { wildcard = new BoundedReferenceType(this); } return wildcard; } /** * 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<RuntimeException>(); } 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) { resolved = ensureRawTypeIfNecessary(ty); typeMap.put(ty.getSignature(), resolved); resolved = ty; } resolved.world = this; return resolved; } /** * When the world is operating in 1.5 mode, the TypeMap should only contain RAW types and never directly generic types. The RAW * type will contain a reference to the generic type. * * @param type a possibly generic type for which the raw needs creating as it is not currently in the world * @return a type suitable for putting into the world */ private ResolvedType ensureRawTypeIfNecessary(ResolvedType type) { if (!isInJava5Mode() || type.isRawType()) { return type; } // Key requirement here is if it is generic, create a RAW entry to be put in the map that points to it if (type instanceof ReferenceType && ((ReferenceType) type).getDelegate() != null && type.isGenericType()) { ReferenceType rawType = new ReferenceType(type.getSignature(), this); rawType.typeKind = UnresolvedType.TypeKind.RAW; ReferenceTypeDelegate delegate = ((ReferenceType) type).getDelegate(); rawType.setDelegate(delegate); rawType.setGenericType((ReferenceType) type); return rawType; } // probably parameterized... return type; } /** * 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 ReferenceType resolveToReferenceType(String name) { return (ReferenceType) resolve(name); } 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 ====================== ResolvedType rt = resolveGenericTypeFor(ty, false); ReferenceType genericType = (ReferenceType) rt; 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; ((ReferenceType) genericType).addDependentType((ReferenceType) rawType); 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 = getWildcard(); } 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); } private boolean allLintIgnored = false; public void setAllLintIgnored() { allLintIgnored = true; } public boolean areAllLintIgnored() { return allLintIgnored; } 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, ResolvedType declaringAspect) { AjAttribute.AdviceAttribute attribute = new AjAttribute.AdviceAttribute(kind, p, extraParameterFlags, loc.getStart(), loc.getEnd(), loc.getSourceContext()); return getWeavingSupport().createAdviceMunger(attribute, p, signature, declaringAspect); } /** * 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<DeclareParents> getDeclareParents() { return crosscuttingMembersSet.getDeclareParents(); } public List<DeclareAnnotation> getDeclareAnnotationOnTypes() { return crosscuttingMembersSet.getDeclareAnnotationOnTypes(); } public List<DeclareAnnotation> getDeclareAnnotationOnFields() { return crosscuttingMembersSet.getDeclareAnnotationOnFields(); } public List<DeclareAnnotation> getDeclareAnnotationOnMethods() { return crosscuttingMembersSet.getDeclareAnnotationOnMethods(); } public List<DeclareTypeErrorOrWarning> getDeclareTypeEows() { return crosscuttingMembersSet.getDeclareTypeEows(); } public List<DeclareSoft> 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 boolean useFinal() { return useFinal; } public boolean isMinimalModel() { ensureAdvancedConfigurationProcessed(); return minimalModel; } public boolean isTargettingRuntime1_6_10() { ensureAdvancedConfigurationProcessed(); return targettingRuntime1_6_10; } public void setBehaveInJava5Way(boolean b) { behaveInJava5Way = b; } /** * Set the timing option (whether to collect timing info), this will also need INFO messages turned on for the message handler * being used. The reportPeriodically flag should be set to false under AJDT so numbers just come out at the end. */ public void setTiming(boolean timersOn, boolean reportPeriodically) { timing = timersOn; timingPeriodically = reportPeriodically; } /** * 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(); } public boolean areInfoMessagesEnabled() { if (infoMessagesEnabled == 0) { infoMessagesEnabled = (messageHandler.isIgnoring(IMessage.INFO) ? 1 : 2); } return infoMessagesEnabled == 2; } /** * may return null */ public Properties getExtraConfiguration() { return extraConfiguration; } public final static String xsetAVOID_FINAL = "avoidFinal"; // default true 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 final static String xsetOVERWEAVING = "overWeaving"; public final static String xsetOPTIMIZED_MATCHING = "optimizedMatching"; public final static String xsetTIMERS_PER_JOINPOINT = "timersPerJoinpoint"; public final static String xsetTIMERS_PER_FASTMATCH_CALL = "timersPerFastMatchCall"; public final static String xsetITD_VERSION = "itdVersion"; public final static String xsetITD_VERSION_ORIGINAL = "1"; public final static String xsetITD_VERSION_2NDGEN = "2"; public final static String xsetITD_VERSION_DEFAULT = xsetITD_VERSION_2NDGEN; public final static String xsetMINIMAL_MODEL = "minimalModel"; public final static String xsetTARGETING_RUNTIME_1610 = "targetRuntime1_6_10"; public boolean isInJava5Mode() { return behaveInJava5Way; } public boolean isTimingEnabled() { return timing; } 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). */ public static class TypeMap { // 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 public List<String> addedSinceLastDemote; public List<String> writtenClasses; private static boolean debug = false; public static boolean useExpendableMap = true; // configurable for reliable testing private boolean demotionSystemActive; private boolean debugDemotion = false; public int policy = USE_WEAK_REFS; // Map of types that never get thrown away final Map<String, ResolvedType> tMap = new HashMap<String, ResolvedType>(); // Map of types that may be ejected from the cache if we need space final Map<String, Reference<ResolvedType>> expendableMap = Collections .synchronizedMap(new WeakHashMap<String, Reference<ResolvedType>>()); private final World w; // profiling tools... private boolean memoryProfiling = false; private int maxExpendableMapSize = -1; private int collectedTypes = 0; private final ReferenceQueue<ResolvedType> rq = new ReferenceQueue<ResolvedType>(); // private static Trace trace = TraceFactory.getTraceFactory().getTrace(World.TypeMap.class); TypeMap(World w) { // Demotion activated when switched on and loadtime weaving or in AJDT demotionSystemActive = w.isDemotionActive() && (w.isLoadtimeWeaving() || w.couldIncrementalCompileFollow()); addedSinceLastDemote = new ArrayList<String>(); writtenClasses = new ArrayList<String>(); this.w = w; memoryProfiling = false;// !w.getMessageHandler().isIgnoring(Message. // INFO); } // For testing public Map<String, Reference<ResolvedType>> getExpendableMap() { return expendableMap; } // For testing public Map<String, ResolvedType> getMainMap() { return tMap; } public int demote() { return demote(false); } /** * 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(boolean atEndOfCompile) { if (!demotionSystemActive) { return 0; } if (debugDemotion) { System.out.println("Demotion running " + addedSinceLastDemote); } boolean isLtw = w.isLoadtimeWeaving(); int demotionCounter = 0; if (isLtw) { // Loadtime weaving demotion strategy for (String key : addedSinceLastDemote) { ResolvedType type = tMap.get(key); if (type != null && !type.isAspect() && !type.equals(UnresolvedType.OBJECT) && !type.isPrimitiveType()) { List<ConcreteTypeMunger> typeMungers = type.getInterTypeMungers(); if (typeMungers == null || typeMungers.size() == 0) { tMap.remove(key); insertInExpendableMap(key, type); demotionCounter++; } } } addedSinceLastDemote.clear(); } else { // Compile time demotion strategy List<String> forRemoval = new ArrayList<String>(); for (String key : addedSinceLastDemote) { ResolvedType type = tMap.get(key); if (type == null) { // TODO not 100% sure why it is not there, where did it go? forRemoval.add(key); continue; } if (!writtenClasses.contains(type.getName())) { // COSTLY continue; } if (type != null && !type.isAspect() && !type.equals(UnresolvedType.OBJECT) && !type.isPrimitiveType()) { List<ConcreteTypeMunger> typeMungers = type.getInterTypeMungers(); if (typeMungers == null || typeMungers.size() == 0) { /* * if (type.isNested()) { try { ReferenceType rt = (ReferenceType) w.resolve(type.getOutermostType()); * if (!rt.isMissing()) { ReferenceTypeDelegate delegate = ((ReferenceType) type).getDelegate(); boolean * isWeavable = delegate == null ? false : delegate.isExposedToWeaver(); boolean hasBeenWoven = delegate * == null ? false : delegate.hasBeenWoven(); if (isWeavable && !hasBeenWoven) { // skip demotion of * this inner type for now continue; } } } catch (ClassCastException cce) { cce.printStackTrace(); * System.out.println("outer of " + key + " is not a reftype? " + type.getOutermostType()); // throw new * IllegalStateException(cce); } } */ ReferenceTypeDelegate delegate = ((ReferenceType) type).getDelegate(); boolean isWeavable = delegate == null ? false : delegate.isExposedToWeaver(); boolean hasBeenWoven = delegate == null ? false : delegate.hasBeenWoven(); if (!isWeavable || hasBeenWoven) { if (debugDemotion) { System.out.println("Demoting " + key); } forRemoval.add(key); tMap.remove(key); insertInExpendableMap(key, type); demotionCounter++; } } else { // no need to try this again, it will never be demoted writtenClasses.remove(type.getName()); forRemoval.add(key); } } else { writtenClasses.remove(type.getName()); // no need to try this again, it will never be demoted forRemoval.add(key); } } addedSinceLastDemote.removeAll(forRemoval); } if (debugDemotion) { System.out.println("Demoted " + demotionCounter + " types. Types remaining in fixed set #" + tMap.keySet().size() + ". addedSinceLastDemote size is " + addedSinceLastDemote.size()); System.out.println("writtenClasses.size() = " + writtenClasses.size() + ": " + writtenClasses); } if (atEndOfCompile) { if (debugDemotion) { System.out.println("Clearing writtenClasses"); } writtenClasses.clear(); } return demotionCounter; } private void insertInExpendableMap(String key, ResolvedType type) { if (useExpendableMap) { if (!expendableMap.containsKey(key)) { if (policy == USE_SOFT_REFS) { expendableMap.put(key, new SoftReference<ResolvedType>(type)); } else { expendableMap.put(key, new WeakReference<ResolvedType>(type)); } } } } /** * 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.isCacheable()) { return 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; } // TODO should this be in as a permanent assertion? /* * if ((type instanceof ReferenceType) && type.getWorld().isInJava5Mode() && (((ReferenceType) type).getDelegate() != * null) && type.isGenericType()) { throw new BCException("Attempt to add generic type to typemap " + type.toString() + * " (should be raw)"); } */ if (w.isExpendable(type)) { if (useExpendableMap) { // Dont use reference queue for tracking if not profiling... if (policy == USE_WEAK_REFS) { if (memoryProfiling) { expendableMap.put(key, new WeakReference<ResolvedType>(type, rq)); } else { expendableMap.put(key, new WeakReference<ResolvedType>(type)); } } else if (policy == USE_SOFT_REFS) { if (memoryProfiling) { expendableMap.put(key, new SoftReference<ResolvedType>(type, rq)); } else { expendableMap.put(key, new SoftReference<ResolvedType>(type)); } // } else { // expendableMap.put(key, type); } } if (memoryProfiling && expendableMap.size() > maxExpendableMapSize) { maxExpendableMapSize = expendableMap.size(); } return type; } else { if (demotionSystemActive) { // System.out.println("Added since last demote " + key); addedSinceLastDemote.add(key); } return 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 = tMap.get(key); if (ret == null) { if (policy == USE_WEAK_REFS) { WeakReference<ResolvedType> ref = (WeakReference<ResolvedType>) expendableMap.get(key); if (ref != null) { ret = ref.get(); } } else if (policy == USE_SOFT_REFS) { SoftReference<ResolvedType> ref = (SoftReference<ResolvedType>) expendableMap.get(key); if (ref != null) { ret = ref.get(); } // } else { // return (ResolvedType) expendableMap.get(key); } } return ret; } /** Remove a type from the map */ public ResolvedType remove(String key) { ResolvedType ret = tMap.remove(key); if (ret == null) { if (policy == USE_WEAK_REFS) { WeakReference<ResolvedType> wref = (WeakReference<ResolvedType>) expendableMap.remove(key); if (wref != null) { ret = wref.get(); } } else if (policy == USE_SOFT_REFS) { SoftReference<ResolvedType> wref = (SoftReference<ResolvedType>) expendableMap.remove(key); if (wref != null) { ret = wref.get(); } // } else { // ret = (ResolvedType) expendableMap.remove(key); } } return ret; } public void classWriteEvent(String classname) { // that is a name com.Foo and not a signature Lcom/Foo; boooooooooo! if (demotionSystemActive) { writtenClasses.add(classname); } if (debugDemotion) { System.out.println("Class write event for " + classname); } } public void demote(ResolvedType type) { String key = type.getSignature(); if (debugDemotion) { addedSinceLastDemote.remove(key); } tMap.remove(key); insertInExpendableMap(key, type); } // 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<PrecedenceCacheKey, Integer> cachedResults; public AspectPrecedenceCalculator(World forSomeWorld) { world = forSomeWorld; cachedResults = new HashMap<PrecedenceCacheKey, Integer>(); } /** * 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 (cachedResults.get(key)).intValue(); } else { int order = 0; DeclarePrecedence orderer = null; // Records the declare // precedence statement that // gives the first ordering for (Iterator<Declare> 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 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; } @Override public boolean equals(Object obj) { if (!(obj instanceof PrecedenceCacheKey)) { return false; } PrecedenceCacheKey other = (PrecedenceCacheKey) obj; return (aspect1 == other.aspect1 && aspect2 == other.aspect2); } @Override 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) --- public boolean isDemotionActive() { return false; } // --- 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<Class<?>, TypeVariable[]> workInProgress1 = new HashMap<Class<?>, TypeVariable[]>(); public TypeVariable[] getTypeVariablesCurrentlyBeingProcessed(Class<?> baseClass) { return 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")); } // ITD Versions // 1 is the first version in use up to AspectJ 1.6.8 // 2 is from 1.6.9 onwards s = p.getProperty(xsetITD_VERSION, xsetITD_VERSION_DEFAULT); if (s.equals(xsetITD_VERSION_ORIGINAL)) { itdVersion = 1; } s = p.getProperty(xsetAVOID_FINAL, "false"); if (s.equalsIgnoreCase("true")) { useFinal = false; // if avoidFinal=true, then set useFinal to false } s = p.getProperty(xsetMINIMAL_MODEL, "false"); if (s.equalsIgnoreCase("true")) { minimalModel = true; } s = p.getProperty(xsetTARGETING_RUNTIME_1610, "false"); if (s.equalsIgnoreCase("true")) { targettingRuntime1_6_10 = true; } 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); // default is: ON (for ltw) OFF (for ctw) if (s != null) { boolean b = typeMap.demotionSystemActive; if (b && s.equalsIgnoreCase("false")) { System.out.println("typeDemotion=false: type demotion switched OFF"); typeMap.demotionSystemActive = false; } else if (!b && s.equalsIgnoreCase("true")) { System.out.println("typeDemotion=true: type demotion switched ON"); typeMap.demotionSystemActive = true; } } s = p.getProperty(xsetOVERWEAVING, "false"); if (s.equalsIgnoreCase("true")) { overWeaving = true; } s = p.getProperty(xsetTYPE_DEMOTION_DEBUG, "false"); if (s.equalsIgnoreCase("true")) { typeMap.debugDemotion = true; } s = p.getProperty(xsetTYPE_REFS, "true"); if (s.equalsIgnoreCase("false")) { typeMap.policy = TypeMap.USE_SOFT_REFS; } runMinimalMemorySet = p.getProperty(xsetRUN_MINIMAL_MEMORY) != null; 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"); s = p.getProperty(xsetOPTIMIZED_MATCHING, "true"); optimizedMatching = s.equalsIgnoreCase("true"); if (!optimizedMatching) { getMessageHandler().handleMessage(MessageUtil.info("[optimizedMatching=false] optimized matching turned off")); } s = p.getProperty(xsetTIMERS_PER_JOINPOINT, "25000"); try { timersPerJoinpoint = Integer.parseInt(s); } catch (Exception e) { getMessageHandler().handleMessage(MessageUtil.error("unable to process timersPerJoinpoint value of " + s)); timersPerJoinpoint = 25000; } s = p.getProperty(xsetTIMERS_PER_FASTMATCH_CALL, "250"); try { timersPerType = Integer.parseInt(s); } catch (Exception e) { getMessageHandler().handleMessage(MessageUtil.error("unable to process timersPerType value of " + s)); timersPerType = 250; } } try { String value = System.getProperty("aspectj.overweaving", "false"); if (value.equalsIgnoreCase("true")) { System.out.println("ASPECTJ: aspectj.overweaving=true: overweaving switched ON"); overWeaving = true; } value = System.getProperty("aspectj.typeDemotion", "false"); if (value.equalsIgnoreCase("true")) { System.out.println("ASPECTJ: aspectj.typeDemotion=true: type demotion switched ON"); typeMap.demotionSystemActive = true; } value = System.getProperty("aspectj.minimalModel", "false"); if (value.equalsIgnoreCase("true")) { System.out.println("ASPECTJ: aspectj.minimalModel=true: minimal model switched ON"); minimalModel = true; } } catch (Throwable t) { System.err.println("ASPECTJ: Unable to read system properties"); t.printStackTrace(); } checkedAdvancedConfiguration = true; } } public boolean isRunMinimalMemory() { ensureAdvancedConfigurationProcessed(); return runMinimalMemory; } public boolean isRunMinimalMemorySet() { ensureAdvancedConfigurationProcessed(); return runMinimalMemorySet; } 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<PointcutDesignatorHandler>(); } pointcutDesignators.add(designatorHandler); } public Set<PointcutDesignatorHandler> getRegisteredPointcutHandlers() { if (pointcutDesignators == null) { return Collections.emptySet(); } return pointcutDesignators; } public void reportMatch(ShadowMunger munger, Shadow shadow) { } public boolean isOverWeaving() { return overWeaving; } 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; } /** * Determine if the named aspect requires a particular type around in order to be useful. The type is named in the aop.xml file * against the aspect. * * @return true if there is a type missing that this aspect really needed around */ public boolean hasUnsatisfiedDependency(ResolvedType aspectType) { return false; } public TypePattern getAspectScope(ResolvedType declaringType) { return null; } public Map<String, ResolvedType> getFixed() { return typeMap.tMap; } public Map<String, Reference<ResolvedType>> 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() && !type.isPrimitiveArray(); } // map from aspect > excluded types // memory issue here? private Map<ResolvedType, Set<ResolvedType>> exclusionMap = new HashMap<ResolvedType, Set<ResolvedType>>(); public Map<ResolvedType, Set<ResolvedType>> getExclusionMap() { return exclusionMap; } private TimeCollector timeCollector = null; /** * Record the time spent matching a pointcut - this will accumulate over the lifetime of this world/weaver and be reported every * 25000 join points. */ public void record(Pointcut pointcut, long timetaken) { if (timeCollector == null) { ensureAdvancedConfigurationProcessed(); timeCollector = new TimeCollector(this); } timeCollector.record(pointcut, timetaken); } /** * Record the time spent fastmatching a pointcut - this will accumulate over the lifetime of this world/weaver and be reported * every 250 types. */ public void recordFastMatch(Pointcut pointcut, long timetaken) { if (timeCollector == null) { ensureAdvancedConfigurationProcessed(); timeCollector = new TimeCollector(this); } timeCollector.recordFastMatch(pointcut, timetaken); } public void reportTimers() { if (timeCollector != null && !timingPeriodically) { timeCollector.report(); timeCollector = new TimeCollector(this); } } private static class TimeCollector { private World world; long joinpointCount; long typeCount; long perJoinpointCount; long perTypes; Map<String, Long> joinpointsPerPointcut = new HashMap<String, Long>(); Map<String, Long> timePerPointcut = new HashMap<String, Long>(); Map<String, Long> fastMatchTimesPerPointcut = new HashMap<String, Long>(); Map<String, Long> fastMatchTypesPerPointcut = new HashMap<String, Long>(); TimeCollector(World world) { this.perJoinpointCount = world.timersPerJoinpoint; this.perTypes = world.timersPerType; this.world = world; this.joinpointCount = 0; this.typeCount = 0; this.joinpointsPerPointcut = new HashMap<String, Long>(); this.timePerPointcut = new HashMap<String, Long>(); } public void report() { long totalTime = 0L; for (String p : joinpointsPerPointcut.keySet()) { totalTime += timePerPointcut.get(p); } world.getMessageHandler().handleMessage( MessageUtil.info("Pointcut matching cost (total=" + (totalTime / 1000000) + "ms for " + joinpointCount + " joinpoint match calls):")); for (String p : joinpointsPerPointcut.keySet()) { StringBuffer sb = new StringBuffer(); sb.append("Time:" + (timePerPointcut.get(p) / 1000000) + "ms (jps:#" + joinpointsPerPointcut.get(p) + ") matching against " + p); world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString())); } world.getMessageHandler().handleMessage(MessageUtil.info("---")); totalTime = 0L; for (String p : fastMatchTimesPerPointcut.keySet()) { totalTime += fastMatchTimesPerPointcut.get(p); } world.getMessageHandler().handleMessage( MessageUtil.info("Pointcut fast matching cost (total=" + (totalTime / 1000000) + "ms for " + typeCount + " fast match calls):")); for (String p : fastMatchTimesPerPointcut.keySet()) { StringBuffer sb = new StringBuffer(); sb.append("Time:" + (fastMatchTimesPerPointcut.get(p) / 1000000) + "ms (types:#" + fastMatchTypesPerPointcut.get(p) + ") fast matching against " + p); world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString())); } world.getMessageHandler().handleMessage(MessageUtil.info("---")); } void record(Pointcut pointcut, long timetakenInNs) { joinpointCount++; String pointcutText = pointcut.toString(); Long jpcounter = joinpointsPerPointcut.get(pointcutText); if (jpcounter == null) { jpcounter = 1L; } else { jpcounter++; } joinpointsPerPointcut.put(pointcutText, jpcounter); Long time = timePerPointcut.get(pointcutText); if (time == null) { time = timetakenInNs; } else { time += timetakenInNs; } timePerPointcut.put(pointcutText, time); if (world.timingPeriodically) { if ((joinpointCount % perJoinpointCount) == 0) { long totalTime = 0L; for (String p : joinpointsPerPointcut.keySet()) { totalTime += timePerPointcut.get(p); } world.getMessageHandler().handleMessage( MessageUtil.info("Pointcut matching cost (total=" + (totalTime / 1000000) + "ms for " + joinpointCount + " joinpoint match calls):")); for (String p : joinpointsPerPointcut.keySet()) { StringBuffer sb = new StringBuffer(); sb.append("Time:" + (timePerPointcut.get(p) / 1000000) + "ms (jps:#" + joinpointsPerPointcut.get(p) + ") matching against " + p); world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString())); } world.getMessageHandler().handleMessage(MessageUtil.info("---")); } } } void recordFastMatch(Pointcut pointcut, long timetakenInNs) { typeCount++; String pointcutText = pointcut.toString(); Long typecounter = fastMatchTypesPerPointcut.get(pointcutText); if (typecounter == null) { typecounter = 1L; } else { typecounter++; } fastMatchTypesPerPointcut.put(pointcutText, typecounter); Long time = fastMatchTimesPerPointcut.get(pointcutText); if (time == null) { time = timetakenInNs; } else { time += timetakenInNs; } fastMatchTimesPerPointcut.put(pointcutText, time); if (world.timingPeriodically) { if ((typeCount % perTypes) == 0) { long totalTime = 0L; for (String p : fastMatchTimesPerPointcut.keySet()) { totalTime += fastMatchTimesPerPointcut.get(p); } world.getMessageHandler().handleMessage( MessageUtil.info("Pointcut fast matching cost (total=" + (totalTime / 1000000) + "ms for " + typeCount + " fast match calls):")); for (String p : fastMatchTimesPerPointcut.keySet()) { StringBuffer sb = new StringBuffer(); sb.append("Time:" + (fastMatchTimesPerPointcut.get(p) / 1000000) + "ms (types:#" + fastMatchTypesPerPointcut.get(p) + ") fast matching against " + p); world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString())); } world.getMessageHandler().handleMessage(MessageUtil.info("---")); } } } } public TypeMap getTypeMap() { return typeMap; } public static void reset() { ResolvedType.resetPrimitives(); } /** * Returns the version of ITD that this world wants to create. The default is the new style (2) but in some cases where there * might be a clash, the old style can be used. It is set through the option -Xset:itdVersion=1 * * @return the ITD version this world wants to create - 1=oldstyle 2=new, transparent style */ public int getItdVersion() { return itdVersion; } // if not loadtime weaving then we are compile time weaving or post-compile time weaving public abstract boolean isLoadtimeWeaving(); public void classWriteEvent(char[][] compoundName) { // override if interested in write events } }
350,855
Bug 350855 overweaving misbehaving when subclassing WeavingURLClassLoader
Raised by the Spring Insight team, they observed that in a system where they are using a special classloader (subclassing weaving url classloader) they see it fail to weave an aspect if overweaving is on.
resolved fixed
2302e94
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-06-30T15:34:56Z"
"2011-06-30T16:06:40Z"
weaver/src/org/aspectj/weaver/bcel/BcelWeaver.java
/* ******************************************************************* * Copyright (c) 2002-2010 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.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.Attributes.Name; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; 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.asm.IProgramElement; import org.aspectj.asm.internal.AspectJElementHierarchy; 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.AjAttribute.WeaverVersionInfo; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.BCException; import org.aspectj.weaver.CompressingDataOutputStream; 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.DeclareTypeErrorOrWarning; 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; /** * * @author PARC * @author Andy Clement * @author Alexandre Vasseur */ public class BcelWeaver { public static final String CLOSURE_CLASS_PREFIX = "$Ajc"; public static final String SYNTHETIC_CLASS_POSTFIX = "$ajc"; private static Trace trace = TraceFactory.getTraceFactory().getTrace(BcelWeaver.class); private transient final BcelWorld world; private final CrosscuttingMembersSet xcutSet; private boolean inReweavableMode = false; private transient List<UnwovenClassFile> addedClasses = new ArrayList<UnwovenClassFile>(); private transient List<String> deletedTypenames = new ArrayList<String>(); // These four are setup by prepareForWeave private transient List<ShadowMunger> shadowMungerList = null; private transient List<ConcreteTypeMunger> typeMungerList = null; private transient List<ConcreteTypeMunger> lateTypeMungerList = null; private transient List<DeclareParents> declareParentsList = null; private Manifest manifest = null; private boolean needToReweaveWorld = false; private boolean isBatchWeave = true; private ZipOutputStream zipOutputStream; private CustomMungerFactory customMungerFactory; 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>"); } } /** * 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(); byte[] bytes = wsi.getUnwovenClassFileData(wovenJavaClass.getBytes()); JavaClass unwovenJavaClass = Utility.makeJavaClass(wovenJavaClass.getFileName(), bytes); world.storeClass(unwovenJavaClass); classType.setJavaClass(unwovenJavaClass, true); // 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 directory containing classes or zip/jar class archive */ public void addLibraryJarFile(File inFile) throws IOException { List<ResolvedType> addedAspects = null; if (inFile.isDirectory()) { addedAspects = addAspectsFromDirectory(inFile); } else { addedAspects = addAspectsFromJarFile(inFile); } if (world.isOverWeaving()) { return; } for (ResolvedType addedAspect : addedAspects) { xcutSet.addOrReplaceAspect(addedAspect); } } private List<ResolvedType> addAspectsFromJarFile(File inFile) throws FileNotFoundException, IOException { ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); // ??? buffered List<ResolvedType> addedAspects = new ArrayList<ResolvedType>(); 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. int size = (int) entry.getSize(); ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName()); JavaClass jc = parser.parse(); inStream.closeEntry(); ResolvedType type = world.addSourceObjectType(jc, false).getResolvedTypeX(); type.setBinaryPath(inFile.getAbsolutePath()); if (type.isAspect()) { addedAspects.add(type); } else { world.demote(type); } } } finally { inStream.close(); } return addedAspects; } /** * Look for .class files that represent aspects in the supplied directory - return the list of accumulated aspects. * * @param directory the directory in which to look for Aspect .class files * @return the list of discovered aspects * @throws FileNotFoundException * @throws IOException */ private List<ResolvedType> addAspectsFromDirectory(File directory) throws FileNotFoundException, IOException { List<ResolvedType> addedAspects = new ArrayList<ResolvedType>(); File[] classFiles = FileUtil.listFiles(directory, new FileFilter() { public boolean accept(File pathname) { return pathname.getName().endsWith(".class"); } }); for (File classFile : classFiles) { FileInputStream fis = new FileInputStream(classFile); byte[] classBytes = FileUtil.readAsByteArray(fis); ResolvedType aspectType = isAspect(classBytes, classFile.getAbsolutePath(), directory); if (aspectType != null) { addedAspects.add(aspectType); } fis.close(); } return addedAspects; } /** * Determine if the supplied bytes represent an aspect, if they do then create a ResolvedType instance for the aspect and return * it, otherwise return null * * @param classbytes the classbytes that might represent an aspect * @param name the name of the class * @param directory directory which contained the class file * @return a ResolvedType if the classbytes represent an aspect, otherwise null */ private ResolvedType isAspect(byte[] classbytes, String name, File dir) throws IOException { ClassParser parser = new ClassParser(new ByteArrayInputStream(classbytes), name); JavaClass jc = parser.parse(); ResolvedType type = world.addSourceObjectType(jc, false).getResolvedTypeX(); String typeName = type.getName().replace('.', File.separatorChar); int end = name.lastIndexOf(typeName + ".class"); String binaryPath = null; // if end is -1 then something weird 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()) { return type; } else { // immediately demote the type we just added since it will have // have been stuffed into the permanent map (assumed to be // an aspect) world.demote(type); return null; } } // // 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<UnwovenClassFile> addDirectoryContents(File inFile, File outDir) throws IOException { List<UnwovenClassFile> addedClassFiles = new ArrayList<UnwovenClassFile>(); // 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<UnwovenClassFile> addJarFile(File inFile, File outDir, boolean canBeDirectory) { // System.err.println("? addJarFile(" + inFile + ", " + outDir + ")"); List<UnwovenClassFile> addedClassFiles = new ArrayList<UnwovenClassFile>(); 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")) { ReferenceType type = this.addClassFile(classFile, false); StringBuffer sb = new StringBuffer(); sb.append(inFile.getAbsolutePath()); sb.append("!"); sb.append(entry.getName()); type.setBinaryPath(sb.toString()); 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 boolean needToReweaveWorld() { return needToReweaveWorld; } /** * Should be addOrReplace */ public ReferenceType addClassFile(UnwovenClassFile classFile, boolean fromInpath) { addedClasses.add(classFile); ReferenceType type = world.addSourceObjectType(classFile.getJavaClass(), false).getResolvedTypeX(); if (fromInpath) { type.setBinaryPath(classFile.getFilename()); } return type; } 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); StringBuffer sb = new StringBuffer(); sb.append(inPathDir.getAbsolutePath()); sb.append("!"); sb.append(filename); ReferenceType type = this.addClassFile(ucf, false); type.setBinaryPath(sb.toString()); } fis.close(); return ucf; } public void deleteClassFile(String typename) { deletedTypenames.add(typename); world.deleteSourceObjectType(UnresolvedType.forName(typename)); } // ---- 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<UnwovenClassFile> i = addedClasses.iterator(); i.hasNext();) { UnwovenClassFile jc = i.next(); String name = jc.getClassName(); ResolvedType type = world.resolve(name); if (type.isAspect() && !world.isOverWeaving()) { needToReweaveWorld |= xcutSet.addOrReplaceAspect(type); } } for (Iterator<String> i = deletedTypenames.iterator(); i.hasNext();) { String name = 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<ShadowMunger>() { public int compare(ShadowMunger sm1, ShadowMunger sm2) { 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<UnwovenClassFile> i = addedClasses.iterator(); i.hasNext();) { UnwovenClassFile jc = 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 (ShadowMunger munger : shadowMungers) { 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()) || advice.isAnnotationStyle()) { 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); } } } } newP.m_ignoreUnboundBindingForNames = p.m_ignoreUnboundBindingForNames; 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> */<Pointcut, Pointcut> pcMap = new HashMap<Pointcut, Pointcut>(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); Pointcut newP = shareEntriesFromMap(p, pcMap); newP.m_ignoreUnboundBindingForNames = p.m_ignoreUnboundBindingForNames; munger.setPointcut(newP); } } private Pointcut shareEntriesFromMap(Pointcut p, Map<Pointcut, Pointcut> 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 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<String> ambiguousNames = new ArrayList<String>(); 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<String> 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 addManifest(Manifest newManifest) { // System.out.println("? addManifest() newManifest=" + newManifest); if (manifest == null) { manifest = newManifest; } } public Manifest getManifest(boolean shouldCreate) { if (manifest == null && shouldCreate) { String WEAVER_MANIFEST_VERSION = "1.0"; Attributes.Name CREATED_BY = new Name("Created-By"); String WEAVER_CREATED_BY = "AspectJ Compiler"; 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 // FOR TESTING public Collection<String> weave(File file) throws IOException { OutputStream os = FileUtil.makeOutputStream(file); this.zipOutputStream = new ZipOutputStream(os); prepareForWeave(); Collection<String> c = weave(new IClassFileProvider() { public boolean isApplyAtAspectJMungersOnly() { return false; } public Iterator<UnwovenClassFile> 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; } private Set<IProgramElement> candidatesForRemoval = null; // variation of "weave" that sources class files from an external source. public Collection<String> weave(IClassFileProvider input) throws IOException { if (trace.isTraceEnabled()) { trace.enter("weave", this, input); } ContextToken weaveToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING, ""); Collection<String> wovenClassNames = new ArrayList<String>(); IWeaveRequestor requestor = input.getRequestor(); if (world.getModel() != null && world.isMinimalModel()) { candidatesForRemoval = new HashSet<IProgramElement>(); } if (world.getModel() != null && !isBatchWeave) { AsmManager manager = world.getModelAsAsmManager(); for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) { UnwovenClassFile classFile = i.next(); // remove all relationships where this file being woven is // the target of the relationship manager.removeRelationshipsTargettingThisType(classFile.getClassName()); } } // Go through the types and ensure any 'damaged' during compile time are // repaired prior to weaving for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) { UnwovenClassFile classFile = 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<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) { UnwovenClassFile classFile = 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<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) { UnwovenClassFile classFile = 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<String> typesToProcess = new ArrayList<String>(); for (Iterator<UnwovenClassFile> iter = input.getClassFileIterator(); iter.hasNext();) { UnwovenClassFile clf = iter.next(); typesToProcess.add(clf.getClassName()); } while (typesToProcess.size() > 0) { weaveParentsFor(typesToProcess, typesToProcess.get(0), null); } for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) { UnwovenClassFile classFile = 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<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) { UnwovenClassFile classFile = 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<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) { UnwovenClassFile classFile = 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.clear(); deletedTypenames.clear(); requestor.weaveCompleted(); CompilationAndWeavingContext.leavingPhase(weaveToken); if (trace.isTraceEnabled()) { trace.exit("weave", wovenClassNames); } if (world.getModel() != null && world.isMinimalModel()) { candidatesForRemoval.clear(); } 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(); } @Override 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; } @Override 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<AdviceLocation> alreadyWarnedLocations = new HashSet<AdviceLocation>(); 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<String> typesForWeaving, String typeToWeave, ResolvedType resolvedTypeToWeave) { if (resolvedTypeToWeave == null) { // resolve it if the caller could not pass in the resolved type resolvedTypeToWeave = world.resolve(typeToWeave); } ResolvedType superclassType = resolvedTypeToWeave.getSuperclass(); String superclassTypename = (superclassType == null ? null : superclassType.getName()); // PR336654 added the 'typesForWeaving.contains(superclassTypename)' clause. // Without it we can delete all type mungers on the parents and yet we only // add back in the declare parents related ones, not the regular ITDs. if (superclassType != null && !superclassType.isTypeHierarchyComplete() && superclassType.isExposedToWeaver() && typesForWeaving.contains(superclassTypename)) { weaveParentsFor(typesForWeaving, superclassTypename, superclassType); } ResolvedType[] interfaceTypes = resolvedTypeToWeave.getDeclaredInterfaces(); for (ResolvedType resolvedSuperInterface : interfaceTypes) { if (!resolvedSuperInterface.isTypeHierarchyComplete()) { String interfaceTypename = resolvedSuperInterface.getName(); if (resolvedSuperInterface.isExposedToWeaver()) { // typesForWeaving.contains(interfaceTypename)) { weaveParentsFor(typesForWeaving, interfaceTypename, resolvedSuperInterface); } } } ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS, resolvedTypeToWeave.getName()); weaveParentTypeMungers(resolvedTypeToWeave); CompilationAndWeavingContext.leavingPhase(tok); typesForWeaving.remove(typeToWeave); resolvedTypeToWeave.tagAsTypeHierarchyComplete(); } 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(); // System.out.println(">> processReweavableStateIfPresent " + className + " wsi=" + wsi); 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<String> aspectsPreviouslyInWorld = wsi.getAspectsAffectingType(); // keep track of them just to ensure unique missing aspect error // reporting Set<String> alreadyConfirmedReweavableState = new HashSet<String>(); for (String requiredTypeSignature : aspectsPreviouslyInWorld) { // for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) { // String requiredTypeName = (String) iter.next(); if (!alreadyConfirmedReweavableState.contains(requiredTypeSignature)) { ResolvedType rtx = world.resolve(UnresolvedType.forSignature(requiredTypeSignature), true); boolean exists = !rtx.isMissing(); if (!exists) { world.getLint().missingAspectForReweaving.signal(new String[] { rtx.getName(), className }, classType.getSourceLocation(), null); // world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE, // requiredTypeName, className), classType.getSourceLocation(), null); } else { if (world.isOverWeaving()) { // System.out.println(">> Removing " + requiredTypeName + " from weaving process: " // + xcutSet.deleteAspect(rtx)); } 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, rtx.getName(), className), null, null); } else if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) { world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.VERIFIED_REWEAVABLE_TYPE, rtx.getName(), rtx.getSourceLocation().getSourceFile()), null, null); } } alreadyConfirmedReweavableState.add(requiredTypeSignature); } } } // old: // classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass // ().getFileName(), wsi.getUnwovenClassFileData())); // new: reweavable default with clever diff if (!world.isOverWeaving()) { byte[] bytes = wsi.getUnwovenClassFileData(classType.getJavaClass().getBytes()); WeaverVersionInfo wvi = classType.getWeaverVersionAttribute(); JavaClass newJavaClass = Utility.makeJavaClass(classType.getJavaClass().getFileName(), bytes); classType.setJavaClass(newJavaClass, true); classType.getResolvedTypeX().ensureConsistent(); } // } 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<UnwovenClassFile.ChildClass> 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<UnwovenClassFile.ChildClass> iter = childClasses.iterator(); iter.hasNext();) { UnwovenClassFile.ChildClass element = 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<DeclareParents> decpToRepeat = new ArrayList<DeclareParents>(); boolean aParentChangeOccurred = false; boolean anAnnotationChangeOccurred = false; // First pass - apply all decp mungers for (DeclareParents decp : declareParentsList) { boolean typeChanged = applyDeclareParents(decp, onType); if (typeChanged) { aParentChangeOccurred = true; } else { decpToRepeat.add(decp); } } // Still first pass - apply all dec @type mungers for (DeclareAnnotation decA : xcutSet.getDeclareAnnotationOnTypes()) { 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 (DeclareAnnotation decA : xcutSet.getDeclareAnnotationOnTypes()) { 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.getAnnotation(); // 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.getAnnotation(); // check the annotation is suitable for the target boolean problemReported = verifyTargetIsOK(decA, onType, annoX, reportProblems); if (!problemReported) { AsmRelationshipProvider.addDeclareAnnotationRelationship(world.getModelAsAsmManager(), decA.getSourceLocation(), onType.getSourceLocation(), false); // 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)), 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 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<ResolvedType> newParents = p.findMatchingNewParents(onType, true); if (!newParents.isEmpty()) { didSomething = true; BcelWorld.getBcelObjectType(onType); // System.err.println("need to do declare parents for: " + onType); for (ResolvedType newParent : newParents) { // 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); NewParentTypeMunger newParentMunger = new NewParentTypeMunger(newParent, p.getDeclaringType()); if (p.isMixin()) { newParentMunger.setIsMixin(true); } newParentMunger.setSourceLocation(p.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p)), false); } } 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 (ConcreteTypeMunger m : typeMungerList) { if (!m.isLateMunger() && m.matches(onType)) { onType.addInterTypeMunger(m, false); } } CompilationAndWeavingContext.leavingPhase(tok); } // exposed for ClassLoader dynamic weaving public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { return weave(classFile, classType, false); } // 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 { try { if (classType.isSynthetic()) { // Don't touch synthetic classes if (dump) { dumpUnchanged(classFile); } return null; } ReferenceType resolvedClassType = classType.getResolvedTypeX(); if (world.isXmlConfigured() && world.getXmlConfiguration().excludesType(resolvedClassType)) { if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) { world.getMessageHandler().handleMessage( MessageUtil.info("Type '" + resolvedClassType.getName() + "' not woven due to exclusion via XML weaver exclude section")); } if (dump) { dumpUnchanged(classFile); } return null; } List<ShadowMunger> shadowMungers = fastMatch(shadowMungerList, resolvedClassType); List<ConcreteTypeMunger> typeMungers = classType.getResolvedTypeX().getInterTypeMungers(); resolvedClassType.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() && resolvedClassType.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, inReweavableMode); } checkDeclareTypeErrorOrWarning(world, classType); 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 (Throwable e) { new RuntimeException("Crashed whilst crashing with this exception: " + e, e).printStackTrace(); // 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)); } } else { checkDeclareTypeErrorOrWarning(world, classType); } // this is very odd return behavior trying to keep everyone happy // can we remove it from the model now? we know it contains no relationship endpoints... AsmManager model = world.getModelAsAsmManager(); if (world.isMinimalModel() && model != null && !classType.isAspect()) { AspectJElementHierarchy hierarchy = (AspectJElementHierarchy) model.getHierarchy(); String pkgname = classType.getResolvedTypeX().getPackageName(); String tname = classType.getResolvedTypeX().getSimpleBaseName(); IProgramElement typeElement = hierarchy.findElementForType(pkgname, tname); if (typeElement != null && hasInnerType(typeElement)) { // Cannot remove it right now (has inner type), schedule it // for possible deletion later if all inner types are // removed candidatesForRemoval.add(typeElement); } if (typeElement != null && !hasInnerType(typeElement)) { IProgramElement parent = typeElement.getParent(); // parent may have children: PACKAGE DECL, IMPORT-REFERENCE, TYPE_DECL if (parent != null) { // if it was the only type we should probably remove // the others too. parent.removeChild(typeElement); if (parent.getKind().isSourceFile()) { removeSourceFileIfNoMoreTypeDeclarationsInside(hierarchy, typeElement, parent); } else { hierarchy.forget(null, typeElement); // At this point, the child has been removed. We // should now check if the parent is in our // 'candidatesForRemoval' set. If it is then that // means we were going to remove it but it had a // child. Now we can check if it still has a child - // if it doesn't it can also be removed! walkUpRemovingEmptyTypesAndPossiblyEmptySourceFile(hierarchy, tname, parent); } } } } 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; } } finally { world.demote(); } } private void walkUpRemovingEmptyTypesAndPossiblyEmptySourceFile(AspectJElementHierarchy hierarchy, String tname, IProgramElement typeThatHasChildRemoved) { // typeThatHasChildRemoved might be a source file, type or a method/ctor // - for a method/ctor find the type/sourcefile while (typeThatHasChildRemoved != null && !(typeThatHasChildRemoved.getKind().isType() || typeThatHasChildRemoved.getKind().isSourceFile())) { // this will take us 'up' through methods that contain anonymous // inner classes typeThatHasChildRemoved = typeThatHasChildRemoved.getParent(); } // now typeThatHasChildRemoved points to the type or sourcefile that has // had something removed if (candidatesForRemoval.contains(typeThatHasChildRemoved) && !hasInnerType(typeThatHasChildRemoved)) { // now we can get rid of it IProgramElement parent = typeThatHasChildRemoved.getParent(); if (parent != null) { parent.removeChild(typeThatHasChildRemoved); candidatesForRemoval.remove(typeThatHasChildRemoved); if (parent.getKind().isSourceFile()) { removeSourceFileIfNoMoreTypeDeclarationsInside(hierarchy, typeThatHasChildRemoved, parent); // System.out.println("Removed on second pass: " + // typeThatHasChildRemoved.getName()); } else { // System.out.println("On later pass, parent of type " + // typeThatHasChildRemoved.getName() // + " was found not to be a sourcefile, recursing up..."); walkUpRemovingEmptyTypesAndPossiblyEmptySourceFile(hierarchy, tname, parent); } } } } private void removeSourceFileIfNoMoreTypeDeclarationsInside(AspectJElementHierarchy hierarchy, IProgramElement typeElement, IProgramElement sourceFileNode) { IProgramElement compilationUnit = sourceFileNode; boolean anyOtherTypeDeclarations = false; for (IProgramElement child : compilationUnit.getChildren()) { IProgramElement.Kind k = child.getKind(); if (k.isType()) { anyOtherTypeDeclarations = true; break; } } // If the compilation unit node contained no // other types, there is no need to keep it if (!anyOtherTypeDeclarations) { IProgramElement cuParent = compilationUnit.getParent(); if (cuParent != null) { compilationUnit.setParent(null); cuParent.removeChild(compilationUnit); } // need to update some caches and structures too? hierarchy.forget(sourceFileNode, typeElement); } else { hierarchy.forget(null, typeElement); } } // ---- writing // TODO could be smarter - really only matters if inner type has been woven, but there is a chance we haven't woven it *yet* private boolean hasInnerType(IProgramElement typeNode) { for (IProgramElement child : typeNode.getChildren()) { IProgramElement.Kind kind = child.getKind(); if (kind.isType()) { return true; } // if (kind == IProgramElement.Kind.ASPECT) { // return true; // } if (kind.isType() || kind == IProgramElement.Kind.METHOD || kind == IProgramElement.Kind.CONSTRUCTOR) { boolean b = hasInnerType(child); if (b) { return b; } } } return false; } private void checkDeclareTypeErrorOrWarning(BcelWorld world2, BcelObjectType classType) { List<DeclareTypeErrorOrWarning> dteows = world.getDeclareTypeEows(); for (DeclareTypeErrorOrWarning dteow : dteows) { if (dteow.getTypePattern().matchesStatically(classType.getResolvedTypeX())) { if (dteow.isError()) { world.getMessageHandler().handleMessage( MessageUtil.error(dteow.getMessage(), classType.getResolvedTypeX().getSourceLocation())); } else { world.getMessageHandler().handleMessage( MessageUtil.warn(dteow.getMessage(), classType.getResolvedTypeX().getSourceLocation())); } } } } 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()); List<UnwovenClassFile.ChildClass> childClasses = clazz.getChildClasses(world); if (!childClasses.isEmpty()) { for (Iterator<UnwovenClassFile.ChildClass> i = childClasses.iterator(); i.hasNext();) { UnwovenClassFile.ChildClass c = 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(); } /** * Perform a fast match of the specified list of shadowmungers against the specified type. A subset of those that might match is * returned. * * @param list list of all shadow mungers that might match * @param type the target type * @return a list of shadow mungers that might match with those that cannot (according to fast match rules) removed */ private List<ShadowMunger> fastMatch(List<ShadowMunger> list, ResolvedType type) { if (list == null) { return Collections.emptyList(); } boolean isOverweaving = world.isOverWeaving(); WeaverStateInfo typeWeaverState = (isOverweaving ? type.getWeaverState() : null); // 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, world); List<ShadowMunger> result = new ArrayList<ShadowMunger>(); if (world.areInfoMessagesEnabled() && world.isTimingEnabled()) { for (ShadowMunger munger : list) { if (typeWeaverState != null) { // will only be null if overweaving is ON and there is weaverstate ResolvedType declaringAspect = munger.getDeclaringType(); if (typeWeaverState.isAspectAlreadyApplied(declaringAspect)) { continue; } } Pointcut pointcut = munger.getPointcut(); long starttime = System.nanoTime(); FuzzyBoolean fb = pointcut.fastMatch(info); long endtime = System.nanoTime(); world.recordFastMatch(pointcut, endtime - starttime); if (fb.maybeTrue()) { result.add(munger); } } } else { for (ShadowMunger munger : list) { if (typeWeaverState != null) { // will only be null if overweaving is ON and there is weaverstate ResolvedType declaringAspect = munger.getConcreteAspect();// getDeclaringType(); if (typeWeaverState.isAspectAlreadyApplied(declaringAspect)) { continue; } } Pointcut pointcut = munger.getPointcut(); FuzzyBoolean fb = pointcut.fastMatch(info); if (fb.maybeTrue()) { result.add(munger); } } } return result; } public void setReweavableMode(boolean xNotReweavable) { inReweavableMode = !xNotReweavable; WeaverStateInfo.setReweavableModeDefaults(!xNotReweavable, false, true); } 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"); } } public void write(CompressingDataOutputStream dos) throws IOException { xcutSet.write(dos); } // only called for testing public void setShadowMungers(List shadowMungers) { shadowMungerList = shadowMungers; } }
352,389
Bug 352389 overweaving can attribute duplicate attributes, one of which will not deserialize correctly
When overweaving it is possible that a class will get a second WeaverState attribute. This second one will not be valid (it hasn't been correctly configured). This isn't normally a problem because the next thing that happens is that the class is defined to the VM. But if *another* weave step occurs, the malformed attribute will cause that weave to fail with this kind of message: bad WeaverState.Kind: -115 The solution is to avoid adding the duplicate when overweaving.
resolved fixed
8553b30
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-07-18T20:44:33Z"
"2011-07-18T20:13:20Z"
weaver/src/org/aspectj/weaver/bcel/LazyClassGen.java
/* ******************************************************************* * Copyright (c) 2002-2010 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 * Andy Clement 6Jul05 generics - signature attribute * Abraham Nevado * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.Vector; 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.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.Synthetic; import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen; import org.aspectj.apache.bcel.generic.BasicType; import org.aspectj.apache.bcel.generic.ClassGen; import org.aspectj.apache.bcel.generic.FieldGen; 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.ObjectType; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjAttribute.WeaverVersionInfo; import org.aspectj.weaver.BCException; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.SignatureUtils; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.UnresolvedType.TypeKind; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.asm.AsmDetector; import org.aspectj.weaver.bcel.asm.StackMapAdder; /** * Lazy lazy lazy. We don't unpack the underlying class unless necessary. Things like new methods and annotations accumulate in here * until they must be written out, don't add them to the underlying MethodGen! Things are slightly different if this represents an * Aspect. */ public final class LazyClassGen { private static final int ACC_SYNTHETIC = 0x1000; private static final String[] NO_STRINGS = new String[0]; int highestLineNumber = 0; // ---- JSR 45 info private final SortedMap<String, InlinedSourceFileInfo> inlinedFiles = new TreeMap<String, InlinedSourceFileInfo>(); private boolean regenerateGenericSignatureAttribute = false; private BcelObjectType myType; // XXX is not set for types we create private ClassGen myGen; private final ConstantPool cp; private final World world; private final String packageName = null; private final List<BcelField> fields = new ArrayList<BcelField>(); private final List<LazyMethodGen> methodGens = new ArrayList<LazyMethodGen>(); private final List<LazyClassGen> classGens = new ArrayList<LazyClassGen>(); private final List<AnnotationGen> annotations = new ArrayList<AnnotationGen>(); private int childCounter = 0; private final InstructionFactory fact; private boolean isSerializable = false; private boolean hasSerialVersionUIDField = false; private boolean serialVersionUIDRequiresInitialization = false; private long calculatedSerialVersionUID; private boolean hasClinit = false; private ResolvedType[] extraSuperInterfaces = null; private ResolvedType superclass = null; // --- static class InlinedSourceFileInfo { int highestLineNumber; int offset; // calculated InlinedSourceFileInfo(int highestLineNumber) { this.highestLineNumber = highestLineNumber; } } void addInlinedSourceFileInfo(String fullpath, int highestLineNumber) { Object o = inlinedFiles.get(fullpath); if (o != null) { InlinedSourceFileInfo info = (InlinedSourceFileInfo) o; if (info.highestLineNumber < highestLineNumber) { info.highestLineNumber = highestLineNumber; } } else { inlinedFiles.put(fullpath, new InlinedSourceFileInfo(highestLineNumber)); } } void calculateSourceDebugExtensionOffsets() { int i = roundUpToHundreds(highestLineNumber); for (InlinedSourceFileInfo element : inlinedFiles.values()) { element.offset = i; i = roundUpToHundreds(i + element.highestLineNumber); } } private static int roundUpToHundreds(int i) { return ((i / 100) + 1) * 100; } int getSourceDebugExtensionOffset(String fullpath) { return inlinedFiles.get(fullpath).offset; } // private Unknown getSourceDebugExtensionAttribute() { // int nameIndex = cp.addUtf8("SourceDebugExtension"); // String data = getSourceDebugExtensionString(); // //System.err.println(data); // byte[] bytes = Utility.stringToUTF(data); // int length = bytes.length; // // return new Unknown(nameIndex, length, bytes, cp); // } // private LazyClassGen() {} // public static void main(String[] args) { // LazyClassGen m = new LazyClassGen(); // m.highestLineNumber = 37; // m.inlinedFiles.put("boo/baz/foo.java", new InlinedSourceFileInfo( 83)); // m.inlinedFiles.put("boo/barz/foo.java", new InlinedSourceFileInfo(292)); // m.inlinedFiles.put("boo/baz/moo.java", new InlinedSourceFileInfo(128)); // m.calculateSourceDebugExtensionOffsets(); // System.err.println(m.getSourceDebugExtensionString()); // } // For the entire pathname, we're using package names. This is probably // wrong. // private String getSourceDebugExtensionString() { // StringBuffer out = new StringBuffer(); // String myFileName = getFileName(); // // header section // out.append("SMAP\n"); // out.append(myFileName); // out.append("\nAspectJ\n"); // // stratum section // out.append("*S AspectJ\n"); // // file section // out.append("*F\n"); // out.append("1 "); // out.append(myFileName); // out.append("\n"); // int i = 2; // for (Iterator iter = inlinedFiles.keySet().iterator(); iter.hasNext();) { // String element = (String) iter.next(); // int ii = element.lastIndexOf('/'); // if (ii == -1) { // out.append(i++); out.append(' '); // out.append(element); out.append('\n'); // } else { // out.append("+ "); out.append(i++); out.append(' '); // out.append(element.substring(ii+1)); out.append('\n'); // out.append(element); out.append('\n'); // } // } // // emit line section // out.append("*L\n"); // out.append("1#1,"); // out.append(highestLineNumber); // out.append(":1,1\n"); // i = 2; // for (Iterator iter = inlinedFiles.values().iterator(); iter.hasNext();) { // InlinedSourceFileInfo element = (InlinedSourceFileInfo) iter.next(); // out.append("1#"); // out.append(i++); out.append(','); // out.append(element.highestLineNumber); out.append(":"); // out.append(element.offset + 1); out.append(",1\n"); // } // // end section // out.append("*E\n"); // // and finish up... // return out.toString(); // } // ---- end JSR45-related stuff /** Emit disassembled class and newline to out */ public static void disassemble(String path, String name, PrintStream out) throws IOException { if (null == out) { return; } // out.println("classPath: " + classPath); BcelWorld world = new BcelWorld(path); UnresolvedType ut = UnresolvedType.forName(name); ut.setNeedsModifiableDelegate(true); LazyClassGen clazz = new LazyClassGen(BcelWorld.getBcelObjectType(world.resolve(ut))); clazz.print(out); out.println(); } public String getNewGeneratedNameTag() { return new Integer(childCounter++).toString(); } // ---- public LazyClassGen(String class_name, String super_class_name, String file_name, int access_flags, String[] interfaces, World world) { myGen = new ClassGen(class_name, super_class_name, file_name, access_flags, interfaces); cp = myGen.getConstantPool(); fact = new InstructionFactory(myGen, cp); regenerateGenericSignatureAttribute = true; this.world = world; } // Non child type, so it comes from a real type in the world. public LazyClassGen(BcelObjectType myType) { myGen = new ClassGen(myType.getJavaClass()); cp = myGen.getConstantPool(); fact = new InstructionFactory(myGen, cp); this.myType = myType; world = myType.getResolvedTypeX().getWorld(); /* Does this class support serialization */ if (implementsSerializable(getType())) { isSerializable = true; // ResolvedMember[] fields = getType().getDeclaredFields(); // for (int i = 0; i < fields.length; i++) { // ResolvedMember field = fields[i]; // if (field.getName().equals("serialVersionUID") // && field.isStatic() && field.getType().equals(ResolvedType.LONG)) // { // hasSerialVersionUIDField = true; // } // } hasSerialVersionUIDField = hasSerialVersionUIDField(getType()); ResolvedMember[] methods = getType().getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { ResolvedMember method = methods[i]; if (method.getName().equals("<clinit>")) { if (method.getKind() != Member.STATIC_INITIALIZATION) { throw new RuntimeException("qui?"); } hasClinit = true; } } // Do we need to calculate an SUID and add it? if (!getType().isInterface() && !hasSerialVersionUIDField && world.isAddSerialVerUID()) { calculatedSerialVersionUID = myGen.getSUID(); FieldGen fg = new FieldGen(Constants.ACC_PRIVATE | Constants.ACC_FINAL | Constants.ACC_STATIC, BasicType.LONG, "serialVersionUID", getConstantPool()); addField(fg); hasSerialVersionUIDField = true; serialVersionUIDRequiresInitialization = true; // warn about what we've done? if (world.getLint().calculatingSerialVersionUID.isEnabled()) { world.getLint().calculatingSerialVersionUID.signal( new String[] { getClassName(), Long.toString(calculatedSerialVersionUID) + "L" }, null, null); } } } ResolvedMember[] methods = myType.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { addMethodGen(new LazyMethodGen((BcelMethod) methods[i], this)); } // Method[] methods = myGen.getMethods(); // for (int i = 0; i < methods.length; i++) { // addMethodGen(new LazyMethodGen(methods[i], this)); // } ResolvedMember[] fields = myType.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { this.fields.add((BcelField) fields[i]); } } public static boolean hasSerialVersionUIDField(ResolvedType type) { ResolvedMember[] fields = type.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { ResolvedMember field = fields[i]; if (field.getName().equals("serialVersionUID") && Modifier.isStatic(field.getModifiers()) && field.getType().equals(ResolvedType.LONG)) { return true; } } return false; } // public void addAttribute(Attribute i) { // myGen.addAttribute(i); // } // ---- public String getInternalClassName() { return getConstantPool().getConstantString_CONSTANTClass(myGen.getClassNameIndex()); // getConstantPool().getConstantString( // myGen.getClassNameIndex(), // Constants.CONSTANT_Class); } public String getInternalFileName() { String str = getInternalClassName(); int index = str.lastIndexOf('/'); if (index == -1) { return getFileName(); } else { return str.substring(0, index + 1) + getFileName(); } } /** * Returns the packagename - if its the default package we return an empty string */ public String getPackageName() { if (packageName != null) { return packageName; } String str = getInternalClassName(); int index = str.indexOf("<"); if (index != -1) { str = str.substring(0, index); // strip off the generics guff } index = str.lastIndexOf("/"); if (index == -1) { return ""; } return str.substring(0, index).replace('/', '.'); } public void addMethodGen(LazyMethodGen gen) { // assert gen.getClassName() == super.getClassName(); methodGens.add(gen); if (highestLineNumber < gen.highestLineNumber) { highestLineNumber = gen.highestLineNumber; } } public boolean removeMethodGen(LazyMethodGen gen) { return methodGens.remove(gen); } public void addMethodGen(LazyMethodGen gen, ISourceLocation sourceLocation) { addMethodGen(gen); if (!gen.getMethod().isPrivate()) { warnOnAddedMethod(gen.getMethod(), sourceLocation); } } public void errorOnAddedField(FieldGen field, ISourceLocation sourceLocation) { if (isSerializable && !hasSerialVersionUIDField) { getWorld().getLint().serialVersionUIDBroken.signal( new String[] { myType.getResolvedTypeX().getName(), field.getName() }, sourceLocation, null); } } public void warnOnAddedInterface(String name, ISourceLocation sourceLocation) { warnOnModifiedSerialVersionUID(sourceLocation, "added interface " + name); } public void warnOnAddedMethod(Method method, ISourceLocation sourceLocation) { warnOnModifiedSerialVersionUID(sourceLocation, "added non-private method " + method.getName()); } public void warnOnAddedStaticInitializer(Shadow shadow, ISourceLocation sourceLocation) { if (!hasClinit) { warnOnModifiedSerialVersionUID(sourceLocation, "added static initializer"); } } public void warnOnModifiedSerialVersionUID(ISourceLocation sourceLocation, String reason) { if (isSerializable && !hasSerialVersionUIDField) { getWorld().getLint().needsSerialVersionUIDField.signal(new String[] { myType.getResolvedTypeX().getName().toString(), reason }, sourceLocation, null); } } public World getWorld() { return world; } public List<LazyMethodGen> getMethodGens() { return methodGens; // ???Collections.unmodifiableList(methodGens); } public List<BcelField> getFieldGens() { return fields; } private void writeBack(BcelWorld world) { if (getConstantPool().getSize() > Short.MAX_VALUE) { reportClassTooBigProblem(); return; } if (annotations.size() > 0) { for (AnnotationGen element : annotations) { myGen.addAnnotation(element); } // Attribute[] annAttributes = // org.aspectj.apache.bcel.classfile.Utility.getAnnotationAttributes( // getConstantPool(),annotations); // for (int i = 0; i < annAttributes.length; i++) { // Attribute attribute = annAttributes[i]; // System.err.println("Adding attribute for "+attribute); // myGen.addAttribute(attribute); // } } // Add a weaver version attribute to the file being produced (if // necessary...) if (!myGen.hasAttribute("org.aspectj.weaver.WeaverVersion")) { myGen.addAttribute(Utility.bcelAttribute(new AjAttribute.WeaverVersionInfo(), getConstantPool())); } if (myType != null && myType.getWeaverState() != null) { myGen.addAttribute(Utility.bcelAttribute(new AjAttribute.WeaverState(myType.getWeaverState()), getConstantPool())); } // FIXME ATAJ needed only for slow Aspects.aspectOf() - keep or remove // make a lot of test fail since the test compare weaved class file // based on some test data as text files... // if (!myGen.isInterface()) { // addAjClassField(); // } addAjcInitializers(); // 17Feb05 - ASC - Skip this for now - it crashes IBM 1.4.2 jvms // (pr80430). Will be revisited when contents // of attribute are confirmed to be correct. boolean sourceDebugExtensionSupportSwitchedOn = false; if (sourceDebugExtensionSupportSwitchedOn) { calculateSourceDebugExtensionOffsets(); } int len = methodGens.size(); myGen.setMethods(Method.NoMethods); for (LazyMethodGen gen : methodGens) { // we skip empty clinits if (isEmptyClinit(gen)) { continue; } myGen.addMethod(gen.getMethod()); } len = fields.size(); myGen.setFields(Field.NoFields); for (int i = 0; i < len; i++) { BcelField gen = fields.get(i); myGen.addField(gen.getField(cp)); } if (sourceDebugExtensionSupportSwitchedOn) { if (inlinedFiles.size() != 0) { if (hasSourceDebugExtensionAttribute(myGen)) { world.showMessage(IMessage.WARNING, WeaverMessages.format(WeaverMessages.OVERWRITE_JSR45, getFileName()), null, null); } // myGen.addAttribute(getSourceDebugExtensionAttribute()); } } fixupGenericSignatureAttribute(); } /** * When working with Java generics, a signature attribute is attached to the type which indicates how it was declared. This * routine ensures the signature attribute for the class we are about to write out is correct. Basically its responsibilities * are: * <ol> * <li> * Checking whether the attribute needs changing (ie. did weaving change the type hierarchy) - if it did, remove the old * attribute * <li> * Check if we need an attribute at all, are we generic? are our supertypes parameterized/generic? * <li> * Build the new attribute which includes all typevariable, supertype and superinterface information * </ol> */ private void fixupGenericSignatureAttribute() { if (getWorld() != null && !getWorld().isInJava5Mode()) { return; } // TODO asc generics Temporarily assume that types we generate dont need // a signature attribute (closure/etc).. will need // revisiting no doubt... // if (myType == null) { // return; // } // 1. Has anything changed that would require us to modify this // attribute? if (!regenerateGenericSignatureAttribute) { return; } // 2. Find the old attribute Signature sigAttr = null; if (myType != null) { // if null, this is a type built from scratch, it // won't already have a sig attribute sigAttr = (Signature) myGen.getAttribute("Signature"); } // 3. Do we need an attribute? boolean needAttribute = false; // If we had one before, we definetly still need one as types can't be // 'removed' from the hierarchy if (sigAttr != null) { needAttribute = true; } // check the interfaces if (!needAttribute) { if (myType != null) { ResolvedType[] interfaceRTXs = myType.getDeclaredInterfaces(); for (int i = 0; i < interfaceRTXs.length; i++) { ResolvedType typeX = interfaceRTXs[i]; if (typeX.isGenericType() || typeX.isParameterizedType()) { needAttribute = true; } } if (extraSuperInterfaces != null) { for (int i = 0; i < extraSuperInterfaces.length; i++) { ResolvedType interfaceType = extraSuperInterfaces[i]; if (interfaceType.isGenericType() || interfaceType.isParameterizedType()) { needAttribute = true; } } } } if (myType == null) { ResolvedType superclassRTX = superclass; if (superclassRTX != null) { if (superclassRTX.isGenericType() || superclassRTX.isParameterizedType()) { needAttribute = true; } } } else { // check the supertype ResolvedType superclassRTX = getSuperClass(); if (superclassRTX.isGenericType() || superclassRTX.isParameterizedType()) { needAttribute = true; } } } if (needAttribute) { StringBuffer signature = new StringBuffer(); // first, the type variables... if (myType != null) { TypeVariable[] tVars = myType.getTypeVariables(); if (tVars.length > 0) { signature.append("<"); for (int i = 0; i < tVars.length; i++) { TypeVariable variable = tVars[i]; signature.append(variable.getSignatureForAttribute()); } signature.append(">"); } } // now the supertype String supersig = getSuperClass().getSignatureForAttribute(); signature.append(supersig); if (myType != null) { ResolvedType[] interfaceRTXs = myType.getDeclaredInterfaces(); for (int i = 0; i < interfaceRTXs.length; i++) { String s = interfaceRTXs[i].getSignatureForAttribute(); signature.append(s); } if (extraSuperInterfaces != null) { for (int i = 0; i < extraSuperInterfaces.length; i++) { String s = extraSuperInterfaces[i].getSignatureForAttribute(); signature.append(s); } } } if (sigAttr != null) { myGen.removeAttribute(sigAttr); } myGen.addAttribute(createSignatureAttribute(signature.toString())); } } /** * Helper method to create a signature attribute based on a string signature: e.g. "Ljava/lang/Object;LI<Ljava/lang/Double;>;" */ private Signature createSignatureAttribute(String signature) { int nameIndex = cp.addUtf8("Signature"); int sigIndex = cp.addUtf8(signature); return new Signature(nameIndex, 2, sigIndex, cp); } /** * */ private void reportClassTooBigProblem() { // PR 59208 // we've generated a class that is just toooooooooo big (you've been // generating programs // again haven't you? come on, admit it, no-one writes classes this big // by hand). // create an empty myGen so that we can give back a return value that // doesn't upset the // rest of the process. myGen = new ClassGen(myGen.getClassName(), myGen.getSuperclassName(), myGen.getFileName(), myGen.getModifiers(), myGen.getInterfaceNames()); // raise an error against this compilation unit. getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.CLASS_TOO_BIG, this.getClassName()), new SourceLocation(new File(myGen.getFileName()), 0), null); } private static boolean hasSourceDebugExtensionAttribute(ClassGen gen) { return gen.hasAttribute("SourceDebugExtension"); } public JavaClass getJavaClass(BcelWorld world) { writeBack(world); return myGen.getJavaClass(); } public byte[] getJavaClassBytesIncludingReweavable(BcelWorld world) { writeBack(world); byte[] wovenClassFileData = myGen.getJavaClass().getBytes(); // if is java 6 class file if (myGen.getMajor() >= Constants.MAJOR_1_6 && world.shouldGenerateStackMaps() && AsmDetector.isAsmAround) { wovenClassFileData = StackMapAdder.addStackMaps(world, wovenClassFileData); } WeaverStateInfo wsi = myType.getWeaverState();// getOrCreateWeaverStateInfo // (); if (wsi != null && wsi.isReweavable()) { // && !reweavableDataInserted // reweavableDataInserted = true; return wsi.replaceKeyWithDiff(wovenClassFileData); } else { return wovenClassFileData; } } public void addGeneratedInner(LazyClassGen newClass) { classGens.add(newClass); } public void addInterface(ResolvedType newInterface, ISourceLocation sourceLocation) { regenerateGenericSignatureAttribute = true; if (extraSuperInterfaces == null) { extraSuperInterfaces = new ResolvedType[1]; extraSuperInterfaces[0] = newInterface; } else { ResolvedType[] x = new ResolvedType[extraSuperInterfaces.length + 1]; System.arraycopy(extraSuperInterfaces, 0, x, 1, extraSuperInterfaces.length); x[0] = newInterface; extraSuperInterfaces = x; } myGen.addInterface(newInterface.getRawName()); if (!newInterface.equals(UnresolvedType.SERIALIZABLE)) { warnOnAddedInterface(newInterface.getName(), sourceLocation); } } public void setSuperClass(ResolvedType newSuperclass) { regenerateGenericSignatureAttribute = true; superclass = newSuperclass; // myType.addParent(typeX); // used for the attribute if (newSuperclass.getGenericType() != null) { newSuperclass = newSuperclass.getGenericType(); } myGen.setSuperclassName(newSuperclass.getName()); // used in the real // class data } // public String getSuperClassname() { // return myGen.getSuperclassName(); // } public ResolvedType getSuperClass() { if (superclass != null) { return superclass; } return myType.getSuperclass(); } public String[] getInterfaceNames() { return myGen.getInterfaceNames(); } // non-recursive, may be a bug, ha ha. private List<LazyClassGen> getClassGens() { List<LazyClassGen> ret = new ArrayList<LazyClassGen>(); ret.add(this); ret.addAll(classGens); return ret; } public List<UnwovenClassFile.ChildClass> getChildClasses(BcelWorld world) { if (classGens.isEmpty()) { return Collections.emptyList(); } List<UnwovenClassFile.ChildClass> ret = new ArrayList<UnwovenClassFile.ChildClass>(); for (LazyClassGen clazz : classGens) { byte[] bytes = clazz.getJavaClass(world).getBytes(); String name = clazz.getName(); int index = name.lastIndexOf('$'); // XXX this could be bad, check use of dollar signs. name = name.substring(index + 1); ret.add(new UnwovenClassFile.ChildClass(name, bytes)); } return ret; } @Override public String toString() { return toShortString(); } public String toShortString() { String s = org.aspectj.apache.bcel.classfile.Utility.accessToString(myGen.getModifiers(), true); if (s != "") { s += " "; } s += org.aspectj.apache.bcel.classfile.Utility.classOrInterface(myGen.getModifiers()); s += " "; s += myGen.getClassName(); return s; } public String toLongString() { ByteArrayOutputStream s = new ByteArrayOutputStream(); print(new PrintStream(s)); return new String(s.toByteArray()); } public void print() { print(System.out); } public void print(PrintStream out) { List<LazyClassGen> classGens = getClassGens(); for (Iterator<LazyClassGen> iter = classGens.iterator(); iter.hasNext();) { LazyClassGen element = iter.next(); element.printOne(out); if (iter.hasNext()) { out.println(); } } } private void printOne(PrintStream out) { out.print(toShortString()); out.print(" extends "); out.print(org.aspectj.apache.bcel.classfile.Utility.compactClassName(myGen.getSuperclassName(), false)); int size = myGen.getInterfaces().length; if (size > 0) { out.print(" implements "); for (int i = 0; i < size; i++) { out.print(myGen.getInterfaceNames()[i]); if (i < size - 1) { out.print(", "); } } } out.print(":"); out.println(); // XXX make sure to pass types correctly around, so this doesn't happen. if (myType != null) { myType.printWackyStuff(out); } Field[] fields = myGen.getFields(); for (int i = 0, len = fields.length; i < len; i++) { out.print(" "); out.println(fields[i]); } List<LazyMethodGen> methodGens = getMethodGens(); for (Iterator<LazyMethodGen> iter = methodGens.iterator(); iter.hasNext();) { LazyMethodGen gen = iter.next(); // we skip empty clinits if (isEmptyClinit(gen)) { continue; } gen.print(out, (myType != null ? myType.getWeaverVersionAttribute() : WeaverVersionInfo.UNKNOWN)); if (iter.hasNext()) { out.println(); } } // out.println(" ATTRIBS: " + Arrays.asList(myGen.getAttributes())); out.println("end " + toShortString()); } private boolean isEmptyClinit(LazyMethodGen gen) { if (!gen.getName().equals("<clinit>")) { return false; } // System.err.println("checking clinig: " + gen); InstructionHandle start = gen.getBody().getStart(); while (start != null) { if (Range.isRangeHandle(start) || (start.getInstruction().opcode == Constants.RETURN)) { start = start.getNext(); } else { return false; } } return true; } public ConstantPool getConstantPool() { return cp; } public String getName() { return myGen.getClassName(); } public boolean isWoven() { return myType.getWeaverState() != null; } public boolean isReweavable() { if (myType.getWeaverState() == null) { return true; } return myType.getWeaverState().isReweavable(); } public Set<String> getAspectsAffectingType() { if (myType.getWeaverState() == null) { return null; } return myType.getWeaverState().getAspectsAffectingType(); } public WeaverStateInfo getOrCreateWeaverStateInfo(boolean inReweavableMode) { WeaverStateInfo ret = myType.getWeaverState(); if (ret != null) { return ret; } ret = new WeaverStateInfo(inReweavableMode); myType.setWeaverState(ret); return ret; } public InstructionFactory getFactory() { return fact; } public LazyMethodGen getStaticInitializer() { for (LazyMethodGen gen : methodGens) { // OPTIMIZE persist kind of member into the gen object? for clinit if (gen.getName().equals("<clinit>")) { return gen; } } LazyMethodGen clinit = new LazyMethodGen(Modifier.STATIC, Type.VOID, "<clinit>", new Type[0], NO_STRINGS, this); clinit.getBody().insert(InstructionConstants.RETURN); methodGens.add(clinit); return clinit; } /** * Retrieve the ajc$preClinit method - this method captures any initialization AspectJ wants to ensure happens in a class. It is * called from the static initializer. Maintaining this separation enables overweaving to ignore join points added due to * earlier weaves. If the ajc$preClinit method cannot be found, it is created and a call to it is placed in the real static * initializer (the call is placed at the start of the static initializer). * * @return the LazyMethodGen representing the ajc$ clinit */ public LazyMethodGen getAjcPreClinit() { if (this.isInterface()) { throw new IllegalStateException(); } for (LazyMethodGen methodGen : methodGens) { if (methodGen.getName().equals(NameMangler.AJC_PRE_CLINIT_NAME)) { return methodGen; } } LazyMethodGen ajcPreClinit = new LazyMethodGen(Modifier.PRIVATE | Modifier.STATIC, Type.VOID, NameMangler.AJC_PRE_CLINIT_NAME, Type.NO_ARGS, NO_STRINGS, this); ajcPreClinit.getBody().insert(InstructionConstants.RETURN); methodGens.add(ajcPreClinit); getStaticInitializer().getBody().insert(Utility.createInvoke(fact, ajcPreClinit)); return ajcPreClinit; } /** * factory method for building multiple extended clinit methods. Constructs a new clinit method that invokes the previous one * and then returns it. The index is used as a name suffix. * * @param previousPreClinit * @param i */ public LazyMethodGen createExtendedAjcPreClinit(LazyMethodGen previousPreClinit, int i) { LazyMethodGen ajcPreClinit = new LazyMethodGen(Modifier.PRIVATE | Modifier.STATIC, Type.VOID, NameMangler.AJC_PRE_CLINIT_NAME + i, Type.NO_ARGS, NO_STRINGS, this); ajcPreClinit.getBody().insert(InstructionConstants.RETURN); methodGens.add(ajcPreClinit); previousPreClinit.getBody().insert(Utility.createInvoke(fact, ajcPreClinit)); return ajcPreClinit; } // // reflective thisJoinPoint support private Map<BcelShadow, Field> tjpFields = new HashMap<BcelShadow, Field>(); Map<CacheKey, Field> annotationCachingFieldCache = new HashMap<CacheKey, Field>(); private int tjpFieldsCounter = -1; // -1 means not yet initialized private int annoFieldsCounter = 0; public static final ObjectType proceedingTjpType = new ObjectType("org.aspectj.lang.ProceedingJoinPoint"); public static final ObjectType tjpType = new ObjectType("org.aspectj.lang.JoinPoint"); public static final ObjectType staticTjpType = new ObjectType("org.aspectj.lang.JoinPoint$StaticPart"); public static final ObjectType typeForAnnotation = new ObjectType("java.lang.annotation.Annotation"); public static final ObjectType enclosingStaticTjpType = new ObjectType("org.aspectj.lang.JoinPoint$EnclosingStaticPart"); private static final ObjectType sigType = new ObjectType("org.aspectj.lang.Signature"); // private static final ObjectType slType = // new ObjectType("org.aspectj.lang.reflect.SourceLocation"); private static final ObjectType factoryType = new ObjectType("org.aspectj.runtime.reflect.Factory"); private static final ObjectType classType = new ObjectType("java.lang.Class"); public Field getTjpField(BcelShadow shadow, final boolean isEnclosingJp) { Field tjpField = tjpFields.get(shadow); if (tjpField != null) { return tjpField; } int modifiers = Modifier.STATIC | Modifier.FINAL; // XXX - Do we ever inline before or after advice? If we do, then we // better include them in the check below. (or just change it to // shadow.getEnclosingMethod().getCanInline()) // If the enclosing method is around advice, we could inline the join // point that has led to this shadow. If we do that then the TJP we are // creating here must be PUBLIC so it is visible to the type in which the // advice is inlined. (PR71377) LazyMethodGen encMethod = shadow.getEnclosingMethod(); boolean shadowIsInAroundAdvice = false; if (encMethod != null && encMethod.getName().startsWith(NameMangler.PREFIX + "around")) { shadowIsInAroundAdvice = true; } if (getType().isInterface() || shadowIsInAroundAdvice) { modifiers |= Modifier.PUBLIC; } else { modifiers |= Modifier.PRIVATE; } ObjectType jpType = null; // Did not have different static joinpoint types in 1.2 if (world.isTargettingAspectJRuntime12()) { jpType = staticTjpType; } else { jpType = isEnclosingJp ? enclosingStaticTjpType : staticTjpType; } if (tjpFieldsCounter == -1) { // not yet initialized, do it now if (!world.isOverWeaving()) { tjpFieldsCounter = 0; } else { List<BcelField> existingFields = getFieldGens(); if (existingFields == null) { tjpFieldsCounter = 0; } else { BcelField lastField = null; // OPTIMIZE: go from last to first? for (BcelField field : existingFields) { if (field.getName().startsWith("ajc$tjp_")) { lastField = field; } } if (lastField == null) { tjpFieldsCounter = 0; } else { tjpFieldsCounter = Integer.parseInt(lastField.getName().substring(8)) + 1; // System.out.println("tjp counter starting at " + tjpFieldsCounter); } } } } FieldGen fGen = new FieldGen(modifiers, jpType, "ajc$tjp_" + tjpFieldsCounter++, getConstantPool()); addField(fGen); tjpField = fGen.getField(); tjpFields.put(shadow, tjpField); return tjpField; } /** * Create a field in the type containing the shadow where the annotation retrieved during binding can be stored - for later fast * access. * * @param shadow the shadow at which the @annotation result is being cached * @return a field */ public Field getAnnotationCachingField(BcelShadow shadow, ResolvedType toType) { // Multiple annotation types at a shadow. A different field would be required for each CacheKey cacheKey = new CacheKey(shadow, toType); Field field = annotationCachingFieldCache.get(cacheKey); if (field == null) { // private static Annotation ajc$anno$<nnn> StringBuilder sb = new StringBuilder(); sb.append(NameMangler.ANNOTATION_CACHE_FIELD_NAME); sb.append(annoFieldsCounter++); FieldGen annotationCacheField = new FieldGen(Modifier.PRIVATE | Modifier.STATIC, typeForAnnotation, sb.toString(), cp); addField(annotationCacheField); field = annotationCacheField.getField(); annotationCachingFieldCache.put(cacheKey, field); } return field; } static class CacheKey { private BcelShadow shadow; private ResolvedType annotationType; CacheKey(BcelShadow shadow, ResolvedType annotationType) { this.shadow = shadow; this.annotationType = annotationType; } @Override public int hashCode() { return shadow.hashCode() * 37 + annotationType.hashCode(); } @Override public boolean equals(Object other) { if (!(other instanceof CacheKey)) { return false; } CacheKey oCacheKey = (CacheKey) other; return shadow.equals(oCacheKey.shadow) && annotationType.equals(oCacheKey.annotationType); } } // FIXME ATAJ needed only for slow Aspects.aspectOf - keep or remove // private void addAjClassField() { // // Andy: Why build it again?? // Field ajClassField = new FieldGen( // Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC, // classType, // "aj$class", // getConstantPool()).getField(); // addField(ajClassField); // // InstructionList il = new InstructionList(); // il.append(new PUSH(getConstantPool(), getClassName())); // il.append(fact.createInvoke("java.lang.Class", "forName", classType, // new Type[] {Type.STRING}, Constants.INVOKESTATIC)); // il.append(fact.createFieldAccess(getClassName(), ajClassField.getName(), // classType, Constants.PUTSTATIC)); // // getStaticInitializer().getBody().insert(il); // } private void addAjcInitializers() { if (tjpFields.size() == 0 && !serialVersionUIDRequiresInitialization) { return; } InstructionList[] il = null; if (tjpFields.size() > 0) { il = initializeAllTjps(); } if (serialVersionUIDRequiresInitialization) { InstructionList[] ilSVUID = new InstructionList[1]; ilSVUID[0] = new InstructionList(); ilSVUID[0].append(InstructionFactory.PUSH(getConstantPool(), calculatedSerialVersionUID)); ilSVUID[0].append(getFactory().createFieldAccess(getClassName(), "serialVersionUID", BasicType.LONG, Constants.PUTSTATIC)); if (il == null) { il = ilSVUID; } else { InstructionList[] newIl = new InstructionList[il.length + ilSVUID.length]; System.arraycopy(il, 0, newIl, 0, il.length); System.arraycopy(ilSVUID, 0, newIl, il.length, ilSVUID.length); il = newIl; } } LazyMethodGen prevMethod; LazyMethodGen nextMethod = null; if (this.isInterface()) { // Cannot sneak stuff into another static method in an interface prevMethod = getStaticInitializer(); } else { prevMethod = getAjcPreClinit(); } for (int counter = 1; counter <= il.length; counter++) { if (il.length > counter) { nextMethod = createExtendedAjcPreClinit(prevMethod, counter); } prevMethod.getBody().insert(il[counter - 1]); prevMethod = nextMethod; } } private InstructionList initInstructionList() { InstructionList list = new InstructionList(); InstructionFactory fact = getFactory(); // make a new factory list.append(fact.createNew(factoryType)); list.append(InstructionFactory.createDup(1)); list.append(InstructionFactory.PUSH(getConstantPool(), getFileName())); // load the current Class object // XXX check that this works correctly for inners/anonymous list.append(fact.PUSHCLASS(cp, myGen.getClassName())); // XXX do we need to worry about the fact the theorectically this could // throw // a ClassNotFoundException list.append(fact.createInvoke(factoryType.getClassName(), "<init>", Type.VOID, new Type[] { Type.STRING, classType }, Constants.INVOKESPECIAL)); list.append(InstructionFactory.createStore(factoryType, 0)); return list; } private InstructionList[] initializeAllTjps() { Vector<InstructionList> lists = new Vector<InstructionList>(); InstructionList list = initInstructionList(); lists.add(list); List<Map.Entry<BcelShadow, Field>> entries = new ArrayList<Map.Entry<BcelShadow, Field>>(tjpFields.entrySet()); Collections.sort(entries, new Comparator<Map.Entry<BcelShadow, Field>>() { public int compare(Map.Entry<BcelShadow, Field> a, Map.Entry<BcelShadow, Field> b) { return (a.getValue()).getName().compareTo((b.getValue()).getName()); } }); long estimatedSize = 0; for (Iterator<Map.Entry<BcelShadow, Field>> i = entries.iterator(); i.hasNext();) { Map.Entry<BcelShadow, Field> entry = i.next(); if (estimatedSize > Constants.MAX_CODE_SIZE) { estimatedSize = 0; list = initInstructionList(); lists.add(list); } estimatedSize += entry.getValue().getSignature().getBytes().length; initializeTjp(fact, list, entry.getValue(), entry.getKey()); } InstructionList listArrayModel[] = new InstructionList[1]; return lists.toArray(listArrayModel); } private void initializeTjp(InstructionFactory fact, InstructionList list, Field field, BcelShadow shadow) { boolean fastSJP = false; // avoid fast SJP if it is for an enclosing joinpoint boolean isFastSJPAvailable = shadow.getWorld().isTargettingRuntime1_6_10() && !enclosingStaticTjpType.equals(field.getType()); Member sig = shadow.getSignature(); // load the factory list.append(InstructionFactory.createLoad(factoryType, 0)); // load the kind list.append(InstructionFactory.PUSH(getConstantPool(), shadow.getKind().getName())); // create the signature if (world.isTargettingAspectJRuntime12() || !isFastSJPAvailable || !sig.getKind().equals(Member.METHOD)) { list.append(InstructionFactory.createLoad(factoryType, 0)); } String signatureMakerName = SignatureUtils.getSignatureMakerName(sig); ObjectType signatureType = new ObjectType(SignatureUtils.getSignatureType(sig)); UnresolvedType[] exceptionTypes = null; if (world.isTargettingAspectJRuntime12()) { // TAG:SUPPORTING12: We // didn't have optimized // factory methods in 1.2 list.append(InstructionFactory.PUSH(cp, SignatureUtils.getSignatureString(sig, shadow.getWorld()))); list.append(fact.createInvoke(factoryType.getClassName(), signatureMakerName, signatureType, Type.STRINGARRAY1, Constants.INVOKEVIRTUAL)); } else if (sig.getKind().equals(Member.METHOD)) { BcelWorld w = shadow.getWorld(); // For methods, push the parts of the signature on. list.append(InstructionFactory.PUSH(cp, makeString(sig.getModifiers(w)))); list.append(InstructionFactory.PUSH(cp, sig.getName())); list.append(InstructionFactory.PUSH(cp, makeString(sig.getDeclaringType()))); list.append(InstructionFactory.PUSH(cp, makeString(sig.getParameterTypes()))); list.append(InstructionFactory.PUSH(cp, makeString(sig.getParameterNames(w)))); exceptionTypes = sig.getExceptions(w); if (isFastSJPAvailable && exceptionTypes.length == 0) { fastSJP = true; } else { list.append(InstructionFactory.PUSH(cp, makeString(exceptionTypes))); } list.append(InstructionFactory.PUSH(cp, makeString(sig.getReturnType()))); // And generate a call to the variant of makeMethodSig() that takes the strings if (isFastSJPAvailable) { fastSJP = true; } else { list.append(fact.createInvoke(factoryType.getClassName(), signatureMakerName, signatureType, Type.STRINGARRAY7, Constants.INVOKEVIRTUAL)); } } else if (sig.getKind().equals(Member.MONITORENTER)) { list.append(InstructionFactory.PUSH(cp, makeString(sig.getDeclaringType()))); list.append(fact.createInvoke(factoryType.getClassName(), signatureMakerName, signatureType, Type.STRINGARRAY1, Constants.INVOKEVIRTUAL)); } else if (sig.getKind().equals(Member.MONITOREXIT)) { list.append(InstructionFactory.PUSH(cp, makeString(sig.getDeclaringType()))); list.append(fact.createInvoke(factoryType.getClassName(), signatureMakerName, signatureType, Type.STRINGARRAY1, Constants.INVOKEVIRTUAL)); } else if (sig.getKind().equals(Member.HANDLER)) { BcelWorld w = shadow.getWorld(); list.append(InstructionFactory.PUSH(cp, makeString(sig.getDeclaringType()))); list.append(InstructionFactory.PUSH(cp, makeString(sig.getParameterTypes()))); list.append(InstructionFactory.PUSH(cp, makeString(sig.getParameterNames(w)))); list.append(fact.createInvoke(factoryType.getClassName(), signatureMakerName, signatureType, Type.STRINGARRAY3, Constants.INVOKEVIRTUAL)); } else if (sig.getKind().equals(Member.CONSTRUCTOR)) { BcelWorld w = shadow.getWorld(); if (w.isJoinpointArrayConstructionEnabled() && sig.getDeclaringType().isArray()) { // its the magical new jp list.append(InstructionFactory.PUSH(cp, makeString(Modifier.PUBLIC))); list.append(InstructionFactory.PUSH(cp, makeString(sig.getDeclaringType()))); list.append(InstructionFactory.PUSH(cp, makeString(sig.getParameterTypes()))); list.append(InstructionFactory.PUSH(cp, "")); // sig.getParameterNames? list.append(InstructionFactory.PUSH(cp, ""));// sig.getExceptions? list.append(fact.createInvoke(factoryType.getClassName(), signatureMakerName, signatureType, Type.STRINGARRAY5, Constants.INVOKEVIRTUAL)); } else { list.append(InstructionFactory.PUSH(cp, makeString(sig.getModifiers(w)))); list.append(InstructionFactory.PUSH(cp, makeString(sig.getDeclaringType()))); list.append(InstructionFactory.PUSH(cp, makeString(sig.getParameterTypes()))); list.append(InstructionFactory.PUSH(cp, makeString(sig.getParameterNames(w)))); list.append(InstructionFactory.PUSH(cp, makeString(sig.getExceptions(w)))); list.append(fact.createInvoke(factoryType.getClassName(), signatureMakerName, signatureType, Type.STRINGARRAY5, Constants.INVOKEVIRTUAL)); } } else if (sig.getKind().equals(Member.FIELD)) { BcelWorld w = shadow.getWorld(); list.append(InstructionFactory.PUSH(cp, makeString(sig.getModifiers(w)))); list.append(InstructionFactory.PUSH(cp, sig.getName())); // see pr227401 UnresolvedType dType = sig.getDeclaringType(); if (dType.getTypekind() == TypeKind.PARAMETERIZED || dType.getTypekind() == TypeKind.GENERIC) { dType = sig.getDeclaringType().resolve(world).getGenericType(); } list.append(InstructionFactory.PUSH(cp, makeString(dType))); list.append(InstructionFactory.PUSH(cp, makeString(sig.getReturnType()))); list.append(fact.createInvoke(factoryType.getClassName(), signatureMakerName, signatureType, Type.STRINGARRAY4, Constants.INVOKEVIRTUAL)); } else if (sig.getKind().equals(Member.ADVICE)) { BcelWorld w = shadow.getWorld(); list.append(InstructionFactory.PUSH(cp, makeString(sig.getModifiers(w)))); list.append(InstructionFactory.PUSH(cp, sig.getName())); list.append(InstructionFactory.PUSH(cp, makeString(sig.getDeclaringType()))); list.append(InstructionFactory.PUSH(cp, makeString(sig.getParameterTypes()))); list.append(InstructionFactory.PUSH(cp, makeString(sig.getParameterNames(w)))); list.append(InstructionFactory.PUSH(cp, makeString(sig.getExceptions(w)))); list.append(InstructionFactory.PUSH(cp, makeString((sig.getReturnType())))); list.append(fact.createInvoke(factoryType.getClassName(), signatureMakerName, signatureType, new Type[] { Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING }, Constants.INVOKEVIRTUAL)); } else if (sig.getKind().equals(Member.STATIC_INITIALIZATION)) { BcelWorld w = shadow.getWorld(); list.append(InstructionFactory.PUSH(cp, makeString(sig.getModifiers(w)))); list.append(InstructionFactory.PUSH(cp, makeString(sig.getDeclaringType()))); list.append(fact.createInvoke(factoryType.getClassName(), signatureMakerName, signatureType, Type.STRINGARRAY2, Constants.INVOKEVIRTUAL)); } else { list.append(InstructionFactory.PUSH(cp, SignatureUtils.getSignatureString(sig, shadow.getWorld()))); list.append(fact.createInvoke(factoryType.getClassName(), signatureMakerName, signatureType, Type.STRINGARRAY1, Constants.INVOKEVIRTUAL)); } // XXX should load source location from shadow list.append(Utility.createConstant(fact, shadow.getSourceLine())); final String factoryMethod; // TAG:SUPPORTING12: We didn't have makeESJP() in 1.2 if (world.isTargettingAspectJRuntime12()) { list.append(fact.createInvoke(factoryType.getClassName(), "makeSJP", staticTjpType, new Type[] { Type.STRING, sigType, Type.INT }, Constants.INVOKEVIRTUAL)); // put it in the field list.append(fact.createFieldAccess(getClassName(), field.getName(), staticTjpType, Constants.PUTSTATIC)); } else { if (staticTjpType.equals(field.getType())) { factoryMethod = "makeSJP"; } else if (enclosingStaticTjpType.equals(field.getType())) { factoryMethod = "makeESJP"; } else { throw new Error("should not happen"); } if (fastSJP) { if (exceptionTypes != null && exceptionTypes.length != 0) { list.append(fact.createInvoke(factoryType.getClassName(), factoryMethod, field.getType(), ARRAY_8STRING_INT, Constants.INVOKEVIRTUAL)); } else { list.append(fact.createInvoke(factoryType.getClassName(), factoryMethod, field.getType(), ARRAY_7STRING_INT, Constants.INVOKEVIRTUAL)); } } else { list.append(fact.createInvoke(factoryType.getClassName(), factoryMethod, field.getType(), new Type[] { Type.STRING, sigType, Type.INT }, Constants.INVOKEVIRTUAL)); } // put it in the field list.append(fact.createFieldAccess(getClassName(), field.getName(), field.getType(), Constants.PUTSTATIC)); } } private static final Type[] ARRAY_7STRING_INT = new Type[] { Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.INT }; private static final Type[] ARRAY_8STRING_INT = new Type[] { Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.INT }; protected String makeString(int i) { return Integer.toString(i, 16); // ??? expensive } protected String makeString(UnresolvedType t) { // this is the inverse of the odd behavior for Class.forName w/ arrays if (t.isArray()) { // this behavior matches the string used by the eclipse compiler for // Foo.class literals return t.getSignature().replace('/', '.'); } else { if (t.isParameterizedType()) { return t.getRawType().getName(); } else { return t.getName(); } } } protected String makeString(UnresolvedType[] types) { if (types == null) { return ""; } StringBuilder buf = new StringBuilder(); for (int i = 0, len = types.length; i < len; i++) { if (i > 0) { buf.append(':'); } buf.append(makeString(types[i])); } return buf.toString(); } protected String makeString(String[] names) { if (names == null) { return ""; } StringBuilder buf = new StringBuilder(); for (int i = 0, len = names.length; i < len; i++) { if (i > 0) { buf.append(':'); } buf.append(names[i]); } return buf.toString(); } public ResolvedType getType() { if (myType == null) { return null; } return myType.getResolvedTypeX(); } public BcelObjectType getBcelObjectType() { return myType; } public String getFileName() { return myGen.getFileName(); } // for *new* fields private void addField(FieldGen field) { makeSyntheticAndTransientIfNeeded(field); BcelField bcelField = null; if (getBcelObjectType() != null) { bcelField = new BcelField(getBcelObjectType(), field.getField()); } else { bcelField = new BcelField(getName(), field.getField(), world); } fields.add(bcelField); // myGen.addField(field.getField()); } private void makeSyntheticAndTransientIfNeeded(FieldGen field) { if (field.getName().startsWith(NameMangler.PREFIX) && !field.getName().startsWith("ajc$interField$") && !field.getName().startsWith("ajc$instance$")) { // it's an aj added field // first do transient if (!field.isStatic()) { field.setModifiers(field.getModifiers() | Constants.ACC_TRANSIENT); } // then do synthetic if (getWorld().isInJava5Mode()) { // add the synthetic modifier flag field.setModifiers(field.getModifiers() | ACC_SYNTHETIC); } if (!hasSyntheticAttribute(field.getAttributes())) { // belt and braces, do the attribute even on Java 5 in addition // to the modifier flag // Attribute[] oldAttrs = field.getAttributes(); // Attribute[] newAttrs = new Attribute[oldAttrs.length + 1]; // System.arraycopy(oldAttrs, 0, newAttrs, 0, oldAttrs.length); ConstantPool cpg = myGen.getConstantPool(); int index = cpg.addUtf8("Synthetic"); Attribute synthetic = new Synthetic(index, 0, new byte[0], cpg); field.addAttribute(synthetic); // newAttrs[newAttrs.length - 1] = synthetic; // field.setAttributes(newAttrs); } } } private boolean hasSyntheticAttribute(List<Attribute> attributes) { for (int i = 0; i < attributes.size(); i++) { if ((attributes.get(i)).getName().equals("Synthetic")) { return true; } } return false; } public void addField(FieldGen field, ISourceLocation sourceLocation) { addField(field); if (!(field.isPrivate() && (field.isStatic() || field.isTransient()))) { errorOnAddedField(field, sourceLocation); } } public String getClassName() { return myGen.getClassName(); } public boolean isInterface() { return myGen.isInterface(); } public boolean isAbstract() { return myGen.isAbstract(); } public LazyMethodGen getLazyMethodGen(Member m) { return getLazyMethodGen(m.getName(), m.getSignature(), false); } public LazyMethodGen getLazyMethodGen(String name, String signature) { return getLazyMethodGen(name, signature, false); } public LazyMethodGen getLazyMethodGen(String name, String signature, boolean allowMissing) { for (LazyMethodGen gen : methodGens) { if (gen.getName().equals(name) && gen.getSignature().equals(signature)) { return gen; } } if (!allowMissing) { throw new BCException("Class " + this.getName() + " does not have a method " + name + " with signature " + signature); } return null; } public void forcePublic() { myGen.setModifiers(Utility.makePublic(myGen.getModifiers())); } public boolean hasAnnotation(UnresolvedType t) { // annotations on the real thing AnnotationGen agens[] = myGen.getAnnotations(); if (agens == null) { return false; } for (int i = 0; i < agens.length; i++) { AnnotationGen gen = agens[i]; if (t.equals(UnresolvedType.forSignature(gen.getTypeSignature()))) { return true; } } // annotations added during this weave return false; } public void addAnnotation(AnnotationGen a) { if (!hasAnnotation(UnresolvedType.forSignature(a.getTypeSignature()))) { annotations.add(new AnnotationGen(a, getConstantPool(), true)); } } // this test is like asking: // if // (UnresolvedType.SERIALIZABLE.resolve(getType().getWorld()).isAssignableFrom // (getType())) { // only we don't do that because this forces us to find all the supertypes // of the type, // and if one of them is missing we fail, and it's not worth failing just to // put out // a warning message! private boolean implementsSerializable(ResolvedType aType) { if (aType.getSignature().equals(UnresolvedType.SERIALIZABLE.getSignature())) { return true; } ResolvedType[] interfaces = aType.getDeclaredInterfaces(); for (int i = 0; i < interfaces.length; i++) { if (interfaces[i].isMissing()) { continue; } if (implementsSerializable(interfaces[i])) { return true; } } ResolvedType superType = aType.getSuperclass(); if (superType != null && !superType.isMissing()) { return implementsSerializable(superType); } return false; } public boolean isAtLeastJava5() { return (myGen.getMajor() >= Constants.MAJOR_1_5); } /** * Return the next available field name with the specified 'prefix', e.g. for prefix 'class$' where class$0, class$1 exist then * return class$2 */ public String allocateField(String prefix) { int highestAllocated = -1; List<BcelField> fs = getFieldGens(); for (BcelField field : fs) { if (field.getName().startsWith(prefix)) { try { int num = Integer.parseInt(field.getName().substring(prefix.length())); if (num > highestAllocated) { highestAllocated = num; } } catch (NumberFormatException nfe) { // something wrong with the number on the end of that // field... } } } return prefix + Integer.toString(highestAllocated + 1); } }
353,100
Bug 353100 Need to demote "warning ignoring duplicate definition" from warning to debug
Build Identifier: 1.6.11 This kind of problem can occur for complex class loader hierarchies, and since it is not really a problem, we should make it debug level message so as not to write log messages un-necessarily. Reproducible: Always Steps to Reproduce: 1. Create an application that has some weaved class loaders hierarchy - recommend some URLClassLoader derived ones 2. Add the same(!) JAR with only an aop.xml file to more than one loader along the hierarchy 3. Make the loader the default context thread loader and start running some code.
resolved fixed
c6fb752
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-07-26T15:52:40Z"
"2011-07-26T11: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.security.ProtectionDomain; 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.Lint.Kind; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; 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 Alexandre Vasseur * @author Andy Clement * @author Abraham Nevado */ 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<TypePattern> m_aspectExcludeTypePattern = new ArrayList<TypePattern>(); private List<String> m_aspectExcludeStartsWith = new ArrayList<String>(); private List<TypePattern> m_aspectIncludeTypePattern = new ArrayList<TypePattern>(); private List<String> m_aspectIncludeStartsWith = new ArrayList<String>(); 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(); } if (activeProtectionDomain != null) { defineClass(loaderRef.getClassLoader(), name, bytes, activeProtectionDomain); } else { 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<Definition> parseDefinitions(final ClassLoader loader) { if (trace.isTraceEnabled()) { trace.enter("parseDefinitions", this); } List<Definition> definitions = new ArrayList<Definition>(); 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<URL> xmls = weavingContext.getResources(nextDefinition); // System.out.println("? registerDefinitions: found-aop.xml=" + xmls.hasMoreElements() + ", loader=" + loader); Set<URL> seenBefore = new HashSet<URL>(); while (xmls.hasMoreElements()) { URL xml = 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<Definition> 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<Definition> definitions) { String fastMatchInfo = null; for (Definition definition : definitions) { for (String exclude : definition.getAspectExcludePatterns()) { 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<Definition> definitions) { String fastMatchInfo = null; for (Definition definition : definitions) { for (String include : definition.getAspectIncludePatterns()) { 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<Definition> 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 (Definition definition : definitions) { for (String aspectClassName : definition.getAspectClassNames()) { if (acceptAspect(aspectClassName)) { info("register aspect " + aspectClassName); // System.err.println("? ClassLoaderWeavingAdaptor.registerAspects() aspectName=" + aspectClassName + // ", loader=" + loader + ", bundle=" + weavingContext.getClassLoaderName()); String requiredType = definition.getAspectRequires(aspectClassName); if (requiredType != null) { // This aspect expresses that it requires a type to be around, otherwise it should 'switch off' ((BcelWorld) weaver.getWorld()).addAspectRequires(aspectClassName, requiredType); } String definedScope = definition.getScopeForAspect(aspectClassName); if (definedScope != null) { ((BcelWorld) weaver.getWorld()).addScopedAspect(aspectClassName, definedScope); } // ResolvedType aspect = weaver.addLibraryAspect(aspectClassName); // generate key for SC if (namespace == null) { namespace = new StringBuffer(aspectClassName); } else { namespace = namespace.append(";").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 (Definition definition : definitions) { 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('/', '.'); 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; } } } fastClassName = fastClassName.replace('$', '.'); 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 if (includeStar) { return true; } if (!includeExactName.isEmpty()) { didSomeIncludeMatching = true; for (String exactname : includeExactName) { if (fastClassName.equals(exactname)) { return true; } } } for (int i = 0; i < m_includeStartsWith.size(); i++) { didSomeIncludeMatching = true; boolean fastaccept = fastClassName.startsWith(m_includeStartsWith.get(i)); if (fastaccept) { return true; } } 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(m_aspectExcludeStartsWith.get(i))) { return false; } } // INCLUDE: if one match then accept for (int i = 0; i < m_aspectIncludeStartsWith.size(); i++) { if (fastClassName.startsWith(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 Method defineClassMethod; private Method defineClassWithProtectionDomainMethod; 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 { if (defineClassMethod == null) { defineClassMethod = ClassLoader.class.getDeclaredMethod("defineClass", new Class[] { String.class, bytes.getClass(), int.class, int.class }); } defineClassMethod.setAccessible(true); clazz = defineClassMethod.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); } } private void defineClass(ClassLoader loader, String name, byte[] bytes, ProtectionDomain protectionDomain) { if (trace.isTraceEnabled()) { trace.enter("defineClass", this, new Object[] { loader, name, bytes, protectionDomain }); } Object clazz = null; debug("generating class '" + name + "'"); try { // System.out.println(">> Defining with protection domain " + name + " pd=" + protectionDomain); if (defineClassWithProtectionDomainMethod == null) { defineClassWithProtectionDomainMethod = ClassLoader.class.getDeclaredMethod("defineClass", new Class[] { String.class, bytes.getClass(), int.class, int.class, ProtectionDomain.class }); } defineClassWithProtectionDomainMethod.setAccessible(true); clazz = defineClassWithProtectionDomainMethod.invoke(loader, new Object[] { name, bytes, new Integer(0), new Integer(bytes.length), protectionDomain }); } 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); } } }
353,349
Bug 353349 NPE in deleteNewAndDup
java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelShadow.deleteNewAndDup(BcelShadow.java:179) at org.aspectj.weaver.bcel.BcelShadow.prepareForMungers(BcelShadow.java:303) at org.aspectj.weaver.Shadow.implement(Shadow.java:543) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:3147) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:490) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:100) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1687) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1631) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1394) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1180) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:467) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:318) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:96)
resolved fixed
e8ef5bf
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-07-28T20:48:42Z"
"2011-07-28T19:06:40Z"
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.ConcreteTypeMunger; 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 static final String[] NoDeclaredExceptions = new String[0]; private ShadowRange range; private final BcelWorld world; private final LazyMethodGen enclosingMethod; // TESTING this will tell us if the optimisation 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<ShadowMunger> src = mungers; if (s.mungers == Collections.EMPTY_LIST) { s.mungers = new ArrayList<ShadowMunger>(); } List<ShadowMunger> dest = s.mungers; for (Iterator<ShadowMunger> i = src.iterator(); i.hasNext();) { dest.add(i.next()); } } return s; } // ---- overridden behaviour @Override 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; } // need a testcase to show this can really happen in a modern compiler - removed due to 315398 // } 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(); boolean skipEndRepositioning = false; if (endHandle.getInstruction().opcode == Constants.SWAP) { } else if (endHandle.getInstruction().opcode == Constants.IMPDEP1) { skipEndRepositioning = true; // pr186884 } 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); if (!skipEndRepositioning) { 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) { for (InstructionTargeter targeter : old.getTargetersCopy()) { if (targeter instanceof ExceptionRange) { ExceptionRange it = (ExceptionRange) targeter; it.updateTarget(old, fresh, it.getBody()); } else { targeter.updateTarget(old, fresh); } } } // records advice that is stopping us doing the lazyTjp optimization private List<BcelAdvice> badAdvice = null; public void addAdvicePreventingLazyTjp(BcelAdvice advice) { if (badAdvice == null) { badAdvice = new ArrayList<BcelAdvice>(); } badAdvice.add(advice); } @Override 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 for (InstructionTargeter t : start.getTargetersCopy()) { 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 (ShadowMunger munger : mungers) { 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<BcelAdvice> iter = badAdvice.iterator(); iter.hasNext();) { BcelAdvice element = 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<BcelAdvice> iter = badAdvice.iterator(); iter.hasNext();) { BcelAdvice element = 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; } @Override public ResolvedType 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<InstructionTargeter> tIter = startOfHandler.getNext().getTargeters().iterator(); while (tIter.hasNext()) { InstructionTargeter targeter = 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) { for (InstructionTargeter source : from.getTargetersCopy()) { 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 !Modifier.isStatic(getSignature().getModifiers()); } 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<ResolvedType, AnnotationAccessVar> kindedAnnotationVars = null; private Map<ResolvedType, TypeAnnotationAccessVar> thisAnnotationVars = null; private Map<ResolvedType, TypeAnnotationAccessVar> targetAnnotationVars = null; // private Map/* <UnresolvedType,BcelVar> */[] argAnnotationVars = null; private Map<ResolvedType, AnnotationAccessVar> withinAnnotationVars = null; private Map<ResolvedType, AnnotationAccessVar> withincodeAnnotationVars = null; private boolean allArgVarsInitialized = false; @Override public Var getThisVar() { if (!hasThis()) { throw new IllegalStateException("no this"); } initializeThisVar(); return thisVar; } @Override 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 = thisAnnotationVars.get(forAnnotationType); if (v == null) { v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world), (BcelVar) getThisVar()); } return v; } @Override public Var getTargetVar() { if (!hasTarget()) { throw new IllegalStateException("no target"); } initializeTargetVar(); return targetVar; } @Override 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 = 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; } @Override public Var getArgVar(int i) { ensureInitializedArgVar(i); return argVars[i]; } @Override public Var getArgAnnotationVar(int i, UnresolvedType forAnnotationType) { return new TypeAnnotationAccessVar(forAnnotationType.resolve(world), (BcelVar) getArgVar(i)); // initializeArgAnnotationVars(); // // Var v = (Var) argAnnotationVars[i].get(forAnnotationType); // if (v == null) { // v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world), (BcelVar) getArgVar(i)); // } // return v; } @Override public Var getKindedAnnotationVar(UnresolvedType forAnnotationType) { initializeKindedAnnotationVars(); return kindedAnnotationVars.get(forAnnotationType); } @Override public Var getWithinAnnotationVar(UnresolvedType forAnnotationType) { initializeWithinAnnotationVars(); return withinAnnotationVars.get(forAnnotationType); } @Override public Var getWithinCodeAnnotationVar(UnresolvedType forAnnotationType) { initializeWithinCodeAnnotationVars(); return 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; @Override public final Var getThisJoinPointStaticPartVar() { return getThisJoinPointStaticPartBcelVar(); } @Override 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")); } } @Override 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 @Override 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(); } } public Member getRealEnclosingCodeSignature() { return enclosingMethod.getMemberView(); } // public Member getEnclosingCodeSignatureForModel() { // 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 { // if (enclosingShadow.getKind() == Shadow.MethodExecution && enclosingMethod.getEffectiveSignature() != null) { // // } 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<ResolvedType, TypeAnnotationAccessVar>(); // populate.. } public void initializeTargetAnnotationVars() { if (targetAnnotationVars != null) { return; } if (getKind().isTargetSameAsThis()) { if (hasThis()) { initializeThisAnnotationVars(); } targetAnnotationVars = thisAnnotationVars; } else { targetAnnotationVars = new HashMap<ResolvedType, TypeAnnotationAccessVar>(); 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<ConcreteTypeMunger> mungers = relevantType.resolve(world).getInterTypeMungers(); for (ConcreteTypeMunger typeMunger : mungers) { 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); // ResolvedMember o = AjcMemberMaker.interMethodBody(fakerm, typeMunger.getAspectType()); // // Object os = o.getAnnotations(); // ResolvedMember foundMember2 = findMethod(typeMunger.getAspectType(), o); // Object os2 = foundMember2.getAnnotations(); // int stop = 1; // foundMember = foundMember2; // foundMember = AjcMemberMaker.interMethod(foundMember, typeMunger.getAspectType()); } // 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<ConcreteTypeMunger> mungers = relevantType.resolve(world).getInterTypeMungers(); for (Iterator<ConcreteTypeMunger> iter = mungers.iterator(); iter.hasNext();) { Object munger = iter.next(); ConcreteTypeMunger typeMunger = (ConcreteTypeMunger) munger; 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, AnnotationAccessVar>(); 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<ConcreteTypeMunger> mungers = relevantType.resolve(world).getInterTypeMungers(); for (ConcreteTypeMunger typeMunger : mungers) { 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 foundMember = findMethod2(relevantType.getDeclaredMethods(), getSignature()); annotations = getAnnotations(foundMember, shadowSignature, relevantType); annotationHolder = getRelevantMember(foundMember, annotationHolder, relevantType); UnresolvedType ut = annotationHolder.getDeclaringType(); relevantType = ut.resolve(world); } 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 (ResolvedType annotationType : annotations) { AnnotationAccessVar accessVar = new AnnotationAccessVar(this, getKind(), annotationType.resolve(world), relevantType, annotationHolder); kindedAnnotationVars.put(annotationType, accessVar); } } private ResolvedMember findMethod2(ResolvedMember members[], Member sig) { String signatureName = sig.getName(); String parameterSignature = sig.getParameterSignature(); for (ResolvedMember member : members) { if (member.getName().equals(signatureName) && member.getParameterSignature().equals(parameterSignature)) { return member; } } return null; } 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, AnnotationAccessVar>(); 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(this, k, ann, getEnclosingType(), null)); } } public void initializeWithinCodeAnnotationVars() { if (withincodeAnnotationVars != null) { return; } withincodeAnnotationVars = new HashMap<ResolvedType, AnnotationAccessVar>(); // 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(this, 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<InstructionHandle> 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<InstructionHandle> i = returns.iterator(); i.hasNext();) { InstructionHandle ih = 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<InstructionHandle> findReturnInstructions() { List<InstructionHandle> returns = new ArrayList<InstructionHandle>(); 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<InstructionHandle> 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 = 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 = 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, munger.getConcreteAspect()) { @Override 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 declaringAspectType = world.resolve(mungerSig.getDeclaringType(), true); if (declaringAspectType.isMissing()) { world.getLint().cantFindType.signal( new String[] { WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE, declaringAspectType.getClassName()) }, getSourceLocation(), new ISourceLocation[] { munger.getSourceLocation() }); } // ??? might want some checks here to give better errors ResolvedType rt = (declaringAspectType.isParameterizedType() ? declaringAspectType.getGenericType() : declaringAspectType); BcelObjectType ot = BcelWorld.getBcelObjectType(rt); LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig); if (!adviceMethod.getCanInline()) { weaveAroundClosure(munger, hasDynamicTest); return; } // specific test for @AJ proceedInInners if (isAnnotationStylePassingProceedingJoinPointOutOfAdvice(munger, hasDynamicTest, adviceMethod)) { 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. // TODO should consider optimizations to recognize simple cases that don't require body extraction enclosingMethod.setCanInline(false); LazyClassGen shadowClass = getEnclosingClass(); // Extract the shadow into a new method. For example: // "private static final void method_aroundBody0(M, M, String, org.aspectj.lang.JoinPoint)" // Parameters are: this if there is one, target if there is one and its different to this, then original arguments // at the shadow, then tjp String extractedShadowMethodName = NameMangler.aroundShadowMethodName(getSignature(), shadowClass.getNewGeneratedNameTag()); List<String> parameterNames = new ArrayList<String>(); LazyMethodGen extractedShadowMethod = extractShadowInstructionsIntoNewMethod(extractedShadowMethodName, Modifier.PRIVATE, munger.getSourceLocation(), parameterNames); List<BcelVar> argsToCallLocalAdviceMethodWith = new ArrayList<BcelVar>(); List<BcelVar> proceedVarList = new ArrayList<BcelVar>(); 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) { argsToCallLocalAdviceMethodWith.add(thisVar); proceedVarList.add(new BcelVar(thisVar.getType(), extraParamOffset)); extraParamOffset += thisVar.getType().getSize(); } if (targetVar != null && targetVar != thisVar) { argsToCallLocalAdviceMethodWith.add(targetVar); proceedVarList.add(new BcelVar(targetVar.getType(), extraParamOffset)); extraParamOffset += targetVar.getType().getSize(); } int idx = 0; for (int i = 0, len = getArgCount(); i < len; i++) { argsToCallLocalAdviceMethodWith.add(argVars[i]); proceedVarList.add(new BcelVar(argVars[i].getType(), extraParamOffset)); extraParamOffset += argVars[i].getType().getSize(); } if (thisJoinPointVar != null) { argsToCallLocalAdviceMethodWith.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()); // 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 adviceMethod.getArgumentTypes(); Type[] extractedMethodParameterTypes = extractedShadowMethod.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); // Extract the advice into a new method. This will go in the same type as the shadow // name will be something like foo_aroundBody1$advice String localAdviceMethodName = NameMangler.aroundAdviceMethodName(getSignature(), shadowClass.getNewGeneratedNameTag()); LazyMethodGen localAdviceMethod = new LazyMethodGen(Modifier.PRIVATE | (world.useFinal() ? Modifier.FINAL : 0) | Modifier.STATIC, BcelWorld.makeBcelType(mungerSig.getReturnType()), localAdviceMethodName, parameterTypes, NoDeclaredExceptions, shadowClass); // Doesnt work properly, so leave it out: // String aspectFilename = adviceMethod.getEnclosingClass().getInternalFileName(); // String shadowFilename = shadowClass.getInternalFileName(); // if (!aspectFilename.equals(shadowFilename)) { // localAdviceMethod.fromFilename = aspectFilename; // shadowClass.addInlinedSourceFileInfo(aspectFilename, adviceMethod.highestLineNumber); // } shadowClass.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); } final InstructionFactory fact = getFactory(); localAdviceMethod.getBody().insert( BcelClassWeaver.genInlineInstructions(adviceMethod, localAdviceMethod, varMap, fact, true)); localAdviceMethod.setMaxLocals(nVars); // 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<BcelVar> i = argsToCallLocalAdviceMethodWith.iterator(); i.hasNext();) { BcelVar var = i.next(); var.appendLoad(advice, fact); } // ??? we don't actually need to push NULL for the closure if we take care boolean isAnnoStyleConcreteAspect = munger.getConcreteAspect().isAnnotationStyleAspect(); boolean isAnnoStyleDeclaringAspect = munger.getDeclaringAspect() != null ? munger.getDeclaringAspect().resolve(world) .isAnnotationStyleAspect() : false; InstructionList iList = null; if (isAnnoStyleConcreteAspect && isAnnoStyleDeclaringAspect) { iList = this.loadThisJoinPoint(); iList.append(Utility.createConversion(getFactory(), LazyClassGen.tjpType, LazyClassGen.proceedingTjpType)); } else { iList = new InstructionList(InstructionConstants.ACONST_NULL); } advice.append(munger.getAdviceArgSetup(this, null, iList)); // adviceMethodInvocation = advice.append(Utility.createInvoke(fact, localAdviceMethod)); // (fact, getWorld(), munger.getSignature())); advice.append(Utility.createConversion(getFactory(), BcelWorld.makeBcelType(mungerSig.getReturnType()), extractedShadowMethod.getReturnType(), world.isInJava5Mode())); if (!isFallsThrough()) { advice.append(InstructionFactory.createReturn(extractedShadowMethod.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(extractedShadowMethod); if (terminatesWithReturn()) { callback.append(InstructionFactory.createReturn(extractedShadowMethod.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, extractedShadowMethod, 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, extractedShadowMethod, munger, localAdviceMethod, proceedVarList, isProceedWithArgs); localAdviceMethod.getBody().append(curr, insteadProceedIl); Utility.deleteInstruction(curr, localAdviceMethod); } curr = next; } } // if (parameterNames.size() == 0) { // On return we have inserted the advice body into the local advice method. We have remapped all the local variables // that were referenced in the advice as we did the copy, and so the local variable table for localAdviceMethod is // now lacking any information about all the initial variables. InstructionHandle start = localAdviceMethod.getBody().getStart(); InstructionHandle end = localAdviceMethod.getBody().getEnd(); // Find the real start and end while (start.getInstruction().opcode == Constants.IMPDEP1) { start = start.getNext(); } while (end.getInstruction().opcode == Constants.IMPDEP1) { end = end.getPrev(); } Type[] args = localAdviceMethod.getArgumentTypes(); int argNumber = 0; for (int slot = 0; slot < extraParamOffset; argNumber++) { // slot will increase by the argument size each time String argumentName = null; if (argNumber >= args.length || parameterNames.size() == 0 || argNumber >= parameterNames.size()) { // this should be unnecessary as I think all known joinpoints and helper methods // propagate the parameter names around correctly - but just in case let us do this // rather than fail. If a bug is raised reporting unknown as a local variable name // then investigate the joinpoint giving rise to the ResolvedMember and why it has // no parameter names specified argumentName = new StringBuffer("unknown").append(argNumber).toString(); } else { argumentName = parameterNames.get(argNumber); } String argumentSignature = args[argNumber].getSignature(); LocalVariableTag lvt = new LocalVariableTag(argumentSignature, argumentName, slot, 0); start.addTargeter(lvt); end.addTargeter(lvt); slot += args[argNumber].getSize(); } } /** * Check if the advice method passes a pjp parameter out via an invoke instruction - if so we can't risk inlining. */ private boolean isAnnotationStylePassingProceedingJoinPointOutOfAdvice(BcelAdvice munger, boolean hasDynamicTest, LazyMethodGen adviceMethod) { 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 true; } } return false; } private InstructionList getRedoneProceedCall(InstructionFactory fact, LazyMethodGen callbackMethod, BcelAdvice munger, LazyMethodGen localAdviceMethod, List<BcelVar> 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 { argVarList.get(i).appendLoad(ret, fact); } } ret.append(Utility.createInvoke(fact, callbackMethod)); ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), BcelWorld.makeBcelType(munger.getSignature().getReturnType()), world.isInJava5Mode())); 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<BcelVar> 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)); int idx = 0; 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 ? // idx++; } else { ret.append(InstructionFactory.createLoad(stateType, idx)); idx += stateType.getSize(); } } } // 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()), world.isInJava5Mode())); 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; @Override public Object visit(ThisOrTargetPointcut node, Object data) { if (node.isThis() && node.isBinding()) { usesThis = true; } return node; } @Override public Object visit(AndPointcut node, Object data) { if (!usesThis) { node.getLeft().accept(this, data); } if (!usesThis) { node.getRight().accept(this, data); } return node; } @Override public Object visit(NotPointcut node, Object data) { if (!usesThis) { node.getNegatedPointcut().accept(this, data); } return node; } @Override 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; @Override public Object visit(ThisOrTargetPointcut node, Object data) { if (!node.isThis() && node.isBinding()) { usesTarget = true; } return node; } @Override public Object visit(AndPointcut node, Object data) { if (!usesTarget) { node.getLeft().accept(this, data); } if (!usesTarget) { node.getRight().accept(this, data); } return node; } @Override public Object visit(NotPointcut node, Object data) { if (!usesTarget) { node.getNegatedPointcut().accept(this, data); } return node; } @Override 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 = extractShadowInstructionsIntoNewMethod( NameMangler.aroundShadowMethodName(getSignature(), getEnclosingClass().getNewGeneratedNameTag()), 0, munger.getSourceLocation(), new ArrayList<String>()); 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 /** * Extract the instructions in the shadow to a new method. * * @param extractedMethodName name for the new method * @param extractedMethodVisibilityModifier visibility modifiers for the new method * @param adviceSourceLocation source location of the advice affecting the shadow */ LazyMethodGen extractShadowInstructionsIntoNewMethod(String extractedMethodName, int extractedMethodVisibilityModifier, ISourceLocation adviceSourceLocation, List<String> parameterNames) { // LazyMethodGen.assertGoodBody(range.getBody(), extractedMethodName); if (!getKind().allowsExtraction()) { throw new BCException("Attempt to extract method from a shadow kind (" + getKind() + ") that does not support this operation"); } LazyMethodGen newMethod = createShadowMethodGen(extractedMethodName, extractedMethodVisibilityModifier, parameterNames); IntMap remapper = makeRemap(); range.extractInstructionsInto(newMethod, remapper, (getKind() != PreInitialization) && isFallsThrough()); if (getKind() == PreInitialization) { addPreInitializationReturnCode(newMethod, getSuperConstructorParameterTypes()); } getEnclosingClass().addMethodGen(newMethod, adviceSourceLocation); return newMethod; } 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 createShadowMethodGen(String newMethodName, int visibilityModifier, List<String> parameterNames) { Type[] shadowParameterTypes = BcelWorld.makeBcelTypes(getArgTypes()); int modifiers = (world.useFinal() ? Modifier.FINAL : 0) | Modifier.STATIC | visibilityModifier; 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(); } } parameterNames.add("target"); // There is a 'target' and it is not the same as 'this', so add it to the parameter list shadowParameterTypes = addTypeToFront(BcelWorld.makeBcelType(targetType), shadowParameterTypes); } if (thisVar != null) { UnresolvedType thisType = getThisType(); parameterNames.add(0, "ajc$this"); shadowParameterTypes = addTypeToFront(BcelWorld.makeBcelType(thisType), shadowParameterTypes); } if (this.getKind() == Shadow.FieldSet || this.getKind() == Shadow.FieldGet) { parameterNames.add(getSignature().getName()); } else { String[] pnames = getSignature().getParameterNames(world); if (pnames != null) { for (int i = 0; i < pnames.length; i++) { if (i == 0 && pnames[i].equals("this")) { parameterNames.add("ajc$this"); } else { parameterNames.add(pnames[i]); } } } } // 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) { parameterNames.add("thisJoinPoint"); shadowParameterTypes = addTypeToEnd(LazyClassGen.tjpType, shadowParameterTypes); } 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, shadowParameterTypes, NoDeclaredExceptions, 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[] addTypeToFront(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(); } @Override 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; } }
340,806
Bug 340806 Race condition in JavaLangTypeToResolvedTypeConverter (potentially exposed through Spring AOP)
null
resolved fixed
167b801
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-08-03T20:22:40Z"
"2011-03-23T19:53:20Z"
weaver5/java5-src/org/aspectj/weaver/reflect/JavaLangTypeToResolvedTypeConverter.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.reflect; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.WildcardType; import java.util.HashMap; import java.util.Map; import org.aspectj.weaver.BoundedReferenceType; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.TypeFactory; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.TypeVariableReferenceType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; /** * Handles the translation of java.lang.reflect.Type objects into AspectJ UnresolvedTypes. * */ public class JavaLangTypeToResolvedTypeConverter { // Used to prevent recursion - we record what we are working on and return it if asked again *whilst* working on it private Map<Type, TypeVariableReferenceType> typeVariablesInProgress = new HashMap<Type, TypeVariableReferenceType>(); private final World world; public JavaLangTypeToResolvedTypeConverter(World aWorld) { this.world = aWorld; } private World getWorld() { return this.world; } public ResolvedType fromType(Type aType) { if (aType instanceof Class) { Class clazz = (Class) aType; String name = clazz.getName(); /** * getName() can return: * * 1. If this class object represents a reference type that is not an array type then the binary name of the class is * returned 2. If this class object represents a primitive type or void, then the name returned is a String equal to the * Java language keyword corresponding to the primitive type or void. 3. If this class object represents a class of * arrays, then the internal form of the name consists of the name of the element type preceded by one or more '[' * characters representing the depth of the array nesting. */ if (clazz.isArray()) { UnresolvedType ut = UnresolvedType.forSignature(name.replace('.', '/')); return getWorld().resolve(ut); } else { return getWorld().resolve(name); } } else if (aType instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) aType; ResolvedType baseType = fromType(pt.getRawType()); Type[] args = pt.getActualTypeArguments(); ResolvedType[] resolvedArgs = fromTypes(args); /* StringBuilder sb = new StringBuilder(); for (int i = 0; i < resolvedArgs.length; i++) { sb.append(resolvedArgs[i]).append(" "); } for (int i = 0; i < resolvedArgs.length; i++) { if (resolvedArgs[i] == null) { String ss = ""; try { ss = aType.toString(); } catch (Exception e) { } throw new IllegalStateException("Parameterized type problem. basetype=" + baseType + " arguments=" + sb.toString() + " ss=" + ss); } } */ return TypeFactory.createParameterizedType(baseType, resolvedArgs, getWorld()); } else if (aType instanceof java.lang.reflect.TypeVariable) { if (typeVariablesInProgress.get(aType) != null) { return typeVariablesInProgress.get(aType); } java.lang.reflect.TypeVariable tv = (java.lang.reflect.TypeVariable) aType; TypeVariable rt_tv = new TypeVariable(tv.getName()); TypeVariableReferenceType tvrt = new TypeVariableReferenceType(rt_tv, getWorld()); typeVariablesInProgress.put(aType, tvrt); // record what we are working on, for recursion case Type[] bounds = tv.getBounds(); ResolvedType[] resBounds = fromTypes(bounds); ResolvedType upperBound = resBounds[0]; ResolvedType[] additionalBounds = new ResolvedType[0]; if (resBounds.length > 1) { additionalBounds = new ResolvedType[resBounds.length - 1]; System.arraycopy(resBounds, 1, additionalBounds, 0, additionalBounds.length); } rt_tv.setUpperBound(upperBound); rt_tv.setAdditionalInterfaceBounds(additionalBounds); typeVariablesInProgress.remove(aType); // we have finished working on it return tvrt; } else if (aType instanceof WildcardType) { WildcardType wildType = (WildcardType) aType; Type[] lowerBounds = wildType.getLowerBounds(); Type[] upperBounds = wildType.getUpperBounds(); ResolvedType bound = null; boolean isExtends = lowerBounds.length == 0; if (isExtends) { bound = fromType(upperBounds[0]); } else { bound = fromType(lowerBounds[0]); } return new BoundedReferenceType((ReferenceType) bound, isExtends, getWorld()); } else if (aType instanceof GenericArrayType) { GenericArrayType gt = (GenericArrayType) aType; Type componentType = gt.getGenericComponentType(); return UnresolvedType.makeArray(fromType(componentType), 1).resolve(getWorld()); } return ResolvedType.MISSING; } public ResolvedType[] fromTypes(Type[] types) { ResolvedType[] ret = new ResolvedType[types.length]; for (int i = 0; i < ret.length; i++) { ret[i] = fromType(types[i]); } return ret; } }
354,022
Bug 354022 constructor inlining can fail for some groovy built code
The file grails.util.BuildSettings contains bytecode where the constructors are recursive. You can't compile this in Java A() { this(); } but groovy generates some code where it switches on a value in the ctor and if it is a certain value, the recursive ctor call is made. I imagine this 'never happens' in practice but because it is in the bytecode it trips up the AspectJ code which inlines this() calls before weaving - since it gets into an infinite loop. For now, just keep track of ctors making the recursive call and so don't get trapped in the infinite loop.
resolved fixed
6ae463a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-08-05T16:17:39Z"
"2011-08-05T16:00:00Z"
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.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; 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.UnresolvedTypeVariableReferenceType; 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); public static boolean weave(BcelWorld world, LazyClassGen clazz, List<ShadowMunger> shadowMungers, List<ConcreteTypeMunger> typeMungers, List<ConcreteTypeMunger> lateTypeMungers, boolean inReweavableMode) { BcelClassWeaver classWeaver = new BcelClassWeaver(world, clazz, shadowMungers, typeMungers, lateTypeMungers); classWeaver.setReweavableMode(inReweavableMode); boolean b = classWeaver.weave(); return b; } // -------------------------------------------- private final LazyClassGen clazz; private final List<ShadowMunger> shadowMungers; private final List<ConcreteTypeMunger> typeMungers; private final List<ConcreteTypeMunger> lateTypeMungers; private List<ShadowMunger>[] indexedShadowMungers; private boolean canMatchBodyShadows = false; 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<LazyMethodGen> addedLazyMethodGens = new ArrayList<LazyMethodGen>(); private final Set<ResolvedMember> addedDispatchTargets = new HashSet<ResolvedMember>(); private boolean inReweavableMode = false; private List<IfaceInitList> addedSuperInitializersAsList = null; private final Map<ResolvedType, IfaceInitList> addedSuperInitializers = new HashMap<ResolvedType, IfaceInitList>(); private final List<ConcreteTypeMunger> addedThisInitializers = new ArrayList<ConcreteTypeMunger>(); private final List<ConcreteTypeMunger> addedClassInitializers = new ArrayList<ConcreteTypeMunger>(); private final Map<ResolvedMember, ResolvedType[]> mapToAnnotations = new HashMap<ResolvedMember, ResolvedType[]>(); // 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<BcelShadow> initializationShadows = new ArrayList<BcelShadow>(); private BcelClassWeaver(BcelWorld world, LazyClassGen clazz, List<ShadowMunger> shadowMungers, List<ConcreteTypeMunger> typeMungers, List<ConcreteTypeMunger> lateTypeMungers) { super(); 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(); indexShadowMungers(); 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 boolean canMatch(Shadow.Kind kind) { return indexedShadowMungers[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]); } } } } /** * Process the shadow mungers into array 'buckets', each bucket represents a shadow kind and contains a list of shadowmungers * that could potentially apply at that shadow kind. */ private void indexShadowMungers() { // beware the annoying property that SHADOW_KINDS[i].getKey == (i+1) ! indexedShadowMungers = new List[Shadow.MAX_SHADOW_KIND + 1]; for (ShadowMunger shadowMunger : shadowMungers) { int couldMatchKinds = shadowMunger.getPointcut().couldMatchKinds(); for (Shadow.Kind kind : Shadow.SHADOW_KINDS) { if (kind.isSet(couldMatchKinds)) { byte k = kind.getKey(); if (indexedShadowMungers[k] == null) { indexedShadowMungers[k] = new ArrayList<ShadowMunger>(); if (!kind.isEnclosingKind()) { canMatchBodyShadows = true; } } indexedShadowMungers[k].add(shadowMunger); } } } } private boolean addSuperInitializer(ResolvedType onType) { if (onType.isRawType() || onType.isParameterizedType()) { onType = onType.getGenericType(); } IfaceInitList l = 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 (Modifier.isStatic(m.getSignature().getModifiers())) { addedClassInitializers.add(cm); } else { if (onType == ty.getResolvedTypeX()) { addedThisInitializers.add(cm); } else { IfaceInitList l = addedSuperInitializers.get(onType); l.list.add(cm); } } } private static class IfaceInitList implements PartialOrder.PartialComparable { final ResolvedType onType; List<ConcreteTypeMunger> list = new ArrayList<ConcreteTypeMunger>(); 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<LazyMethodGen> i = addedLazyMethodGens.iterator(); i.hasNext();) { LazyMethodGen existing = 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<LazyMethodGen> i = clazz.getMethodGens().iterator(); i.hasNext();) { LazyMethodGen existing = 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); } /** * Weave a class and indicate through the return value whether the class was modified. * * @return true if the class was modified */ 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<String> aspectsAffectingType = null; if (inReweavableMode || clazz.getType().isAspect()) { aspectsAffectingType = new HashSet<String>(); } boolean isChanged = false; // we want to "touch" all aspects if (clazz.getType().isAspect()) { isChanged = true; } WeaverStateInfo typeWeaverState = (world.isOverWeaving() ? getLazyClassGen().getType().getWeaverState() : null); // start by munging all typeMungers for (ConcreteTypeMunger o : typeMungers) { if (!(o instanceof BcelTypeMunger)) { // ???System.err.println("surprising: " + o); continue; } BcelTypeMunger munger = (BcelTypeMunger) o; if (typeWeaverState != null && typeWeaverState.isAspectAlreadyApplied(munger.getAspectType())) { continue; } boolean typeMungerAffectedType = munger.munge(this); if (typeMungerAffectedType) { isChanged = true; if (inReweavableMode || clazz.getType().isAspect()) { aspectsAffectingType.add(munger.getAspectType().getSignature()); } } } // 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<IfaceInitList>(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<LazyMethodGen> methodGens = new ArrayList<LazyMethodGen>(clazz.getMethodGens()); for (LazyMethodGen member : methodGens) { if (!member.hasBody()) { continue; } if (world.isJoinpointSynchronizationEnabled() && world.areSynchronizationPointcutsInUse() && member.getMethod().isSynchronized()) { transformSynchronizedMethod(member); } boolean shadowMungerMatched = match(member); if (shadowMungerMatched) { // For matching mungers, add their declaring aspects to the list // that affected this type if (inReweavableMode || clazz.getType().isAspect()) { aspectsAffectingType.addAll(findAspectsForMungers(member)); } isChanged = true; } } // now we weave all but the initialization shadows for (LazyMethodGen methodGen : methodGens) { if (!methodGen.hasBody()) { continue; } implement(methodGen); } // 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<ConcreteTypeMunger> 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().getSignature()); } } } } } // 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 (LazyMethodGen mg : methodGens) { BcelMethod method = mg.getMemberView(); if (method != null) { method.wipeJoinpointSignatures(); } } return isChanged; } // **************************** start of bridge method creation code // ***************** // FIXASC tidy this lot up !! // FIXASC 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 (Modifier.isStatic(methodThatMightBeGettingOverridden.getModifiers())) { // we can't be overriding a static method return null; } if (Modifier.isPrivate(methodThatMightBeGettingOverridden.getModifiers())) { // we can't be overriding a private method return null; } if (!methodThatMightBeGettingOverridden.getName().equals(mname)) { // names do not match (this will also skip <init> and <clinit>) return null; } if (methodThatMightBeGettingOverridden.getParameterTypes().length != methodParamsArray.length) { // not the same number of parameters return null; } if (!isVisibilityOverride(mmods, methodThatMightBeGettingOverridden, inSamePackage)) { // not override from visibility point of view return null; } if (typeToCheck.getWorld().forDEBUG_bridgingCode) { System.err.println(" Bridging:seriously considering this might be getting overridden '" + methodThatMightBeGettingOverridden + "'"); } World w = typeToCheck.getWorld(); // Look at erasures of parameters (List<String> erased is List) boolean sameParams = true; for (int p = 0, max = methodThatMightBeGettingOverridden.getParameterTypes().length; p < max; p++) { UnresolvedType mtmbgoParameter = methodThatMightBeGettingOverridden.getParameterTypes()[p]; UnresolvedType ptype = methodParamsArray[p]; if (mtmbgoParameter.isTypeVariableReference()) { if (!mtmbgoParameter.resolve(w).isAssignableFrom(ptype.resolve(w))) { sameParams = false; } } else { // old condition: boolean b = !methodThatMightBeGettingOverridden.getParameterTypes()[p].getErasureSignature().equals( methodParamsArray[p].getErasureSignature()); UnresolvedType parameterType = methodThatMightBeGettingOverridden.getParameterTypes()[p]; // Collapse to first bound (isn't that the same as erasure! if (parameterType instanceof UnresolvedTypeVariableReferenceType) { parameterType = ((UnresolvedTypeVariableReferenceType) parameterType).getTypeVariable().getFirstBound(); } if (b) { // !parameterType.resolve(w).equals(parameterType2.resolve(w))) { sameParams = false; } } // // if (!ut.getErasureSignature().equals(ut2.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 // FIXASC Why bother with the return type? If it is incompatible then the code has other problems! if (sameParams) { 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; } // } else if (typeToCheck.isParameterizedType()) { // return methodThatMightBeGettingOverridden.getBackingGenericMember(); } else { 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) { int inheritedModifiers = inheritedMethod.getModifiers(); if (Modifier.isStatic(inheritedModifiers)) { return false; } if (methodMods == inheritedModifiers) { return true; } if (Modifier.isPrivate(inheritedModifiers)) { return false; } boolean isPackageVisible = !Modifier.isPrivate(inheritedModifiers) && !Modifier.isProtected(inheritedModifiers) && !Modifier.isPublic(inheritedModifiers); 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; } } // was: List l = typeToCheck.getInterTypeMungers(); List<ConcreteTypeMunger> l = (typeToCheck.isRawType() ? typeToCheck.getGenericType().getInterTypeMungers() : typeToCheck .getInterTypeMungers()); for (Iterator<ConcreteTypeMunger> iterator = l.iterator(); iterator.hasNext();) { ConcreteTypeMunger 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<String> methodsSet = new HashSet<String>(); for (int i = 0; i < methods.size(); i++) { LazyMethodGen aMethod = 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 = 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<Integer> reportedProblems = new ArrayList<Integer>(); List<DeclareAnnotation> allDecams = world.getDeclareAnnotationOnMethods(); if (allDecams.isEmpty()) { return false; } boolean isChanged = false; // deal with ITDs List<ConcreteTypeMunger> 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<LazyMethodGen> members = clazz.getMethodGens(); List<DeclareAnnotation> decaMs = getMatchingSubset(allDecams, clazz.getType()); if (decaMs.isEmpty()) { return false; // nothing to do } if (!members.isEmpty()) { Set<DeclareAnnotation> unusedDecams = new HashSet<DeclareAnnotation>(); unusedDecams.addAll(decaMs); for (int memberCounter = 0; memberCounter < members.size(); memberCounter++) { LazyMethodGen mg = members.get(memberCounter); if (!mg.getName().startsWith(NameMangler.PREFIX)) { // Single first pass List<DeclareAnnotation> worthRetrying = new ArrayList<DeclareAnnotation>(); boolean modificationOccured = false; List<AnnotationGen> annotationsToAdd = null; for (DeclareAnnotation decaM : decaMs) { 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>(); } AnnotationGen a = ((BcelAnnotation) decaM.getAnnotation()).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, clazz.getConstantPool(), true); annotationsToAdd.add(ag); mg.addAnnotation(decaM.getAnnotation()); AsmRelationshipProvider.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<DeclareAnnotation> forRemoval = new ArrayList<DeclareAnnotation>(); for (DeclareAnnotation decaM : worthRetrying) { 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>(); } AnnotationGen a = ((BcelAnnotation) decaM.getAnnotation()).getBcelAnnotation(); // create copy to get the annotation type into the right constant pool AnnotationGen ag = new AnnotationGen(a, clazz.getConstantPool(), true); annotationsToAdd.add(ag); mg.addAnnotation(decaM.getAnnotation()); AsmRelationshipProvider.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); for (AnnotationGen a : annotationsToAdd) { myGen.addAnnotation(a); } Method newMethod = myGen.getMethod(); members.set(memberCounter, new LazyMethodGen(newMethod, clazz)); } } } checkUnusedDeclareAts(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<DeclareAnnotation> getMatchingSubset(List<DeclareAnnotation> declareAnnotations, ResolvedType type) { List<DeclareAnnotation> subset = new ArrayList<DeclareAnnotation>(); for (DeclareAnnotation da : declareAnnotations) { if (da.couldEverMatch(type)) { subset.add(da); } } return subset; } /** * Get a subset of all the type mungers defined on this aspect */ private List<ConcreteTypeMunger> getITDSubset(LazyClassGen clazz, ResolvedTypeMunger.Kind wantedKind) { List<ConcreteTypeMunger> subset = new ArrayList<ConcreteTypeMunger>(); for (ConcreteTypeMunger typeMunger : clazz.getBcelObjectType().getTypeMungers()) { if (typeMunger.getMunger().getKind() == wantedKind) { subset.add(typeMunger); } } return subset; } public LazyMethodGen locateAnnotationHolderForFieldMunger(LazyClassGen clazz, ConcreteTypeMunger fieldMunger) { NewFieldTypeMunger newFieldMunger = (NewFieldTypeMunger) fieldMunger.getMunger(); ResolvedMember lookingFor = AjcMemberMaker.interFieldInitializer(newFieldMunger.getSignature(), clazz.getType()); for (LazyMethodGen method : clazz.getMethodGens()) { if (method.getName().equals(lookingFor.getName())) { return method; } } return null; } // FIXME asc refactor this to neaten it up public LazyMethodGen locateAnnotationHolderForMethodCtorMunger(LazyClassGen clazz, ConcreteTypeMunger 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); } String name = lookingFor.getName(); String paramSignature = lookingFor.getParameterSignature(); for (LazyMethodGen member : clazz.getMethodGens()) { if (member.getName().equals(name) && member.getParameterSignature().equals(paramSignature)) { return member; } } 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<DeclareAnnotation> decaFs, List<ConcreteTypeMunger> itdFields, List<Integer> reportedErrors) { boolean isChanged = false; for (Iterator<ConcreteTypeMunger> iter = itdFields.iterator(); iter.hasNext();) { BcelTypeMunger fieldMunger = (BcelTypeMunger) iter.next(); ResolvedMember itdIsActually = fieldMunger.getSignature(); Set<DeclareAnnotation> worthRetrying = new LinkedHashSet<DeclareAnnotation>(); boolean modificationOccured = false; for (Iterator<DeclareAnnotation> iter2 = decaFs.iterator(); iter2.hasNext();) { DeclareAnnotation decaF = iter2.next(); if (decaF.matches(itdIsActually, world)) { if (decaF.isRemover()) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, fieldMunger); if (annotationHolder.hasAnnotation(decaF.getAnnotationType())) { isChanged = true; // something to remove annotationHolder.removeAnnotation(decaF.getAnnotationType()); AsmRelationshipProvider.addDeclareAnnotationRelationship(world.getModelAsAsmManager(), decaF.getSourceLocation(), itdIsActually.getSourceLocation(), true); } else { worthRetrying.add(decaF); } } else { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, fieldMunger); if (doesAlreadyHaveAnnotation(annotationHolder, itdIsActually, decaF, reportedErrors)) { continue; // skip this one... } annotationHolder.addAnnotation(decaF.getAnnotation()); AsmRelationshipProvider.addDeclareAnnotationRelationship(world.getModelAsAsmManager(), decaF.getSourceLocation(), itdIsActually.getSourceLocation(), false); 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<DeclareAnnotation> forRemoval = new ArrayList<DeclareAnnotation>(); for (Iterator<DeclareAnnotation> iter2 = worthRetrying.iterator(); iter2.hasNext();) { DeclareAnnotation decaF = iter2.next(); if (decaF.matches(itdIsActually, world)) { if (decaF.isRemover()) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, fieldMunger); if (annotationHolder.hasAnnotation(decaF.getAnnotationType())) { isChanged = true; // something to remove annotationHolder.removeAnnotation(decaF.getAnnotationType()); AsmRelationshipProvider.addDeclareAnnotationRelationship(world.getModelAsAsmManager(), decaF.getSourceLocation(), itdIsActually.getSourceLocation(), true); forRemoval.add(decaF); } } else { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, fieldMunger); if (doesAlreadyHaveAnnotation(annotationHolder, itdIsActually, decaF, reportedErrors)) { continue; // skip this one... } annotationHolder.addAnnotation(decaF.getAnnotation()); AsmRelationshipProvider.addDeclareAnnotationRelationship(world.getModelAsAsmManager(), decaF.getSourceLocation(), itdIsActually.getSourceLocation(), false); 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<DeclareAnnotation> decaMCs, List<ConcreteTypeMunger> itdsForMethodAndConstructor, List<Integer> reportedErrors) { boolean isChanged = false; AsmManager asmManager = world.getModelAsAsmManager(); for (ConcreteTypeMunger methodctorMunger : itdsForMethodAndConstructor) { // for (Iterator iter = itdsForMethodAndConstructor.iterator(); iter.hasNext();) { // BcelTypeMunger methodctorMunger = (BcelTypeMunger) iter.next(); ResolvedMember unMangledInterMethod = methodctorMunger.getSignature(); List<DeclareAnnotation> worthRetrying = new ArrayList<DeclareAnnotation>(); boolean modificationOccured = false; for (Iterator<DeclareAnnotation> iter2 = decaMCs.iterator(); iter2.hasNext();) { DeclareAnnotation decaMC = 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.getAnnotation()); isChanged = true; AsmRelationshipProvider.addDeclareAnnotationRelationship(asmManager, decaMC.getSourceLocation(), unMangledInterMethod.getSourceLocation(), false); 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<DeclareAnnotation> forRemoval = new ArrayList<DeclareAnnotation>(); for (Iterator<DeclareAnnotation> iter2 = worthRetrying.iterator(); iter2.hasNext();) { DeclareAnnotation decaMC = 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.getAnnotation()); unMangledInterMethod.addAnnotation(decaMC.getAnnotation()); AsmRelationshipProvider.addDeclareAnnotationRelationship(asmManager, decaMC.getSourceLocation(), unMangledInterMethod.getSourceLocation(), false); isChanged = true; modificationOccured = true; forRemoval.add(decaMC); } worthRetrying.removeAll(forRemoval); } } } return isChanged; } private boolean dontAddTwice(DeclareAnnotation decaF, AnnotationAJ[] dontAddMeTwice) { for (AnnotationAJ ann : dontAddMeTwice) { if (ann != null && decaF.getAnnotation().getTypeName().equals(ann.getTypeName())) { return true; } } return false; } // 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 /** * Weave any declare @field statements into the fields of the supplied class. This will attempt to apply them to the ITDs too. * * 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) { List<Integer> reportedProblems = new ArrayList<Integer>(); List<DeclareAnnotation> allDecafs = world.getDeclareAnnotationOnFields(); if (allDecafs.isEmpty()) { return false; } boolean typeIsChanged = false; List<ConcreteTypeMunger> relevantItdFields = getITDSubset(clazz, ResolvedTypeMunger.Field); if (relevantItdFields != null) { typeIsChanged = weaveAtFieldRepeatedly(allDecafs, relevantItdFields, reportedProblems); } List<DeclareAnnotation> decafs = getMatchingSubset(allDecafs, clazz.getType()); if (decafs.isEmpty()) { return typeIsChanged; } List<BcelField> fields = clazz.getFieldGens(); if (fields != null) { Set<DeclareAnnotation> unusedDecafs = new HashSet<DeclareAnnotation>(); unusedDecafs.addAll(decafs); for (BcelField field : fields) { if (!field.getName().startsWith(NameMangler.PREFIX)) { // Single first pass Set<DeclareAnnotation> worthRetrying = new LinkedHashSet<DeclareAnnotation>(); boolean modificationOccured = false; AnnotationAJ[] dontAddMeTwice = field.getAnnotations(); // go through all the declare @field statements for (DeclareAnnotation decaf : decafs) { if (decaf.getAnnotation() == null) { return false; } if (decaf.matches(field, world)) { if (decaf.isRemover()) { AnnotationAJ annotation = decaf.getAnnotation(); if (field.hasAnnotation(annotation.getType())) { // something to remove typeIsChanged = true; field.removeAnnotation(annotation); AsmRelationshipProvider.addDeclareAnnotationFieldRelationship(world.getModelAsAsmManager(), decaf.getSourceLocation(), clazz.getName(), field, true); reportFieldAnnotationWeavingMessage(clazz, field, decaf, true); } else { worthRetrying.add(decaf); } unusedDecafs.remove(decaf); } else { if (!dontAddTwice(decaf, dontAddMeTwice)) { if (doesAlreadyHaveAnnotation(field, decaf, reportedProblems)) { // remove the declare @field since don't want an error when the annotation is already there unusedDecafs.remove(decaf); continue; } field.addAnnotation(decaf.getAnnotation()); } AsmRelationshipProvider.addDeclareAnnotationFieldRelationship(world.getModelAsAsmManager(), decaf.getSourceLocation(), clazz.getName(), field, false); reportFieldAnnotationWeavingMessage(clazz, field, decaf, false); typeIsChanged = true; modificationOccured = true; unusedDecafs.remove(decaf); } } else if (!decaf.isStarredAnnotationPattern() || decaf.isRemover()) { 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 with any remaining ones List<DeclareAnnotation> forRemoval = new ArrayList<DeclareAnnotation>(); for (Iterator<DeclareAnnotation> iter = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaF = iter.next(); if (decaF.matches(field, world)) { if (decaF.isRemover()) { AnnotationAJ annotation = decaF.getAnnotation(); if (field.hasAnnotation(annotation.getType())) { // something to remove typeIsChanged = modificationOccured = true; forRemoval.add(decaF); field.removeAnnotation(annotation); AsmRelationshipProvider.addDeclareAnnotationFieldRelationship(world.getModelAsAsmManager(), decaF.getSourceLocation(), clazz.getName(), field, true); reportFieldAnnotationWeavingMessage(clazz, field, decaF, true); } } else { // below code is for recursive things unusedDecafs.remove(decaF); if (doesAlreadyHaveAnnotation(field, decaF, reportedProblems)) { continue; } field.addAnnotation(decaF.getAnnotation()); AsmRelationshipProvider.addDeclareAnnotationFieldRelationship(world.getModelAsAsmManager(), decaF.getSourceLocation(), clazz.getName(), field, false); typeIsChanged = modificationOccured = true; forRemoval.add(decaF); } } } worthRetrying.removeAll(forRemoval); } } } checkUnusedDeclareAts(unusedDecafs, true); } return typeIsChanged; } // 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 checkUnusedDeclareAts(Set<DeclareAnnotation> unusedDecaTs, boolean isDeclareAtField) { for (DeclareAnnotation declA : unusedDecaTs) { // Error if an exact type pattern was specified boolean shouldCheck = declA.isExactPattern() || declA.getSignaturePattern().getExactDeclaringTypes().size() != 0; if (shouldCheck && declA.getKind() != DeclareAnnotation.AT_CONSTRUCTOR) { if (declA.getSignaturePattern().isMatchOnAnyName()) { shouldCheck = false; } else { List<ExactTypePattern> declaringTypePatterns = declA.getSignaturePattern().getExactDeclaringTypes(); if (declaringTypePatterns.size() == 0) { shouldCheck = false; } else { for (ExactTypePattern exactTypePattern : declaringTypePatterns) { if (exactTypePattern.isIncludeSubtypes()) { shouldCheck = false; break; } } } } } if (shouldCheck) { // Quickly check if an ITD supplies the 'missing' member boolean itdMatch = false; List<ConcreteTypeMunger> lst = clazz.getType().getInterTypeMungers(); for (Iterator<ConcreteTypeMunger> iterator = lst.iterator(); iterator.hasNext() && !itdMatch;) { ConcreteTypeMunger element = iterator.next(); if (element.getMunger() instanceof NewFieldTypeMunger) { NewFieldTypeMunger nftm = (NewFieldTypeMunger) element.getMunger(); itdMatch = declA.matches(nftm.getSignature(), world); } else if (element.getMunger() instanceof NewMethodTypeMunger) { NewMethodTypeMunger nmtm = (NewMethodTypeMunger) element.getMunger(); itdMatch = declA.matches(nmtm.getSignature(), world); } else if (element.getMunger() instanceof NewConstructorTypeMunger) { NewConstructorTypeMunger nctm = (NewConstructorTypeMunger) element.getMunger(); itdMatch = declA.matches(nctm.getSignature(), world); } } 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, BcelField theField, DeclareAnnotation decaf, boolean isRemove) { if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { world.getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage( isRemove ? WeaveMessage.WEAVEMESSAGE_REMOVES_ANNOTATION : 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<Integer> reportedProblems) { if (rm.hasAnnotation(deca.getAnnotationType())) { 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.getAnnotationType().toString() }, rm.getSourceLocation(), new ISourceLocation[] { deca.getSourceLocation() }); } } return true; } return false; } private boolean doesAlreadyHaveAnnotation(LazyMethodGen rm, ResolvedMember itdfieldsig, DeclareAnnotation deca, List<Integer> reportedProblems) { if (rm != null && rm.hasAnnotation(deca.getAnnotationType())) { 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.getAnnotationType().toString() }, rm.getSourceLocation(), new ISourceLocation[] { deca.getSourceLocation() }); } } return true; } return false; } private Set<String> findAspectsForMungers(LazyMethodGen mg) { Set<String> aspectsAffectingType = new HashSet<String>(); for (BcelShadow shadow : mg.matchedShadows) { for (ShadowMunger munger : shadow.getMungers()) { if (munger instanceof BcelAdvice) { BcelAdvice bcelAdvice = (BcelAdvice) munger; if (bcelAdvice.getConcreteAspect() != null) { aspectsAffectingType.add(bcelAdvice.getConcreteAspect().getSignature()); } } else { // It is a 'Checker' - we don't need to remember aspects // that only contributed Checkers... } } } return aspectsAffectingType; } private boolean inlineSelfConstructors(List<LazyMethodGen> methodGens) { boolean inlinedSomething = false; for (LazyMethodGen methodGen : methodGens) { if (!methodGen.getName().equals("<init>")) { continue; } InstructionHandle ih = findSuperOrThisCall(methodGen); if (ih != null && isThisCall(ih)) { LazyMethodGen donor = getCalledMethod(ih); inlineMethod(donor, methodGen, ih); inlinedSomething = true; } } return inlinedSomething; } private void positionAndImplement(List<BcelShadow> initializationShadows) { for (BcelShadow s : initializationShadows) { 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<InstructionHandle> rets = new ArrayList<InstructionHandle>(); 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<InstructionHandle> iter = rets.iterator(); iter.hasNext();) { InstructionHandle element = 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 for (InstructionTargeter targeter : element.getTargetersCopy()) { // 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<InstructionHandle> rets = new ArrayList<InstructionHandle>(); 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 (InstructionHandle ret : rets) { // 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(ret, monitorExitBlock); // now move the targeters from the RET to the start of // the monitorexit block for (InstructionTargeter targeter : ret.getTargetersCopy()) { // 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(ret, 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<InstructionHandle> rets = new ArrayList<InstructionHandle>(); 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<InstructionHandle> iter = rets.iterator(); iter.hasNext();) { InstructionHandle element = 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 for (InstructionTargeter targeter : element.getTargetersCopy()) { // 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<InstructionHandle, InstructionHandle> srcToDest = new HashMap<InstructionHandle, InstructionHandle>(); 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<Tag, Tag> tagMap = new HashMap<Tag, Tag>(); Map<BcelShadow, BcelShadow> shadowMap = new HashMap<BcelShadow, BcelShadow>(); 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 = 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, srcToDest.get(oldTargets[k])); } } } } // copy over tags and range attributes Iterator<InstructionTargeter> tIter = src.getTargeters().iterator(); while (tIter.hasNext()) { InstructionTargeter old = tIter.next(); if (old instanceof Tag) { Tag oldTag = (Tag) old; Tag fresh = 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, srcToDest.get(er.getEnd()), 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, srcToDest.get(oldRange.getEnd())); shadowMap.put(oldShadow, freshShadow); // 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<LazyMethodGen>() { public int compare(LazyMethodGen aa, LazyMethodGen bb) { int i = aa.getName().compareTo(bb.getName()); if (i != 0) { return i; } return aa.getSignature().compareTo(bb.getSignature()); } }); for (LazyMethodGen addedMember : addedLazyMethodGens) { clazz.addMethodGen(addedMember); } } // 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<BcelShadow> shadowAccumulator = new ArrayList<BcelShadow>(); boolean isOverweaving = world.isOverWeaving(); 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)) { 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) { // Don't want ajc$preClinit to be considered for matching if (isOverweaving && mg.getName().startsWith(NameMangler.PREFIX)) { return false; } 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<BcelShadow> 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<IfaceInitList> i = addedSuperInitializersAsList.iterator(); i.hasNext();) { IfaceInitList l = 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<ConcreteTypeMunger> list, boolean isStatic) { list = PartialOrder.sort(list); if (list == null) { throw new BCException("circularity in inter-types"); } InstructionList ret = new InstructionList(); for (ConcreteTypeMunger cmunger : list) { 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<BcelShadow> shadowAccumulator) { Instruction i = ih.getInstruction(); // Exception handlers (pr230817) if (canMatch(Shadow.ExceptionHandler) && !Range.isRangeHandle(ih)) { Set<InstructionTargeter> targeters = ih.getTargetersCopy(); for (InstructionTargeter t : targeters) { 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 (InstructionTargeter t2 : targeters) { newNOP.addTargeter(t2); } 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)) { if (i.opcode == Constants.ANEWARRAY) { // ANEWARRAY arrayInstruction = (ANEWARRAY)i; // ObjectType arrayType = i.getLoadClassType(clazz.getConstantPool()); 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(); 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()); 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<BcelShadow> 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<BcelShadow> 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; } /** * Find the specified member in the specified type. * * @param type the type to search for the member * @param methodName the name of the method to find * @param params the method parameters that the discovered method should have */ private ResolvedMember findResolvedMemberNamed(ResolvedType type, String methodName, UnresolvedType[] params) { ResolvedMember[] allMethods = type.getDeclaredMethods(); List<ResolvedMember> candidates = new ArrayList<ResolvedMember>(); for (int i = 0; i < allMethods.length; i++) { ResolvedMember candidate = allMethods[i]; if (candidate.getName().equals(methodName)) { if (candidate.getArity() == params.length) { candidates.add(candidate); } } } if (candidates.size() == 0) { return null; } else if (candidates.size() == 1) { return candidates.get(0); } else { // multiple candidates for (ResolvedMember candidate : candidates) { // These checks will break down with generics... but that would need two ITDs with the same name, same arity and // generics boolean allOK = true; UnresolvedType[] candidateParams = candidate.getParameterTypes(); for (int p = 0; p < candidateParams.length; p++) { if (!candidateParams[p].getErasureSignature().equals(params[p].getErasureSignature())) { allOK = false; break; } } if (allOK) { return candidate; } } } 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 = 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 theRealMember = findResolvedMemberNamed(memberHostType.resolve(world), realthing.getName(), realthing.getParameterTypes()); 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<BcelShadow> 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)) { boolean proceed = true; // overweaving needs to ignore some calls added by the previous weave if (world.isOverWeaving()) { String s = invoke.getClassName(mg.getConstantPool()); // skip all the inc/dec/isValid/etc if (s.length() > 4 && s.charAt(4) == 'a' && (s.equals("org.aspectj.runtime.internal.CFlowCounter") || s.equals("org.aspectj.runtime.internal.CFlowStack") || s .equals("org.aspectj.runtime.reflect.Factory"))) { proceed = false; } else { if (methodName.equals("aspectOf")) { proceed = false; } } } if (proceed) { 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<BcelShadow> shadowAccumulator) { // Duplicate blocks - one with context one without, seems faster than multiple 'ifs' if (captureLowLevelContext) { ContextToken shadowMatchToken = CompilationAndWeavingContext.enteringPhase( CompilationAndWeavingContext.MATCHING_SHADOW, shadow); boolean isMatched = false; Shadow.Kind shadowKind = shadow.getKind(); List<ShadowMunger> candidateMungers = indexedShadowMungers[shadowKind.getKey()]; // System.out.println("Candidates " + candidateMungers); if (candidateMungers != null) { for (ShadowMunger munger : candidateMungers) { 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; Shadow.Kind shadowKind = shadow.getKind(); List<ShadowMunger> candidateMungers = indexedShadowMungers[shadowKind.getKey()]; // System.out.println("Candidates at " + shadowKind + " are " + candidateMungers); if (candidateMungers != null) { for (ShadowMunger munger : candidateMungers) { 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<BcelShadow> 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 (BcelShadow shadow : shadows) { 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 BcelWorld getWorld() { return world; } public void setReweavableMode(boolean mode) { inReweavableMode = mode; } public boolean getReweavableMode() { return inReweavableMode; } @Override public String toString() { return "BcelClassWeaver instance for : " + clazz; } }
353,457
Bug 353457 NPE when saving an aspect - Aspectj Internal Compiler Error
null
resolved fixed
0f506ab
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-08-15T20:28:37Z"
"2011-07-30T21:06: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.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.SourceLocation; import org.aspectj.util.FuzzyBoolean; 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 { public static final ShadowMunger[] NONE = new ShadowMunger[0]; private static int VERSION_1 = 1; // ShadowMunger version for serialization protected static final int ShadowMungerAdvice = 1; protected static final int ShadowMungerDeow = 2; public String handle = null; private int shadowMungerKind; protected int start, end; protected ISourceContext sourceContext; private ISourceLocation sourceLocation; private ISourceLocation binarySourceLocation; private File binaryFile; private ResolvedType declaringType; private boolean isBinary; private boolean checkedIsBinary; protected Pointcut pointcut; protected ShadowMunger() { } public ShadowMunger(Pointcut pointcut, int start, int end, ISourceContext sourceContext, int shadowMungerKind) { this.shadowMungerKind = shadowMungerKind; this.pointcut = pointcut; this.start = start; this.end = end; this.sourceContext = sourceContext; } /** * 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) { // Check the 'cached' exclusion map Set<ResolvedType> excludedTypes = world.getExclusionMap().get(declaringType); ResolvedType type = shadow.getEnclosingType().resolve(world); if (excludedTypes != null && excludedTypes.contains(type)) { return false; } boolean b = scoped.matches(type, TypePattern.STATIC).alwaysTrue(); if (!b) { if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) { world.getMessageHandler().handleMessage( MessageUtil.info("Type '" + type.getName() + "' not woven by aspect '" + declaringType.getName() + "' due to scope exclusion in XML definition")); } if (excludedTypes == null) { excludedTypes = new HashSet<ResolvedType>(); excludedTypes.add(type); world.getExclusionMap().put(declaringType, excludedTypes); } else { excludedTypes.add(type); } return false; } } } if (world.areInfoMessagesEnabled() && world.isTimingEnabled()) { long starttime = System.nanoTime(); FuzzyBoolean isMatch = pointcut.match(shadow); long endtime = System.nanoTime(); world.record(pointcut, endtime - starttime); return isMatch.maybeTrue(); } else { FuzzyBoolean isMatch = pointcut.match(shadow); return isMatch.maybeTrue(); } } 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; } 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; } public abstract ResolvedType getConcreteAspect(); /** * 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(); if (s.indexOf("!") == -1) { File f = getDeclaringType().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"; } binaryFile = new File(s + "!" + path); } else { binaryFile = new File(s); } } 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 calculating 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; } 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 implement was successful */ public abstract boolean implementOn(Shadow shadow); public abstract ShadowMunger parameterizeWith(ResolvedType declaringType, Map<String, UnresolvedType> typeVariableMap); /** * @return a Collection of ResolvedTypes for all checked exceptions that might be thrown by this munger */ public abstract Collection<ResolvedType> getThrownExceptions(); /** * Does the munger have to check that its exception are accepted by the shadow ? It is not the case for annotation style around * advice, for example: 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 thrown based on the shadow */ public abstract boolean mustCheckExceptions(); public void write(CompressingDataOutputStream stream) throws IOException { stream.writeInt(VERSION_1); stream.writeInt(shadowMungerKind); // determines real subclass stream.writeInt(start); stream.writeInt(end); PersistenceSupport.write(stream, sourceContext); PersistenceSupport.write(stream, sourceLocation); PersistenceSupport.write(stream, binarySourceLocation); PersistenceSupport.write(stream, binaryFile); declaringType.write(stream); stream.writeBoolean(isBinary); stream.writeBoolean(checkedIsBinary); pointcut.write(stream); } // // public static ShadowMunger read(VersionedDataInputStream stream, World world) throws IOException { // stream.readInt(); // int kind = stream.readInt(); // ShadowMunger newShadowMunger = null; // switch (kind) { // case ShadowMungerAdvice: // // world.getWeavingSupport().createAdviceMunger(attribute, pointcut, signature) // case ShadowMungerDeow: // newShadowMunger = Checker.read(stream, world); // default: // throw new IllegalStateException("Unexpected type of shadow munger found on deserialization: " + kind); // } // newShadowMunger.binaryFile = null; // } }
354,947
Bug 354947 Nullpointer-Exception while parsing definition file (aop.xml) in DocumentParser
Build Identifier: 20100617-1415 With an activated NullpointerException-Breakpoint i recently stumpled upon a thrown NPE in the DocumentParser.parse()-method (Line 106): public static Definition parse(final URL url) throws Exception { InputStream in = null; try { if (CACHE && parsedFiles.containsKey(url.toString())) { return parsedFiles.get(url.toString()); } Definition def=null; if(LIGHTPARSER){ def = SimpleAOPParser.parse(url); }else{ def = saxParsing(url); } if (CACHE && def.getAspectClassNames().size() > 0) { parsedFiles.put(url.toString(), def); } return def; } finally { try { in.close(); } catch (Throwable t) { } } } ... The parsing of the configuration file works fine, merely the InputStream seems not to be used anymore. Reproducible: Always
resolved fixed
e71e287
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-08-17T15:54:09Z"
"2011-08-17T14:06: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 * Abraham Nevado - Lucierna simple caching strategy *******************************************************************************/ package org.aspectj.weaver.loadtime.definition; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Hashtable; 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 Alexandre Vasseur * @author A. Nevado * @author Andy Clement */ 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"; 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 REQUIRES_ATTRIBUTE = "requires"; 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 static Hashtable<String, Definition> parsedFiles = new Hashtable<String, Definition>(); private static final boolean CACHE; private static final boolean LIGHTPARSER; static { boolean value = false; try { value = System.getProperty("org.aspectj.weaver.loadtime.configuration.cache", "true").equalsIgnoreCase("true"); } catch (Throwable t) { t.printStackTrace(); } CACHE = value; value = false; try { value = System.getProperty("org.aspectj.weaver.loadtime.configuration.lightxmlparser", "false").equalsIgnoreCase("true"); } catch (Throwable t) { t.printStackTrace(); } LIGHTPARSER = value; } private DocumentParser() { m_definition = new Definition(); } public static Definition parse(final URL url) throws Exception { InputStream in = null; try { if (CACHE && parsedFiles.containsKey(url.toString())) { return parsedFiles.get(url.toString()); } Definition def=null; if(LIGHTPARSER){ def = SimpleAOPParser.parse(url); }else{ def = saxParsing(url); } if (CACHE && def.getAspectClassNames().size() > 0) { parsedFiles.put(url.toString(), def); } return def; } finally { try { in.close(); } catch (Throwable t) { } } } private static Definition saxParsing(URL url) throws SAXException, ParserConfigurationException, IOException { 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); InputStream in = url.openStream(); xmlReader.parse(new InputSource(in)); return parser.m_definition; } 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 = DocumentParser.class.getResourceAsStream("/aspectj_1_5_0.dtd"); 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)); String requiredType = attributes.getValue(REQUIRES_ATTRIBUTE); if (!isNull(name)) { m_definition.getAspectClassNames().add(name); if (scopePattern != null) { m_definition.addScopedAspect(name, scopePattern); } if (requiredType != null) { m_definition.setAspectRequires(name, requiredType); } } } 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")); } }
359,332
Bug 359332 NPE in AjBuildManager.java:528 after non-Java/AJ file was renamed
Build Identifier: Upon using Eclipse's "Rename Resource" dialog to rename my project's "src/main/resources/META-INF/spring/email.properties" file to "scheduler.properties" in the same directory, Eclipse displayed the "AspectJ Internal Compiler Error" dialog with this stack trace: java.io.FileNotFoundException at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:120) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.copyResourcesFromFile(AjBuildManager.java:528) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.copyResourcesToDestination(AjBuildManager.java:466) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performBuild(AjBuildManager.java:363) ... e error: FileNotFoundException thrown: /Users/aswan/projects/foo/src/main/resources/META-INF/spring/email.properties (No such file or directory) Reproducible: Couldn't Reproduce Steps to Reproduce: N/A
resolved fixed
14a6eac
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-09-29T16:34:42Z"
"2011-09-29T04:20:00Z"
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<File> 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) { BcelWorld bcelWorld = getBcelWorld(); bcelWorld.reportTimers(); bcelWorld.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 = 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<File, List<String>> outputDirsAndAspects = findOutputDirsForAspects(); Set<Map.Entry<File, List<String>>> outputDirs = outputDirsAndAspects.entrySet(); for (Iterator<Map.Entry<File, List<String>>> iterator = outputDirs.iterator(); iterator.hasNext();) { Map.Entry<File, List<String>> entry = iterator.next(); File outputDir = entry.getKey(); List<String> aspects = 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<File, List<String>> outputDirsToAspects = new HashMap<File, List<String>>(); Map<String, char[]> 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<String> aspectNames = new ArrayList<String>(); if (aspectNamesToFileNames != null) { Set<String> keys = aspectNamesToFileNames.keySet(); for (String name : keys) { 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<String>()); } if (aspectNamesToFileNames != null) { Set<Map.Entry<String, char[]>> entrySet = aspectNamesToFileNames.entrySet(); for (Iterator<Map.Entry<String, char[]>> iterator = entrySet.iterator(); iterator.hasNext();) { Map.Entry<String, char[]> entry = iterator.next(); String aspectName = entry.getKey(); char[] fileName = entry.getValue(); File outputDir = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass( new File(new String(fileName))); if (!outputDirsToAspects.containsKey(outputDir)) { outputDirsToAspects.put(outputDir, new ArrayList<String>()); } ((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<String, IProgramElement>()); // 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.setTiming(buildConfig.isTiming(), false); 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 (File inJar : buildConfig.getInJars()) { List<UnwovenClassFile> unwovenClasses = bcelWeaver.addJarFile(inJar, outputDir, false); state.recordBinarySource(inJar.getPath(), unwovenClasses); } for (File inPathElement : buildConfig.getInpath()) { 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<UnwovenClassFile> 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<UnwovenClassFile> ucfl = new ArrayList<UnwovenClassFile>(); 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<File> 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<File> fIterator = files.iterator(); fIterator.hasNext();) { File f = 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<String> cps = buildConfig.getFullClasspath(); Dump.saveFullClasspath(cps); String[] classpaths = new String[cps.size()]; for (int i = 0; i < cps.size(); i++) { classpaths[i] = cps.get(i); } environment = new StatefulNameEnvironment(getLibraryAccess(classpaths, filenames), state.getClassNameToFileMap(), state); state.setNameEnvironment(environment); } else { ((StatefulNameEnvironment) environment).update(state.getClassNameToFileMap(), state.deltaAddedClasses); state.deltaAddedClasses.clear(); } 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; // le = 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<ClassFile> classFiles = unitResult.compiledTypes.values(); boolean shouldAddAspectName = (buildConfig.getOutxmlName() != null); for (Iterator<ClassFile> iter = classFiles.iterator(); iter.hasNext();) { 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); getWorld().classWriteEvent(classFile.getCompoundName()); 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(); } try { BufferedOutputStream os = FileUtil.makeOutputStream(new File(outFile)); os.write(classFile.getBytes()); os.close(); } catch (FileNotFoundException fnfe) { IMessage msg = new Message("unable to write out class file: '" + filename + "' - reason: " + fnfe.getMessage(), IMessage.ERROR, null, new SourceLocation(new File(outFile), 0)); handler.handleMessage(msg); } 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 if (p.isFile() && p.getName().indexOf("org.aspectj.runtime") != -1) { // likely to be a variant from the springsource bundle repo b272591 return null; } 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(), buildConfig.isMakeReflectable(), state); } else { return new AjCompilerAdapter(forCompiler, batchCompile, getBcelWorld(), getWeaver(), factory, getInterimResultRequestor(), progressListener, this, // IOutputFilenameProvider this, // IBinarySourceProvider state.getBinarySourceMap(), buildConfig.isTerminateAfterCompilation(), buildConfig.getProceedOnError(), buildConfig.isNoAtAspectJAnnotationProcessing(), buildConfig.isMakeReflectable(), 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; } }
362,956
Bug 362956 neo4j NPE
java.lang.NullPointerException at org.aspectj.weaver.patterns.ExactAnnotationTypePattern.matches(ExactAnnotationTypePattern.java:128) at org.aspectj.weaver.patterns.ExactAnnotationTypePattern.matches(ExactAnnotationTypePattern.java:96) at org.aspectj.weaver.patterns.AndAnnotationTypePattern.matches(AndAnnotationTypePattern.java:42) at org.aspectj.weaver.patterns.AnyWithAnnotationTypePattern.matchesExactly(AnyWithAnnotationTypePattern.java:55) at org.aspectj.weaver.patterns.TypePattern.matchesStatically(TypePattern.java:132) at org.aspectj.weaver.patterns.TypePattern.matches(TypePattern.java:146) at org.aspectj.weaver.patterns.SignaturePattern.couldEverMatch(SignaturePattern.java:999) at org.aspectj.weaver.patterns.DeclareAnnotation.couldEverMatch(DeclareAnnotation.java:483) at org.aspectj.weaver.bcel.BcelClassWeaver.getMatchingSubset(BcelClassWeaver.java:1065) at org.aspectj.weaver.bcel.BcelClassWeaver.weaveDeclareAtField(BcelClassWeaver.java:1301) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:445) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:100) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1687) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1631) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1394) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1180) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.weaveQueuedEntries(AjPipeliningCompilerAdapter.java:514) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.queueForWeaving(AjPipeliningCompilerAdapter.java:447) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.afterProcessing(AjPipeliningCompilerAdapter.java:432) 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:1021) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performBuild(AjBuildManager.java:268) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:181) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:112) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:371)
resolved fixed
942da06
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2011-11-07T16:17:10Z"
"2011-11-04T23:40:00Z"
org.aspectj.matcher/src/org/aspectj/weaver/ReferenceType.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 * Andy Clement - June 2005 - separated out from ResolvedType * ******************************************************************/ package org.aspectj.weaver; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.PerClause; /** * A reference type represents some 'real' type, not a primitive, not an array - but a real type, for example java.util.List. Each * ReferenceType has a delegate that is the underlying artifact - either an eclipse artifact or a bcel artifact. If the type * represents a raw type (i.e. there is a generic form) then the genericType field is set to point to the generic type. If it is for * a parameterized type then the generic type is also set to point to the generic form. */ public class ReferenceType extends ResolvedType { public static final ReferenceType[] EMPTY_ARRAY = new ReferenceType[0]; /** * For generic types, this list holds references to all the derived raw and parameterized versions. We need this so that if the * generic delegate is swapped during incremental compilation, the delegate of the derivatives is swapped also. */ private final Set<ReferenceType> derivativeTypes = new HashSet<ReferenceType>(); /** * For parameterized types (or the raw type) - this field points to the actual reference type from which they are derived. */ ReferenceType genericType = null; ReferenceTypeDelegate delegate = null; int startPos = 0; int endPos = 0; // cached values for members ResolvedMember[] parameterizedMethods = null; ResolvedMember[] parameterizedFields = null; ResolvedMember[] parameterizedPointcuts = null; WeakReference<ResolvedType[]> parameterizedInterfaces = new WeakReference<ResolvedType[]>(null); Collection<Declare> parameterizedDeclares = null; // Collection parameterizedTypeMungers = null; // During matching it can be necessary to temporary mark types as annotated. For example // a declare @type may trigger a separate declare parents to match, and so the annotation // is temporarily held against the referencetype, the annotation will be properly // added to the class during weaving. private ResolvedType[] annotationTypes = null; private AnnotationAJ[] annotations = null; // Similarly these are temporary replacements and additions for the superclass and // superinterfaces private ResolvedType newSuperclass; private ResolvedType[] newInterfaces; // ??? should set delegate before any use public ReferenceType(String signature, World world) { super(signature, world); } public ReferenceType(String signature, String signatureErasure, World world) { super(signature, signatureErasure, world); } public static ReferenceType fromTypeX(UnresolvedType tx, World world) { ReferenceType rt = new ReferenceType(tx.getErasureSignature(), world); rt.typeKind = tx.typeKind; return rt; } /** * Constructor used when creating a parameterized type. */ public ReferenceType(ResolvedType theGenericType, ResolvedType[] theParameters, World aWorld) { super(makeParameterizedSignature(theGenericType, theParameters), theGenericType.signatureErasure, aWorld); ReferenceType genericReferenceType = (ReferenceType) theGenericType; this.typeParameters = theParameters; this.genericType = genericReferenceType; this.typeKind = TypeKind.PARAMETERIZED; this.delegate = genericReferenceType.getDelegate(); genericReferenceType.addDependentType(this); } /** * Constructor used when creating a raw type. */ // public ReferenceType( // ResolvedType theGenericType, // World aWorld) { // super(theGenericType.getErasureSignature(), // theGenericType.getErasureSignature(), // aWorld); // ReferenceType genericReferenceType = (ReferenceType) theGenericType; // this.typeParameters = null; // this.genericType = genericReferenceType; // this.typeKind = TypeKind.RAW; // this.delegate = genericReferenceType.getDelegate(); // genericReferenceType.addDependentType(this); // } synchronized void addDependentType(ReferenceType dependent) { this.derivativeTypes.add(dependent); } @Override public String getSignatureForAttribute() { if (genericType == null || typeParameters == null) { return getSignature(); } return makeDeclaredSignature(genericType, typeParameters); } /** * Create a reference type for a generic type */ public ReferenceType(UnresolvedType genericType, World world) { super(genericType.getSignature(), world); typeKind = TypeKind.GENERIC; } @Override public boolean isClass() { return getDelegate().isClass(); } @Override public int getCompilerVersion() { return getDelegate().getCompilerVersion(); } @Override public boolean isGenericType() { return !isParameterizedType() && !isRawType() && getDelegate().isGeneric(); } public String getGenericSignature() { String sig = getDelegate().getDeclaredGenericSignature(); return (sig == null) ? "" : sig; } @Override public AnnotationAJ[] getAnnotations() { return getDelegate().getAnnotations(); } @Override public void addAnnotation(AnnotationAJ annotationX) { if (annotations == null) { annotations = new AnnotationAJ[1]; annotations[0] = annotationX; } else { AnnotationAJ[] newAnnotations = new AnnotationAJ[annotations.length + 1]; System.arraycopy(annotations, 0, newAnnotations, 1, annotations.length); newAnnotations[0] = annotationX; annotations = newAnnotations; } addAnnotationType(annotationX.getType()); } public boolean hasAnnotation(UnresolvedType ofType) { boolean onDelegate = getDelegate().hasAnnotation(ofType); if (onDelegate) { return true; } if (annotationTypes != null) { for (int i = 0; i < annotationTypes.length; i++) { if (annotationTypes[i].equals(ofType)) { return true; } } } return false; } private void addAnnotationType(ResolvedType ofType) { if (annotationTypes == null) { annotationTypes = new ResolvedType[1]; annotationTypes[0] = ofType; } else { ResolvedType[] newAnnotationTypes = new ResolvedType[annotationTypes.length + 1]; System.arraycopy(annotationTypes, 0, newAnnotationTypes, 1, annotationTypes.length); newAnnotationTypes[0] = ofType; annotationTypes = newAnnotationTypes; } } @Override public ResolvedType[] getAnnotationTypes() { if (getDelegate() == null) { throw new BCException("Unexpected null delegate for type " + this.getName()); } if (annotationTypes == null) { // there are no extras: return getDelegate().getAnnotationTypes(); } else { ResolvedType[] delegateAnnotationTypes = getDelegate().getAnnotationTypes(); ResolvedType[] result = new ResolvedType[annotationTypes.length + delegateAnnotationTypes.length]; System.arraycopy(delegateAnnotationTypes, 0, result, 0, delegateAnnotationTypes.length); System.arraycopy(annotationTypes, 0, result, delegateAnnotationTypes.length, annotationTypes.length); return result; } } @Override public String getNameAsIdentifier() { return getRawName().replace('.', '_'); } @Override public AnnotationAJ getAnnotationOfType(UnresolvedType ofType) { AnnotationAJ[] axs = getDelegate().getAnnotations(); if (axs == null) { if (annotations != null) { String searchSig = ofType.getSignature(); for (int i = 0; i < annotations.length; i++) { if (annotations[i].getTypeSignature().equals(searchSig)) { return annotations[i]; } } } return null; } for (int i = 0; i < axs.length; i++) { if (axs[i].getTypeSignature().equals(ofType.getSignature())) { return axs[i]; } } return null; } @Override public boolean isAspect() { return getDelegate().isAspect(); } @Override public boolean isAnnotationStyleAspect() { return getDelegate().isAnnotationStyleAspect(); } @Override public boolean isEnum() { return getDelegate().isEnum(); } @Override public boolean isAnnotation() { return getDelegate().isAnnotation(); } @Override public boolean isAnonymous() { return getDelegate().isAnonymous(); } @Override public boolean isNested() { return getDelegate().isNested(); } public ResolvedType getOuterClass() { return getDelegate().getOuterClass(); } public String getRetentionPolicy() { return getDelegate().getRetentionPolicy(); } @Override public boolean isAnnotationWithRuntimeRetention() { return getDelegate().isAnnotationWithRuntimeRetention(); } @Override public boolean canAnnotationTargetType() { return getDelegate().canAnnotationTargetType(); } @Override public AnnotationTargetKind[] getAnnotationTargetKinds() { return getDelegate().getAnnotationTargetKinds(); } // true iff the statement "this = (ThisType) other" would compile @Override public boolean isCoerceableFrom(ResolvedType o) { ResolvedType other = o.resolve(world); if (this.isAssignableFrom(other) || other.isAssignableFrom(this)) { return true; } if (this.isParameterizedType() && other.isParameterizedType()) { return isCoerceableFromParameterizedType(other); } if (this.isParameterizedType() && other.isRawType()) { return ((ReferenceType) this.getRawType()).isCoerceableFrom(other.getGenericType()); } if (this.isRawType() && other.isParameterizedType()) { return this.getGenericType().isCoerceableFrom((other.getRawType())); } if (!this.isInterface() && !other.isInterface()) { return false; } if (this.isFinal() || other.isFinal()) { return false; } // ??? needs to be Methods, not just declared methods? JLS 5.5 unclear ResolvedMember[] a = getDeclaredMethods(); ResolvedMember[] b = other.getDeclaredMethods(); // ??? is this cast // always safe for (int ai = 0, alen = a.length; ai < alen; ai++) { for (int bi = 0, blen = b.length; bi < blen; bi++) { if (!b[bi].isCompatibleWith(a[ai])) { return false; } } } return true; } private final boolean isCoerceableFromParameterizedType(ResolvedType other) { if (!other.isParameterizedType()) { return false; } ResolvedType myRawType = getRawType(); ResolvedType theirRawType = other.getRawType(); if (myRawType == theirRawType || myRawType.isCoerceableFrom(theirRawType)) { if (getTypeParameters().length == other.getTypeParameters().length) { // there's a chance it can be done ResolvedType[] myTypeParameters = getResolvedTypeParameters(); ResolvedType[] theirTypeParameters = other.getResolvedTypeParameters(); for (int i = 0; i < myTypeParameters.length; i++) { if (myTypeParameters[i] != theirTypeParameters[i]) { // thin ice now... but List<String> may still be // coerceable from e.g. List<T> if (myTypeParameters[i].isGenericWildcard()) { BoundedReferenceType wildcard = (BoundedReferenceType) myTypeParameters[i]; if (!wildcard.canBeCoercedTo(theirTypeParameters[i])) { return false; } } else if (myTypeParameters[i].isTypeVariableReference()) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) myTypeParameters[i]; TypeVariable tv = tvrt.getTypeVariable(); tv.resolve(world); if (!tv.canBeBoundTo(theirTypeParameters[i])) { return false; } } else if (theirTypeParameters[i].isTypeVariableReference()) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) theirTypeParameters[i]; TypeVariable tv = tvrt.getTypeVariable(); tv.resolve(world); if (!tv.canBeBoundTo(myTypeParameters[i])) { return false; } } else if (theirTypeParameters[i].isGenericWildcard()) { BoundedReferenceType wildcard = (BoundedReferenceType) theirTypeParameters[i]; if (!wildcard.canBeCoercedTo(myTypeParameters[i])) { return false; } } else { return false; } } } return true; } // } else { // // we do this walk for situations like the following: // // Base<T>, Sub<S,T> extends Base<S> // // is Sub<Y,Z> coerceable from Base<X> ??? // for (Iterator i = getDirectSupertypes(); i.hasNext();) { // ReferenceType parent = (ReferenceType) i.next(); // if (parent.isCoerceableFromParameterizedType(other)) // return true; // } } return false; } @Override public boolean isAssignableFrom(ResolvedType other) { return isAssignableFrom(other, false); } // TODO rewrite this method - it is a terrible mess // true iff the statement "this = other" would compile. @Override public boolean isAssignableFrom(ResolvedType other, boolean allowMissing) { if (other.isPrimitiveType()) { if (!world.isInJava5Mode()) { return false; } if (ResolvedType.validBoxing.contains(this.getSignature() + other.getSignature())) { return true; } } if (this == other) { return true; } if (this.getSignature().equals("Ljava/lang/Object;")) { return true; } if (!isTypeVariableReference() && other.getSignature().equals("Ljava/lang/Object;")) { return false; } boolean thisRaw = this.isRawType(); if (thisRaw && other.isParameterizedOrGenericType()) { return isAssignableFrom(other.getRawType()); } boolean thisGeneric = this.isGenericType(); if (thisGeneric && other.isParameterizedOrRawType()) { return isAssignableFrom(other.getGenericType()); } if (this.isParameterizedType()) { // look at wildcards... if (((ReferenceType) this.getRawType()).isAssignableFrom(other)) { boolean wildcardsAllTheWay = true; ResolvedType[] myParameters = this.getResolvedTypeParameters(); for (int i = 0; i < myParameters.length; i++) { if (!myParameters[i].isGenericWildcard()) { wildcardsAllTheWay = false; } else { BoundedReferenceType boundedRT = (BoundedReferenceType) myParameters[i]; if (boundedRT.isExtends() || boundedRT.isSuper()) { wildcardsAllTheWay = false; } } } if (wildcardsAllTheWay && !other.isParameterizedType()) { return true; } // we have to match by parameters one at a time ResolvedType[] theirParameters = other.getResolvedTypeParameters(); boolean parametersAssignable = true; if (myParameters.length == theirParameters.length) { for (int i = 0; i < myParameters.length && parametersAssignable; i++) { if (myParameters[i] == theirParameters[i]) { continue; } // dont do this: pr253109 // if (myParameters[i].isAssignableFrom(theirParameters[i], allowMissing)) { // continue; // } ResolvedType mp = myParameters[i]; ResolvedType tp = theirParameters[i]; if (mp.isParameterizedType() && tp.isParameterizedType()) { if (mp.getGenericType().equals(tp.getGenericType())) { UnresolvedType[] mtps = mp.getTypeParameters(); UnresolvedType[] ttps = tp.getTypeParameters(); for (int ii = 0; ii < mtps.length; ii++) { if (mtps[ii].isTypeVariableReference() && ttps[ii].isTypeVariableReference()) { TypeVariable mtv = ((TypeVariableReferenceType) mtps[ii]).getTypeVariable(); boolean b = mtv.canBeBoundTo((ResolvedType) ttps[ii]); if (!b) {// TODO incomplete testing here I think parametersAssignable = false; break; } } else { parametersAssignable = false; break; } } continue; } else { parametersAssignable = false; break; } } if (myParameters[i].isTypeVariableReference() && theirParameters[i].isTypeVariableReference()) { TypeVariable myTV = ((TypeVariableReferenceType) myParameters[i]).getTypeVariable(); // TypeVariable theirTV = ((TypeVariableReferenceType) theirParameters[i]).getTypeVariable(); boolean b = myTV.canBeBoundTo(theirParameters[i]); if (!b) {// TODO incomplete testing here I think parametersAssignable = false; break; } else { continue; } } if (!myParameters[i].isGenericWildcard()) { parametersAssignable = false; break; } else { BoundedReferenceType wildcardType = (BoundedReferenceType) myParameters[i]; if (!wildcardType.alwaysMatches(theirParameters[i])) { parametersAssignable = false; break; } } } } else { parametersAssignable = false; } if (parametersAssignable) { return true; } } } // eg this=T other=Ljava/lang/Object; if (isTypeVariableReference() && !other.isTypeVariableReference()) { TypeVariable aVar = ((TypeVariableReference) this).getTypeVariable(); return aVar.resolve(world).canBeBoundTo(other); } if (other.isTypeVariableReference()) { TypeVariableReferenceType otherType = (TypeVariableReferenceType) other; if (this instanceof TypeVariableReference) { return ((TypeVariableReference) this).getTypeVariable().resolve(world) .canBeBoundTo(otherType.getTypeVariable().getFirstBound().resolve(world));// pr171952 // return // ((TypeVariableReference)this).getTypeVariable()==otherType // .getTypeVariable(); } else { // FIXME asc should this say canBeBoundTo?? return this.isAssignableFrom(otherType.getTypeVariable().getFirstBound().resolve(world)); } } if (allowMissing && other.isMissing()) { return false; } ResolvedType[] interfaces = other.getDeclaredInterfaces(); for (ResolvedType intface : interfaces) { boolean b; if (thisRaw && intface.isParameterizedOrGenericType()) { b = this.isAssignableFrom(intface.getRawType(), allowMissing); } else { b = this.isAssignableFrom(intface, allowMissing); } if (b) { return true; } } ResolvedType superclass = other.getSuperclass(); if (superclass != null) { boolean b; if (thisRaw && superclass.isParameterizedOrGenericType()) { b = this.isAssignableFrom(superclass.getRawType(), allowMissing); } else { b = this.isAssignableFrom(superclass, allowMissing); } if (b) { return true; } } return false; } @Override public ISourceContext getSourceContext() { return getDelegate().getSourceContext(); } @Override public ISourceLocation getSourceLocation() { ISourceContext isc = getDelegate().getSourceContext(); return isc.makeSourceLocation(new Position(startPos, endPos)); } @Override public boolean isExposedToWeaver() { return (getDelegate() == null) || delegate.isExposedToWeaver(); } @Override public WeaverStateInfo getWeaverState() { return getDelegate().getWeaverState(); } @Override public ResolvedMember[] getDeclaredFields() { if (parameterizedFields != null) { return parameterizedFields; } if (isParameterizedType() || isRawType()) { ResolvedMember[] delegateFields = getDelegate().getDeclaredFields(); parameterizedFields = new ResolvedMember[delegateFields.length]; for (int i = 0; i < delegateFields.length; i++) { parameterizedFields[i] = delegateFields[i].parameterizedWith(getTypesForMemberParameterization(), this, isParameterizedType()); } return parameterizedFields; } else { return getDelegate().getDeclaredFields(); } } /** * Find out from the generic signature the true signature of any interfaces I implement. If I am parameterized, these may then * need to be parameterized before returning. */ @Override public ResolvedType[] getDeclaredInterfaces() { ResolvedType[] interfaces = parameterizedInterfaces.get(); if (interfaces != null) { return interfaces; } ResolvedType[] delegateInterfaces = getDelegate().getDeclaredInterfaces(); if (isRawType()) { if (newInterfaces!=null) { throw new IllegalStateException("The raw type should never be accumulating new interfaces, they should be on the generic type. Type is "+this.getName()); } ResolvedType[] newInterfacesFromGenericType = genericType.newInterfaces; if (newInterfacesFromGenericType!=null) { ResolvedType[] extraInterfaces = new ResolvedType[delegateInterfaces.length + newInterfacesFromGenericType.length]; System.arraycopy(delegateInterfaces, 0, extraInterfaces, 0, delegateInterfaces.length); System.arraycopy(newInterfacesFromGenericType, 0, extraInterfaces, delegateInterfaces.length, newInterfacesFromGenericType.length); delegateInterfaces = extraInterfaces; } } else if (newInterfaces != null) { // OPTIMIZE does this part of the method trigger often? ResolvedType[] extraInterfaces = new ResolvedType[delegateInterfaces.length + newInterfaces.length]; System.arraycopy(delegateInterfaces, 0, extraInterfaces, 0, delegateInterfaces.length); System.arraycopy(newInterfaces, 0, extraInterfaces, delegateInterfaces.length, newInterfaces.length); delegateInterfaces = extraInterfaces; } if (isParameterizedType()) { // UnresolvedType[] paramTypes = // getTypesForMemberParameterization(); interfaces = new ResolvedType[delegateInterfaces.length]; for (int i = 0; i < delegateInterfaces.length; i++) { // We may have to sub/super set the set of parametertypes if the // implemented interface // needs more or less than this type does. (pr124803/pr125080) if (delegateInterfaces[i].isParameterizedType()) { interfaces[i] = delegateInterfaces[i].parameterize(getMemberParameterizationMap()).resolve(world); } else { interfaces[i] = delegateInterfaces[i]; } } parameterizedInterfaces = new WeakReference<ResolvedType[]>(interfaces); return interfaces; } else if (isRawType()) { UnresolvedType[] paramTypes = getTypesForMemberParameterization(); interfaces = new ResolvedType[delegateInterfaces.length]; for (int i = 0, max = interfaces.length; i < max; i++) { interfaces[i] = delegateInterfaces[i]; if (interfaces[i].isGenericType()) { // a generic supertype of a raw type is replaced by its raw // equivalent interfaces[i] = interfaces[i].getRawType().resolve(getWorld()); } else if (interfaces[i].isParameterizedType()) { // a parameterized supertype collapses any type vars to // their upper bounds UnresolvedType[] toUseForParameterization = determineThoseTypesToUse(interfaces[i], paramTypes); interfaces[i] = interfaces[i].parameterizedWith(toUseForParameterization); } } parameterizedInterfaces = new WeakReference<ResolvedType[]>(interfaces); return interfaces; } if (getDelegate().isCacheable()) { parameterizedInterfaces = new WeakReference<ResolvedType[]>(delegateInterfaces); } return delegateInterfaces; } // private String toString(ResolvedType[] delegateInterfaces) { // StringBuffer sb = new StringBuffer(); // if (delegateInterfaces != null) { // for (ResolvedType rt : delegateInterfaces) { // sb.append(rt).append(" "); // } // } // return sb.toString(); // } /** * Locates the named type variable in the list of those on this generic type and returns the type parameter from the second list * supplied. Returns null if it can't be found */ // private UnresolvedType findTypeParameterInList(String name, // TypeVariable[] tvarsOnThisGenericType, UnresolvedType[] // paramTypes) { // int position = -1; // for (int i = 0; i < tvarsOnThisGenericType.length; i++) { // TypeVariable tv = tvarsOnThisGenericType[i]; // if (tv.getName().equals(name)) position = i; // } // if (position == -1 ) return null; // return paramTypes[position]; // } /** * It is possible this type has multiple type variables but the interface we are about to parameterize only uses a subset - this * method determines the subset to use by looking at the type variable names used. For example: <code> * class Foo<T extends String,E extends Number> implements SuperInterface<T> {} * </code> where <code> * interface SuperInterface<Z> {} * </code> In that example, a use of the 'Foo' raw type should know that it implements the SuperInterface<String>. */ private UnresolvedType[] determineThoseTypesToUse(ResolvedType parameterizedInterface, UnresolvedType[] paramTypes) { // What are the type parameters for the supertype? UnresolvedType[] tParms = parameterizedInterface.getTypeParameters(); UnresolvedType[] retVal = new UnresolvedType[tParms.length]; // Go through the supertypes type parameters, if any of them is a type // variable, use the // real type variable on the declaring type. // it is possibly overkill to look up the type variable - ideally the // entry in the type parameter list for the // interface should be the a ref to the type variable in the current // type ... but I'm not 100% confident right now. for (int i = 0; i < tParms.length; i++) { UnresolvedType tParm = tParms[i]; if (tParm.isTypeVariableReference()) { TypeVariableReference tvrt = (TypeVariableReference) tParm; TypeVariable tv = tvrt.getTypeVariable(); int rank = getRank(tv.getName()); // -1 probably means it is a reference to a type variable on the // outer generic type (see pr129566) if (rank != -1) { retVal[i] = paramTypes[rank]; } else { retVal[i] = tParms[i]; } } else { retVal[i] = tParms[i]; } } return retVal; } /** * Returns the position within the set of type variables for this type for the specified type variable name. Returns -1 if there * is no type variable with the specified name. */ private int getRank(String tvname) { TypeVariable[] thisTypesTVars = getGenericType().getTypeVariables(); for (int i = 0; i < thisTypesTVars.length; i++) { TypeVariable tv = thisTypesTVars[i]; if (tv.getName().equals(tvname)) { return i; } } return -1; } @Override public ResolvedMember[] getDeclaredMethods() { if (parameterizedMethods != null) { return parameterizedMethods; } if (isParameterizedType() || isRawType()) { ResolvedMember[] delegateMethods = getDelegate().getDeclaredMethods(); UnresolvedType[] parameters = getTypesForMemberParameterization(); parameterizedMethods = new ResolvedMember[delegateMethods.length]; for (int i = 0; i < delegateMethods.length; i++) { parameterizedMethods[i] = delegateMethods[i].parameterizedWith(parameters, this, isParameterizedType()); } return parameterizedMethods; } else { return getDelegate().getDeclaredMethods(); } } @Override public ResolvedMember[] getDeclaredPointcuts() { if (parameterizedPointcuts != null) { return parameterizedPointcuts; } if (isParameterizedType()) { ResolvedMember[] delegatePointcuts = getDelegate().getDeclaredPointcuts(); parameterizedPointcuts = new ResolvedMember[delegatePointcuts.length]; for (int i = 0; i < delegatePointcuts.length; i++) { parameterizedPointcuts[i] = delegatePointcuts[i].parameterizedWith(getTypesForMemberParameterization(), this, isParameterizedType()); } return parameterizedPointcuts; } else { return getDelegate().getDeclaredPointcuts(); } } private UnresolvedType[] getTypesForMemberParameterization() { UnresolvedType[] parameters = null; if (isParameterizedType()) { parameters = getTypeParameters(); } else if (isRawType()) { // raw type, use upper bounds of type variables on generic type TypeVariable[] tvs = getGenericType().getTypeVariables(); parameters = new UnresolvedType[tvs.length]; for (int i = 0; i < tvs.length; i++) { parameters[i] = tvs[i].getFirstBound(); } } return parameters; } @Override public TypeVariable[] getTypeVariables() { if (this.typeVariables == null) { this.typeVariables = getDelegate().getTypeVariables(); for (int i = 0; i < this.typeVariables.length; i++) { this.typeVariables[i].resolve(world); } } return this.typeVariables; } @Override public PerClause getPerClause() { PerClause pclause = getDelegate().getPerClause(); if (pclause != null && isParameterizedType()) { // could cache the result here... Map<String, UnresolvedType> parameterizationMap = getAjMemberParameterizationMap(); pclause = (PerClause) pclause.parameterizeWith(parameterizationMap, world); } return pclause; } @Override public Collection<Declare> getDeclares() { if (parameterizedDeclares != null) { return parameterizedDeclares; } Collection<Declare> declares = null; if (ajMembersNeedParameterization()) { Collection<Declare> genericDeclares = getDelegate().getDeclares(); parameterizedDeclares = new ArrayList<Declare>(); Map<String, UnresolvedType> parameterizationMap = getAjMemberParameterizationMap(); for (Declare declareStatement : genericDeclares) { parameterizedDeclares.add(declareStatement.parameterizeWith(parameterizationMap, world)); } declares = parameterizedDeclares; } else { declares = getDelegate().getDeclares(); } for (Declare d : declares) { d.setDeclaringType(this); } return declares; } @Override public Collection<ConcreteTypeMunger> getTypeMungers() { return getDelegate().getTypeMungers(); } // GENERICITDFIX // // Map parameterizationMap = getAjMemberParameterizationMap(); // // // if (parameterizedTypeMungers != null) return parameterizedTypeMungers; // Collection ret = null; // if (ajMembersNeedParameterization()) { // Collection genericDeclares = delegate.getTypeMungers(); // parameterizedTypeMungers = new ArrayList(); // Map parameterizationMap = getAjMemberParameterizationMap(); // for (Iterator iter = genericDeclares.iterator(); iter.hasNext();) { // ConcreteTypeMunger munger = (ConcreteTypeMunger)iter.next(); // parameterizedTypeMungers.add(munger.parameterizeWith(parameterizationMap, // world)); // } // ret = parameterizedTypeMungers; // } else { // ret = delegate.getTypeMungers(); // } // return ret; // } @Override public Collection<ResolvedMember> getPrivilegedAccesses() { return getDelegate().getPrivilegedAccesses(); } @Override public int getModifiers() { return getDelegate().getModifiers(); } WeakReference<ResolvedType> superclassReference = new WeakReference<ResolvedType>(null); @Override public ResolvedType getSuperclass() { ResolvedType ret = null;// superclassReference.get(); // if (ret != null) { // return ret; // } if (newSuperclass != null) { if (this.isParameterizedType() && newSuperclass.isParameterizedType()) { return newSuperclass.parameterize(getMemberParameterizationMap()).resolve(getWorld()); } if (getDelegate().isCacheable()) { superclassReference = new WeakReference<ResolvedType>(ret); } return newSuperclass; } try { world.setTypeVariableLookupScope(this); ret = getDelegate().getSuperclass(); } finally { world.setTypeVariableLookupScope(null); } if (this.isParameterizedType() && ret.isParameterizedType()) { ret = ret.parameterize(getMemberParameterizationMap()).resolve(getWorld()); } if (getDelegate().isCacheable()) { superclassReference = new WeakReference<ResolvedType>(ret); } return ret; } public ReferenceTypeDelegate getDelegate() { return delegate; } public void setDelegate(ReferenceTypeDelegate delegate) { // Don't copy from BcelObjectType to EclipseSourceType - the context may // be tidied (result null'd) after previous weaving if (this.delegate != null && this.delegate.copySourceContext() && this.delegate.getSourceContext() != SourceContextImpl.UNKNOWN_SOURCE_CONTEXT) { ((AbstractReferenceTypeDelegate) delegate).setSourceContext(this.delegate.getSourceContext()); } this.delegate = delegate; for (ReferenceType dependent : derivativeTypes) { dependent.setDelegate(delegate); } // If we are raw, we have a generic type - we should ensure it uses the // same delegate if (isRawType() && getGenericType() != null) { ReferenceType genType = (ReferenceType) getGenericType(); if (genType.getDelegate() != delegate) { // avoids circular updates genType.setDelegate(delegate); } } clearParameterizationCaches(); ensureConsistent(); } private void clearParameterizationCaches() { parameterizedFields = null; parameterizedInterfaces.clear(); parameterizedMethods = null; parameterizedPointcuts = null; superclassReference = new WeakReference<ResolvedType>(null); } public int getEndPos() { return endPos; } public int getStartPos() { return startPos; } public void setEndPos(int endPos) { this.endPos = endPos; } public void setStartPos(int startPos) { this.startPos = startPos; } @Override public boolean doesNotExposeShadowMungers() { return getDelegate().doesNotExposeShadowMungers(); } public String getDeclaredGenericSignature() { return getDelegate().getDeclaredGenericSignature(); } public void setGenericType(ReferenceType rt) { genericType = rt; // Should we 'promote' this reference type from simple to raw? // makes sense if someone is specifying that it has a generic form if (typeKind == TypeKind.SIMPLE) { typeKind = TypeKind.RAW; signatureErasure = signature; } if (typeKind==TypeKind.RAW){ genericType.addDependentType(this); } if (this.isRawType() && rt.isRawType()) { new RuntimeException("PR341926 diagnostics: Incorrect setup for a generic type, raw type should not point to raw: " + this.getName()).printStackTrace(); } } public void demoteToSimpleType() { genericType = null; typeKind = TypeKind.SIMPLE; signatureErasure = null; } @Override public ResolvedType getGenericType() { if (isGenericType()) { return this; } return genericType; } /** * a parameterized signature starts with a "P" in place of the "L", see the comment on signatures in UnresolvedType. * * @param aGenericType * @param someParameters * @return */ private static String makeParameterizedSignature(ResolvedType aGenericType, ResolvedType[] someParameters) { String rawSignature = aGenericType.getErasureSignature(); StringBuffer ret = new StringBuffer(); ret.append(PARAMETERIZED_TYPE_IDENTIFIER); ret.append(rawSignature.substring(1, rawSignature.length() - 1)); ret.append("<"); for (int i = 0; i < someParameters.length; i++) { ret.append(someParameters[i].getSignature()); } ret.append(">;"); return ret.toString(); } private static String makeDeclaredSignature(ResolvedType aGenericType, UnresolvedType[] someParameters) { StringBuffer ret = new StringBuffer(); String rawSig = aGenericType.getErasureSignature(); ret.append(rawSig.substring(0, rawSig.length() - 1)); ret.append("<"); for (int i = 0; i < someParameters.length; i++) { try { ret.append(((ReferenceType) someParameters[i]).getSignatureForAttribute()); } catch (ClassCastException cce) { throw new IllegalStateException("DebugFor325731: expected a ReferenceType but was "+someParameters[i]+ " of type "+someParameters[i].getClass().getName(),cce); } } ret.append(">;"); return ret.toString(); } @Override public void ensureConsistent() { annotations = null; annotationTypes = null; newSuperclass = null; newInterfaces = null; typeVariables = null; parameterizedInterfaces.clear(); superclassReference = new WeakReference<ResolvedType>(null); if (getDelegate() != null) { delegate.ensureConsistent(); } } @Override public void addParent(ResolvedType newParent) { if (newParent.isClass()) { newSuperclass = newParent; superclassReference = new WeakReference<ResolvedType>(null); } else { if (newInterfaces == null) { newInterfaces = new ResolvedType[1]; newInterfaces[0] = newParent; } else { ResolvedType[] existing = getDelegate().getDeclaredInterfaces(); if (existing != null) { for (int i = 0; i < existing.length; i++) { if (existing[i].equals(newParent)) { return; // already has this interface } } } ResolvedType[] newNewInterfaces = new ResolvedType[newInterfaces.length + 1]; System.arraycopy(newInterfaces, 0, newNewInterfaces, 1, newInterfaces.length); newNewInterfaces[0] = newParent; newInterfaces = newNewInterfaces; } if (this.isGenericType()) { for (ReferenceType derivativeType:derivativeTypes) { derivativeType.parameterizedInterfaces.clear(); } } parameterizedInterfaces.clear(); } } }
371,684
Bug 371684 type construction for signature makes mistakes with wildcards
If you have a type with multiple type params, like this: Foo<?,T> the signature is: LFoo<*TT;>; and the handling of * is not working in TypeFactory. If that signature is passed in it will actually build: Foo<?> having lost the second type parameter, this breaks code later that has expectations on the number of params. (e.g. ArrayIndexOutOfBoundsException when building parameterization map)
resolved fixed
89756cd
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-02-15T22:25:02Z"
"2012-02-15T21:06:40Z"
org.aspectj.matcher/src/org/aspectj/weaver/TypeFactory.java
/* ******************************************************************* * Copyright (c) 2005-2010 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 * ******************************************************************/ package org.aspectj.weaver; import java.util.ArrayList; import java.util.List; /** * @author Adrian Colyer * @author Andy Clement */ 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 */ 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. */ 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); return new UnresolvedType(signature, signatureErasure, UnresolvedType.NONE); } else { int endOfParams = locateMatchingEndAngleBracket(signature, startOfParams); StringBuffer erasureSig = new StringBuffer(signature); erasureSig.setCharAt(0, 'L'); while (startOfParams != -1) { erasureSig.delete(startOfParams, endOfParams + 1); startOfParams = locateFirstBracket(erasureSig); if (startOfParams != -1) { endOfParams = locateMatchingEndAngleBracket(erasureSig, startOfParams); } } String signatureErasure = erasureSig.toString();// "L" + erasureSig.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("<"); UnresolvedType[] typeParams = UnresolvedType.NONE; if (startOfParams != -1) { endOfParams = locateMatchingEndAngleBracket(lastType, startOfParams); typeParams = createTypeParams(lastType.substring(startOfParams + 1, endOfParams)); } StringBuilder s = new StringBuilder(); int firstAngleBracket = signature.indexOf('<'); s.append("P").append(signature.substring(1, firstAngleBracket)); s.append('<'); for (UnresolvedType typeParameter : typeParams) { s.append(typeParameter.getSignature()); } s.append(">;"); signature = s.toString();// 'P' + signature.substring(1); return new UnresolvedType(signature, signatureErasure, typeParams); } // can't replace above with convertSigToType - leads to stackoverflow } else if ((firstChar == '?' || firstChar == '*') && signature.length() == 1) { return WildcardedUnresolvedType.QUESTIONMARK; } else if (firstChar == '+') { // ? extends ... UnresolvedType upperBound = convertSigToType(signature.substring(1)); WildcardedUnresolvedType wildcardedUT = new WildcardedUnresolvedType(signature, upperBound, null); return wildcardedUT; } else if (firstChar == '-') { // ? super ... UnresolvedType lowerBound = convertSigToType(signature.substring(1)); WildcardedUnresolvedType wildcardedUT = new WildcardedUnresolvedType(signature, null, lowerBound); return wildcardedUT; } 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 UnresolvedType.VOID; case 'Z': return UnresolvedType.BOOLEAN; case 'B': return UnresolvedType.BYTE; case 'C': return UnresolvedType.CHAR; case 'D': return UnresolvedType.DOUBLE; case 'F': return UnresolvedType.FLOAT; case 'I': return UnresolvedType.INT; case 'J': return UnresolvedType.LONG; case 'S': return UnresolvedType.SHORT; } } else if (firstChar == '@') { // missing type return ResolvedType.MISSING; } else if (firstChar == 'L') { // only an issue if there is also an angle bracket int leftAngleBracket = signature.indexOf('<'); if (leftAngleBracket == -1) { return new UnresolvedType(signature); } else { int endOfParams = locateMatchingEndAngleBracket(signature, leftAngleBracket); StringBuffer erasureSig = new StringBuffer(signature); erasureSig.setCharAt(0, 'L'); while (leftAngleBracket != -1) { erasureSig.delete(leftAngleBracket, endOfParams + 1); leftAngleBracket = locateFirstBracket(erasureSig); if (leftAngleBracket != -1) { endOfParams = locateMatchingEndAngleBracket(erasureSig, leftAngleBracket); } } String signatureErasure = erasureSig.toString(); // TODO should consider all the intermediate parameterizations as well! // 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); } leftAngleBracket = lastType.indexOf("<"); UnresolvedType[] typeParams = UnresolvedType.NONE; if (leftAngleBracket != -1) { endOfParams = locateMatchingEndAngleBracket(lastType, leftAngleBracket); typeParams = createTypeParams(lastType.substring(leftAngleBracket + 1, endOfParams)); } StringBuilder s = new StringBuilder(); int firstAngleBracket = signature.indexOf('<'); s.append("P").append(signature.substring(1, firstAngleBracket)); s.append('<'); for (UnresolvedType typeParameter : typeParams) { s.append(typeParameter.getSignature()); } s.append(">;"); signature = s.toString();// 'P' + signature.substring(1); return new UnresolvedType(signature, signatureErasure, typeParams); } } return new UnresolvedType(signature); } private static int locateMatchingEndAngleBracket(CharSequence signature, int startOfParams) { if (startOfParams == -1) { return -1; } int count = 1; int idx = startOfParams; int max = signature.length(); while (idx < max) { char ch = signature.charAt(++idx); if (ch == '<') { count++; } else if (ch == '>') { if (count == 1) { break; } count--; } } return idx; } private static int locateFirstBracket(StringBuffer signature) { int idx = 0; int max = signature.length(); while (idx < max) { if (signature.charAt(idx) == '<') { return idx; } idx++; } return -1; } private static UnresolvedType[] createTypeParams(String typeParameterSpecification) { String remainingToProcess = typeParameterSpecification; List<UnresolvedType> types = new ArrayList<UnresolvedType>(); while (remainingToProcess.length() != 0) { int endOfSig = 0; int anglies = 0; boolean hadAnglies = false; boolean sigFound = false; // OPTIMIZE can this be done better? for (endOfSig = 0; (endOfSig < remainingToProcess.length()) && !sigFound; endOfSig++) { char thisChar = remainingToProcess.charAt(endOfSig); switch (thisChar) { case '<': anglies++; hadAnglies = true; break; case '>': anglies--; break; case '[': if (anglies == 0) { // the next char might be a [ or a primitive type ref (BCDFIJSZ) int nextChar = endOfSig + 1; while (remainingToProcess.charAt(nextChar) == '[') { nextChar++; } if ("BCDFIJSZ".indexOf(remainingToProcess.charAt(nextChar)) != -1) { // it is something like [I or [[S sigFound = true; endOfSig = nextChar; break; } } break; case ';': if (anglies == 0) { sigFound = true; break; } } } String forProcessing = remainingToProcess.substring(0, endOfSig); if (hadAnglies && forProcessing.charAt(0) == 'L') { forProcessing = "P" + forProcessing.substring(1); } types.add(createTypeFromSignature(forProcessing)); remainingToProcess = remainingToProcess.substring(endOfSig); } UnresolvedType[] typeParams = new UnresolvedType[types.size()]; types.toArray(typeParams); return typeParams; } // OPTIMIZE improve all this signature processing stuff, use char arrays, etc /** * Create a signature then delegate to the other factory method. Same input/output: baseTypeSignature="LSomeType;" arguments[0]= * something with sig "Pcom/Foo<Ljava/lang/String;>;" signature created = "PSomeType<Pcom/Foo<Ljava/lang/String;>;>;" */ public static UnresolvedType createUnresolvedParameterizedType(String baseTypeSignature, UnresolvedType[] arguments) { StringBuffer parameterizedSig = new StringBuffer(); parameterizedSig.append(ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER); parameterizedSig.append(baseTypeSignature.substring(1, baseTypeSignature.length() - 1)); if (arguments.length > 0) { parameterizedSig.append("<"); for (int i = 0; i < arguments.length; i++) { parameterizedSig.append(arguments[i].getSignature()); } parameterizedSig.append(">"); } parameterizedSig.append(";"); return createUnresolvedParameterizedType(parameterizedSig.toString(), baseTypeSignature, arguments); } }
371,684
Bug 371684 type construction for signature makes mistakes with wildcards
If you have a type with multiple type params, like this: Foo<?,T> the signature is: LFoo<*TT;>; and the handling of * is not working in TypeFactory. If that signature is passed in it will actually build: Foo<?> having lost the second type parameter, this breaks code later that has expectations on the number of params. (e.g. ArrayIndexOutOfBoundsException when building parameterization map)
resolved fixed
89756cd
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-02-15T22:25:02Z"
"2012-02-15T21:06:40Z"
tests/src/org/aspectj/systemtest/ajc170/Ajc170Tests.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.ajc170; import java.io.File; import junit.framework.Test; import org.aspectj.testing.XMLBasedAjcTestCase; /** * @author Andy Clement */ public class Ajc170Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testPerThis() { runTest("perthis"); } public void testPerTarget() { runTest("pertarget"); } public void testPerCflow() { runTest("percflow"); } public void testPerTypeWithin() { runTest("pertypewithin"); } // not specifying -1.7 public void testDiamond1() { runTest("diamond 1"); } public void testDiamond2() { runTest("diamond 2"); } public void testDiamondItd1() { runTest("diamond itd 1"); } public void testLiterals1() { runTest("literals 1"); } public void testLiterals2() { runTest("literals 2"); } public void testLiteralsItd1() { runTest("literals itd 1"); } public void testStringSwitch1() { runTest("string switch 1"); } public void testStringSwitch2() { runTest("string switch 2"); } public void testMultiCatch1() { runTest("multi catch 1"); } public void testMultiCatch2() { runTest("multi catch 2"); } public void testMultiCatchWithHandler1() { runTest("multi catch with handler 1"); } public void testMultiCatchAspect1() { runTest("multi catch aspect 1"); } // public void testMultiCatchWithHandler2() { // runTest("multi catch with handler 2"); // } public void testSanity1() { runTest("sanity 1"); } public void testMissingImpl_363979() { runTest("missing impl"); } public void testMissingImpl_363979_2() { runTest("missing impl 2"); } public void testStackOverflow_364380() { runTest("stackoverflow"); } // public void testTryResources1() { // runTest("try resources 1"); // } // // public void testTryResources2() { // runTest("try resources 2"); // } // --- public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc170Tests.class); } @Override protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc170/ajc170.xml"); } }
371,998
Bug 371998 org.aspectj.weaver.BCException compiling @DeclareParents with value using "||"
Build Identifier: 20110916-0149 Using: import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.DeclareParents; @Aspect public class AspectTest { private interface X {} private static class XImpl {} @DeclareParents(value="java.lang.Runnable || java.util.concurrent.Callable", defaultImpl=XImpl.class) private X xImpl; } Throws: org.aspectj.weaver.BCException at org.aspectj.weaver.patterns.ExactTypePattern.resolveBindings(ExactTypePattern.java:312) at org.aspectj.weaver.patterns.OrTypePattern.resolveBindings(OrTypePattern.java:121) at org.aspectj.weaver.bcel.AtAjAttributes.handleDeclareParentsAnnotation(AtAjAttributes.java:746) at org.aspectj.weaver.bcel.AtAjAttributes.readAj5ClassAttributes(AtAjAttributes.java:384) at org.aspectj.weaver.bcel.BcelObjectType.ens ... \Program Files\Java\jre6\lib\ext\sunjce_provider.jar;C:\Users\xxx\software\eclipse-j2ee\\plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar; Current workaround is to use multiple DeclareParents annotations on different variables. Reproducible: Always Steps to Reproduce: 1. Create new class given the code in the details. 2. Save and compile in Eclipse.
resolved fixed
f37c56e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-03-02T16:17:44Z"
"2012-02-19T19:33:20Z"
tests/bugs170/pr371998/AspectTest.java
371,998
Bug 371998 org.aspectj.weaver.BCException compiling @DeclareParents with value using "||"
Build Identifier: 20110916-0149 Using: import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.DeclareParents; @Aspect public class AspectTest { private interface X {} private static class XImpl {} @DeclareParents(value="java.lang.Runnable || java.util.concurrent.Callable", defaultImpl=XImpl.class) private X xImpl; } Throws: org.aspectj.weaver.BCException at org.aspectj.weaver.patterns.ExactTypePattern.resolveBindings(ExactTypePattern.java:312) at org.aspectj.weaver.patterns.OrTypePattern.resolveBindings(OrTypePattern.java:121) at org.aspectj.weaver.bcel.AtAjAttributes.handleDeclareParentsAnnotation(AtAjAttributes.java:746) at org.aspectj.weaver.bcel.AtAjAttributes.readAj5ClassAttributes(AtAjAttributes.java:384) at org.aspectj.weaver.bcel.BcelObjectType.ens ... \Program Files\Java\jre6\lib\ext\sunjce_provider.jar;C:\Users\xxx\software\eclipse-j2ee\\plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar; Current workaround is to use multiple DeclareParents annotations on different variables. Reproducible: Always Steps to Reproduce: 1. Create new class given the code in the details. 2. Save and compile in Eclipse.
resolved fixed
f37c56e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-03-02T16:17:44Z"
"2012-02-19T19:33:20Z"
tests/src/org/aspectj/systemtest/ajc170/Ajc170Tests.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.ajc170; import java.io.File; import java.util.List; import junit.framework.Test; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.weaver.CrosscuttingMembers; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.TypeFactory; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelWorld; /** * @author Andy Clement */ public class Ajc170Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testGenericsWithTwoTypeParamsOneWildcard() { UnresolvedType ut; ut = TypeFactory.createTypeFromSignature("LFoo<**>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<***>;"); assertEquals(3,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<TP;*+Ljava/lang/String;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<*+Ljava/lang/String;TP;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<*+Ljava/lang/String;TP;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<*TT;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<[I>;"); assertEquals(1,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<[I[Z>;"); assertEquals(2,ut.getTypeParameters().length); } public void testPerThis() { runTest("perthis"); } public void testPerTarget() { runTest("pertarget"); } public void testPerCflow() { runTest("percflow"); } public void testPerTypeWithin() { runTest("pertypewithin"); } // not specifying -1.7 public void testDiamond1() { runTest("diamond 1"); } public void testDiamond2() { runTest("diamond 2"); } public void testDiamondItd1() { runTest("diamond itd 1"); } public void testLiterals1() { runTest("literals 1"); } public void testLiterals2() { runTest("literals 2"); } public void testLiteralsItd1() { runTest("literals itd 1"); } public void testStringSwitch1() { runTest("string switch 1"); } public void testStringSwitch2() { runTest("string switch 2"); } public void testMultiCatch1() { runTest("multi catch 1"); } public void testMultiCatch2() { runTest("multi catch 2"); } public void testMultiCatchWithHandler1() { runTest("multi catch with handler 1"); } public void testMultiCatchAspect1() { runTest("multi catch aspect 1"); } // public void testMultiCatchWithHandler2() { // runTest("multi catch with handler 2"); // } public void testSanity1() { runTest("sanity 1"); } public void testMissingImpl_363979() { runTest("missing impl"); } public void testMissingImpl_363979_2() { runTest("missing impl 2"); } public void testStackOverflow_364380() { runTest("stackoverflow"); } // public void testTryResources1() { // runTest("try resources 1"); // } // // public void testTryResources2() { // runTest("try resources 2"); // } // --- public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc170Tests.class); } @Override protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc170/ajc170.xml"); } }
371,998
Bug 371998 org.aspectj.weaver.BCException compiling @DeclareParents with value using "||"
Build Identifier: 20110916-0149 Using: import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.DeclareParents; @Aspect public class AspectTest { private interface X {} private static class XImpl {} @DeclareParents(value="java.lang.Runnable || java.util.concurrent.Callable", defaultImpl=XImpl.class) private X xImpl; } Throws: org.aspectj.weaver.BCException at org.aspectj.weaver.patterns.ExactTypePattern.resolveBindings(ExactTypePattern.java:312) at org.aspectj.weaver.patterns.OrTypePattern.resolveBindings(OrTypePattern.java:121) at org.aspectj.weaver.bcel.AtAjAttributes.handleDeclareParentsAnnotation(AtAjAttributes.java:746) at org.aspectj.weaver.bcel.AtAjAttributes.readAj5ClassAttributes(AtAjAttributes.java:384) at org.aspectj.weaver.bcel.BcelObjectType.ens ... \Program Files\Java\jre6\lib\ext\sunjce_provider.jar;C:\Users\xxx\software\eclipse-j2ee\\plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar; Current workaround is to use multiple DeclareParents annotations on different variables. Reproducible: Always Steps to Reproduce: 1. Create new class given the code in the details. 2. Save and compile in Eclipse.
resolved fixed
f37c56e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-03-02T16:17:44Z"
"2012-02-19T19:33:20Z"
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.io.ByteArrayInputStream; import java.io.IOException; 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.Unknown; 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.AjAttribute.WeaverVersionInfo; 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.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; 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<AjAttribute> 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; WeaverVersionInfo wvinfo = null; 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; } } for (int i = attributes.length - 1; i >= 0; i--) { Attribute attribute = attributes[i]; if (attribute.getName().equals(WeaverVersionInfo.AttributeName)) { try { VersionedDataInputStream s = new VersionedDataInputStream(new ByteArrayInputStream( ((Unknown) attribute).getBytes()), null); wvinfo = WeaverVersionInfo.read(s); struct.ajAttributes.add(0, wvinfo); } catch (IOException ioe) { ioe.printStackTrace(); } } } if (wvinfo == null) { // If we are in here due to a resetState() call (presumably because of reweavable state processing), the // original type delegate will have been set with a version but that version will be missing from // the new set of attributes (looks like a bug where the version attribute was not included in the // data compressed into the attribute). So rather than 'defaulting' to current, we should use one // if it set on the delegate for the type. ReferenceTypeDelegate delegate = type.getDelegate(); if (delegate instanceof BcelObjectType) { wvinfo = ((BcelObjectType) delegate).getWeaverVersionAttribute(); if (wvinfo != null) { if (wvinfo.getMajorVersion() != WeaverVersionInfo.WEAVER_VERSION_MAJOR_UNKNOWN) { // use this one struct.ajAttributes.add(0, wvinfo); } else { wvinfo = null; } } } if (wvinfo == null) { struct.ajAttributes.add(0, wvinfo = new AjAttribute.WeaverVersionInfo()); } } // 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) { 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<AjAttribute> 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.emptyList(); } /** * 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 // Not setting version here // 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<TypePattern> parents = new ArrayList<TypePattern>(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; Iterator<ResolvedMember> methodIterator = fieldType.getMethodsIncludingIntertypeDeclarations(false, true); while (methodIterator.hasNext()) { ResolvedMember method = methodIterator.next(); // ResolvedMember[] methods = fieldType.getMethodsWithoutIterator(true, false, 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<ResolvedType> iterator = newInterfaceTypes.iterator(); iterator.hasNext();) { ResolvedType typeForDelegation = 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, false).toArray( new ResolvedMember[0]); for (int i = 0; i < methods.length; i++) { ResolvedMember method = methods[i]; if (method.isAbstract()) { hasAtLeastOneMethod = true; if (method.hasBackingGenericMember()) { method = method.getBackingGenericMember(); } 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 (AnnotationGen rv : rvs.getAnnotations()) { 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 (NameValuePair element : annotation.getValues()) { 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) { LocalVariable[] lvt = lt.getLocalVariableTable(); for (int j = 0; j < lvt.length; j++) { LocalVariable localVariable = lvt[j]; if (localVariable != null) { // pr348488 if (localVariable.getStartPC() == 0) { if (localVariable.getIndex() >= startAtStackIndex) { arguments.add(new MethodArgument(localVariable.getName(), localVariable.getIndex())); } } } else { String typename = (methodStruct.enclosingType != null ? methodStruct.enclosingType.getName() : ""); System.err.println("AspectJ: 348488 debug: unusual local variable table for method " + typename + "." + method.getName()); } } if (arguments.size() == 0) { // could be cobertura code where some extra bytecode has been stuffed in at the start of the method // but the local variable table hasn't been repaired - for example: // LocalVariable(start_pc = 6, length = 40, index = 0:com.example.ExampleAspect this) // LocalVariable(start_pc = 6, length = 40, index = 1:org.aspectj.lang.ProceedingJoinPoint pjp) // LocalVariable(start_pc = 6, length = 40, index = 2:int __cobertura__line__number__) // LocalVariable(start_pc = 6, length = 40, index = 3:int __cobertura__branch__number__) LocalVariable localVariable = lvt[0]; if (localVariable != null) { // pr348488 if (localVariable.getStartPC() != 0) { // looks suspicious so let's use this information for (int j = 0; j < lvt.length && arguments.size() < method.getArgumentTypes().length; j++) { localVariable = lvt[j]; 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<MethodArgument>() { public int compare(MethodArgument mo, MethodArgument mo1) { 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, Pointcut.makeMatchesNothing(Pointcut.RESOLVED)); 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<String> ignores = new ArrayList<String>(); for (int i = 0; i < bindings.length; i++) { FormalBinding formalBinding = bindings[i]; if (formalBinding instanceof FormalBinding.ImplicitFormalBinding) { ignores.add(formalBinding.getName()); } } pointcut.m_ignoreUnboundBindingForNames = 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; } } }
373,195
Bug 373195 Memory leak in CompilationAndWeavingContext leading to PermGen OOME
Build Identifier: 1.6.11 The static contextMap in CompilationAndWeavingContext keeps strong references to Thread instances (which in turn strongly reference their contextClassLoader which prevents all kinds of stuff from unloading). In my particular use case I am running unit tests, each in their own WeavingURLClassLoader, but these ClassLoaders are never released, and running several unit tests at once leads to PermGen OutOfMemoryError. Using -XX:+HeapDumpOnOutOfMemory and analyzing the resulting heap dump in Eclipse Memory Analyzer points to CompilationAndWeavingContext.contextMap. I am able to work around this issue by executing the following at the end of each unit test to clear out this contextMap: CompilationAndWeavingContext.setMultiThreaded(false); CompilationAndWeavingContext.reset(); CompilationAndWeavingContext.setMultiThreaded(true); I am also able to resolve this issue (more satisfactorily) by patching CompilationAndWeavingContext and changing contextMap into a ThreadLocal. Reproducible: Always
resolved fixed
6defb4e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-03-06T16:33:16Z"
"2012-03-04T05:46:40Z"
bridge/src/org/aspectj/bridge/context/CompilationAndWeavingContext.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.bridge.context; import java.lang.ref.WeakReference; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Stack; /** * @author colyer This class is responsible for tracking progress through the various phases of compilation and weaving. When an * exception occurs (or a message is issued, if desired), you can ask this class for a "stack trace" that gives information * about what the compiler was doing at the time. The trace will say something like: * * when matching pointcut xyz when matching shadow sss when weaving type ABC when weaving shadow mungers * * Since we can't use ThreadLocal (have to work on 1.3), we use a map from Thread -> ContextStack. */ public class CompilationAndWeavingContext { private static int nextTokenId = 1; // unique constants for the different phases that can be registered // "FRONT END" public static final int BATCH_BUILD = 0; public static final int INCREMENTAL_BUILD = 1; public static final int PROCESSING_COMPILATION_UNIT = 2; public static final int RESOLVING_COMPILATION_UNIT = 3; public static final int ANALYSING_COMPILATION_UNIT = 4; public static final int GENERATING_UNWOVEN_CODE_FOR_COMPILATION_UNIT = 5; public static final int COMPLETING_TYPE_BINDINGS = 6; public static final int PROCESSING_DECLARE_PARENTS = 7; public static final int CHECK_AND_SET_IMPORTS = 8; public static final int CONNECTING_TYPE_HIERARCHY = 9; public static final int BUILDING_FIELDS_AND_METHODS = 10; public static final int COLLECTING_ITDS_AND_DECLARES = 11; public static final int PROCESSING_DECLARE_ANNOTATIONS = 12; public static final int WEAVING_INTERTYPE_DECLARATIONS = 13; public static final int RESOLVING_POINTCUT_DECLARATIONS = 14; public static final int ADDING_DECLARE_WARNINGS_AND_ERRORS = 15; public static final int VALIDATING_AT_ASPECTJ_ANNOTATIONS = 16; public static final int ACCESS_FOR_INLINE = 17; public static final int ADDING_AT_ASPECTJ_ANNOTATIONS = 18; public static final int FIXING_SUPER_CALLS_IN_ITDS = 19; public static final int FIXING_SUPER_CALLS = 20; public static final int OPTIMIZING_THIS_JOIN_POINT_CALLS = 21; // "BACK END" public static final int WEAVING = 22; public static final int PROCESSING_REWEAVABLE_STATE = 23; public static final int PROCESSING_TYPE_MUNGERS = 24; public static final int WEAVING_ASPECTS = 25; public static final int WEAVING_CLASSES = 26; public static final int WEAVING_TYPE = 27; public static final int MATCHING_SHADOW = 28; public static final int IMPLEMENTING_ON_SHADOW = 29; public static final int MATCHING_POINTCUT = 30; public static final int MUNGING_WITH = 31; public static final int PROCESSING_ATASPECTJTYPE_MUNGERS_ONLY = 32; // phase names public static final String[] PHASE_NAMES = new String[] { "batch building", "incrementally building", "processing compilation unit", "resolving types defined in compilation unit", "analysing types defined in compilation unit", "generating unwoven code for type defined in compilation unit", "completing type bindings", "processing declare parents", "checking and setting imports", "connecting type hierarchy", "building fields and methods", "collecting itds and declares", "processing declare annotations", "weaving intertype declarations", "resolving pointcut declarations", "adding declare warning and errors", "validating @AspectJ annotations", "creating accessors for inlining", "adding @AspectJ annotations", "fixing super calls in ITDs in interface context", "fixing super calls in ITDs", "optimizing thisJoinPoint calls", // BACK END "weaving", "processing reweavable state", "processing type mungers", "weaving aspects", "weaving classes", "weaving type", "matching shadow", "implementing on shadow", "matching pointcut", "type munging with", "type munging for @AspectJ aspectOf" }; // context stacks, one per thread private static Map<Thread, Stack<ContextStackEntry>> contextMap = Collections .synchronizedMap(new HashMap<Thread, Stack<ContextStackEntry>>()); // single thread mode stack private static Stack<ContextStackEntry> contextStack = new Stack<ContextStackEntry>(); // formatters, by phase id private static Map<Integer, ContextFormatter> formatterMap = new HashMap<Integer, ContextFormatter>(); private static ContextFormatter defaultFormatter = new DefaultFormatter(); private static boolean multiThreaded = true; /** * this is a static service */ private CompilationAndWeavingContext() { } public static void reset() { if (!multiThreaded) { contextMap.clear(); contextStack.clear(); formatterMap.clear(); nextTokenId = 1; } else { contextMap.remove(Thread.currentThread()); // TODO what about formatterMap? // TODO what about nextTokenId? } } public static void setMultiThreaded(boolean mt) { multiThreaded = mt; } public static void registerFormatter(int phaseId, ContextFormatter aFormatter) { formatterMap.put(new Integer(phaseId), aFormatter); } /** * Returns a string description of what the compiler/weaver is currently doing */ public static String getCurrentContext() { Stack<ContextStackEntry> contextStack = getContextStack(); Stack<String> explanationStack = new Stack<String>(); for (ContextStackEntry entry : contextStack) { Object data = entry.getData(); if (data != null) { explanationStack.push(getFormatter(entry).formatEntry(entry.phaseId, data)); } } StringBuffer sb = new StringBuffer(); while (!explanationStack.isEmpty()) { sb.append("when "); sb.append(explanationStack.pop().toString()); sb.append("\n"); } return sb.toString(); } public static ContextToken enteringPhase(int phaseId, Object data) { Stack<ContextStackEntry> contextStack = getContextStack(); ContextTokenImpl nextToken = nextToken(); contextStack.push(new ContextStackEntry(nextToken, phaseId, new WeakReference<Object>(data))); return nextToken; } /** * Exit a phase, all stack entries from the one with the given token down will be removed. */ public static void leavingPhase(ContextToken aToken) { Stack contextStack = getContextStack(); while (!contextStack.isEmpty()) { ContextStackEntry entry = (ContextStackEntry) contextStack.pop(); if (entry.contextToken == aToken) { break; } } } /** * Forget about the context for the current thread */ public static void resetForThread() { if (!multiThreaded) { return; } contextMap.remove(Thread.currentThread()); } private static Stack<ContextStackEntry> getContextStack() { if (!multiThreaded) { return contextStack; } else { Stack<ContextStackEntry> contextStack = contextMap.get(Thread.currentThread()); if (contextStack == null) { contextStack = new Stack<ContextStackEntry>(); contextMap.put(Thread.currentThread(), contextStack); } return contextStack; } } private static ContextTokenImpl nextToken() { return new ContextTokenImpl(nextTokenId++); } private static ContextFormatter getFormatter(ContextStackEntry entry) { Integer key = new Integer(entry.phaseId); if (formatterMap.containsKey(key)) { return formatterMap.get(key); } else { return defaultFormatter; } } private static class ContextTokenImpl implements ContextToken { public int tokenId; public ContextTokenImpl(int id) { this.tokenId = id; } } // dumb data structure private static class ContextStackEntry { public ContextTokenImpl contextToken; public int phaseId; private WeakReference<Object> dataRef; public ContextStackEntry(ContextTokenImpl ct, int phase, WeakReference<Object> data) { this.contextToken = ct; this.phaseId = phase; this.dataRef = data; } public Object getData() { return dataRef.get(); } public String toString() { Object data = getData(); if (data == null) { return "referenced context entry has gone out of scope"; } else { return CompilationAndWeavingContext.getFormatter(this).formatEntry(phaseId, data); } } } private static class DefaultFormatter implements ContextFormatter { public String formatEntry(int phaseId, Object data) { StringBuffer sb = new StringBuffer(); sb.append(PHASE_NAMES[phaseId]); sb.append(" "); if (data instanceof char[]) { sb.append(new String((char[]) data)); } else { try { sb.append(data.toString()); } catch (RuntimeException ex) { // don't lose vital info because of bad toString sb.append("** broken toString in data object **"); } } return sb.toString(); } } }
374,745
Bug 374745 Performance regression in 1.6.12
null
resolved fixed
549d227
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-03-23T23:57:10Z"
"2012-03-20T10:40: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.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.IMessage.Kind; import org.aspectj.bridge.ISourceLocation; 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.ProblemReasons; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ProblemReferenceBinding; 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.BCException; 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.ResolvedTypeMunger; 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.UnresolvedType.TypeKind; import org.aspectj.weaver.UnresolvedTypeVariableReferenceType; import org.aspectj.weaver.WildcardedUnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; /** * @author Jim Hugunin */ public class EclipseFactory { public static boolean DEBUG = false; public static int debug_mungerCount = -1; private final AjBuildManager buildManager; private final LookupEnvironment lookupEnvironment; private final boolean xSerializableAspects; private final World world; public PushinCollector pushinCollector; public List<ConcreteTypeMunger> 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 final Map/* UnresolvedType, TypeBinding */typexToBinding = new HashMap(); private final 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 LookupEnvironment getLookupEnvironment() { return this.lookupEnvironment; } 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.pushinCollector = PushinCollector.createInstance(this.world); this.xSerializableAspects = buildManager.buildConfig.isXserializableAspects(); } public EclipseFactory(LookupEnvironment lookupEnvironment, World world, boolean xSer) { this.lookupEnvironment = lookupEnvironment; this.world = world; this.xSerializableAspects = xSer; this.pushinCollector = PushinCollector.createInstance(this.world); 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]; } // StringBuffer parameterizedSig = new StringBuffer(); // parameterizedSig.append(ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER); // // // String parameterizedSig = new // StringBuffer().append(ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER).append(CharOperation // .charToString(binding.genericTypeSignature()).substring(1)).toString(); // return TypeFactory.createUnresolvedParameterizedType(parameterizedSig,baseTypeSignature,arguments); return TypeFactory.createUnresolvedParameterizedType(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())); } } // was: UnresolvedType.forName(getName(binding)); UnresolvedType ut = UnresolvedType.forSignature(new String(binding.signature())); return ut; } /** * 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 = null; if (aTypeVariableBinding == null || aTypeVariableBinding.superInterfaces == null) { // sign of another bug that will be reported elsewhere superinterfaces = UnresolvedType.NONE; } else { superinterfaces = new UnresolvedType[aTypeVariableBinding.superInterfaces.length]; for (int i = 0; i < superinterfaces.length; i++) { superinterfaces[i] = fromBinding(aTypeVariableBinding.superInterfaces[i]); } } tv.setSuperclass(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 List<DeclareParents> getDeclareParents() { return getWorld().getDeclareParents(); } public List<DeclareAnnotation> getDeclareAnnotationOnTypes() { return getWorld().getDeclareAnnotationOnTypes(); } public List<DeclareAnnotation> getDeclareAnnotationOnFields() { return getWorld().getDeclareAnnotationOnFields(); } public List<DeclareAnnotation> getDeclareAnnotationOnMethods() { return getWorld().getDeclareAnnotationOnMethods(); } public boolean areTypeMungersFinished() { return finishedTypeMungers != null; } public void finishTypeMungers() { // make sure that type mungers are List<ConcreteTypeMunger> ret = new ArrayList<ConcreteTypeMunger>(); List<ConcreteTypeMunger> 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 (ConcreteTypeMunger munger : baseTypeMungers) { EclipseTypeMunger etm = makeEclipseTypeMunger(munger); if (etm != null) { if (munger.getMunger().getKind() == ResolvedTypeMunger.InnerClass) { ret.add(0, etm); } else { 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 List<ConcreteTypeMunger> getTypeMungers() { // ??? assert finishedTypeMungers != null return finishedTypeMungers; } public ResolvedMemberImpl makeResolvedMember(MethodBinding binding) { return makeResolvedMember(binding, binding.declaringClass); } public ResolvedMemberImpl 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 final 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 ResolvedMemberImpl makeResolvedMemberForITD(MethodBinding binding, TypeBinding declaringType, Map /* * TypeVariableBinding > * original alias name */recoveryAliases) { ResolvedMemberImpl result = null; try { typeVariablesForAliasRecovery = recoveryAliases; result = makeResolvedMember(binding, declaringType); } finally { typeVariablesForAliasRecovery = null; } return result; } public ResolvedMemberImpl makeResolvedMember(MethodBinding binding, TypeBinding declaringType) { return makeResolvedMember(binding, declaringType, binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD); } public ResolvedMemberImpl 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 (ret != null) {// && !(ret instanceof ProblemReferenceBinding)) { if (!(typeX instanceof BoundedReferenceType) && !(typeX instanceof UnresolvedTypeVariableReferenceType)) { if (typeX.isRawType()) { rawTypeXToBinding.put(typeX, ret); } else { typexToBinding.put(typeX, ret); } } } } 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.equals(UnresolvedType.BOOLEAN)) { return TypeBinding.BOOLEAN; } if (typeX.equals(UnresolvedType.BYTE)) { return TypeBinding.BYTE; } if (typeX.equals(UnresolvedType.CHAR)) { return TypeBinding.CHAR; } if (typeX.equals(UnresolvedType.DOUBLE)) { return TypeBinding.DOUBLE; } if (typeX.equals(UnresolvedType.FLOAT)) { return TypeBinding.FLOAT; } if (typeX.equals(UnresolvedType.INT)) { return TypeBinding.INT; } if (typeX.equals(UnresolvedType.LONG)) { return TypeBinding.LONG; } if (typeX.equals(UnresolvedType.SHORT)) { return TypeBinding.SHORT; } if (typeX.equals(UnresolvedType.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()) { if (typeX instanceof WildcardedUnresolvedType) { WildcardedUnresolvedType wut = (WildcardedUnresolvedType) typeX; int boundkind = Wildcard.UNBOUND; TypeBinding bound = null; if (wut.isExtends()) { boundkind = Wildcard.EXTENDS; bound = makeTypeBinding(wut.getUpperBound()); } else if (wut.isSuper()) { boundkind = Wildcard.SUPER; bound = makeTypeBinding(wut.getLowerBound()); } TypeBinding[] otherBounds = null; // TODO 2 ought to support extra bounds for WildcardUnresolvedType // if (wut.getAdditionalBounds()!=null && wut.getAdditionalBounds().length!=0) otherBounds = // makeTypeBindings(wut.getAdditionalBounds()); WildcardBinding wb = lookupEnvironment.createWildcard(baseTypeForParameterizedType, indexOfTypeParameterBeingConverted, bound, otherBounds, boundkind); return wb; } else if (typeX instanceof BoundedReferenceType) { // 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 { throw new BCException("This type " + typeX + " (class " + typeX.getClass().getName() + ") should not be claiming to be a wildcard!"); } } else { return lookupBinding(typeX.getName()); } } private ReferenceBinding lookupBinding(String sname) { char[][] name = CharOperation.splitOn('.', sname.toCharArray()); ReferenceBinding rb = lookupEnvironment.getType(name); if (rb == null && !sname.equals(UnresolvedType.MISSING_NAME)) { return new ProblemReferenceBinding(name, null, ProblemReasons.NotFound); } 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(); ReferenceBinding declaringType = (ReferenceBinding) makeTypeBinding(member.getDeclaringType()); // If there are aliases, place them in the map if (aliases != null && aliases.size() > 0 && declaringType.typeVariables() != null && declaringType.typeVariables().length != 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 && declaringType.typeVariables() != null && declaringType.typeVariables().length != 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 final 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=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(),this.lookupEnvironment); typeVariableToTypeBinding.put(tv.getName(), tvBinding); if (tv.getSuperclass() != null && (!tv.getSuperclass().getSignature().equals("Ljava/lang/Object;") || tv.getSuperInterfaces() != null)) { tvBinding.superclass = (ReferenceBinding) makeTypeBinding(tv.getSuperclass()); } tvBinding.firstBound = makeTypeBinding(tv.getFirstBound()); if (tv.getSuperInterfaces() == null) { tvBinding.superInterfaces = TypeVariableBinding.NO_SUPERINTERFACES; } else { TypeBinding tbs[] = makeTypeBindings(tv.getSuperInterfaces()); 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(); } public int getItdVersion() { return world.getItdVersion(); } }
374,745
Bug 374745 Performance regression in 1.6.12
null
resolved fixed
549d227
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-03-23T23:57:10Z"
"2012-03-20T10:40:00Z"
org.aspectj.matcher/src/org/aspectj/weaver/ReferenceType.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 * Andy Clement - June 2005 - separated out from ResolvedType * ******************************************************************/ package org.aspectj.weaver; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.PerClause; /** * A reference type represents some 'real' type, not a primitive, not an array - but a real type, for example java.util.List. Each * ReferenceType has a delegate that is the underlying artifact - either an eclipse artifact or a bcel artifact. If the type * represents a raw type (i.e. there is a generic form) then the genericType field is set to point to the generic type. If it is for * a parameterized type then the generic type is also set to point to the generic form. */ public class ReferenceType extends ResolvedType { public static final ReferenceType[] EMPTY_ARRAY = new ReferenceType[0]; /** * For generic types, this list holds references to all the derived raw and parameterized versions. We need this so that if the * generic delegate is swapped during incremental compilation, the delegate of the derivatives is swapped also. */ private final Set<ReferenceType> derivativeTypes = new HashSet<ReferenceType>(); /** * For parameterized types (or the raw type) - this field points to the actual reference type from which they are derived. */ ReferenceType genericType = null; ReferenceTypeDelegate delegate = null; int startPos = 0; int endPos = 0; // cached values for members ResolvedMember[] parameterizedMethods = null; ResolvedMember[] parameterizedFields = null; ResolvedMember[] parameterizedPointcuts = null; WeakReference<ResolvedType[]> parameterizedInterfaces = new WeakReference<ResolvedType[]>(null); Collection<Declare> parameterizedDeclares = null; // Collection parameterizedTypeMungers = null; // During matching it can be necessary to temporary mark types as annotated. For example // a declare @type may trigger a separate declare parents to match, and so the annotation // is temporarily held against the referencetype, the annotation will be properly // added to the class during weaving. private ResolvedType[] annotationTypes = null; private AnnotationAJ[] annotations = null; // Similarly these are temporary replacements and additions for the superclass and // superinterfaces private ResolvedType newSuperclass; private ResolvedType[] newInterfaces; // ??? should set delegate before any use public ReferenceType(String signature, World world) { super(signature, world); } public ReferenceType(String signature, String signatureErasure, World world) { super(signature, signatureErasure, world); } public static ReferenceType fromTypeX(UnresolvedType tx, World world) { ReferenceType rt = new ReferenceType(tx.getErasureSignature(), world); rt.typeKind = tx.typeKind; return rt; } /** * Constructor used when creating a parameterized type. */ public ReferenceType(ResolvedType theGenericType, ResolvedType[] theParameters, World aWorld) { super(makeParameterizedSignature(theGenericType, theParameters), theGenericType.signatureErasure, aWorld); ReferenceType genericReferenceType = (ReferenceType) theGenericType; this.typeParameters = theParameters; this.genericType = genericReferenceType; this.typeKind = TypeKind.PARAMETERIZED; this.delegate = genericReferenceType.getDelegate(); genericReferenceType.addDependentType(this); } /** * Constructor used when creating a raw type. */ // public ReferenceType( // ResolvedType theGenericType, // World aWorld) { // super(theGenericType.getErasureSignature(), // theGenericType.getErasureSignature(), // aWorld); // ReferenceType genericReferenceType = (ReferenceType) theGenericType; // this.typeParameters = null; // this.genericType = genericReferenceType; // this.typeKind = TypeKind.RAW; // this.delegate = genericReferenceType.getDelegate(); // genericReferenceType.addDependentType(this); // } synchronized void addDependentType(ReferenceType dependent) { this.derivativeTypes.add(dependent); } @Override public String getSignatureForAttribute() { if (genericType == null || typeParameters == null) { return getSignature(); } return makeDeclaredSignature(genericType, typeParameters); } /** * Create a reference type for a generic type */ public ReferenceType(UnresolvedType genericType, World world) { super(genericType.getSignature(), world); typeKind = TypeKind.GENERIC; } @Override public boolean isClass() { return getDelegate().isClass(); } @Override public int getCompilerVersion() { return getDelegate().getCompilerVersion(); } @Override public boolean isGenericType() { return !isParameterizedType() && !isRawType() && getDelegate().isGeneric(); } public String getGenericSignature() { String sig = getDelegate().getDeclaredGenericSignature(); return (sig == null) ? "" : sig; } @Override public AnnotationAJ[] getAnnotations() { return getDelegate().getAnnotations(); } @Override public void addAnnotation(AnnotationAJ annotationX) { if (annotations == null) { annotations = new AnnotationAJ[1]; annotations[0] = annotationX; } else { AnnotationAJ[] newAnnotations = new AnnotationAJ[annotations.length + 1]; System.arraycopy(annotations, 0, newAnnotations, 1, annotations.length); newAnnotations[0] = annotationX; annotations = newAnnotations; } addAnnotationType(annotationX.getType()); } public boolean hasAnnotation(UnresolvedType ofType) { boolean onDelegate = getDelegate().hasAnnotation(ofType); if (onDelegate) { return true; } if (annotationTypes != null) { for (int i = 0; i < annotationTypes.length; i++) { if (annotationTypes[i].equals(ofType)) { return true; } } } return false; } private void addAnnotationType(ResolvedType ofType) { if (annotationTypes == null) { annotationTypes = new ResolvedType[1]; annotationTypes[0] = ofType; } else { ResolvedType[] newAnnotationTypes = new ResolvedType[annotationTypes.length + 1]; System.arraycopy(annotationTypes, 0, newAnnotationTypes, 1, annotationTypes.length); newAnnotationTypes[0] = ofType; annotationTypes = newAnnotationTypes; } } @Override public ResolvedType[] getAnnotationTypes() { if (getDelegate() == null) { throw new BCException("Unexpected null delegate for type " + this.getName()); } if (annotationTypes == null) { // there are no extras: return getDelegate().getAnnotationTypes(); } else { ResolvedType[] delegateAnnotationTypes = getDelegate().getAnnotationTypes(); ResolvedType[] result = new ResolvedType[annotationTypes.length + delegateAnnotationTypes.length]; System.arraycopy(delegateAnnotationTypes, 0, result, 0, delegateAnnotationTypes.length); System.arraycopy(annotationTypes, 0, result, delegateAnnotationTypes.length, annotationTypes.length); return result; } } @Override public String getNameAsIdentifier() { return getRawName().replace('.', '_'); } @Override public AnnotationAJ getAnnotationOfType(UnresolvedType ofType) { AnnotationAJ[] axs = getDelegate().getAnnotations(); if (axs != null) { for (int i = 0; i < axs.length; i++) { if (axs[i].getTypeSignature().equals(ofType.getSignature())) { return axs[i]; } } } if (annotations != null) { String searchSig = ofType.getSignature(); for (int i = 0; i < annotations.length; i++) { if (annotations[i].getTypeSignature().equals(searchSig)) { return annotations[i]; } } } return null; } @Override public boolean isAspect() { return getDelegate().isAspect(); } @Override public boolean isAnnotationStyleAspect() { return getDelegate().isAnnotationStyleAspect(); } @Override public boolean isEnum() { return getDelegate().isEnum(); } @Override public boolean isAnnotation() { return getDelegate().isAnnotation(); } @Override public boolean isAnonymous() { return getDelegate().isAnonymous(); } @Override public boolean isNested() { return getDelegate().isNested(); } public ResolvedType getOuterClass() { return getDelegate().getOuterClass(); } public String getRetentionPolicy() { return getDelegate().getRetentionPolicy(); } @Override public boolean isAnnotationWithRuntimeRetention() { return getDelegate().isAnnotationWithRuntimeRetention(); } @Override public boolean canAnnotationTargetType() { return getDelegate().canAnnotationTargetType(); } @Override public AnnotationTargetKind[] getAnnotationTargetKinds() { return getDelegate().getAnnotationTargetKinds(); } // true iff the statement "this = (ThisType) other" would compile @Override public boolean isCoerceableFrom(ResolvedType o) { ResolvedType other = o.resolve(world); if (this.isAssignableFrom(other) || other.isAssignableFrom(this)) { return true; } if (this.isParameterizedType() && other.isParameterizedType()) { return isCoerceableFromParameterizedType(other); } if (this.isParameterizedType() && other.isRawType()) { return ((ReferenceType) this.getRawType()).isCoerceableFrom(other.getGenericType()); } if (this.isRawType() && other.isParameterizedType()) { return this.getGenericType().isCoerceableFrom((other.getRawType())); } if (!this.isInterface() && !other.isInterface()) { return false; } if (this.isFinal() || other.isFinal()) { return false; } // ??? needs to be Methods, not just declared methods? JLS 5.5 unclear ResolvedMember[] a = getDeclaredMethods(); ResolvedMember[] b = other.getDeclaredMethods(); // ??? is this cast // always safe for (int ai = 0, alen = a.length; ai < alen; ai++) { for (int bi = 0, blen = b.length; bi < blen; bi++) { if (!b[bi].isCompatibleWith(a[ai])) { return false; } } } return true; } private final boolean isCoerceableFromParameterizedType(ResolvedType other) { if (!other.isParameterizedType()) { return false; } ResolvedType myRawType = getRawType(); ResolvedType theirRawType = other.getRawType(); if (myRawType == theirRawType || myRawType.isCoerceableFrom(theirRawType)) { if (getTypeParameters().length == other.getTypeParameters().length) { // there's a chance it can be done ResolvedType[] myTypeParameters = getResolvedTypeParameters(); ResolvedType[] theirTypeParameters = other.getResolvedTypeParameters(); for (int i = 0; i < myTypeParameters.length; i++) { if (myTypeParameters[i] != theirTypeParameters[i]) { // thin ice now... but List<String> may still be // coerceable from e.g. List<T> if (myTypeParameters[i].isGenericWildcard()) { BoundedReferenceType wildcard = (BoundedReferenceType) myTypeParameters[i]; if (!wildcard.canBeCoercedTo(theirTypeParameters[i])) { return false; } } else if (myTypeParameters[i].isTypeVariableReference()) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) myTypeParameters[i]; TypeVariable tv = tvrt.getTypeVariable(); tv.resolve(world); if (!tv.canBeBoundTo(theirTypeParameters[i])) { return false; } } else if (theirTypeParameters[i].isTypeVariableReference()) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) theirTypeParameters[i]; TypeVariable tv = tvrt.getTypeVariable(); tv.resolve(world); if (!tv.canBeBoundTo(myTypeParameters[i])) { return false; } } else if (theirTypeParameters[i].isGenericWildcard()) { BoundedReferenceType wildcard = (BoundedReferenceType) theirTypeParameters[i]; if (!wildcard.canBeCoercedTo(myTypeParameters[i])) { return false; } } else { return false; } } } return true; } // } else { // // we do this walk for situations like the following: // // Base<T>, Sub<S,T> extends Base<S> // // is Sub<Y,Z> coerceable from Base<X> ??? // for (Iterator i = getDirectSupertypes(); i.hasNext();) { // ReferenceType parent = (ReferenceType) i.next(); // if (parent.isCoerceableFromParameterizedType(other)) // return true; // } } return false; } @Override public boolean isAssignableFrom(ResolvedType other) { return isAssignableFrom(other, false); } // TODO rewrite this method - it is a terrible mess // true iff the statement "this = other" would compile. @Override public boolean isAssignableFrom(ResolvedType other, boolean allowMissing) { if (other.isPrimitiveType()) { if (!world.isInJava5Mode()) { return false; } if (ResolvedType.validBoxing.contains(this.getSignature() + other.getSignature())) { return true; } } if (this == other) { return true; } if (this.getSignature().equals("Ljava/lang/Object;")) { return true; } if (!isTypeVariableReference() && other.getSignature().equals("Ljava/lang/Object;")) { return false; } boolean thisRaw = this.isRawType(); if (thisRaw && other.isParameterizedOrGenericType()) { return isAssignableFrom(other.getRawType()); } boolean thisGeneric = this.isGenericType(); if (thisGeneric && other.isParameterizedOrRawType()) { return isAssignableFrom(other.getGenericType()); } if (this.isParameterizedType()) { // look at wildcards... if (((ReferenceType) this.getRawType()).isAssignableFrom(other)) { boolean wildcardsAllTheWay = true; ResolvedType[] myParameters = this.getResolvedTypeParameters(); for (int i = 0; i < myParameters.length; i++) { if (!myParameters[i].isGenericWildcard()) { wildcardsAllTheWay = false; } else { BoundedReferenceType boundedRT = (BoundedReferenceType) myParameters[i]; if (boundedRT.isExtends() || boundedRT.isSuper()) { wildcardsAllTheWay = false; } } } if (wildcardsAllTheWay && !other.isParameterizedType()) { return true; } // we have to match by parameters one at a time ResolvedType[] theirParameters = other.getResolvedTypeParameters(); boolean parametersAssignable = true; if (myParameters.length == theirParameters.length) { for (int i = 0; i < myParameters.length && parametersAssignable; i++) { if (myParameters[i] == theirParameters[i]) { continue; } // dont do this: pr253109 // if (myParameters[i].isAssignableFrom(theirParameters[i], allowMissing)) { // continue; // } ResolvedType mp = myParameters[i]; ResolvedType tp = theirParameters[i]; if (mp.isParameterizedType() && tp.isParameterizedType()) { if (mp.getGenericType().equals(tp.getGenericType())) { UnresolvedType[] mtps = mp.getTypeParameters(); UnresolvedType[] ttps = tp.getTypeParameters(); for (int ii = 0; ii < mtps.length; ii++) { if (mtps[ii].isTypeVariableReference() && ttps[ii].isTypeVariableReference()) { TypeVariable mtv = ((TypeVariableReferenceType) mtps[ii]).getTypeVariable(); boolean b = mtv.canBeBoundTo((ResolvedType) ttps[ii]); if (!b) {// TODO incomplete testing here I think parametersAssignable = false; break; } } else { parametersAssignable = false; break; } } continue; } else { parametersAssignable = false; break; } } if (myParameters[i].isTypeVariableReference() && theirParameters[i].isTypeVariableReference()) { TypeVariable myTV = ((TypeVariableReferenceType) myParameters[i]).getTypeVariable(); // TypeVariable theirTV = ((TypeVariableReferenceType) theirParameters[i]).getTypeVariable(); boolean b = myTV.canBeBoundTo(theirParameters[i]); if (!b) {// TODO incomplete testing here I think parametersAssignable = false; break; } else { continue; } } if (!myParameters[i].isGenericWildcard()) { parametersAssignable = false; break; } else { BoundedReferenceType wildcardType = (BoundedReferenceType) myParameters[i]; if (!wildcardType.alwaysMatches(theirParameters[i])) { parametersAssignable = false; break; } } } } else { parametersAssignable = false; } if (parametersAssignable) { return true; } } } // eg this=T other=Ljava/lang/Object; if (isTypeVariableReference() && !other.isTypeVariableReference()) { TypeVariable aVar = ((TypeVariableReference) this).getTypeVariable(); return aVar.resolve(world).canBeBoundTo(other); } if (other.isTypeVariableReference()) { TypeVariableReferenceType otherType = (TypeVariableReferenceType) other; if (this instanceof TypeVariableReference) { return ((TypeVariableReference) this).getTypeVariable().resolve(world) .canBeBoundTo(otherType.getTypeVariable().getFirstBound().resolve(world));// pr171952 // return // ((TypeVariableReference)this).getTypeVariable()==otherType // .getTypeVariable(); } else { // FIXME asc should this say canBeBoundTo?? return this.isAssignableFrom(otherType.getTypeVariable().getFirstBound().resolve(world)); } } if (allowMissing && other.isMissing()) { return false; } ResolvedType[] interfaces = other.getDeclaredInterfaces(); for (ResolvedType intface : interfaces) { boolean b; if (thisRaw && intface.isParameterizedOrGenericType()) { b = this.isAssignableFrom(intface.getRawType(), allowMissing); } else { b = this.isAssignableFrom(intface, allowMissing); } if (b) { return true; } } ResolvedType superclass = other.getSuperclass(); if (superclass != null) { boolean b; if (thisRaw && superclass.isParameterizedOrGenericType()) { b = this.isAssignableFrom(superclass.getRawType(), allowMissing); } else { b = this.isAssignableFrom(superclass, allowMissing); } if (b) { return true; } } return false; } @Override public ISourceContext getSourceContext() { return getDelegate().getSourceContext(); } @Override public ISourceLocation getSourceLocation() { ISourceContext isc = getDelegate().getSourceContext(); return isc.makeSourceLocation(new Position(startPos, endPos)); } @Override public boolean isExposedToWeaver() { return (getDelegate() == null) || delegate.isExposedToWeaver(); } @Override public WeaverStateInfo getWeaverState() { return getDelegate().getWeaverState(); } @Override public ResolvedMember[] getDeclaredFields() { if (parameterizedFields != null) { return parameterizedFields; } if (isParameterizedType() || isRawType()) { ResolvedMember[] delegateFields = getDelegate().getDeclaredFields(); parameterizedFields = new ResolvedMember[delegateFields.length]; for (int i = 0; i < delegateFields.length; i++) { parameterizedFields[i] = delegateFields[i].parameterizedWith(getTypesForMemberParameterization(), this, isParameterizedType()); } return parameterizedFields; } else { return getDelegate().getDeclaredFields(); } } /** * Find out from the generic signature the true signature of any interfaces I implement. If I am parameterized, these may then * need to be parameterized before returning. */ @Override public ResolvedType[] getDeclaredInterfaces() { ResolvedType[] interfaces = parameterizedInterfaces.get(); if (interfaces != null) { return interfaces; } ResolvedType[] delegateInterfaces = getDelegate().getDeclaredInterfaces(); if (isRawType()) { if (newInterfaces != null) { throw new IllegalStateException( "The raw type should never be accumulating new interfaces, they should be on the generic type. Type is " + this.getName()); } ResolvedType[] newInterfacesFromGenericType = genericType.newInterfaces; if (newInterfacesFromGenericType != null) { ResolvedType[] extraInterfaces = new ResolvedType[delegateInterfaces.length + newInterfacesFromGenericType.length]; System.arraycopy(delegateInterfaces, 0, extraInterfaces, 0, delegateInterfaces.length); System.arraycopy(newInterfacesFromGenericType, 0, extraInterfaces, delegateInterfaces.length, newInterfacesFromGenericType.length); delegateInterfaces = extraInterfaces; } } else if (newInterfaces != null) { // OPTIMIZE does this part of the method trigger often? ResolvedType[] extraInterfaces = new ResolvedType[delegateInterfaces.length + newInterfaces.length]; System.arraycopy(delegateInterfaces, 0, extraInterfaces, 0, delegateInterfaces.length); System.arraycopy(newInterfaces, 0, extraInterfaces, delegateInterfaces.length, newInterfaces.length); delegateInterfaces = extraInterfaces; } if (isParameterizedType()) { // UnresolvedType[] paramTypes = // getTypesForMemberParameterization(); interfaces = new ResolvedType[delegateInterfaces.length]; for (int i = 0; i < delegateInterfaces.length; i++) { // We may have to sub/super set the set of parametertypes if the // implemented interface // needs more or less than this type does. (pr124803/pr125080) if (delegateInterfaces[i].isParameterizedType()) { interfaces[i] = delegateInterfaces[i].parameterize(getMemberParameterizationMap()).resolve(world); } else { interfaces[i] = delegateInterfaces[i]; } } parameterizedInterfaces = new WeakReference<ResolvedType[]>(interfaces); return interfaces; } else if (isRawType()) { UnresolvedType[] paramTypes = getTypesForMemberParameterization(); interfaces = new ResolvedType[delegateInterfaces.length]; for (int i = 0, max = interfaces.length; i < max; i++) { interfaces[i] = delegateInterfaces[i]; if (interfaces[i].isGenericType()) { // a generic supertype of a raw type is replaced by its raw // equivalent interfaces[i] = interfaces[i].getRawType().resolve(getWorld()); } else if (interfaces[i].isParameterizedType()) { // a parameterized supertype collapses any type vars to // their upper bounds UnresolvedType[] toUseForParameterization = determineThoseTypesToUse(interfaces[i], paramTypes); interfaces[i] = interfaces[i].parameterizedWith(toUseForParameterization); } } parameterizedInterfaces = new WeakReference<ResolvedType[]>(interfaces); return interfaces; } if (getDelegate().isCacheable()) { parameterizedInterfaces = new WeakReference<ResolvedType[]>(delegateInterfaces); } return delegateInterfaces; } // private String toString(ResolvedType[] delegateInterfaces) { // StringBuffer sb = new StringBuffer(); // if (delegateInterfaces != null) { // for (ResolvedType rt : delegateInterfaces) { // sb.append(rt).append(" "); // } // } // return sb.toString(); // } /** * Locates the named type variable in the list of those on this generic type and returns the type parameter from the second list * supplied. Returns null if it can't be found */ // private UnresolvedType findTypeParameterInList(String name, // TypeVariable[] tvarsOnThisGenericType, UnresolvedType[] // paramTypes) { // int position = -1; // for (int i = 0; i < tvarsOnThisGenericType.length; i++) { // TypeVariable tv = tvarsOnThisGenericType[i]; // if (tv.getName().equals(name)) position = i; // } // if (position == -1 ) return null; // return paramTypes[position]; // } /** * It is possible this type has multiple type variables but the interface we are about to parameterize only uses a subset - this * method determines the subset to use by looking at the type variable names used. For example: <code> * class Foo<T extends String,E extends Number> implements SuperInterface<T> {} * </code> where <code> * interface SuperInterface<Z> {} * </code> In that example, a use of the 'Foo' raw type should know that it implements the SuperInterface<String>. */ private UnresolvedType[] determineThoseTypesToUse(ResolvedType parameterizedInterface, UnresolvedType[] paramTypes) { // What are the type parameters for the supertype? UnresolvedType[] tParms = parameterizedInterface.getTypeParameters(); UnresolvedType[] retVal = new UnresolvedType[tParms.length]; // Go through the supertypes type parameters, if any of them is a type // variable, use the // real type variable on the declaring type. // it is possibly overkill to look up the type variable - ideally the // entry in the type parameter list for the // interface should be the a ref to the type variable in the current // type ... but I'm not 100% confident right now. for (int i = 0; i < tParms.length; i++) { UnresolvedType tParm = tParms[i]; if (tParm.isTypeVariableReference()) { TypeVariableReference tvrt = (TypeVariableReference) tParm; TypeVariable tv = tvrt.getTypeVariable(); int rank = getRank(tv.getName()); // -1 probably means it is a reference to a type variable on the // outer generic type (see pr129566) if (rank != -1) { retVal[i] = paramTypes[rank]; } else { retVal[i] = tParms[i]; } } else { retVal[i] = tParms[i]; } } return retVal; } /** * Returns the position within the set of type variables for this type for the specified type variable name. Returns -1 if there * is no type variable with the specified name. */ private int getRank(String tvname) { TypeVariable[] thisTypesTVars = getGenericType().getTypeVariables(); for (int i = 0; i < thisTypesTVars.length; i++) { TypeVariable tv = thisTypesTVars[i]; if (tv.getName().equals(tvname)) { return i; } } return -1; } @Override public ResolvedMember[] getDeclaredMethods() { if (parameterizedMethods != null) { return parameterizedMethods; } if (isParameterizedType() || isRawType()) { ResolvedMember[] delegateMethods = getDelegate().getDeclaredMethods(); UnresolvedType[] parameters = getTypesForMemberParameterization(); parameterizedMethods = new ResolvedMember[delegateMethods.length]; for (int i = 0; i < delegateMethods.length; i++) { parameterizedMethods[i] = delegateMethods[i].parameterizedWith(parameters, this, isParameterizedType()); } return parameterizedMethods; } else { return getDelegate().getDeclaredMethods(); } } @Override public ResolvedMember[] getDeclaredPointcuts() { if (parameterizedPointcuts != null) { return parameterizedPointcuts; } if (isParameterizedType()) { ResolvedMember[] delegatePointcuts = getDelegate().getDeclaredPointcuts(); parameterizedPointcuts = new ResolvedMember[delegatePointcuts.length]; for (int i = 0; i < delegatePointcuts.length; i++) { parameterizedPointcuts[i] = delegatePointcuts[i].parameterizedWith(getTypesForMemberParameterization(), this, isParameterizedType()); } return parameterizedPointcuts; } else { return getDelegate().getDeclaredPointcuts(); } } private UnresolvedType[] getTypesForMemberParameterization() { UnresolvedType[] parameters = null; if (isParameterizedType()) { parameters = getTypeParameters(); } else if (isRawType()) { // raw type, use upper bounds of type variables on generic type TypeVariable[] tvs = getGenericType().getTypeVariables(); parameters = new UnresolvedType[tvs.length]; for (int i = 0; i < tvs.length; i++) { parameters[i] = tvs[i].getFirstBound(); } } return parameters; } @Override public TypeVariable[] getTypeVariables() { if (this.typeVariables == null) { this.typeVariables = getDelegate().getTypeVariables(); for (int i = 0; i < this.typeVariables.length; i++) { this.typeVariables[i].resolve(world); } } return this.typeVariables; } @Override public PerClause getPerClause() { PerClause pclause = getDelegate().getPerClause(); if (pclause != null && isParameterizedType()) { // could cache the result here... Map<String, UnresolvedType> parameterizationMap = getAjMemberParameterizationMap(); pclause = (PerClause) pclause.parameterizeWith(parameterizationMap, world); } return pclause; } @Override public Collection<Declare> getDeclares() { if (parameterizedDeclares != null) { return parameterizedDeclares; } Collection<Declare> declares = null; if (ajMembersNeedParameterization()) { Collection<Declare> genericDeclares = getDelegate().getDeclares(); parameterizedDeclares = new ArrayList<Declare>(); Map<String, UnresolvedType> parameterizationMap = getAjMemberParameterizationMap(); for (Declare declareStatement : genericDeclares) { parameterizedDeclares.add(declareStatement.parameterizeWith(parameterizationMap, world)); } declares = parameterizedDeclares; } else { declares = getDelegate().getDeclares(); } for (Declare d : declares) { d.setDeclaringType(this); } return declares; } @Override public Collection<ConcreteTypeMunger> getTypeMungers() { return getDelegate().getTypeMungers(); } // GENERICITDFIX // // Map parameterizationMap = getAjMemberParameterizationMap(); // // // if (parameterizedTypeMungers != null) return parameterizedTypeMungers; // Collection ret = null; // if (ajMembersNeedParameterization()) { // Collection genericDeclares = delegate.getTypeMungers(); // parameterizedTypeMungers = new ArrayList(); // Map parameterizationMap = getAjMemberParameterizationMap(); // for (Iterator iter = genericDeclares.iterator(); iter.hasNext();) { // ConcreteTypeMunger munger = (ConcreteTypeMunger)iter.next(); // parameterizedTypeMungers.add(munger.parameterizeWith(parameterizationMap, // world)); // } // ret = parameterizedTypeMungers; // } else { // ret = delegate.getTypeMungers(); // } // return ret; // } @Override public Collection<ResolvedMember> getPrivilegedAccesses() { return getDelegate().getPrivilegedAccesses(); } @Override public int getModifiers() { return getDelegate().getModifiers(); } WeakReference<ResolvedType> superclassReference = new WeakReference<ResolvedType>(null); @Override public ResolvedType getSuperclass() { ResolvedType ret = null;// superclassReference.get(); // if (ret != null) { // return ret; // } if (newSuperclass != null) { if (this.isParameterizedType() && newSuperclass.isParameterizedType()) { return newSuperclass.parameterize(getMemberParameterizationMap()).resolve(getWorld()); } if (getDelegate().isCacheable()) { superclassReference = new WeakReference<ResolvedType>(ret); } return newSuperclass; } try { world.setTypeVariableLookupScope(this); ret = getDelegate().getSuperclass(); } finally { world.setTypeVariableLookupScope(null); } if (this.isParameterizedType() && ret.isParameterizedType()) { ret = ret.parameterize(getMemberParameterizationMap()).resolve(getWorld()); } if (getDelegate().isCacheable()) { superclassReference = new WeakReference<ResolvedType>(ret); } return ret; } public ReferenceTypeDelegate getDelegate() { return delegate; } public void setDelegate(ReferenceTypeDelegate delegate) { // Don't copy from BcelObjectType to EclipseSourceType - the context may // be tidied (result null'd) after previous weaving if (this.delegate != null && this.delegate.copySourceContext() && this.delegate.getSourceContext() != SourceContextImpl.UNKNOWN_SOURCE_CONTEXT) { ((AbstractReferenceTypeDelegate) delegate).setSourceContext(this.delegate.getSourceContext()); } this.delegate = delegate; for (ReferenceType dependent : derivativeTypes) { dependent.setDelegate(delegate); } // If we are raw, we have a generic type - we should ensure it uses the // same delegate if (isRawType() && getGenericType() != null) { ReferenceType genType = (ReferenceType) getGenericType(); if (genType.getDelegate() != delegate) { // avoids circular updates genType.setDelegate(delegate); } } clearParameterizationCaches(); ensureConsistent(); } private void clearParameterizationCaches() { parameterizedFields = null; parameterizedInterfaces.clear(); parameterizedMethods = null; parameterizedPointcuts = null; superclassReference = new WeakReference<ResolvedType>(null); } public int getEndPos() { return endPos; } public int getStartPos() { return startPos; } public void setEndPos(int endPos) { this.endPos = endPos; } public void setStartPos(int startPos) { this.startPos = startPos; } @Override public boolean doesNotExposeShadowMungers() { return getDelegate().doesNotExposeShadowMungers(); } public String getDeclaredGenericSignature() { return getDelegate().getDeclaredGenericSignature(); } public void setGenericType(ReferenceType rt) { genericType = rt; // Should we 'promote' this reference type from simple to raw? // makes sense if someone is specifying that it has a generic form if (typeKind == TypeKind.SIMPLE) { typeKind = TypeKind.RAW; signatureErasure = signature; } if (typeKind == TypeKind.RAW) { genericType.addDependentType(this); } if (this.isRawType() && rt.isRawType()) { new RuntimeException("PR341926 diagnostics: Incorrect setup for a generic type, raw type should not point to raw: " + this.getName()).printStackTrace(); } } public void demoteToSimpleType() { genericType = null; typeKind = TypeKind.SIMPLE; signatureErasure = null; } @Override public ResolvedType getGenericType() { if (isGenericType()) { return this; } return genericType; } /** * a parameterized signature starts with a "P" in place of the "L", see the comment on signatures in UnresolvedType. * * @param aGenericType * @param someParameters * @return */ private static String makeParameterizedSignature(ResolvedType aGenericType, ResolvedType[] someParameters) { String rawSignature = aGenericType.getErasureSignature(); StringBuffer ret = new StringBuffer(); ret.append(PARAMETERIZED_TYPE_IDENTIFIER); ret.append(rawSignature.substring(1, rawSignature.length() - 1)); ret.append("<"); for (int i = 0; i < someParameters.length; i++) { ret.append(someParameters[i].getSignature()); } ret.append(">;"); return ret.toString(); } private static String makeDeclaredSignature(ResolvedType aGenericType, UnresolvedType[] someParameters) { StringBuffer ret = new StringBuffer(); String rawSig = aGenericType.getErasureSignature(); ret.append(rawSig.substring(0, rawSig.length() - 1)); ret.append("<"); for (int i = 0; i < someParameters.length; i++) { try { ret.append(((ReferenceType) someParameters[i]).getSignatureForAttribute()); } catch (ClassCastException cce) { throw new IllegalStateException("DebugFor325731: expected a ReferenceType but was " + someParameters[i] + " of type " + someParameters[i].getClass().getName(), cce); } } ret.append(">;"); return ret.toString(); } @Override public void ensureConsistent() { annotations = null; annotationTypes = null; newSuperclass = null; newInterfaces = null; typeVariables = null; parameterizedInterfaces.clear(); superclassReference = new WeakReference<ResolvedType>(null); if (getDelegate() != null) { delegate.ensureConsistent(); } } @Override public void addParent(ResolvedType newParent) { if (newParent.isClass()) { newSuperclass = newParent; superclassReference = new WeakReference<ResolvedType>(null); } else { if (newInterfaces == null) { newInterfaces = new ResolvedType[1]; newInterfaces[0] = newParent; } else { ResolvedType[] existing = getDelegate().getDeclaredInterfaces(); if (existing != null) { for (int i = 0; i < existing.length; i++) { if (existing[i].equals(newParent)) { return; // already has this interface } } } ResolvedType[] newNewInterfaces = new ResolvedType[newInterfaces.length + 1]; System.arraycopy(newInterfaces, 0, newNewInterfaces, 1, newInterfaces.length); newNewInterfaces[0] = newParent; newInterfaces = newNewInterfaces; } if (this.isGenericType()) { for (ReferenceType derivativeType : derivativeTypes) { derivativeType.parameterizedInterfaces.clear(); } } parameterizedInterfaces.clear(); } } }
374,745
Bug 374745 Performance regression in 1.6.12
null
resolved fixed
549d227
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-03-23T23:57:10Z"
"2012-03-20T10:40:00Z"
org.aspectj.matcher/src/org/aspectj/weaver/ResolvedType.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; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; 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.Queue; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjAttribute.WeaverVersionInfo; import org.aspectj.weaver.Iterators.Getter; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.PerClause; public abstract class ResolvedType extends UnresolvedType implements AnnotatedElement { public static final ResolvedType[] EMPTY_RESOLVED_TYPE_ARRAY = new ResolvedType[0]; public static final String PARAMETERIZED_TYPE_IDENTIFIER = "P"; // Set temporarily during a type pattern match call - this currently used to hold the // annotations that may be attached to a type when it used as a parameter public ResolvedType[] temporaryAnnotationTypes; private ResolvedType[] resolvedTypeParams; private String binaryPath; protected World world; private int bits; private static int AnnotationBitsInitialized = 0x0001; private static int AnnotationMarkedInherited = 0x0002; private static int MungersAnalyzed = 0x0004; private static int HasParentMunger = 0x0008; private static int TypeHierarchyCompleteBit = 0x0010; private static int GroovyObjectInitialized = 0x0020; private static int IsGroovyObject = 0x0040; protected ResolvedType(String signature, World world) { super(signature); this.world = world; } protected ResolvedType(String signature, String signatureErasure, World world) { super(signature, signatureErasure); this.world = world; } public int getSize() { return 1; } /** * Returns an iterator through ResolvedType objects representing all the direct supertypes of this type. That is, through the * superclass, if any, and all declared interfaces. */ public final Iterator<ResolvedType> getDirectSupertypes() { Iterator<ResolvedType> interfacesIterator = Iterators.array(getDeclaredInterfaces()); ResolvedType superclass = getSuperclass(); if (superclass == null) { return interfacesIterator; } else { return Iterators.snoc(interfacesIterator, superclass); } } public abstract ResolvedMember[] getDeclaredFields(); public abstract ResolvedMember[] getDeclaredMethods(); public abstract ResolvedType[] getDeclaredInterfaces(); public abstract ResolvedMember[] getDeclaredPointcuts(); public boolean isCacheable() { return true; } /** * @return the superclass of this type, or null (if this represents a jlObject, primitive, or void) */ public abstract ResolvedType getSuperclass(); public abstract int getModifiers(); // return true if this resolved type couldn't be found (but we know it's name maybe) public boolean isMissing() { return false; } // FIXME asc I wonder if in some circumstances MissingWithKnownSignature // should not be considered // 'really' missing as some code can continue based solely on the signature public static boolean isMissing(UnresolvedType unresolved) { if (unresolved instanceof ResolvedType) { ResolvedType resolved = (ResolvedType) unresolved; return resolved.isMissing(); } else { return (unresolved == MISSING); } } public ResolvedType[] getAnnotationTypes() { return EMPTY_RESOLVED_TYPE_ARRAY; } public AnnotationAJ getAnnotationOfType(UnresolvedType ofType) { return null; } // public final UnresolvedType getSuperclass(World world) { // return getSuperclass(); // } // This set contains pairs of types whose signatures are concatenated // together, this means with a fast lookup we can tell if two types // are equivalent. protected static Set<String> validBoxing = new HashSet<String>(); static { validBoxing.add("Ljava/lang/Byte;B"); validBoxing.add("Ljava/lang/Character;C"); validBoxing.add("Ljava/lang/Double;D"); validBoxing.add("Ljava/lang/Float;F"); validBoxing.add("Ljava/lang/Integer;I"); validBoxing.add("Ljava/lang/Long;J"); validBoxing.add("Ljava/lang/Short;S"); validBoxing.add("Ljava/lang/Boolean;Z"); validBoxing.add("BLjava/lang/Byte;"); validBoxing.add("CLjava/lang/Character;"); validBoxing.add("DLjava/lang/Double;"); validBoxing.add("FLjava/lang/Float;"); validBoxing.add("ILjava/lang/Integer;"); validBoxing.add("JLjava/lang/Long;"); validBoxing.add("SLjava/lang/Short;"); validBoxing.add("ZLjava/lang/Boolean;"); } // utilities public ResolvedType getResolvedComponentType() { return null; } public World getWorld() { return world; } // ---- things from object @Override public final boolean equals(Object other) { if (other instanceof ResolvedType) { return this == other; } else { return super.equals(other); } } // ---- difficult things /** * returns an iterator through all of the fields of this type, in order for checking from JVM spec 2ed 5.4.3.2. This means that * the order is * <p/> * <ul> * <li>fields from current class</li> * <li>recur into direct superinterfaces</li> * <li>recur into superclass</li> * </ul> * <p/> * We keep a hashSet of interfaces that we've visited so we don't spiral out into 2^n land. */ public Iterator<ResolvedMember> getFields() { final Iterators.Filter<ResolvedType> dupFilter = Iterators.dupFilter(); Iterators.Getter<ResolvedType, ResolvedType> typeGetter = new Iterators.Getter<ResolvedType, ResolvedType>() { public Iterator<ResolvedType> get(ResolvedType o) { return dupFilter.filter(o.getDirectSupertypes()); } }; return Iterators.mapOver(Iterators.recur(this, typeGetter), FieldGetterInstance); } /** * returns an iterator through all of the methods of this type, in order for checking from JVM spec 2ed 5.4.3.3. This means that * the order is * <p/> * <ul> * <li>methods from current class</li> * <li>recur into superclass, all the way up, not touching interfaces</li> * <li>recur into all superinterfaces, in some unspecified order (but those 'closest' to this type are first)</li> * </ul> * <p/> * * @param wantGenerics is true if the caller would like all generics information, otherwise those methods are collapsed to their * erasure */ public Iterator<ResolvedMember> getMethods(boolean wantGenerics, boolean wantDeclaredParents) { return Iterators.mapOver(getHierarchy(wantGenerics, wantDeclaredParents), MethodGetterInstance); } public Iterator<ResolvedMember> getMethodsIncludingIntertypeDeclarations(boolean wantGenerics, boolean wantDeclaredParents) { return Iterators.mapOver(getHierarchy(wantGenerics, wantDeclaredParents), MethodGetterWithItdsInstance); } /** * An Iterators.Getter that returns an iterator over all methods declared on some resolved type. */ private static class MethodGetter implements Iterators.Getter<ResolvedType, ResolvedMember> { public Iterator<ResolvedMember> get(ResolvedType type) { return Iterators.array(type.getDeclaredMethods()); } } /** * An Iterators.Getter that returns an iterator over all pointcuts declared on some resolved type. */ private static class PointcutGetter implements Iterators.Getter<ResolvedType, ResolvedMember> { public Iterator<ResolvedMember> get(ResolvedType o) { return Iterators.array(o.getDeclaredPointcuts()); } } // OPTIMIZE could cache the result of discovering ITDs // Getter that returns all declared methods for a type through an iterator - including intertype declarations private static class MethodGetterIncludingItds implements Iterators.Getter<ResolvedType, ResolvedMember> { public Iterator<ResolvedMember> get(ResolvedType type) { ResolvedMember[] methods = type.getDeclaredMethods(); if (type.interTypeMungers != null) { int additional = 0; for (ConcreteTypeMunger typeTransformer : type.interTypeMungers) { ResolvedMember rm = typeTransformer.getSignature(); // BUG won't this include fields? When we are looking for methods if (rm != null) { // new parent type munger can have null signature additional++; } } if (additional > 0) { ResolvedMember[] methods2 = new ResolvedMember[methods.length + additional]; System.arraycopy(methods, 0, methods2, 0, methods.length); additional = methods.length; for (ConcreteTypeMunger typeTransformer : type.interTypeMungers) { ResolvedMember rm = typeTransformer.getSignature(); if (rm != null) { // new parent type munger can have null signature methods2[additional++] = typeTransformer.getSignature(); } } methods = methods2; } } return Iterators.array(methods); } } /** * An Iterators.Getter that returns an iterator over all fields declared on some resolved type. */ private static class FieldGetter implements Iterators.Getter<ResolvedType, ResolvedMember> { public Iterator<ResolvedMember> get(ResolvedType type) { return Iterators.array(type.getDeclaredFields()); } } private final static MethodGetter MethodGetterInstance = new MethodGetter(); private final static MethodGetterIncludingItds MethodGetterWithItdsInstance = new MethodGetterIncludingItds(); private final static PointcutGetter PointcutGetterInstance = new PointcutGetter(); private final static FieldGetter FieldGetterInstance = new FieldGetter(); /** * Return an iterator over the types in this types hierarchy - starting with this type first, then all superclasses up to Object * and then all interfaces (starting with those 'nearest' this type). * * @param wantGenerics true if the caller wants full generic information * @param wantDeclaredParents true if the caller even wants those parents introduced via declare parents * @return an iterator over all types in the hierarchy of this type */ public Iterator<ResolvedType> getHierarchy() { return getHierarchy(false, false); } public Iterator<ResolvedType> getHierarchy(final boolean wantGenerics, final boolean wantDeclaredParents) { final Iterators.Getter<ResolvedType, ResolvedType> interfaceGetter = new Iterators.Getter<ResolvedType, ResolvedType>() { List<String> alreadySeen = new ArrayList<String>(); // Strings are signatures (ResolvedType.getSignature()) public Iterator<ResolvedType> get(ResolvedType type) { ResolvedType[] interfaces = type.getDeclaredInterfaces(); // remove interfaces introduced by declare parents // relatively expensive but hopefully uncommon if (!wantDeclaredParents && type.hasNewParentMungers()) { // Throw away interfaces from that array if they were decp'd onto here List<Integer> forRemoval = new ArrayList<Integer>(); for (ConcreteTypeMunger munger : type.interTypeMungers) { if (munger.getMunger() != null) { ResolvedTypeMunger m = munger.getMunger(); if (m.getKind() == ResolvedTypeMunger.Parent) { ResolvedType newType = ((NewParentTypeMunger) m).getNewParent(); if (!wantGenerics && newType.isParameterizedOrGenericType()) { newType = newType.getRawType(); } for (int ii = 0; ii < interfaces.length; ii++) { ResolvedType iface = interfaces[ii]; if (!wantGenerics && iface.isParameterizedOrGenericType()) { iface = iface.getRawType(); } if (newType.getSignature().equals(iface.getSignature())) { // pr171953 forRemoval.add(ii); } } } } } // Found some to remove from those we are going to iterate over if (forRemoval.size() > 0) { ResolvedType[] interfaces2 = new ResolvedType[interfaces.length - forRemoval.size()]; int p = 0; for (int ii = 0; ii < interfaces.length; ii++) { if (!forRemoval.contains(ii)) { interfaces2[p++] = interfaces[ii]; } } interfaces = interfaces2; } } return new Iterators.ResolvedTypeArrayIterator(interfaces, alreadySeen, wantGenerics); } }; // If this type is an interface, there are only interfaces to walk if (this.isInterface()) { return new SuperInterfaceWalker(interfaceGetter, this); } else { SuperInterfaceWalker superInterfaceWalker = new SuperInterfaceWalker(interfaceGetter); Iterator<ResolvedType> superClassesIterator = new SuperClassWalker(this, superInterfaceWalker, wantGenerics); // append() will check if the second iterator is empty before appending - but the types which the superInterfaceWalker // needs to visit are only accumulated whilst the superClassesIterator is in progress return Iterators.append1(superClassesIterator, superInterfaceWalker); } } /** * Return a list of methods, first those declared on this class, then those declared on the superclass (recurse) and then those * declared on the superinterfaces. This is expensive - use the getMethods() method if you can! */ public List<ResolvedMember> getMethodsWithoutIterator(boolean includeITDs, boolean allowMissing, boolean genericsAware) { List<ResolvedMember> methods = new ArrayList<ResolvedMember>(); Set<String> knowninterfaces = new HashSet<String>(); addAndRecurse(knowninterfaces, methods, this, includeITDs, allowMissing, genericsAware); return methods; } /** * Return a list of the types in the hierarchy of this type, starting with this type. The order in the list is the superclasses * followed by the super interfaces. * * @param genericsAware should the list include parameterized/generic types (if not, they will be collapsed to raw)? * @return list of resolvedtypes in this types hierarchy, including this type first */ public List<ResolvedType> getHierarchyWithoutIterator(boolean includeITDs, boolean allowMissing, boolean genericsAware) { List<ResolvedType> types = new ArrayList<ResolvedType>(); Set<String> visited = new HashSet<String>(); recurseHierarchy(visited, types, this, includeITDs, allowMissing, genericsAware); return types; } private void addAndRecurse(Set<String> knowninterfaces, List<ResolvedMember> collector, ResolvedType resolvedType, boolean includeITDs, boolean allowMissing, boolean genericsAware) { // Add the methods declared on this type collector.addAll(Arrays.asList(resolvedType.getDeclaredMethods())); // now add all the inter-typed members too if (includeITDs && resolvedType.interTypeMungers != null) { for (ConcreteTypeMunger typeTransformer : interTypeMungers) { ResolvedMember rm = typeTransformer.getSignature(); if (rm != null) { // new parent type munger can have null signature collector.add(typeTransformer.getSignature()); } } } // BUG? interface type superclass is Object - is that correct? if (!resolvedType.isInterface() && !resolvedType.equals(ResolvedType.OBJECT)) { ResolvedType superType = resolvedType.getSuperclass(); if (superType != null && !superType.isMissing()) { if (!genericsAware && superType.isParameterizedOrGenericType()) { superType = superType.getRawType(); } // Recurse if we are not at the top addAndRecurse(knowninterfaces, collector, superType, includeITDs, allowMissing, genericsAware); } } // Go through the interfaces on the way back down ResolvedType[] interfaces = resolvedType.getDeclaredInterfaces(); for (int i = 0; i < interfaces.length; i++) { ResolvedType iface = interfaces[i]; if (!genericsAware && iface.isParameterizedOrGenericType()) { iface = iface.getRawType(); } // we need to know if it is an interface from Parent kind munger // as those are used for @AJ ITD and we precisely want to skip those boolean shouldSkip = false; for (int j = 0; j < resolvedType.interTypeMungers.size(); j++) { ConcreteTypeMunger munger = resolvedType.interTypeMungers.get(j); if (munger.getMunger() != null && munger.getMunger().getKind() == ResolvedTypeMunger.Parent && ((NewParentTypeMunger) munger.getMunger()).getNewParent().equals(iface) // pr171953 ) { shouldSkip = true; break; } } // Do not do interfaces more than once if (!shouldSkip && !knowninterfaces.contains(iface.getSignature())) { knowninterfaces.add(iface.getSignature()); if (allowMissing && iface.isMissing()) { if (iface instanceof MissingResolvedTypeWithKnownSignature) { ((MissingResolvedTypeWithKnownSignature) iface).raiseWarningOnMissingInterfaceWhilstFindingMethods(); } } else { addAndRecurse(knowninterfaces, collector, iface, includeITDs, allowMissing, genericsAware); } } } } /** * Recurse up a type hierarchy, first the superclasses then the super interfaces. */ private void recurseHierarchy(Set<String> knowninterfaces, List<ResolvedType> collector, ResolvedType resolvedType, boolean includeITDs, boolean allowMissing, boolean genericsAware) { collector.add(resolvedType); if (!resolvedType.isInterface() && !resolvedType.equals(ResolvedType.OBJECT)) { ResolvedType superType = resolvedType.getSuperclass(); if (superType != null && !superType.isMissing()) { if (!genericsAware && (superType.isParameterizedType() || superType.isGenericType())) { superType = superType.getRawType(); } // Recurse if we are not at the top recurseHierarchy(knowninterfaces, collector, superType, includeITDs, allowMissing, genericsAware); } } // Go through the interfaces on the way back down ResolvedType[] interfaces = resolvedType.getDeclaredInterfaces(); for (int i = 0; i < interfaces.length; i++) { ResolvedType iface = interfaces[i]; if (!genericsAware && (iface.isParameterizedType() || iface.isGenericType())) { iface = iface.getRawType(); } // we need to know if it is an interface from Parent kind munger // as those are used for @AJ ITD and we precisely want to skip those boolean shouldSkip = false; for (int j = 0; j < resolvedType.interTypeMungers.size(); j++) { ConcreteTypeMunger munger = resolvedType.interTypeMungers.get(j); if (munger.getMunger() != null && munger.getMunger().getKind() == ResolvedTypeMunger.Parent && ((NewParentTypeMunger) munger.getMunger()).getNewParent().equals(iface) // pr171953 ) { shouldSkip = true; break; } } // Do not do interfaces more than once if (!shouldSkip && !knowninterfaces.contains(iface.getSignature())) { knowninterfaces.add(iface.getSignature()); if (allowMissing && iface.isMissing()) { if (iface instanceof MissingResolvedTypeWithKnownSignature) { ((MissingResolvedTypeWithKnownSignature) iface).raiseWarningOnMissingInterfaceWhilstFindingMethods(); } } else { recurseHierarchy(knowninterfaces, collector, iface, includeITDs, allowMissing, genericsAware); } } } } public ResolvedType[] getResolvedTypeParameters() { if (resolvedTypeParams == null) { resolvedTypeParams = world.resolve(typeParameters); } return resolvedTypeParams; } /** * described in JVM spec 2ed 5.4.3.2 */ public ResolvedMember lookupField(Member field) { Iterator<ResolvedMember> i = getFields(); while (i.hasNext()) { ResolvedMember resolvedMember = i.next(); if (matches(resolvedMember, field)) { return resolvedMember; } if (resolvedMember.hasBackingGenericMember() && field.getName().equals(resolvedMember.getName())) { // might be worth checking the member behind the parameterized member (see pr137496) if (matches(resolvedMember.getBackingGenericMember(), field)) { return resolvedMember; } } } return null; } /** * described in JVM spec 2ed 5.4.3.3. Doesnt check ITDs. * * <p> * Check the current type for the method. If it is not found, check the super class and any super interfaces. Taking care not to * process interfaces multiple times. */ public ResolvedMember lookupMethod(Member m) { List<ResolvedType> typesTolookat = new ArrayList<ResolvedType>(); typesTolookat.add(this); int pos = 0; while (pos < typesTolookat.size()) { ResolvedType type = typesTolookat.get(pos++); if (!type.isMissing()) { ResolvedMember[] methods = type.getDeclaredMethods(); if (methods != null) { for (int i = 0; i < methods.length; i++) { ResolvedMember method = methods[i]; if (matches(method, m)) { return method; } // might be worth checking the method behind the parameterized method (137496) if (method.hasBackingGenericMember() && m.getName().equals(method.getName())) { if (matches(method.getBackingGenericMember(), m)) { return method; } } } } } // Queue the superclass: ResolvedType superclass = type.getSuperclass(); if (superclass != null) { typesTolookat.add(superclass); } // Queue any interfaces not already checked: ResolvedType[] superinterfaces = type.getDeclaredInterfaces(); if (superinterfaces != null) { for (int i = 0; i < superinterfaces.length; i++) { ResolvedType interf = superinterfaces[i]; if (!typesTolookat.contains(interf)) { typesTolookat.add(interf); } } } } return null; } /** * @param member the member to lookup in intertype declarations affecting this type * @return the real signature defined by any matching intertype declaration, otherwise null */ public ResolvedMember lookupMethodInITDs(Member member) { for (ConcreteTypeMunger typeTransformer : interTypeMungers) { if (matches(typeTransformer.getSignature(), member)) { return typeTransformer.getSignature(); } } return null; } /** * return null if not found */ private ResolvedMember lookupMember(Member m, ResolvedMember[] a) { for (int i = 0; i < a.length; i++) { ResolvedMember f = a[i]; if (matches(f, m)) { return f; } } return null; } // Bug (1) Do callers expect ITDs to be involved in the lookup? or do they do their own walk over ITDs? /** * Looks for the first member in the hierarchy matching aMember. This method differs from lookupMember(Member) in that it takes * into account parameters which are type variables - which clearly an unresolved Member cannot do since it does not know * anything about type variables. */ public ResolvedMember lookupResolvedMember(ResolvedMember aMember, boolean allowMissing, boolean eraseGenerics) { Iterator<ResolvedMember> toSearch = null; ResolvedMember found = null; if ((aMember.getKind() == Member.METHOD) || (aMember.getKind() == Member.CONSTRUCTOR)) { // toSearch = getMethodsWithoutIterator(true, allowMissing, !eraseGenerics).iterator(); toSearch = getMethodsIncludingIntertypeDeclarations(!eraseGenerics, true); } else { assert aMember.getKind() == Member.FIELD; toSearch = getFields(); } while (toSearch.hasNext()) { ResolvedMember candidate = toSearch.next(); if (eraseGenerics) { if (candidate.hasBackingGenericMember()) { candidate = candidate.getBackingGenericMember(); } } // OPTIMIZE speed up matches? optimize order of checks if (candidate.matches(aMember, eraseGenerics)) { found = candidate; break; } } return found; } public static boolean matches(Member m1, Member m2) { if (m1 == null) { return m2 == null; } if (m2 == null) { return false; } // Check the names boolean equalNames = m1.getName().equals(m2.getName()); if (!equalNames) { return false; } // Check the signatures boolean equalSignatures = m1.getSignature().equals(m2.getSignature()); if (equalSignatures) { return true; } // If they aren't the same, we need to allow for covariance ... where // one sig might be ()LCar; and // the subsig might be ()LFastCar; - where FastCar is a subclass of Car boolean equalCovariantSignatures = m1.getParameterSignature().equals(m2.getParameterSignature()); if (equalCovariantSignatures) { return true; } return false; } public static boolean conflictingSignature(Member m1, Member m2) { if (m1 == null || m2 == null) { return false; } if (!m1.getName().equals(m2.getName())) { return false; } if (m1.getKind() != m2.getKind()) { return false; } if (m1.getKind() == Member.FIELD) { return m1.getDeclaringType().equals(m2.getDeclaringType()); } else if (m1.getKind() == Member.POINTCUT) { return true; } UnresolvedType[] p1 = m1.getGenericParameterTypes(); UnresolvedType[] p2 = m2.getGenericParameterTypes(); if (p1 == null) { p1 = m1.getParameterTypes(); } if (p2 == null) { p2 = m2.getParameterTypes(); } int n = p1.length; if (n != p2.length) { return false; } for (int i = 0; i < n; i++) { if (!p1[i].equals(p2[i])) { return false; } } return true; } /** * returns an iterator through all of the pointcuts of this type, in order for checking from JVM spec 2ed 5.4.3.2 (as for * fields). This means that the order is * <p/> * <ul> * <li>pointcuts from current class</li> * <li>recur into direct superinterfaces</li> * <li>recur into superclass</li> * </ul> * <p/> * We keep a hashSet of interfaces that we've visited so we don't spiral out into 2^n land. */ public Iterator<ResolvedMember> getPointcuts() { final Iterators.Filter<ResolvedType> dupFilter = Iterators.dupFilter(); // same order as fields Iterators.Getter<ResolvedType, ResolvedType> typeGetter = new Iterators.Getter<ResolvedType, ResolvedType>() { public Iterator<ResolvedType> get(ResolvedType o) { return dupFilter.filter(o.getDirectSupertypes()); } }; return Iterators.mapOver(Iterators.recur(this, typeGetter), PointcutGetterInstance); } public ResolvedPointcutDefinition findPointcut(String name) { for (Iterator<ResolvedMember> i = getPointcuts(); i.hasNext();) { ResolvedPointcutDefinition f = (ResolvedPointcutDefinition) i.next(); // the ResolvedPointcutDefinition can be null if there are other problems that prevented its resolution if (f != null && name.equals(f.getName())) { return f; } } // pr120521 if (!getOutermostType().equals(this)) { ResolvedType outerType = getOutermostType().resolve(world); ResolvedPointcutDefinition rpd = outerType.findPointcut(name); return rpd; } return null; // should we throw an exception here? } // all about collecting CrosscuttingMembers // ??? collecting data-structure, shouldn't really be a field public CrosscuttingMembers crosscuttingMembers; public CrosscuttingMembers collectCrosscuttingMembers(boolean shouldConcretizeIfNeeded) { crosscuttingMembers = new CrosscuttingMembers(this, shouldConcretizeIfNeeded); if (getPerClause() == null) { return crosscuttingMembers; } crosscuttingMembers.setPerClause(getPerClause()); crosscuttingMembers.addShadowMungers(collectShadowMungers()); // GENERICITDFIX // crosscuttingMembers.addTypeMungers(collectTypeMungers()); crosscuttingMembers.addTypeMungers(getTypeMungers()); // FIXME AV - skip but needed ?? or ?? // crosscuttingMembers.addLateTypeMungers(getLateTypeMungers()); crosscuttingMembers.addDeclares(collectDeclares(!this.doesNotExposeShadowMungers())); crosscuttingMembers.addPrivilegedAccesses(getPrivilegedAccesses()); // System.err.println("collected cc members: " + this + ", " + // collectDeclares()); return crosscuttingMembers; } public final List<Declare> collectDeclares(boolean includeAdviceLike) { if (!this.isAspect()) { return Collections.emptyList(); } List<Declare> ret = new ArrayList<Declare>(); // if (this.isAbstract()) { // for (Iterator i = getDeclares().iterator(); i.hasNext();) { // Declare dec = (Declare) i.next(); // if (!dec.isAdviceLike()) ret.add(dec); // } // // if (!includeAdviceLike) return ret; if (!this.isAbstract()) { // ret.addAll(getDeclares()); final Iterators.Filter<ResolvedType> dupFilter = Iterators.dupFilter(); Iterators.Getter<ResolvedType, ResolvedType> typeGetter = new Iterators.Getter<ResolvedType, ResolvedType>() { public Iterator<ResolvedType> get(ResolvedType o) { return dupFilter.filter((o).getDirectSupertypes()); } }; Iterator<ResolvedType> typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedType ty = typeIterator.next(); // System.out.println("super: " + ty + ", " + ); for (Iterator<Declare> i = ty.getDeclares().iterator(); i.hasNext();) { Declare dec = i.next(); if (dec.isAdviceLike()) { if (includeAdviceLike) { ret.add(dec); } } else { ret.add(dec); } } } } return ret; } private final List<ShadowMunger> collectShadowMungers() { if (!this.isAspect() || this.isAbstract() || this.doesNotExposeShadowMungers()) { return Collections.emptyList(); } List<ShadowMunger> acc = new ArrayList<ShadowMunger>(); final Iterators.Filter<ResolvedType> dupFilter = Iterators.dupFilter(); Iterators.Getter<ResolvedType, ResolvedType> typeGetter = new Iterators.Getter<ResolvedType, ResolvedType>() { public Iterator<ResolvedType> get(ResolvedType o) { return dupFilter.filter((o).getDirectSupertypes()); } }; Iterator<ResolvedType> typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedType ty = typeIterator.next(); acc.addAll(ty.getDeclaredShadowMungers()); } return acc; } public void addParent(ResolvedType newParent) { // Nothing to do for anything except a ReferenceType } protected boolean doesNotExposeShadowMungers() { return false; } public PerClause getPerClause() { return null; } public Collection<Declare> getDeclares() { return Collections.emptyList(); } public Collection<ConcreteTypeMunger> getTypeMungers() { return Collections.emptyList(); } public Collection<ResolvedMember> getPrivilegedAccesses() { return Collections.emptyList(); } // ---- useful things public final boolean isInterface() { return Modifier.isInterface(getModifiers()); } public final boolean isAbstract() { return Modifier.isAbstract(getModifiers()); } public boolean isClass() { return false; } public boolean isAspect() { return false; } public boolean isAnnotationStyleAspect() { return false; } /** * Note: Only overridden by Name subtype. */ public boolean isEnum() { return false; } /** * Note: Only overridden by Name subtype. */ public boolean isAnnotation() { return false; } public boolean isAnonymous() { return false; } public boolean isNested() { return false; } public void addAnnotation(AnnotationAJ annotationX) { throw new RuntimeException("ResolvedType.addAnnotation() should never be called"); } public AnnotationAJ[] getAnnotations() { throw new RuntimeException("ResolvedType.getAnnotations() should never be called"); } /** * Note: Only overridden by ReferenceType subtype */ public boolean canAnnotationTargetType() { return false; } /** * Note: Only overridden by ReferenceType subtype */ public AnnotationTargetKind[] getAnnotationTargetKinds() { return null; } /** * Note: Only overridden by Name subtype. */ public boolean isAnnotationWithRuntimeRetention() { return false; } public boolean isSynthetic() { return signature.indexOf("$ajc") != -1; } public final boolean isFinal() { return Modifier.isFinal(getModifiers()); } protected Map<String, UnresolvedType> getMemberParameterizationMap() { if (!isParameterizedType()) { return Collections.emptyMap(); } TypeVariable[] tvs = getGenericType().getTypeVariables(); Map<String, UnresolvedType> parameterizationMap = new HashMap<String, UnresolvedType>(); for (int i = 0; i < tvs.length; i++) { parameterizationMap.put(tvs[i].getName(), typeParameters[i]); } return parameterizationMap; } public List<ShadowMunger> getDeclaredAdvice() { List<ShadowMunger> l = new ArrayList<ShadowMunger>(); ResolvedMember[] methods = getDeclaredMethods(); if (isParameterizedType()) { methods = getGenericType().getDeclaredMethods(); } Map<String, UnresolvedType> typeVariableMap = getAjMemberParameterizationMap(); for (int i = 0, len = methods.length; i < len; i++) { ShadowMunger munger = methods[i].getAssociatedShadowMunger(); if (munger != null) { if (ajMembersNeedParameterization()) { // munger.setPointcut(munger.getPointcut().parameterizeWith( // typeVariableMap)); munger = munger.parameterizeWith(this, typeVariableMap); if (munger instanceof Advice) { Advice advice = (Advice) munger; // update to use the parameterized signature... UnresolvedType[] ptypes = methods[i].getGenericParameterTypes(); UnresolvedType[] newPTypes = new UnresolvedType[ptypes.length]; for (int j = 0; j < ptypes.length; j++) { if (ptypes[j] instanceof TypeVariableReferenceType) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) ptypes[j]; if (typeVariableMap.containsKey(tvrt.getTypeVariable().getName())) { newPTypes[j] = typeVariableMap.get(tvrt.getTypeVariable().getName()); } else { newPTypes[j] = ptypes[j]; } } else { newPTypes[j] = ptypes[j]; } } advice.setBindingParameterTypes(newPTypes); } } munger.setDeclaringType(this); l.add(munger); } } return l; } public List<ShadowMunger> getDeclaredShadowMungers() { return getDeclaredAdvice(); } // ---- only for testing! public ResolvedMember[] getDeclaredJavaFields() { return filterInJavaVisible(getDeclaredFields()); } public ResolvedMember[] getDeclaredJavaMethods() { return filterInJavaVisible(getDeclaredMethods()); } private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) { List<ResolvedMember> l = new ArrayList<ResolvedMember>(); for (int i = 0, len = ms.length; i < len; i++) { if (!ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) { l.add(ms[i]); } } return l.toArray(new ResolvedMember[l.size()]); } public abstract ISourceContext getSourceContext(); // ---- fields public static final ResolvedType[] NONE = new ResolvedType[0]; public static final ResolvedType[] EMPTY_ARRAY = NONE; public static final Missing MISSING = new Missing(); // ---- types public static ResolvedType makeArray(ResolvedType type, int dim) { if (dim == 0) { return type; } ResolvedType array = new ArrayReferenceType("[" + type.getSignature(), "[" + type.getErasureSignature(), type.getWorld(), type); return makeArray(array, dim - 1); } static class Primitive extends ResolvedType { private final int size; private final int index; Primitive(String signature, int size, int index) { super(signature, null); this.size = size; this.index = index; this.typeKind = TypeKind.PRIMITIVE; } @Override public final int getSize() { return size; } @Override public final int getModifiers() { return Modifier.PUBLIC | Modifier.FINAL; } @Override public final boolean isPrimitiveType() { return true; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } @Override public final boolean isAssignableFrom(ResolvedType other) { if (!other.isPrimitiveType()) { if (!world.isInJava5Mode()) { return false; } return validBoxing.contains(this.getSignature() + other.getSignature()); } return assignTable[((Primitive) other).index][index]; } @Override public final boolean isAssignableFrom(ResolvedType other, boolean allowMissing) { return isAssignableFrom(other); } @Override public final boolean isCoerceableFrom(ResolvedType other) { if (this == other) { return true; } if (!other.isPrimitiveType()) { return false; } if (index > 6 || ((Primitive) other).index > 6) { return false; } return true; } @Override public ResolvedType resolve(World world) { if (this.world != world) { throw new IllegalStateException(); } this.world = world; return super.resolve(world); } @Override public final boolean needsNoConversionFrom(ResolvedType other) { if (!other.isPrimitiveType()) { return false; } return noConvertTable[((Primitive) other).index][index]; } private static final boolean[][] assignTable = {// to: B C D F I J S V Z // from { true, true, true, true, true, true, true, false, false }, // B { false, true, true, true, true, true, false, false, false }, // C { false, false, true, false, false, false, false, false, false }, // D { false, false, true, true, false, false, false, false, false }, // F { false, false, true, true, true, true, false, false, false }, // I { false, false, true, true, false, true, false, false, false }, // J { false, false, true, true, true, true, true, false, false }, // S { false, false, false, false, false, false, false, true, false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; private static final boolean[][] noConvertTable = {// to: B C D F I J S // V Z from { true, true, false, false, true, false, true, false, false }, // B { false, true, false, false, true, false, false, false, false }, // C { false, false, true, false, false, false, false, false, false }, // D { false, false, false, true, false, false, false, false, false }, // F { false, false, false, false, true, false, false, false, false }, // I { false, false, false, false, false, true, false, false, false }, // J { false, false, false, false, true, false, true, false, false }, // S { false, false, false, false, false, false, false, true, false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; // ---- @Override public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } @Override public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } @Override public final ResolvedType[] getDeclaredInterfaces() { return ResolvedType.NONE; } @Override public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } @Override public final ResolvedType getSuperclass() { return null; } @Override public ISourceContext getSourceContext() { return null; } } static class Missing extends ResolvedType { Missing() { super(MISSING_NAME, null); } // public final String toString() { // return "<missing>"; // } @Override public final String getName() { return MISSING_NAME; } @Override public final boolean isMissing() { return true; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } @Override public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } @Override public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } @Override public final ResolvedType[] getDeclaredInterfaces() { return ResolvedType.NONE; } @Override public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } @Override public final ResolvedType getSuperclass() { return null; } @Override public final int getModifiers() { return 0; } @Override public final boolean isAssignableFrom(ResolvedType other) { return false; } @Override public final boolean isAssignableFrom(ResolvedType other, boolean allowMissing) { return false; } @Override public final boolean isCoerceableFrom(ResolvedType other) { return false; } @Override public boolean needsNoConversionFrom(ResolvedType other) { return false; } @Override public ISourceContext getSourceContext() { return null; } } /** * Look up a member, takes into account any ITDs on this type. return null if not found */ public ResolvedMember lookupMemberNoSupers(Member member) { ResolvedMember ret = lookupDirectlyDeclaredMemberNoSupers(member); if (ret == null && interTypeMungers != null) { for (ConcreteTypeMunger tm : interTypeMungers) { if (matches(tm.getSignature(), member)) { return tm.getSignature(); } } } return ret; } public ResolvedMember lookupMemberWithSupersAndITDs(Member member) { ResolvedMember ret = lookupMemberNoSupers(member); if (ret != null) { return ret; } ResolvedType supert = getSuperclass(); while (ret == null && supert != null) { ret = supert.lookupMemberNoSupers(member); if (ret == null) { supert = supert.getSuperclass(); } } return ret; } /** * as lookupMemberNoSupers, but does not include ITDs * * @param member * @return */ public ResolvedMember lookupDirectlyDeclaredMemberNoSupers(Member member) { ResolvedMember ret; if (member.getKind() == Member.FIELD) { ret = lookupMember(member, getDeclaredFields()); } else { // assert member.getKind() == Member.METHOD || member.getKind() == // Member.CONSTRUCTOR ret = lookupMember(member, getDeclaredMethods()); } return ret; } /** * This lookup has specialized behaviour - a null result tells the EclipseTypeMunger that it should make a default * implementation of a method on this type. * * @param member * @return */ public ResolvedMember lookupMemberIncludingITDsOnInterfaces(Member member) { return lookupMemberIncludingITDsOnInterfaces(member, this); } private ResolvedMember lookupMemberIncludingITDsOnInterfaces(Member member, ResolvedType onType) { ResolvedMember ret = onType.lookupMemberNoSupers(member); if (ret != null) { return ret; } else { ResolvedType superType = onType.getSuperclass(); if (superType != null) { ret = lookupMemberIncludingITDsOnInterfaces(member, superType); } if (ret == null) { // try interfaces then, but only ITDs now... ResolvedType[] superInterfaces = onType.getDeclaredInterfaces(); for (int i = 0; i < superInterfaces.length; i++) { ret = superInterfaces[i].lookupMethodInITDs(member); if (ret != null) { return ret; } } } } return ret; } protected List<ConcreteTypeMunger> interTypeMungers = new ArrayList<ConcreteTypeMunger>(); public List<ConcreteTypeMunger> getInterTypeMungers() { return interTypeMungers; } public List<ConcreteTypeMunger> getInterTypeParentMungers() { List<ConcreteTypeMunger> l = new ArrayList<ConcreteTypeMunger>(); for (ConcreteTypeMunger element : interTypeMungers) { if (element.getMunger() instanceof NewParentTypeMunger) { l.add(element); } } return l; } /** * ??? This method is O(N*M) where N = number of methods and M is number of inter-type declarations in my super */ public List<ConcreteTypeMunger> getInterTypeMungersIncludingSupers() { ArrayList<ConcreteTypeMunger> ret = new ArrayList<ConcreteTypeMunger>(); collectInterTypeMungers(ret); return ret; } public List<ConcreteTypeMunger> getInterTypeParentMungersIncludingSupers() { ArrayList<ConcreteTypeMunger> ret = new ArrayList<ConcreteTypeMunger>(); collectInterTypeParentMungers(ret); return ret; } private void collectInterTypeParentMungers(List<ConcreteTypeMunger> collector) { for (Iterator<ResolvedType> iter = getDirectSupertypes(); iter.hasNext();) { ResolvedType superType = iter.next(); superType.collectInterTypeParentMungers(collector); } collector.addAll(getInterTypeParentMungers()); } protected void collectInterTypeMungers(List<ConcreteTypeMunger> collector) { for (Iterator<ResolvedType> iter = getDirectSupertypes(); iter.hasNext();) { ResolvedType superType = iter.next(); if (superType == null) { throw new BCException("UnexpectedProblem: a supertype in the hierarchy for " + this.getName() + " is null"); } superType.collectInterTypeMungers(collector); } outer: for (Iterator<ConcreteTypeMunger> iter1 = collector.iterator(); iter1.hasNext();) { ConcreteTypeMunger superMunger = iter1.next(); if (superMunger.getSignature() == null) { continue; } if (!superMunger.getSignature().isAbstract()) { continue; } for (ConcreteTypeMunger myMunger : getInterTypeMungers()) { if (conflictingSignature(myMunger.getSignature(), superMunger.getSignature())) { iter1.remove(); continue outer; } } if (!superMunger.getSignature().isPublic()) { continue; } for (Iterator<ResolvedMember> iter = getMethods(true, true); iter.hasNext();) { ResolvedMember method = iter.next(); if (conflictingSignature(method, superMunger.getSignature())) { iter1.remove(); continue outer; } } } collector.addAll(getInterTypeMungers()); } /** * Check: 1) That we don't have any abstract type mungers unless this type is abstract. 2) That an abstract ITDM on an interface * is declared public. (Compiler limitation) (PR70794) */ public void checkInterTypeMungers() { if (isAbstract()) { return; } boolean itdProblem = false; for (ConcreteTypeMunger munger : getInterTypeMungersIncludingSupers()) { itdProblem = checkAbstractDeclaration(munger) || itdProblem; // Rule 2 } if (itdProblem) { return; // If the rules above are broken, return right now } for (ConcreteTypeMunger munger : getInterTypeMungersIncludingSupers()) { if (munger.getSignature() != null && munger.getSignature().isAbstract()) { // Rule 1 if (munger.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate2) { // ignore for @AJ ITD as munger.getSignature() is the // interface method hence abstract } else { world.getMessageHandler() .handleMessage( new Message("must implement abstract inter-type declaration: " + munger.getSignature(), "", IMessage.ERROR, getSourceLocation(), null, new ISourceLocation[] { getMungerLocation(munger) })); } } } } /** * See PR70794. This method checks that if an abstract inter-type method declaration is made on an interface then it must also * be public. This is a compiler limitation that could be made to work in the future (if someone provides a worthwhile usecase) * * @return indicates if the munger failed the check */ private boolean checkAbstractDeclaration(ConcreteTypeMunger munger) { if (munger.getMunger() != null && (munger.getMunger() instanceof NewMethodTypeMunger)) { ResolvedMember itdMember = munger.getSignature(); ResolvedType onType = itdMember.getDeclaringType().resolve(world); if (onType.isInterface() && itdMember.isAbstract() && !itdMember.isPublic()) { world.getMessageHandler().handleMessage( new Message(WeaverMessages.format(WeaverMessages.ITD_ABSTRACT_MUST_BE_PUBLIC_ON_INTERFACE, munger.getSignature(), onType), "", Message.ERROR, getSourceLocation(), null, new ISourceLocation[] { getMungerLocation(munger) })); return true; } } return false; } /** * Get a source location for the munger. Until intertype mungers remember where they came from, the source location for the * munger itself is null. In these cases use the source location for the aspect containing the ITD. */ private ISourceLocation getMungerLocation(ConcreteTypeMunger munger) { ISourceLocation sloc = munger.getSourceLocation(); if (sloc == null) { sloc = munger.getAspectType().getSourceLocation(); } return sloc; } /** * Returns a ResolvedType object representing the declaring type of this type, or null if this type does not represent a * non-package-level-type. * <p/> * <strong>Warning</strong>: This is guaranteed to work for all member types. For anonymous/local types, the only guarantee is * given in JLS 13.1, where it guarantees that if you call getDeclaringType() repeatedly, you will eventually get the top-level * class, but it does not say anything about classes in between. * * @return the declaring UnresolvedType object, or null. */ public ResolvedType getDeclaringType() { if (isArray()) { return null; } String name = getName(); int lastDollar = name.lastIndexOf('$'); while (lastDollar > 0) { // allow for classes starting '$' (pr120474) ResolvedType ret = world.resolve(UnresolvedType.forName(name.substring(0, lastDollar)), true); if (!ResolvedType.isMissing(ret)) { return ret; } lastDollar = name.lastIndexOf('$', lastDollar - 1); } return null; } public static boolean isVisible(int modifiers, ResolvedType targetType, ResolvedType fromType) { // System.err.println("mod: " + modifiers + ", " + targetType + " and " // + fromType); if (Modifier.isPublic(modifiers)) { return true; } else if (Modifier.isPrivate(modifiers)) { return targetType.getOutermostType().equals(fromType.getOutermostType()); } else if (Modifier.isProtected(modifiers)) { return samePackage(targetType, fromType) || targetType.isAssignableFrom(fromType); } else { // package-visible return samePackage(targetType, fromType); } } private static boolean samePackage(ResolvedType targetType, ResolvedType fromType) { String p1 = targetType.getPackageName(); String p2 = fromType.getPackageName(); if (p1 == null) { return p2 == null; } if (p2 == null) { return false; } return p1.equals(p2); } /** * Checks if the generic type for 'this' and the generic type for 'other' are the same - it can be passed raw or parameterized * versions and will just compare the underlying generic type. */ private boolean genericTypeEquals(ResolvedType other) { ResolvedType rt = other; if (rt.isParameterizedType() || rt.isRawType()) { rt.getGenericType(); } if (((isParameterizedType() || isRawType()) && getGenericType().equals(rt)) || (this.equals(other))) { return true; } return false; } /** * Look up the actual occurence of a particular type in the hierarchy for 'this' type. The input is going to be a generic type, * and the caller wants to know if it was used in its RAW or a PARAMETERIZED form in this hierarchy. * * returns null if it can't be found. */ public ResolvedType discoverActualOccurrenceOfTypeInHierarchy(ResolvedType lookingFor) { if (!lookingFor.isGenericType()) { throw new BCException("assertion failed: method should only be called with generic type, but " + lookingFor + " is " + lookingFor.typeKind); } if (this.equals(ResolvedType.OBJECT)) { return null; } if (genericTypeEquals(lookingFor)) { return this; } ResolvedType superT = getSuperclass(); if (superT.genericTypeEquals(lookingFor)) { return superT; } ResolvedType[] superIs = getDeclaredInterfaces(); for (int i = 0; i < superIs.length; i++) { ResolvedType superI = superIs[i]; if (superI.genericTypeEquals(lookingFor)) { return superI; } ResolvedType checkTheSuperI = superI.discoverActualOccurrenceOfTypeInHierarchy(lookingFor); if (checkTheSuperI != null) { return checkTheSuperI; } } return superT.discoverActualOccurrenceOfTypeInHierarchy(lookingFor); } /** * Called for all type mungers but only does something if they share type variables with a generic type which they target. When * this happens this routine will check for the target type in the target hierarchy and 'bind' any type parameters as * appropriate. For example, for the ITD "List<T> I<T>.x" against a type like this: "class A implements I<String>" this routine * will return a parameterized form of the ITD "List<String> I.x" */ public ConcreteTypeMunger fillInAnyTypeParameters(ConcreteTypeMunger munger) { boolean debug = false; ResolvedMember member = munger.getSignature(); if (munger.isTargetTypeParameterized()) { if (debug) { System.err.println("Processing attempted parameterization of " + munger + " targetting type " + this); } if (debug) { System.err.println(" This type is " + this + " (" + typeKind + ")"); } // need to tailor this munger instance for the particular target... if (debug) { System.err.println(" Signature that needs parameterizing: " + member); } // Retrieve the generic type ResolvedType onTypeResolved = world.resolve(member.getDeclaringType()); ResolvedType onType = onTypeResolved.getGenericType(); if (onType == null) { // The target is not generic getWorld().getMessageHandler().handleMessage( MessageUtil.error("The target type for the intertype declaration is not generic", munger.getSourceLocation())); return munger; } member.resolve(world); // Ensure all parts of the member are resolved if (debug) { System.err.println(" Actual target ontype: " + onType + " (" + onType.typeKind + ")"); } // quickly find the targettype in the type hierarchy for this type // (it will be either RAW or PARAMETERIZED) ResolvedType actualTarget = discoverActualOccurrenceOfTypeInHierarchy(onType); if (actualTarget == null) { throw new BCException("assertion failed: asked " + this + " for occurrence of " + onType + " in its hierarchy??"); } // only bind the tvars if its a parameterized type or the raw type // (in which case they collapse to bounds) - don't do it // for generic types ;) if (!actualTarget.isGenericType()) { if (debug) { System.err.println("Occurrence in " + this + " is actually " + actualTarget + " (" + actualTarget.typeKind + ")"); // parameterize the signature // ResolvedMember newOne = // member.parameterizedWith(actualTarget.getTypeParameters(), // onType,actualTarget.isParameterizedType()); } } // if (!actualTarget.isRawType()) munger = munger.parameterizedFor(actualTarget); if (debug) { System.err.println("New sig: " + munger.getSignature()); } if (debug) { System.err.println("====================================="); } } return munger; } /** * Add an intertype munger to this type. isDuringCompilation tells us if we should be checking for an error scenario where two * ITD fields are trying to use the same name. When this happens during compilation one of them is altered to get mangled name * but when it happens during weaving it is too late and we need to put out an error asking them to recompile. */ public void addInterTypeMunger(ConcreteTypeMunger munger, boolean isDuringCompilation) { ResolvedMember sig = munger.getSignature(); bits = (bits & ~MungersAnalyzed); // clear the bit - as the mungers have changed if (sig == null || munger.getMunger() == null || munger.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess) { interTypeMungers.add(munger); return; } // ConcreteTypeMunger originalMunger = munger; // we will use the 'parameterized' ITD for all the comparisons but we // say the original // one passed in actually matched as it will be added to the intertype // member finder // for the target type. It is possible we only want to do this if a // generic type // is discovered and the tvar is collapsed to a bound? munger = fillInAnyTypeParameters(munger); sig = munger.getSignature(); // possibly changed when type parms filled in if (sig.getKind() == Member.METHOD) { // OPTIMIZE can this be sped up? if (clashesWithExistingMember(munger, getMethods(true, false))) { // ITDs checked below return; } if (this.isInterface()) { // OPTIMIZE this set of methods are always the same - must we keep creating them as a list? if (clashesWithExistingMember(munger, Arrays.asList(world.getCoreType(OBJECT).getDeclaredMethods()).iterator())) { return; } } } else if (sig.getKind() == Member.FIELD) { if (clashesWithExistingMember(munger, Arrays.asList(getDeclaredFields()).iterator())) { return; } // Cannot cope with two version '2' style mungers for the same field on the same type // Must error and request the user recompile at least one aspect with the // -Xset:itdStyle=1 option if (!isDuringCompilation) { ResolvedTypeMunger thisRealMunger = munger.getMunger(); if (thisRealMunger instanceof NewFieldTypeMunger) { NewFieldTypeMunger newFieldTypeMunger = (NewFieldTypeMunger) thisRealMunger; if (newFieldTypeMunger.version == NewFieldTypeMunger.VersionTwo) { String thisRealMungerSignatureName = newFieldTypeMunger.getSignature().getName(); for (ConcreteTypeMunger typeMunger : interTypeMungers) { if (typeMunger.getMunger() instanceof NewFieldTypeMunger) { if (typeMunger.getSignature().getKind() == Member.FIELD) { NewFieldTypeMunger existing = (NewFieldTypeMunger) typeMunger.getMunger(); if (existing.getSignature().getName().equals(thisRealMungerSignatureName) && existing.version == NewFieldTypeMunger.VersionTwo // this check ensures no problem for a clash with an ITD on an interface && existing.getSignature().getDeclaringType() .equals(newFieldTypeMunger.getSignature().getDeclaringType())) { // report error on the aspect StringBuffer sb = new StringBuffer(); sb.append("Cannot handle two aspects both attempting to use new style ITDs for the same named field "); sb.append("on the same target type. Please recompile at least one aspect with '-Xset:itdVersion=1'."); sb.append(" Aspects involved: " + munger.getAspectType().getName() + " and " + typeMunger.getAspectType().getName() + "."); sb.append(" Field is named '" + existing.getSignature().getName() + "'"); getWorld().getMessageHandler().handleMessage( new Message(sb.toString(), getSourceLocation(), true)); return; } } } } } } } } else { if (clashesWithExistingMember(munger, Arrays.asList(getDeclaredMethods()).iterator())) { return; } } // now compare to existingMungers for (Iterator<ConcreteTypeMunger> i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger existingMunger = i.next(); if (conflictingSignature(existingMunger.getSignature(), munger.getSignature())) { // System.err.println("match " + munger + " with " + // existingMunger); if (isVisible(munger.getSignature().getModifiers(), munger.getAspectType(), existingMunger.getAspectType())) { // System.err.println(" is visible"); int c = compareMemberPrecedence(sig, existingMunger.getSignature()); if (c == 0) { c = getWorld().compareByPrecedenceAndHierarchy(munger.getAspectType(), existingMunger.getAspectType()); } // System.err.println(" compare: " + c); if (c < 0) { // the existing munger dominates the new munger checkLegalOverride(munger.getSignature(), existingMunger.getSignature(), 0x11, null); return; } else if (c > 0) { // the new munger dominates the existing one checkLegalOverride(existingMunger.getSignature(), munger.getSignature(), 0x11, null); i.remove(); break; } else { interTypeConflictError(munger, existingMunger); interTypeConflictError(existingMunger, munger); return; } } } } // System.err.println("adding: " + munger + " to " + this); // we are adding the parameterized form of the ITD to the list of // mungers. Within it, the munger knows the original declared // signature for the ITD so it can be retrieved. interTypeMungers.add(munger); } /** * Compare the type transformer with the existing members. A clash may not be an error (the ITD may be the 'default * implementation') so returning false is not always a sign of an error. * * @return true if there is a clash */ private boolean clashesWithExistingMember(ConcreteTypeMunger typeTransformer, Iterator<ResolvedMember> existingMembers) { ResolvedMember typeTransformerSignature = typeTransformer.getSignature(); // ResolvedType declaringAspectType = munger.getAspectType(); // if (declaringAspectType.isRawType()) declaringAspectType = // declaringAspectType.getGenericType(); // if (declaringAspectType.isGenericType()) { // // ResolvedType genericOnType = // getWorld().resolve(sig.getDeclaringType()).getGenericType(); // ConcreteTypeMunger ctm = // munger.parameterizedFor(discoverActualOccurrenceOfTypeInHierarchy // (genericOnType)); // sig = ctm.getSignature(); // possible sig change when type // } // if (munger.getMunger().hasTypeVariableAliases()) { // ResolvedType genericOnType = // getWorld().resolve(sig.getDeclaringType()).getGenericType(); // ConcreteTypeMunger ctm = // munger.parameterizedFor(discoverActualOccurrenceOfTypeInHierarchy( // genericOnType)); // sig = ctm.getSignature(); // possible sig change when type parameters // filled in // } while (existingMembers.hasNext()) { ResolvedMember existingMember = existingMembers.next(); // don't worry about clashing with bridge methods if (existingMember.isBridgeMethod()) { continue; } if (conflictingSignature(existingMember, typeTransformerSignature)) { // System.err.println("conflict: existingMember=" + // existingMember + " typeMunger=" + munger); // System.err.println(munger.getSourceLocation() + ", " + // munger.getSignature() + ", " + // munger.getSignature().getSourceLocation()); if (isVisible(existingMember.getModifiers(), this, typeTransformer.getAspectType())) { int c = compareMemberPrecedence(typeTransformerSignature, existingMember); // System.err.println(" c: " + c); if (c < 0) { // existingMember dominates munger checkLegalOverride(typeTransformerSignature, existingMember, 0x10, typeTransformer.getAspectType()); return true; } else if (c > 0) { // munger dominates existingMember checkLegalOverride(existingMember, typeTransformerSignature, 0x01, typeTransformer.getAspectType()); // interTypeMungers.add(munger); // ??? might need list of these overridden abstracts continue; } else { // bridge methods can differ solely in return type. // FIXME this whole method seems very hokey - unaware of covariance/varargs/bridging - it // could do with a rewrite ! boolean sameReturnTypes = (existingMember.getReturnType().equals(typeTransformerSignature.getReturnType())); if (sameReturnTypes) { // pr206732 - if the existingMember is due to a // previous application of this same ITD (which can // happen if this is a binary type being brought in // from the aspectpath). The 'better' fix is // to recognize it is from the aspectpath at a // higher level and dont do this, but that is rather // more work. boolean isDuplicateOfPreviousITD = false; ResolvedType declaringRt = existingMember.getDeclaringType().resolve(world); WeaverStateInfo wsi = declaringRt.getWeaverState(); if (wsi != null) { List<ConcreteTypeMunger> mungersAffectingThisType = wsi.getTypeMungers(declaringRt); if (mungersAffectingThisType != null) { for (Iterator<ConcreteTypeMunger> iterator = mungersAffectingThisType.iterator(); iterator .hasNext() && !isDuplicateOfPreviousITD;) { ConcreteTypeMunger ctMunger = iterator.next(); // relatively crude check - is the ITD // for the same as the existingmember // and does it come // from the same aspect if (ctMunger.getSignature().equals(existingMember) && ctMunger.aspectType.equals(typeTransformer.getAspectType())) { isDuplicateOfPreviousITD = true; } } } } if (!isDuplicateOfPreviousITD) { // b275032 - this is OK if it is the default ctor and that default ctor was generated // at compile time, otherwise we cannot overwrite it if (!(typeTransformerSignature.getName().equals("<init>") && existingMember.isDefaultConstructor())) { String aspectName = typeTransformer.getAspectType().getName(); ISourceLocation typeTransformerLocation = typeTransformer.getSourceLocation(); ISourceLocation existingMemberLocation = existingMember.getSourceLocation(); String msg = WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT, aspectName, existingMember); // this isn't quite right really... as I think the errors should only be recorded against // what is currently being processed or they may get lost or reported twice // report error on the aspect getWorld().getMessageHandler().handleMessage(new Message(msg, typeTransformerLocation, true)); // report error on the affected type, if we can if (existingMemberLocation != null) { getWorld().getMessageHandler() .handleMessage(new Message(msg, existingMemberLocation, true)); } return true; // clash - so ignore this itd } } } } } else if (isDuplicateMemberWithinTargetType(existingMember, this, typeTransformerSignature)) { getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT, typeTransformer .getAspectType().getName(), existingMember), typeTransformer.getSourceLocation())); return true; } } } return false; } // we know that the member signature matches, but that the member in the // target type is not visible to the aspect. // this may still be disallowed if it would result in two members within the // same declaring type with the same // signature AND more than one of them is concrete AND they are both visible // within the target type. private boolean isDuplicateMemberWithinTargetType(ResolvedMember existingMember, ResolvedType targetType, ResolvedMember itdMember) { if ((existingMember.isAbstract() || itdMember.isAbstract())) { return false; } UnresolvedType declaringType = existingMember.getDeclaringType(); if (!targetType.equals(declaringType)) { return false; } // now have to test that itdMember is visible from targetType if (Modifier.isPrivate(itdMember.getModifiers())) { return false; } if (itdMember.isPublic()) { return true; } // must be in same package to be visible then... if (!targetType.getPackageName().equals(itdMember.getDeclaringType().getPackageName())) { return false; } // trying to put two members with the same signature into the exact same // type..., and both visible in that type. return true; } /** * @param transformerPosition which parameter is the type transformer (0x10 for first, 0x01 for second, 0x11 for both, 0x00 for * neither) * @param aspectType the declaring type of aspect defining the *first* type transformer * @return true if the override is legal note: calling showMessage with two locations issues TWO messages, not ONE message with * an additional source location. */ public boolean checkLegalOverride(ResolvedMember parent, ResolvedMember child, int transformerPosition, ResolvedType aspectType) { // System.err.println("check: " + child.getDeclaringType() + // " overrides " + parent.getDeclaringType()); if (Modifier.isFinal(parent.getModifiers())) { // If the ITD matching is occurring due to pulling in a BinaryTypeBinding then this check can incorrectly // signal an error because the ITD transformer being examined here will exactly match the member it added // during the first round of compilation. This situation can only occur if the ITD is on an interface whilst // the class is the top most implementor. If the ITD is on the same type that received it during compilation, // this method won't be called as the previous check for precedence level will return 0. if (transformerPosition == 0x10 && aspectType != null) { ResolvedType nonItdDeclaringType = child.getDeclaringType().resolve(world); WeaverStateInfo wsi = nonItdDeclaringType.getWeaverState(); if (wsi != null) { List<ConcreteTypeMunger> transformersOnThisType = wsi.getTypeMungers(nonItdDeclaringType); if (transformersOnThisType != null) { for (ConcreteTypeMunger transformer : transformersOnThisType) { // relatively crude check - is the ITD // for the same as the existingmember // and does it come // from the same aspect if (transformer.aspectType.equals(aspectType)) { if (parent.equalsApartFromDeclaringType(transformer.getSignature())) { return true; } } } } } } world.showMessage(Message.ERROR, WeaverMessages.format(WeaverMessages.CANT_OVERRIDE_FINAL_MEMBER, parent), child.getSourceLocation(), null); return false; } boolean incompatibleReturnTypes = false; // In 1.5 mode, allow for covariance on return type if (world.isInJava5Mode() && parent.getKind() == Member.METHOD) { // Look at the generic types when doing this comparison ResolvedType rtParentReturnType = parent.resolve(world).getGenericReturnType().resolve(world); ResolvedType rtChildReturnType = child.resolve(world).getGenericReturnType().resolve(world); incompatibleReturnTypes = !rtParentReturnType.isAssignableFrom(rtChildReturnType); // For debug, uncomment this bit and we'll repeat the check - stick // a breakpoint on the call // if (incompatibleReturnTypes) { // incompatibleReturnTypes = // !rtParentReturnType.isAssignableFrom(rtChildReturnType); // } } else { incompatibleReturnTypes = !parent.getReturnType().equals(child.getReturnType()); } if (incompatibleReturnTypes) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_RETURN_TYPE_MISMATCH, parent, child), child.getSourceLocation(), parent.getSourceLocation()); return false; } if (parent.getKind() == Member.POINTCUT) { UnresolvedType[] pTypes = parent.getParameterTypes(); UnresolvedType[] cTypes = child.getParameterTypes(); if (!Arrays.equals(pTypes, cTypes)) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_PARAM_TYPE_MISMATCH, parent, child), child.getSourceLocation(), parent.getSourceLocation()); return false; } } // System.err.println("check: " + child.getModifiers() + // " more visible " + parent.getModifiers()); if (isMoreVisible(parent.getModifiers(), child.getModifiers())) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_VISIBILITY_REDUCTION, parent, child), child.getSourceLocation(), parent.getSourceLocation()); return false; } // check declared exceptions ResolvedType[] childExceptions = world.resolve(child.getExceptions()); ResolvedType[] parentExceptions = world.resolve(parent.getExceptions()); ResolvedType runtimeException = world.resolve("java.lang.RuntimeException"); ResolvedType error = world.resolve("java.lang.Error"); outer: for (int i = 0, leni = childExceptions.length; i < leni; i++) { // System.err.println("checking: " + childExceptions[i]); if (runtimeException.isAssignableFrom(childExceptions[i])) { continue; } if (error.isAssignableFrom(childExceptions[i])) { continue; } for (int j = 0, lenj = parentExceptions.length; j < lenj; j++) { if (parentExceptions[j].isAssignableFrom(childExceptions[i])) { continue outer; } } // this message is now better handled my MethodVerifier in JDT core. // world.showMessage(IMessage.ERROR, // WeaverMessages.format(WeaverMessages.ITD_DOESNT_THROW, // childExceptions[i].getName()), // child.getSourceLocation(), null); return false; } boolean parentStatic = Modifier.isStatic(parent.getModifiers()); boolean childStatic = Modifier.isStatic(child.getModifiers()); if (parentStatic && !childStatic) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_OVERRIDDEN_STATIC, child, parent), child.getSourceLocation(), null); return false; } else if (childStatic && !parentStatic) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_OVERIDDING_STATIC, child, parent), child.getSourceLocation(), null); return false; } return true; } private int compareMemberPrecedence(ResolvedMember m1, ResolvedMember m2) { // if (!m1.getReturnType().equals(m2.getReturnType())) return 0; // need to allow for the special case of 'clone' - which is like // abstract but is // not marked abstract. The code below this next line seems to make // assumptions // about what will have gotten through the compiler based on the normal // java rules. clone goes against these... if (Modifier.isProtected(m2.getModifiers()) && m2.getName().charAt(0) == 'c') { UnresolvedType declaring = m2.getDeclaringType(); if (declaring != null) { if (declaring.getName().equals("java.lang.Object") && m2.getName().equals("clone")) { return +1; } } } if (Modifier.isAbstract(m1.getModifiers())) { return -1; } if (Modifier.isAbstract(m2.getModifiers())) { return +1; } if (m1.getDeclaringType().equals(m2.getDeclaringType())) { return 0; } ResolvedType t1 = m1.getDeclaringType().resolve(world); ResolvedType t2 = m2.getDeclaringType().resolve(world); if (t1.isAssignableFrom(t2)) { return -1; } if (t2.isAssignableFrom(t1)) { return +1; } return 0; } public static boolean isMoreVisible(int m1, int m2) { if (Modifier.isPrivate(m1)) { return false; } if (isPackage(m1)) { return Modifier.isPrivate(m2); } if (Modifier.isProtected(m1)) { return /* private package */(Modifier.isPrivate(m2) || isPackage(m2)); } if (Modifier.isPublic(m1)) { return /* private package protected */!Modifier.isPublic(m2); } throw new RuntimeException("bad modifier: " + m1); } private static boolean isPackage(int i) { return (0 == (i & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED))); } private void interTypeConflictError(ConcreteTypeMunger m1, ConcreteTypeMunger m2) { // XXX this works only if we ignore separate compilation issues // XXX dual errors possible if (this instanceof BcelObjectType) return; /* * if (m1.getMunger().getKind() == ResolvedTypeMunger.Field && m2.getMunger().getKind() == ResolvedTypeMunger.Field) { // if * *exactly* the same, it's ok return true; } */ // System.err.println("conflict at " + m2.getSourceLocation()); getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_CONFLICT, m1.getAspectType().getName(), m2.getSignature(), m2 .getAspectType().getName()), m2.getSourceLocation(), getSourceLocation()); // return false; } public ResolvedMember lookupSyntheticMember(Member member) { // ??? horribly inefficient // for (Iterator i = // System.err.println("lookup " + member + " in " + interTypeMungers); for (ConcreteTypeMunger m : interTypeMungers) { ResolvedMember ret = m.getMatchingSyntheticMember(member); if (ret != null) { // System.err.println(" found: " + ret); return ret; } } // Handling members for the new array join point if (world.isJoinpointArrayConstructionEnabled() && this.isArray()) { if (member.getKind() == Member.CONSTRUCTOR) { ResolvedMemberImpl ret = new ResolvedMemberImpl(Member.CONSTRUCTOR, this, Modifier.PUBLIC, UnresolvedType.VOID, "<init>", world.resolve(member.getParameterTypes())); // Give the parameters names - they are going to be the dimensions uses to build the array (dim0 > dimN) int count = ret.getParameterTypes().length; String[] paramNames = new String[count]; for (int i = 0; i < count; i++) { paramNames[i] = new StringBuffer("dim").append(i).toString(); } ret.setParameterNames(paramNames); return ret; } } // if (this.getSuperclass() != ResolvedType.OBJECT && // this.getSuperclass() != null) { // return getSuperclass().lookupSyntheticMember(member); // } return null; } static class SuperClassWalker implements Iterator<ResolvedType> { private ResolvedType curr; private SuperInterfaceWalker iwalker; private boolean wantGenerics; public SuperClassWalker(ResolvedType type, SuperInterfaceWalker iwalker, boolean genericsAware) { this.curr = type; this.iwalker = iwalker; this.wantGenerics = genericsAware; } public boolean hasNext() { return curr != null; } public ResolvedType next() { ResolvedType ret = curr; if (!wantGenerics && ret.isParameterizedOrGenericType()) { ret = ret.getRawType(); } iwalker.push(ret); // tell the interface walker about another class whose interfaces need visiting curr = curr.getSuperclass(); return ret; } public void remove() { throw new UnsupportedOperationException(); } } static class SuperInterfaceWalker implements Iterator<ResolvedType> { private Getter<ResolvedType, ResolvedType> ifaceGetter; Iterator<ResolvedType> delegate = null; public Queue<ResolvedType> toPersue = new LinkedList<ResolvedType>(); public Set<ResolvedType> visited = new HashSet<ResolvedType>(); SuperInterfaceWalker(Iterators.Getter<ResolvedType, ResolvedType> ifaceGetter) { this.ifaceGetter = ifaceGetter; } SuperInterfaceWalker(Iterators.Getter<ResolvedType, ResolvedType> ifaceGetter, ResolvedType interfaceType) { this.ifaceGetter = ifaceGetter; this.delegate = Iterators.one(interfaceType); } public boolean hasNext() { if (delegate == null || !delegate.hasNext()) { // either we set it up or we have run out, is there anything else to look at? if (toPersue.isEmpty()) { return false; } do { ResolvedType next = toPersue.remove(); visited.add(next); delegate = ifaceGetter.get(next); // retrieve interfaces from a class or another interface } while (!delegate.hasNext() && !toPersue.isEmpty()); } return delegate.hasNext(); } public void push(ResolvedType ret) { toPersue.add(ret); } public ResolvedType next() { ResolvedType next = delegate.next(); // BUG should check for generics and erase? // if (!visited.contains(next)) { // visited.add(next); if (visited.add(next)) { toPersue.add(next); // pushes on interfaces already visited? } return next; } public void remove() { throw new UnsupportedOperationException(); } } public void clearInterTypeMungers() { if (isRawType()) { ResolvedType genericType = getGenericType(); if (genericType.isRawType()) { // ERROR SITUATION: PR341926 // For some reason the raw type is pointing to another raw form (possibly itself) System.err.println("DebugFor341926: Type " + this.getName() + " has an incorrect generic form"); } else { genericType.clearInterTypeMungers(); } } // interTypeMungers.clear(); // BUG? Why can't this be clear() instead: 293620 c6 interTypeMungers = new ArrayList<ConcreteTypeMunger>(); } public boolean isTopmostImplementor(ResolvedType interfaceType) { boolean b = true; if (isInterface()) { b = false; } else if (!interfaceType.isAssignableFrom(this, true)) { b = false; } else { ResolvedType superclass = this.getSuperclass(); if (superclass.isMissing()) { b = true; // we don't know anything about supertype, and it can't be exposed to weaver } else if (interfaceType.isAssignableFrom(superclass, true)) { // check that I'm truly the topmost implementor b = false; } } // System.out.println("is " + getName() + " topmostimplementor of " + interfaceType + "? " + b); return b; } public ResolvedType getTopmostImplementor(ResolvedType interfaceType) { if (isInterface()) { return null; } if (!interfaceType.isAssignableFrom(this)) { return null; } // Check if my super class is an implementor? ResolvedType higherType = this.getSuperclass().getTopmostImplementor(interfaceType); if (higherType != null) { return higherType; } return this; } public List<ResolvedMember> getExposedPointcuts() { List<ResolvedMember> ret = new ArrayList<ResolvedMember>(); if (getSuperclass() != null) { ret.addAll(getSuperclass().getExposedPointcuts()); } for (ResolvedType type : getDeclaredInterfaces()) { addPointcutsResolvingConflicts(ret, Arrays.asList(type.getDeclaredPointcuts()), false); } addPointcutsResolvingConflicts(ret, Arrays.asList(getDeclaredPointcuts()), true); for (ResolvedMember member : ret) { ResolvedPointcutDefinition inherited = (ResolvedPointcutDefinition) member; if (inherited != null && inherited.isAbstract()) { if (!this.isAbstract()) { getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.POINCUT_NOT_CONCRETE, inherited, this.getName()), inherited.getSourceLocation(), this.getSourceLocation()); } } } return ret; } private void addPointcutsResolvingConflicts(List<ResolvedMember> acc, List<ResolvedMember> added, boolean isOverriding) { for (Iterator<ResolvedMember> i = added.iterator(); i.hasNext();) { ResolvedPointcutDefinition toAdd = (ResolvedPointcutDefinition) i.next(); for (Iterator<ResolvedMember> j = acc.iterator(); j.hasNext();) { ResolvedPointcutDefinition existing = (ResolvedPointcutDefinition) j.next(); if (toAdd == null || existing == null || existing == toAdd) { continue; } UnresolvedType pointcutDeclaringTypeUT = existing.getDeclaringType(); if (pointcutDeclaringTypeUT != null) { ResolvedType pointcutDeclaringType = pointcutDeclaringTypeUT.resolve(getWorld()); if (!isVisible(existing.getModifiers(), pointcutDeclaringType, this)) { // if they intended to override it but it is not visible, // give them a nicer message if (existing.isAbstract() && conflictingSignature(existing, toAdd)) { getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.POINTCUT_NOT_VISIBLE, existing.getDeclaringType() .getName() + "." + existing.getName() + "()", this.getName()), toAdd.getSourceLocation(), null); j.remove(); } continue; } } if (conflictingSignature(existing, toAdd)) { if (isOverriding) { checkLegalOverride(existing, toAdd, 0x00, null); j.remove(); } else { getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.CONFLICTING_INHERITED_POINTCUTS, this.getName() + toAdd.getSignature()), existing.getSourceLocation(), toAdd.getSourceLocation()); j.remove(); } } } acc.add(toAdd); } } public ISourceLocation getSourceLocation() { return null; } public boolean isExposedToWeaver() { return false; } public WeaverStateInfo getWeaverState() { return null; } /** * Overridden by ReferenceType to return a sensible answer for parameterized and raw types. * * @return */ public ResolvedType getGenericType() { // if (!(isParameterizedType() || isRawType())) // throw new BCException("The type " + getBaseName() + " is not parameterized or raw - it has no generic type"); return null; } @Override public ResolvedType getRawType() { return super.getRawType().resolve(world); } public ResolvedType parameterizedWith(UnresolvedType[] typeParameters) { if (!(isGenericType() || isParameterizedType())) { return this; } return TypeFactory.createParameterizedType(this.getGenericType(), typeParameters, getWorld()); } /** * Iff I am a parameterized type, and any of my parameters are type variable references, return a version with those type * parameters replaced in accordance with the passed bindings. */ @Override public UnresolvedType parameterize(Map<String, UnresolvedType> typeBindings) { if (!isParameterizedType()) { return this;// throw new IllegalStateException( } // "Can't parameterize a type that is not a parameterized type" // ); boolean workToDo = false; for (int i = 0; i < typeParameters.length; i++) { if (typeParameters[i].isTypeVariableReference() || (typeParameters[i] instanceof BoundedReferenceType)) { workToDo = true; } } if (!workToDo) { return this; } else { UnresolvedType[] newTypeParams = new UnresolvedType[typeParameters.length]; for (int i = 0; i < newTypeParams.length; i++) { newTypeParams[i] = typeParameters[i]; if (newTypeParams[i].isTypeVariableReference()) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) newTypeParams[i]; UnresolvedType binding = typeBindings.get(tvrt.getTypeVariable().getName()); if (binding != null) { newTypeParams[i] = binding; } } else if (newTypeParams[i] instanceof BoundedReferenceType) { BoundedReferenceType brType = (BoundedReferenceType) newTypeParams[i]; newTypeParams[i] = brType.parameterize(typeBindings); // brType.parameterize(typeBindings) } } return TypeFactory.createParameterizedType(getGenericType(), newTypeParams, getWorld()); } } // public boolean hasParameterizedSuperType() { // getParameterizedSuperTypes(); // return parameterizedSuperTypes.length > 0; // } // public boolean hasGenericSuperType() { // ResolvedType[] superTypes = getDeclaredInterfaces(); // for (int i = 0; i < superTypes.length; i++) { // if (superTypes[i].isGenericType()) // return true; // } // return false; // } // private ResolvedType[] parameterizedSuperTypes = null; /** * Similar to the above method, but accumulates the super types * * @return */ // public ResolvedType[] getParameterizedSuperTypes() { // if (parameterizedSuperTypes != null) // return parameterizedSuperTypes; // List accumulatedTypes = new ArrayList(); // accumulateParameterizedSuperTypes(this, accumulatedTypes); // ResolvedType[] ret = new ResolvedType[accumulatedTypes.size()]; // parameterizedSuperTypes = (ResolvedType[]) accumulatedTypes.toArray(ret); // return parameterizedSuperTypes; // } // private void accumulateParameterizedSuperTypes(ResolvedType forType, List // parameterizedTypeList) { // if (forType.isParameterizedType()) { // parameterizedTypeList.add(forType); // } // if (forType.getSuperclass() != null) { // accumulateParameterizedSuperTypes(forType.getSuperclass(), // parameterizedTypeList); // } // ResolvedType[] interfaces = forType.getDeclaredInterfaces(); // for (int i = 0; i < interfaces.length; i++) { // accumulateParameterizedSuperTypes(interfaces[i], parameterizedTypeList); // } // } /** * @return true if assignable to java.lang.Exception */ public boolean isException() { return (world.getCoreType(UnresolvedType.JL_EXCEPTION).isAssignableFrom(this)); } /** * @return true if it is an exception and it is a checked one, false otherwise. */ public boolean isCheckedException() { if (!isException()) { return false; } if (world.getCoreType(UnresolvedType.RUNTIME_EXCEPTION).isAssignableFrom(this)) { return false; } return true; } /** * Determines if variables of this type could be assigned values of another with lots of help. java.lang.Object is convertable * from all types. A primitive type is convertable from X iff it's assignable from X. A reference type is convertable from X iff * it's coerceable from X. In other words, X isConvertableFrom Y iff the compiler thinks that _some_ value of Y could be * assignable to a variable of type X without loss of precision. * * @param other the other type * @param world the {@link World} in which the possible assignment should be checked. * @return true iff variables of this type could be assigned values of other with possible conversion */ public final boolean isConvertableFrom(ResolvedType other) { // // version from TypeX // if (this.equals(OBJECT)) return true; // if (this.isPrimitiveType() || other.isPrimitiveType()) return // this.isAssignableFrom(other); // return this.isCoerceableFrom(other); // // version from ResolvedTypeX if (this.equals(OBJECT)) { return true; } if (world.isInJava5Mode()) { if (this.isPrimitiveType() ^ other.isPrimitiveType()) { // If one is // primitive // and the // other // isnt if (validBoxing.contains(this.getSignature() + other.getSignature())) { return true; } } } if (this.isPrimitiveType() || other.isPrimitiveType()) { return this.isAssignableFrom(other); } return this.isCoerceableFrom(other); } /** * Determines if the variables of this type could be assigned values of another type without casting. This still allows for * assignment conversion as per JLS 2ed 5.2. For object types, this means supertypeOrEqual(THIS, OTHER). * * @param other the other type * @param world the {@link World} in which the possible assignment should be checked. * @return true iff variables of this type could be assigned values of other without casting * @throws NullPointerException if other is null */ public abstract boolean isAssignableFrom(ResolvedType other); public abstract boolean isAssignableFrom(ResolvedType other, boolean allowMissing); /** * Determines if values of another type could possibly be cast to this type. The rules followed are from JLS 2ed 5.5, * "Casting Conversion". * <p/> * <p> * This method should be commutative, i.e., for all UnresolvedType a, b and all World w: * <p/> * <blockquote> * * <pre> * a.isCoerceableFrom(b, w) == b.isCoerceableFrom(a, w) * </pre> * * </blockquote> * * @param other the other type * @param world the {@link World} in which the possible coersion should be checked. * @return true iff values of other could possibly be cast to this type. * @throws NullPointerException if other is null. */ public abstract boolean isCoerceableFrom(ResolvedType other); public boolean needsNoConversionFrom(ResolvedType o) { return isAssignableFrom(o); } public String getSignatureForAttribute() { return signature; // Assume if this is being called that it is for a // simple type (eg. void, int, etc) } private FuzzyBoolean parameterizedWithTypeVariable = FuzzyBoolean.MAYBE; /** * return true if the parameterization of this type includes a member type variable. Member type variables occur in generic * methods/ctors. */ public boolean isParameterizedWithTypeVariable() { // MAYBE means we haven't worked it out yet... if (parameterizedWithTypeVariable == FuzzyBoolean.MAYBE) { // if there are no type parameters then we cant be... if (typeParameters == null || typeParameters.length == 0) { parameterizedWithTypeVariable = FuzzyBoolean.NO; return false; } for (int i = 0; i < typeParameters.length; i++) { ResolvedType aType = (ResolvedType) typeParameters[i]; if (aType.isTypeVariableReference() // Changed according to the problems covered in bug 222648 // Don't care what kind of type variable - the fact that there // is one // at all means we can't risk caching it against we get confused // later // by another variation of the parameterization that just // happens to // use the same type variable name // assume the worst - if its definetly not a type declared one, // it could be anything // && ((TypeVariableReference)aType).getTypeVariable(). // getDeclaringElementKind()!=TypeVariable.TYPE ) { parameterizedWithTypeVariable = FuzzyBoolean.YES; return true; } if (aType.isParameterizedType()) { boolean b = aType.isParameterizedWithTypeVariable(); if (b) { parameterizedWithTypeVariable = FuzzyBoolean.YES; return true; } } if (aType.isGenericWildcard()) { BoundedReferenceType boundedRT = (BoundedReferenceType) aType; if (boundedRT.isExtends()) { boolean b = false; UnresolvedType upperBound = boundedRT.getUpperBound(); if (upperBound.isParameterizedType()) { b = ((ResolvedType) upperBound).isParameterizedWithTypeVariable(); } else if (upperBound.isTypeVariableReference() && ((TypeVariableReference) upperBound).getTypeVariable().getDeclaringElementKind() == TypeVariable.METHOD) { b = true; } if (b) { parameterizedWithTypeVariable = FuzzyBoolean.YES; return true; } // FIXME asc need to check additional interface bounds } if (boundedRT.isSuper()) { boolean b = false; UnresolvedType lowerBound = boundedRT.getLowerBound(); if (lowerBound.isParameterizedType()) { b = ((ResolvedType) lowerBound).isParameterizedWithTypeVariable(); } else if (lowerBound.isTypeVariableReference() && ((TypeVariableReference) lowerBound).getTypeVariable().getDeclaringElementKind() == TypeVariable.METHOD) { b = true; } if (b) { parameterizedWithTypeVariable = FuzzyBoolean.YES; return true; } } } } parameterizedWithTypeVariable = FuzzyBoolean.NO; } return parameterizedWithTypeVariable.alwaysTrue(); } protected boolean ajMembersNeedParameterization() { if (isParameterizedType()) { return true; } ResolvedType superclass = getSuperclass(); if (superclass != null && !superclass.isMissing()) { return superclass.ajMembersNeedParameterization(); } return false; } protected Map<String, UnresolvedType> getAjMemberParameterizationMap() { Map<String, UnresolvedType> myMap = getMemberParameterizationMap(); if (myMap.isEmpty()) { // might extend a parameterized aspect that we also need to // consider... if (getSuperclass() != null) { return getSuperclass().getAjMemberParameterizationMap(); } } return myMap; } public void setBinaryPath(String binaryPath) { this.binaryPath = binaryPath; } /** * Returns the path to the jar or class file from which this binary aspect came or null if not a binary aspect */ public String getBinaryPath() { return binaryPath; } /** * Undo any temporary modifications to the type (for example it may be holding annotations temporarily whilst some matching is * occurring - These annotations will be added properly during weaving but sometimes for type completion they need to be held * here for a while). */ public void ensureConsistent() { // Nothing to do for anything except a ReferenceType } /** * For an annotation type, this will return if it is marked with @Inherited */ public boolean isInheritedAnnotation() { ensureAnnotationBitsInitialized(); return (bits & AnnotationMarkedInherited) != 0; } /* * Setup the bitflags if they have not already been done. */ private void ensureAnnotationBitsInitialized() { if ((bits & AnnotationBitsInitialized) == 0) { bits |= AnnotationBitsInitialized; // Is it marked @Inherited? if (hasAnnotation(UnresolvedType.AT_INHERITED)) { bits |= AnnotationMarkedInherited; } } } private boolean hasNewParentMungers() { if ((bits & MungersAnalyzed) == 0) { bits |= MungersAnalyzed; for (ConcreteTypeMunger munger : interTypeMungers) { ResolvedTypeMunger resolvedTypeMunger = munger.getMunger(); if (resolvedTypeMunger != null && resolvedTypeMunger.getKind() == ResolvedTypeMunger.Parent) { bits |= HasParentMunger; } } } return (bits & HasParentMunger) != 0; } public void tagAsTypeHierarchyComplete() { bits |= TypeHierarchyCompleteBit; } public boolean isTypeHierarchyComplete() { return (bits & TypeHierarchyCompleteBit) != 0; } /** * return the weaver version used to build this type - defaults to the most recent version unless discovered otherwise. * * @return the (major) version, {@link WeaverVersionInfo} */ public int getCompilerVersion() { return WeaverVersionInfo.getCurrentWeaverMajorVersion(); } public boolean isPrimitiveArray() { return false; } public boolean isGroovyObject() { if ((bits & GroovyObjectInitialized) == 0) { ResolvedType[] intfaces = getDeclaredInterfaces(); boolean done = false; // TODO do we need to walk more of these? (i.e. the interfaces interfaces and supertypes supertype). Check what groovy // does in the case where a hierarchy is involved and there are types in between GroovyObject/GroovyObjectSupport and // the type if (intfaces != null) { for (ResolvedType intface : intfaces) { if (intface.getName().equals("groovy.lang.GroovyObject")) { bits |= IsGroovyObject; done = true; break; } } } if (!done) { // take a look at the supertype if (getSuperclass().getName().equals("groovy.lang.GroovyObjectSupport")) { bits |= IsGroovyObject; } } bits |= GroovyObjectInitialized; } return (bits & IsGroovyObject) != 0; } }
374,745
Bug 374745 Performance regression in 1.6.12
null
resolved fixed
549d227
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-03-23T23:57:10Z"
"2012-03-20T10:40:00Z"
org.aspectj.matcher/src/org/aspectj/weaver/TypeFactory.java
/* ******************************************************************* * Copyright (c) 2005-2010 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 * ******************************************************************/ package org.aspectj.weaver; import java.util.ArrayList; import java.util.List; /** * @author Adrian Colyer * @author Andy Clement */ 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 */ 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. */ 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); return new UnresolvedType(signature, signatureErasure, UnresolvedType.NONE); } else { int endOfParams = locateMatchingEndAngleBracket(signature, startOfParams); StringBuffer erasureSig = new StringBuffer(signature); erasureSig.setCharAt(0, 'L'); while (startOfParams != -1) { erasureSig.delete(startOfParams, endOfParams + 1); startOfParams = locateFirstBracket(erasureSig); if (startOfParams != -1) { endOfParams = locateMatchingEndAngleBracket(erasureSig, startOfParams); } } String signatureErasure = erasureSig.toString();// "L" + erasureSig.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("<"); UnresolvedType[] typeParams = UnresolvedType.NONE; if (startOfParams != -1) { endOfParams = locateMatchingEndAngleBracket(lastType, startOfParams); typeParams = createTypeParams(lastType.substring(startOfParams + 1, endOfParams)); } StringBuilder s = new StringBuilder(); int firstAngleBracket = signature.indexOf('<'); s.append("P").append(signature.substring(1, firstAngleBracket)); s.append('<'); for (UnresolvedType typeParameter : typeParams) { s.append(typeParameter.getSignature()); } s.append(">;"); signature = s.toString();// 'P' + signature.substring(1); return new UnresolvedType(signature, signatureErasure, typeParams); } // can't replace above with convertSigToType - leads to stackoverflow } else if ((firstChar == '?' || firstChar == '*') && signature.length()==1) { return WildcardedUnresolvedType.QUESTIONMARK; } else if (firstChar == '+') { // ? extends ... UnresolvedType upperBound = convertSigToType(signature.substring(1)); WildcardedUnresolvedType wildcardedUT = new WildcardedUnresolvedType(signature, upperBound, null); return wildcardedUT; } else if (firstChar == '-') { // ? super ... UnresolvedType lowerBound = convertSigToType(signature.substring(1)); WildcardedUnresolvedType wildcardedUT = new WildcardedUnresolvedType(signature, null, lowerBound); return wildcardedUT; } 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 UnresolvedType.VOID; case 'Z': return UnresolvedType.BOOLEAN; case 'B': return UnresolvedType.BYTE; case 'C': return UnresolvedType.CHAR; case 'D': return UnresolvedType.DOUBLE; case 'F': return UnresolvedType.FLOAT; case 'I': return UnresolvedType.INT; case 'J': return UnresolvedType.LONG; case 'S': return UnresolvedType.SHORT; } } else if (firstChar == '@') { // missing type return ResolvedType.MISSING; } else if (firstChar == 'L') { // only an issue if there is also an angle bracket int leftAngleBracket = signature.indexOf('<'); if (leftAngleBracket == -1) { return new UnresolvedType(signature); } else { int endOfParams = locateMatchingEndAngleBracket(signature, leftAngleBracket); StringBuffer erasureSig = new StringBuffer(signature); erasureSig.setCharAt(0, 'L'); while (leftAngleBracket != -1) { erasureSig.delete(leftAngleBracket, endOfParams + 1); leftAngleBracket = locateFirstBracket(erasureSig); if (leftAngleBracket != -1) { endOfParams = locateMatchingEndAngleBracket(erasureSig, leftAngleBracket); } } String signatureErasure = erasureSig.toString(); // TODO should consider all the intermediate parameterizations as well! // 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); } leftAngleBracket = lastType.indexOf("<"); UnresolvedType[] typeParams = UnresolvedType.NONE; if (leftAngleBracket != -1) { endOfParams = locateMatchingEndAngleBracket(lastType, leftAngleBracket); typeParams = createTypeParams(lastType.substring(leftAngleBracket + 1, endOfParams)); } StringBuilder s = new StringBuilder(); int firstAngleBracket = signature.indexOf('<'); s.append("P").append(signature.substring(1, firstAngleBracket)); s.append('<'); for (UnresolvedType typeParameter : typeParams) { s.append(typeParameter.getSignature()); } s.append(">;"); signature = s.toString();// 'P' + signature.substring(1); return new UnresolvedType(signature, signatureErasure, typeParams); } } return new UnresolvedType(signature); } private static int locateMatchingEndAngleBracket(CharSequence signature, int startOfParams) { if (startOfParams == -1) { return -1; } int count = 1; int idx = startOfParams; int max = signature.length(); while (idx < max) { char ch = signature.charAt(++idx); if (ch == '<') { count++; } else if (ch == '>') { if (count == 1) { break; } count--; } } return idx; } private static int locateFirstBracket(StringBuffer signature) { int idx = 0; int max = signature.length(); while (idx < max) { if (signature.charAt(idx) == '<') { return idx; } idx++; } return -1; } private static UnresolvedType[] createTypeParams(String typeParameterSpecification) { String remainingToProcess = typeParameterSpecification; List<UnresolvedType> types = new ArrayList<UnresolvedType>(); while (remainingToProcess.length() != 0) { int endOfSig = 0; int anglies = 0; boolean hadAnglies = false; boolean sigFound = false; // OPTIMIZE can this be done better? for (endOfSig = 0; (endOfSig < remainingToProcess.length()) && !sigFound; endOfSig++) { char thisChar = remainingToProcess.charAt(endOfSig); switch (thisChar) { case '<': anglies++; hadAnglies = true; break; case '>': anglies--; break; case '*': if (anglies==0) { int nextCharPos = endOfSig+1; if (nextCharPos>=remainingToProcess.length()) { sigFound=true; } else { char nextChar = remainingToProcess.charAt(nextCharPos); if (!(nextChar=='+' || nextChar=='-')) { // dont need to set endOfSig as the loop will increment // it to the right place before it exits sigFound=true; } } } break; case '[': if (anglies == 0) { // the next char might be a [ or a primitive type ref (BCDFIJSZ) int nextChar = endOfSig + 1; while (remainingToProcess.charAt(nextChar) == '[') { nextChar++; } if ("BCDFIJSZ".indexOf(remainingToProcess.charAt(nextChar)) != -1) { // it is something like [I or [[S sigFound = true; endOfSig = nextChar; break; } } break; case ';': if (anglies == 0) { sigFound = true; break; } } } String forProcessing = remainingToProcess.substring(0, endOfSig); if (hadAnglies && forProcessing.charAt(0) == 'L') { forProcessing = "P" + forProcessing.substring(1); } types.add(createTypeFromSignature(forProcessing)); remainingToProcess = remainingToProcess.substring(endOfSig); } UnresolvedType[] typeParams = new UnresolvedType[types.size()]; types.toArray(typeParams); return typeParams; } // OPTIMIZE improve all this signature processing stuff, use char arrays, etc /** * Create a signature then delegate to the other factory method. Same input/output: baseTypeSignature="LSomeType;" arguments[0]= * something with sig "Pcom/Foo<Ljava/lang/String;>;" signature created = "PSomeType<Pcom/Foo<Ljava/lang/String;>;>;" */ public static UnresolvedType createUnresolvedParameterizedType(String baseTypeSignature, UnresolvedType[] arguments) { StringBuffer parameterizedSig = new StringBuffer(); parameterizedSig.append(ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER); parameterizedSig.append(baseTypeSignature.substring(1, baseTypeSignature.length() - 1)); if (arguments.length > 0) { parameterizedSig.append("<"); for (int i = 0; i < arguments.length; i++) { parameterizedSig.append(arguments[i].getSignature()); } parameterizedSig.append(">"); } parameterizedSig.append(";"); return createUnresolvedParameterizedType(parameterizedSig.toString(), baseTypeSignature, arguments); } }
374,745
Bug 374745 Performance regression in 1.6.12
null
resolved fixed
549d227
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-03-23T23:57:10Z"
"2012-03-20T10:40:00Z"
org.aspectj.matcher/src/org/aspectj/weaver/TypeVariableReferenceType.java
/* ******************************************************************* * Copyright (c) 2005-2010 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 * ******************************************************************/ package org.aspectj.weaver; import java.util.Map; /** * ReferenceType representing a type variable. The delegate for this reference type is the upperbound on the type variable (so * Object if not otherwise specified). * * @author Adrian Colyer * @author Andy Clement */ public class TypeVariableReferenceType extends ReferenceType implements TypeVariableReference { private TypeVariable typeVariable; // If 'fixedUp' then the type variable in here is a reference to the real one that may // exist either on a member or a type. Not fixedUp means that we unpacked a generic // signature and weren't able to fix it up during resolution (didn't quite know enough // at the right time). Wonder if we can fix it up late? boolean fixedUp = false; public TypeVariableReferenceType(TypeVariable typeVariable, World world) { super(typeVariable.getGenericSignature(), typeVariable.getErasureSignature(), world); this.typeVariable = typeVariable; // setDelegate(new BoundedReferenceTypeDelegate(backing)); // this.isExtends = false; // this.isSuper = false; } /** * For a TypeVariableReferenceType the delegate is the delegate for the first bound. */ @Override public ReferenceTypeDelegate getDelegate() { if (this.delegate == null) { ResolvedType resolvedFirstBound = typeVariable.getFirstBound().resolve(world); BoundedReferenceTypeDelegate brtd = null; if (resolvedFirstBound.isMissing()) { brtd = new BoundedReferenceTypeDelegate((ReferenceType) world.resolve(UnresolvedType.OBJECT)); setDelegate(brtd); // set now because getSourceLocation() below will cause a recursive step to discover the delegate world.getLint().cantFindType.signal( "Unable to find type for generic bound. Missing type is " + resolvedFirstBound.getName(), getSourceLocation()); } else { brtd = new BoundedReferenceTypeDelegate((ReferenceType) resolvedFirstBound); setDelegate(brtd); } } return this.delegate; } @Override public UnresolvedType parameterize(Map<String, UnresolvedType> typeBindings) { UnresolvedType ut = typeBindings.get(getName()); if (ut != null) { return world.resolve(ut); } return this; } public TypeVariable getTypeVariable() { // if (!fixedUp) // throw new BCException("ARGH"); // fix it up now? return typeVariable; } @Override public boolean isTypeVariableReference() { return true; } @Override public String toString() { return typeVariable.getName(); } @Override public boolean isGenericWildcard() { return false; } @Override public boolean isAnnotation() { ReferenceType upper = (ReferenceType) typeVariable.getUpperBound(); if (upper.isAnnotation()) { return true; } World world = upper.getWorld(); typeVariable.resolve(world); ResolvedType annotationType = ResolvedType.ANNOTATION.resolve(world); UnresolvedType[] ifBounds = typeVariable.getSuperInterfaces();// AdditionalBounds(); for (int i = 0; i < ifBounds.length; i++) { if (((ReferenceType) ifBounds[i]).isAnnotation()) { return true; } if (ifBounds[i].equals(annotationType)) { return true; // annotation itself does not have the annotation flag set in Java! } } return false; } /** * return the signature for a *REFERENCE* to a type variable, which is simply: Tname; there is no bounds info included, that is * in the signature of the type variable itself */ @Override public String getSignature() { StringBuffer sb = new StringBuffer(); sb.append("T"); sb.append(typeVariable.getName()); sb.append(";"); return sb.toString(); } /** * @return the name of the type variable */ public String getTypeVariableName() { return typeVariable.getName(); } public ReferenceType getUpperBound() { return (ReferenceType) typeVariable.resolve(world).getUpperBound(); } /** * resolve the type variable we are managing and then return this object. 'this' is already a ResolvedType but the type variable * may transition from a not-resolved to a resolved state. */ public ResolvedType resolve(World world) { typeVariable.resolve(world); return this; } /** * @return true if the type variable this reference is managing is resolved */ public boolean isTypeVariableResolved() { return typeVariable.isResolved; } }
374,745
Bug 374745 Performance regression in 1.6.12
null
resolved fixed
549d227
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-03-23T23:57:10Z"
"2012-03-20T10:40:00Z"
org.aspectj.matcher/src/org/aspectj/weaver/UnresolvedType.java
/* ******************************************************************* * Copyright (c) 2002,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 * Andy Clement start of generics upgrade... * Adrian Colyer - overhaul * ******************************************************************/ package org.aspectj.weaver; import java.io.DataInputStream; import java.io.IOException; import java.util.Map; import org.aspectj.util.GenericSignature; import org.aspectj.util.GenericSignature.ClassSignature; import org.aspectj.util.GenericSignatureParser; import org.aspectj.weaver.tools.Traceable; /** * A UnresolvedType represents a type to the weaver. UnresolvedTypes are resolved in some World (a type repository). When a * UnresolvedType is resolved it turns into a ResolvedType which may be a primitive type, or a ReferenceType. ReferenceTypes may * refer to simple, generic, parameterized or type-variable based reference types. A ReferenceType is backed by a delegate that * provides information about the type based on some repository (for example an Eclipse based delegate, a bytecode based delegate or * a reflection based delegate). * <p> * Every UnresolvedType has a signature, the unique key for the type in the world. */ public class UnresolvedType implements Traceable, TypeVariableDeclaringElement { // common type structures public static final UnresolvedType[] NONE = new UnresolvedType[0]; public static final UnresolvedType OBJECT = forSignature("Ljava/lang/Object;"); public static final UnresolvedType OBJECTARRAY = forSignature("[Ljava/lang/Object;"); public static final UnresolvedType CLONEABLE = forSignature("Ljava/lang/Cloneable;"); public static final UnresolvedType SERIALIZABLE = forSignature("Ljava/io/Serializable;"); public static final UnresolvedType THROWABLE = forSignature("Ljava/lang/Throwable;"); public static final UnresolvedType RUNTIME_EXCEPTION = forSignature("Ljava/lang/RuntimeException;"); public static final UnresolvedType ERROR = forSignature("Ljava/lang/Error;"); public static final UnresolvedType AT_INHERITED = forSignature("Ljava/lang/annotation/Inherited;"); public static final UnresolvedType AT_RETENTION = forSignature("Ljava/lang/annotation/Retention;"); public static final UnresolvedType ENUM = forSignature("Ljava/lang/Enum;"); public static final UnresolvedType ANNOTATION = forSignature("Ljava/lang/annotation/Annotation;"); public static final UnresolvedType JL_CLASS = forSignature("Ljava/lang/Class;"); public static final UnresolvedType JAVA_LANG_CLASS_ARRAY = forSignature("[Ljava/lang/Class;"); public static final UnresolvedType JL_STRING = forSignature("Ljava/lang/String;"); public static final UnresolvedType JL_EXCEPTION = forSignature("Ljava/lang/Exception;"); public static final UnresolvedType JAVA_LANG_REFLECT_METHOD = forSignature("Ljava/lang/reflect/Method;"); public static final UnresolvedType JAVA_LANG_REFLECT_FIELD = forSignature("Ljava/lang/reflect/Field;"); public static final UnresolvedType JAVA_LANG_REFLECT_CONSTRUCTOR = forSignature("Ljava/lang/reflect/Constructor;"); public static final UnresolvedType JAVA_LANG_ANNOTATION = forSignature("Ljava/lang/annotation/Annotation;"); public static final UnresolvedType SUPPRESS_AJ_WARNINGS = forSignature("Lorg/aspectj/lang/annotation/SuppressAjWarnings;"); public static final UnresolvedType AT_TARGET = forSignature("Ljava/lang/annotation/Target;"); public static final UnresolvedType SOMETHING = new UnresolvedType("?"); public static final UnresolvedType[] ARRAY_WITH_JUST_OBJECT = new UnresolvedType[] { OBJECT }; public static final UnresolvedType JOINPOINT_STATICPART = forSignature("Lorg/aspectj/lang/JoinPoint$StaticPart;"); public static final UnresolvedType JOINPOINT_ENCLOSINGSTATICPART = forSignature("Lorg/aspectj/lang/JoinPoint$EnclosingStaticPart;"); public static final UnresolvedType BOOLEAN = forPrimitiveType("Z"); public static final UnresolvedType BYTE = forPrimitiveType("B"); public static final UnresolvedType CHAR = forPrimitiveType("C"); public static final UnresolvedType DOUBLE = forPrimitiveType("D"); public static final UnresolvedType FLOAT = forPrimitiveType("F"); public static final UnresolvedType INT = forPrimitiveType("I"); public static final UnresolvedType LONG = forPrimitiveType("J"); public static final UnresolvedType SHORT = forPrimitiveType("S"); public static final UnresolvedType VOID = forPrimitiveType("V"); // A type is considered missing if we have a signature for it but cannot find the delegate public static final String MISSING_NAME = "@missing@"; // OPTIMIZE I dont think you can ask something unresolved what kind of type it is, how can it always know? Push down into // resolvedtype that will force references to resolvedtypes to be correct rather than relying on unresolvedtypes to answer // questions protected TypeKind typeKind = TypeKind.SIMPLE; // what kind of type am I? protected String signature; /** * The erasure of the signature. Contains only the Java signature of the type with all supertype, superinterface, type variable, * and parameter information removed. */ protected String signatureErasure; /** * Calculated on first request - the package name (java.lang for type java.lang.String) */ private String packageName; /** * Calculated on first request - the class name (String for type java.lang.String) */ private String className; /** * Iff isParameterized(), then these are the type parameters */ protected UnresolvedType[] typeParameters; /** * Iff isGeneric(), then these are the type variables declared on the type Iff isParameterized(), then these are the type * variables bound as parameters in the type */ // OPTIMIZE should be no state in here that will damage whether equals() is correct... protected TypeVariable[] typeVariables; public boolean isPrimitiveType() { return typeKind == TypeKind.PRIMITIVE; } public boolean isVoid() { // OPTIMIZE promote to bitflag? return signature.equals("V"); } public boolean isSimpleType() { return typeKind == TypeKind.SIMPLE; } public boolean isRawType() { return typeKind == TypeKind.RAW; } public boolean isGenericType() { return typeKind == TypeKind.GENERIC; } public boolean isParameterizedType() { return typeKind == TypeKind.PARAMETERIZED; } public boolean isParameterizedOrGenericType() { return typeKind == TypeKind.GENERIC || typeKind == TypeKind.PARAMETERIZED; } public boolean isParameterizedOrRawType() { return typeKind == TypeKind.PARAMETERIZED || typeKind == TypeKind.RAW; } public boolean isTypeVariableReference() { return typeKind == TypeKind.TYPE_VARIABLE; } public boolean isGenericWildcard() { return typeKind == TypeKind.WILDCARD; } public TypeKind getTypekind() { return typeKind; } // for any reference type, we can get some extra information... public final boolean isArray() { return signature.length() > 0 && signature.charAt(0) == '['; } /** * Equality is checked based on the underlying signature. */ @Override public boolean equals(Object other) { if (!(other instanceof UnresolvedType)) { return false; } return signature.equals(((UnresolvedType) other).signature); } /** * Equality is checked based on the underlying signature, so the hash code of a particular type is the hash code of its * signature string. */ @Override public final int hashCode() { return signature.hashCode(); } protected UnresolvedType(String signature) { this.signature = signature; this.signatureErasure = signature; } protected UnresolvedType(String signature, String signatureErasure) { this.signature = signature; this.signatureErasure = signatureErasure; } // called from TypeFactory public UnresolvedType(String signature, String signatureErasure, UnresolvedType[] typeParams) { this.signature = signature; this.signatureErasure = signatureErasure; this.typeParameters = typeParams; if (typeParams != null) { this.typeKind = TypeKind.PARAMETERIZED; } } // The operations supported by an UnresolvedType are those that do not require a world /** * This is the size of this type as used in JVM. */ public int getSize() { return size; } private int size = 1; /** * NOTE: Use forSignature() if you can, it'll be cheaper ! Constructs a UnresolvedType for a java language type name. For * example: * * <blockquote> * * <pre> * UnresolvedType.forName(&quot;java.lang.Thread[]&quot;) * UnresolvedType.forName(&quot;int&quot;) * </pre> * * </blockquote> * * Types may equivalently be produced by this or by {@link #forSignature(String)}. * * <blockquote> * * <pre> * UnresolvedType.forName(&quot;java.lang.Thread[]&quot;).equals(Type.forSignature(&quot;[Ljava/lang/Thread;&quot;) * UnresolvedType.forName(&quot;int&quot;).equals(Type.forSignature(&quot;I&quot;)) * </pre> * * </blockquote> * * @param name the java language type name in question. * @return a type object representing that java language type. */ // OPTIMIZE change users of this to use forSignature, especially for simple cases public static UnresolvedType forName(String name) { return forSignature(nameToSignature(name)); } /** * Constructs a UnresolvedType for each java language type name in an incoming array. * * @param names an array of java language type names. * @return an array of UnresolvedType objects. * @see #forName(String) */ public static UnresolvedType[] forNames(String[] names) { UnresolvedType[] ret = new UnresolvedType[names.length]; for (int i = 0, len = names.length; i < len; i++) { ret[i] = UnresolvedType.forName(names[i]); } return ret; } public static UnresolvedType forGenericType(String name, TypeVariable[] tvbs, String genericSig) { // TODO asc generics needs a declared sig String sig = nameToSignature(name); UnresolvedType ret = UnresolvedType.forSignature(sig); ret.typeKind = TypeKind.GENERIC; ret.typeVariables = tvbs; ret.signatureErasure = sig; return ret; } public static UnresolvedType forGenericTypeSignature(String sig, String declaredGenericSig) { UnresolvedType ret = UnresolvedType.forSignature(sig); ret.typeKind = TypeKind.GENERIC; ClassSignature csig = new GenericSignatureParser().parseAsClassSignature(declaredGenericSig); GenericSignature.FormalTypeParameter[] ftps = csig.formalTypeParameters; ret.typeVariables = new TypeVariable[ftps.length]; for (int i = 0; i < ftps.length; i++) { GenericSignature.FormalTypeParameter parameter = ftps[i]; if (parameter.classBound instanceof GenericSignature.ClassTypeSignature) { GenericSignature.ClassTypeSignature cts = (GenericSignature.ClassTypeSignature) parameter.classBound; ret.typeVariables[i] = new TypeVariable(ftps[i].identifier, UnresolvedType.forSignature(cts.outerType.identifier + ";")); } else if (parameter.classBound instanceof GenericSignature.TypeVariableSignature) { GenericSignature.TypeVariableSignature tvs = (GenericSignature.TypeVariableSignature) parameter.classBound; UnresolvedTypeVariableReferenceType utvrt = new UnresolvedTypeVariableReferenceType(new TypeVariable( tvs.typeVariableName)); ret.typeVariables[i] = new TypeVariable(ftps[i].identifier, utvrt); } else { throw new BCException( "UnresolvedType.forGenericTypeSignature(): Do not know how to process type variable bound of type '" + parameter.classBound.getClass() + "'. Full signature is '" + sig + "'"); } } ret.signatureErasure = sig; ret.signature = ret.signatureErasure; return ret; } public static UnresolvedType forGenericTypeVariables(String sig, TypeVariable[] tVars) { UnresolvedType ret = UnresolvedType.forSignature(sig); ret.typeKind = TypeKind.GENERIC; ret.typeVariables = tVars; ret.signatureErasure = sig; ret.signature = ret.signatureErasure; return ret; } public static UnresolvedType forRawTypeName(String name) { UnresolvedType ret = UnresolvedType.forName(name); ret.typeKind = TypeKind.RAW; return ret; } public static UnresolvedType forPrimitiveType(String signature) { UnresolvedType ret = new UnresolvedType(signature); ret.typeKind = TypeKind.PRIMITIVE; if (signature.equals("J") || signature.equals("D")) { ret.size = 2; } else if (signature.equals("V")) { ret.size = 0; } return ret; } /** * Creates a new type array with a fresh type appended to the end. * * @param types the left hand side of the new array * @param end the right hand side of the new array */ public static UnresolvedType[] add(UnresolvedType[] types, UnresolvedType end) { int len = types.length; UnresolvedType[] ret = new UnresolvedType[len + 1]; System.arraycopy(types, 0, ret, 0, len); ret[len] = end; return ret; } /** * Creates a new type array with a fresh type inserted at the beginning. * * * @param start the left hand side of the new array * @param types the right hand side of the new array */ public static UnresolvedType[] insert(UnresolvedType start, UnresolvedType[] types) { int len = types.length; UnresolvedType[] ret = new UnresolvedType[len + 1]; ret[0] = start; System.arraycopy(types, 0, ret, 1, len); return ret; } /** * Constructs a Type for a JVM bytecode signature string. For example: * * <blockquote> * * <pre> * UnresolvedType.forSignature(&quot;[Ljava/lang/Thread;&quot;) * UnresolvedType.forSignature(&quot;I&quot;); * </pre> * * </blockquote> * * Types may equivalently be produced by this or by {@link #forName(String)}. This method should not be passed P signatures. * * <blockquote> * * <pre> * UnresolvedType.forName(&quot;java.lang.Thread[]&quot;).equals(Type.forSignature(&quot;[Ljava/lang/Thread;&quot;) * UnresolvedType.forName(&quot;int&quot;).equals(Type.forSignature(&quot;I&quot;)) * </pre> * * </blockquote> * * @param signature the JVM bytecode signature string for the desired type. * @return a type object represnting that JVM bytecode signature. */ public static UnresolvedType forSignature(String signature) { assert !(signature.startsWith("L") && signature.indexOf("<") != -1); switch (signature.charAt(0)) { case 'B': return UnresolvedType.BYTE; case 'C': return UnresolvedType.CHAR; case 'D': return UnresolvedType.DOUBLE; case 'F': return UnresolvedType.FLOAT; case 'I': return UnresolvedType.INT; case 'J': return UnresolvedType.LONG; case 'L': return TypeFactory.createTypeFromSignature(signature); case 'P': return TypeFactory.createTypeFromSignature(signature); case 'S': return UnresolvedType.SHORT; case 'V': return UnresolvedType.VOID; case 'Z': return UnresolvedType.BOOLEAN; case '[': return TypeFactory.createTypeFromSignature(signature); case '+': return TypeFactory.createTypeFromSignature(signature); case '-': return TypeFactory.createTypeFromSignature(signature); case '?': return TypeFactory.createTypeFromSignature(signature); case 'T': return TypeFactory.createTypeFromSignature(signature); default: throw new BCException("Bad type signature " + signature); } } /** * Constructs a UnresolvedType for each JVM bytecode type signature in an incoming array. * * @param names an array of JVM bytecode type signatures * @return an array of UnresolvedType objects. * @see #forSignature(String) */ public static UnresolvedType[] forSignatures(String[] sigs) { UnresolvedType[] ret = new UnresolvedType[sigs.length]; for (int i = 0, len = sigs.length; i < len; i++) { ret[i] = UnresolvedType.forSignature(sigs[i]); } return ret; } /** * Returns the name of this type in java language form (e.g. java.lang.Thread or boolean[]). This produces a more aesthetically * pleasing string than {@link java.lang.Class#getName()}. * * @return the java language name of this type. */ public String getName() { return signatureToName(signature); } public String getSimpleName() { String name = getRawName(); int lastDot = name.lastIndexOf('.'); if (lastDot != -1) { name = name.substring(lastDot + 1); } if (isParameterizedType()) { StringBuffer sb = new StringBuffer(name); sb.append("<"); for (int i = 0; i < (typeParameters.length - 1); i++) { sb.append(typeParameters[i].getSimpleName()); sb.append(","); } sb.append(typeParameters[typeParameters.length - 1].getSimpleName()); sb.append(">"); name = sb.toString(); } return name; } public String getRawName() { return signatureToName((signatureErasure == null ? signature : signatureErasure)); } public String getBaseName() { String name = getName(); if (isParameterizedType() || isGenericType()) { if (typeParameters == null) { return name; } else { return name.substring(0, name.indexOf("<")); } } else { return name; } } public String getSimpleBaseName() { String name = getBaseName(); int lastDot = name.lastIndexOf('.'); if (lastDot != -1) { name = name.substring(lastDot + 1); } return name; } /** * Returns an array of strings representing the java langauge names of an array of types. * * @param types an array of UnresolvedType objects * @return an array of Strings fo the java language names of types. * @see #getName() */ public static String[] getNames(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; } /** * Returns the name of this type in JVM signature form. For all UnresolvedType t: * * <blockquote> * * <pre> * UnresolvedType.forSignature(t.getSignature()).equals(t) * </pre> * * </blockquote> * * and for all String s where s is a lexically valid JVM type signature string: * * <blockquote> * * <pre> * UnresolvedType.forSignature(s).getSignature().equals(s) * </pre> * * </blockquote> * * @return the java JVM signature string for this type. */ public String getSignature() { return signature; } /** * For parameterized types, return the signature for the raw type */ public String getErasureSignature() { if (signatureErasure == null) { return signature; } return signatureErasure; } private boolean needsModifiableDelegate = false; public boolean needsModifiableDelegate() { return needsModifiableDelegate; } public void setNeedsModifiableDelegate(boolean b) { this.needsModifiableDelegate = b; } public UnresolvedType getRawType() { return UnresolvedType.forSignature(getErasureSignature()); } /** * Returns a UnresolvedType object representing the effective outermost enclosing type for a name type. For all other types, * this will return the type itself. * * The only guarantee is given in JLS 13.1 where code generated according to those rules will have type names that can be split * apart in this way. * * @return the outermost enclosing UnresolvedType object or this. */ public UnresolvedType getOutermostType() { if (isArray() || isPrimitiveType()) { return this; } String sig = getErasureSignature(); int dollar = sig.indexOf('$'); if (dollar != -1) { return UnresolvedType.forSignature(sig.substring(0, dollar) + ';'); } else { return this; } } /** * Returns a UnresolvedType object representing the component type of this array, or null if this type does not represent an * array type. * * @return the component UnresolvedType object, or null. */ public UnresolvedType getComponentType() { if (isArray()) { return forSignature(signature.substring(1)); } else { return null; } } /** * Returns a java language string representation of this type. */ @Override public String toString() { return getName(); // + " - " + getKind(); } public String toDebugString() { return getName(); } // ---- requires worlds /** * Returns a resolved version of this type according to a particular world. * * @param world the {@link World} within which to resolve. * @return a resolved type representing this type in the appropriate world. */ public ResolvedType resolve(World world) { return world.resolve(this); } // ---- helpers private static String signatureToName(String signature) { switch (signature.charAt(0)) { case 'B': return "byte"; case 'C': return "char"; case 'D': return "double"; case 'F': return "float"; case 'I': return "int"; case 'J': return "long"; case 'L': String name = signature.substring(1, signature.length() - 1).replace('/', '.'); return name; case 'T': StringBuffer nameBuff2 = new StringBuffer(); int colon = signature.indexOf(";"); String tvarName = signature.substring(1, colon); nameBuff2.append(tvarName); return nameBuff2.toString(); case 'P': // it's one of our parameterized type sigs StringBuffer nameBuff = new StringBuffer(); // signature for parameterized types is e.g. // List<String> -> Ljava/util/List<Ljava/lang/String;>; // Map<String,List<Integer>> -> Ljava/util/Map<java/lang/String;Ljava/util/List<Ljava/lang/Integer;>;>; int paramNestLevel = 0; for (int i = 1; i < signature.length(); i++) { char c = signature.charAt(i); switch (c) { case '/': nameBuff.append('.'); break; case '<': nameBuff.append("<"); paramNestLevel++; StringBuffer innerBuff = new StringBuffer(); while (paramNestLevel > 0) { c = signature.charAt(++i); if (c == '<') { paramNestLevel++; } if (c == '>') { paramNestLevel--; } if (paramNestLevel > 0) { innerBuff.append(c); } if (c == ';' && paramNestLevel == 1) { nameBuff.append(signatureToName(innerBuff.toString())); if (signature.charAt(i + 1) != '>') { nameBuff.append(','); } innerBuff = new StringBuffer(); } } nameBuff.append(">"); break; case ';': break; default: nameBuff.append(c); } } return nameBuff.toString(); case 'S': return "short"; case 'V': return "void"; case 'Z': return "boolean"; case '[': return signatureToName(signature.substring(1, signature.length())) + "[]"; // case '<': // // its a generic! // if (signature.charAt(1)=='>') return signatureToName(signature.substring(2)); case '+': return "? extends " + signatureToName(signature.substring(1, signature.length())); case '-': return "? super " + signatureToName(signature.substring(1, signature.length())); case '*': return "?"; default: throw new BCException("Bad type signature: " + signature); } } private static String nameToSignature(String name) { int len = name.length(); if (len < 8) { if (name.equals("byte")) { return "B"; } if (name.equals("char")) { return "C"; } if (name.equals("double")) { return "D"; } if (name.equals("float")) { return "F"; } if (name.equals("int")) { return "I"; } if (name.equals("long")) { return "J"; } if (name.equals("short")) { return "S"; } if (name.equals("boolean")) { return "Z"; } if (name.equals("void")) { return "V"; } if (name.equals("?")) { return name; } } if (name.endsWith("[]")) { return "[" + nameToSignature(name.substring(0, name.length() - 2)); } if (len == 0) { throw new BCException("Bad type name: " + name); } if (name.indexOf("<") == -1) { // not parameterized return new StringBuilder("L").append(name.replace('.', '/')).append(';').toString(); } else { StringBuffer nameBuff = new StringBuffer(); int nestLevel = 0; nameBuff.append("P"); for (int i = 0; i < len; i++) { char c = name.charAt(i); switch (c) { case '.': nameBuff.append('/'); break; case '<': nameBuff.append("<"); nestLevel++; StringBuffer innerBuff = new StringBuffer(); while (nestLevel > 0) { c = name.charAt(++i); if (c == '<') { nestLevel++; } else if (c == '>') { nestLevel--; } if (c == ',' && nestLevel == 1) { nameBuff.append(nameToSignature(innerBuff.toString())); innerBuff = new StringBuffer(); } else { if (nestLevel > 0) { innerBuff.append(c); } } } nameBuff.append(nameToSignature(innerBuff.toString())); nameBuff.append('>'); break; // case '>': // throw new IllegalStateException("Should by matched by <"); // case ',': // throw new IllegalStateException("Should only happen inside <...>"); default: nameBuff.append(c); } } nameBuff.append(";"); return nameBuff.toString(); } } /** * Write out an UnresolvedType - the signature should be enough. */ public final void write(CompressingDataOutputStream s) throws IOException { s.writeUTF(getSignature()); } /** * Read in an UnresolvedType - just read the signature and rebuild the UnresolvedType. */ public static UnresolvedType read(DataInputStream s) throws IOException { String sig = s.readUTF(); if (sig.equals(MISSING_NAME)) { return ResolvedType.MISSING; } else { // TODO isn't it a shame to build these (this method is expensive) and then chuck them away on resolution? // TODO review callers and see if they are immediately resolving it, maybe we can do something more optimal if they are return UnresolvedType.forSignature(sig); } } public String getNameAsIdentifier() { return getName().replace('.', '_'); } public String getPackageNameAsIdentifier() { String name = getName(); int index = name.lastIndexOf('.'); if (index == -1) { return ""; } else { return name.substring(0, index).replace('.', '_'); } } public UnresolvedType[] getTypeParameters() { return typeParameters == null ? UnresolvedType.NONE : typeParameters; } public TypeVariable[] getTypeVariables() { return typeVariables; } public static class TypeKind { // Note: It is not sufficient to say that a parameterized type with no type parameters in fact // represents a raw type - a parameterized type with no type parameters can represent // an inner type of a parameterized type that specifies no type parameters of its own. public final static TypeKind PRIMITIVE = new TypeKind("primitive"); public final static TypeKind SIMPLE = new TypeKind("simple"); // a type with NO type parameters/vars public final static TypeKind RAW = new TypeKind("raw"); // the erasure of a generic type public final static TypeKind GENERIC = new TypeKind("generic"); // a generic type public final static TypeKind PARAMETERIZED = new TypeKind("parameterized"); // a parameterized type public final static TypeKind TYPE_VARIABLE = new TypeKind("type_variable"); // a type variable public final static TypeKind WILDCARD = new TypeKind("wildcard"); // a generic wildcard type @Override public String toString() { return type; } private TypeKind(String type) { this.type = type; } private final String type; } public TypeVariable getTypeVariableNamed(String name) { TypeVariable[] vars = getTypeVariables(); if (vars == null || vars.length == 0) { return null; } for (int i = 0; i < vars.length; i++) { TypeVariable aVar = vars[i]; if (aVar.getName().equals(name)) { return aVar; } } return null; } public String toTraceString() { return getClass().getName() + "[" + getName() + "]"; } /** * Return a version of this parameterized type in which any type parameters that are type variable references are replaced by * their matching type variable binding. */ // OPTIMIZE methods like this just allow callers to be lazy and not ensure they are working with the right (resolved) subtype public UnresolvedType parameterize(Map<String, UnresolvedType> typeBindings) { throw new UnsupportedOperationException("unable to parameterize unresolved type: " + signature); } /** * @return the class name (does not include the package name) */ public String getClassName() { if (className == null) { String name = getName(); if (name.indexOf("<") != -1) { name = name.substring(0, name.indexOf("<")); } int index = name.lastIndexOf('.'); if (index == -1) { className = name; } else { className = name.substring(index + 1); } } return className; } /** * @return the package name (no class name included) */ public String getPackageName() { if (packageName == null) { String name = getName(); if (name.indexOf("<") != -1) { name = name.substring(0, name.indexOf("<")); } int index = name.lastIndexOf('.'); if (index == -1) { packageName = ""; } else { packageName = name.substring(0, index); } } return packageName; } // TODO these move to a TypeUtils class public static void writeArray(UnresolvedType[] types, CompressingDataOutputStream stream) throws IOException { int len = types.length; stream.writeShort(len); for (UnresolvedType type : types) { type.write(stream); } } public static UnresolvedType[] readArray(DataInputStream s) throws IOException { int len = s.readShort(); if (len == 0) { return UnresolvedType.NONE; } UnresolvedType[] types = new UnresolvedType[len]; for (int i = 0; i < len; i++) { types[i] = UnresolvedType.read(s); } return types; } public static UnresolvedType makeArray(UnresolvedType base, int dims) { StringBuffer sig = new StringBuffer(); for (int i = 0; i < dims; i++) { sig.append("["); } sig.append(base.getSignature()); return UnresolvedType.forSignature(sig.toString()); } }
374,745
Bug 374745 Performance regression in 1.6.12
null
resolved fixed
549d227
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-03-23T23:57:10Z"
"2012-03-20T10:40:00Z"
org.aspectj.matcher/src/org/aspectj/weaver/UnresolvedTypeVariableReferenceType.java
/* ******************************************************************* * Copyright (c) 2005-2010 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 * ******************************************************************/ package org.aspectj.weaver; /** * @author Adrian Colyer * @author Andy Clement */ public class UnresolvedTypeVariableReferenceType extends UnresolvedType implements TypeVariableReference { private TypeVariable typeVariable; // constructor used as place-holder when dealing with circular refs such as Enum public UnresolvedTypeVariableReferenceType() { super("Ljava/lang/Object;"); } public UnresolvedTypeVariableReferenceType(TypeVariable aTypeVariable) { super("T" + aTypeVariable.getName() + ";", aTypeVariable.getFirstBound().getErasureSignature());//aTypeVariable.getFirstBound().getSignature()); this.typeVariable = aTypeVariable; } // only used when resolving circular refs... public void setTypeVariable(TypeVariable aTypeVariable) { this.signature = "T" + aTypeVariable.getName() + ";"; // aTypeVariable.getUpperBound().getSignature(); this.signatureErasure = aTypeVariable.getFirstBound().getErasureSignature(); this.typeVariable = aTypeVariable; this.typeKind = TypeKind.TYPE_VARIABLE; } @Override public ResolvedType resolve(World world) { TypeVariableDeclaringElement typeVariableScope = world.getTypeVariableLookupScope(); TypeVariable resolvedTypeVariable = null; TypeVariableReferenceType tvrt = null; if (typeVariableScope == null) { // throw new BCException("There is no scope in which to lookup type variables!"); // FIXME asc correct thing to do is go bang, but to limp along, lets cope with the scope missing resolvedTypeVariable = typeVariable.resolve(world); tvrt = new TypeVariableReferenceType(resolvedTypeVariable, world); } else { boolean foundOK = false; resolvedTypeVariable = typeVariableScope.getTypeVariableNamed(typeVariable.getName()); // FIXME asc remove this when the shared type var stuff is sorted if (resolvedTypeVariable == null) { resolvedTypeVariable = typeVariable.resolve(world); } else { foundOK = true; } tvrt = new TypeVariableReferenceType(resolvedTypeVariable, world); tvrt.fixedUp = foundOK; } return tvrt; } @Override public boolean isTypeVariableReference() { return true; } public TypeVariable getTypeVariable() { return typeVariable; } @Override public String toString() { if (typeVariable == null) { return "<type variable not set!>"; } else { return "T" + typeVariable.getName() + ";"; } } @Override public String toDebugString() { return typeVariable.getName(); } @Override public String getErasureSignature() { return typeVariable.getFirstBound().getSignature(); } }
374,745
Bug 374745 Performance regression in 1.6.12
null
resolved fixed
549d227
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-03-23T23:57:10Z"
"2012-03-20T10:40:00Z"
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, Abraham Nevado * ******************************************************************/ package org.aspectj.weaver; import java.lang.ref.Reference; 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.IMessage; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.context.PinpointingMessageHandler; import org.aspectj.util.IStructureModel; import org.aspectj.weaver.ResolvedType.Primitive; import org.aspectj.weaver.UnresolvedType.TypeKind; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.DeclareSoft; import org.aspectj.weaver.patterns.DeclareTypeErrorOrWarning; 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<PointcutDesignatorHandler> 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; /** Should timing information be reported (as info messages)? */ private boolean timing = false; private boolean timingPeriodically = true; /** 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 transientTjpFields = false; private boolean runMinimalMemorySet = false; private boolean shouldPipelineCompilation = true; private boolean shouldGenerateStackMaps = false; protected boolean bcelRepositoryCaching = xsetBCEL_REPOSITORY_CACHING_DEFAULT.equalsIgnoreCase("true"); private boolean fastMethodPacking = false; private int itdVersion = 2; // defaults to 2nd generation itds // Minimal Model controls whether model entities that are not involved in relationships are deleted post-build private boolean minimalModel = true; private boolean useFinal = true; private boolean targettingRuntime1_6_10 = false; private boolean completeBinaryTypes = false; private boolean overWeaving = false; private static boolean systemPropertyOverWeaving = false; public boolean forDEBUG_structuralChangesCode = false; public boolean forDEBUG_bridgingCode = false; public boolean optimizedMatching = true; protected long timersPerJoinpoint = 25000; protected long timersPerType = 250; public int infoMessagesEnabled = 0; // 0=uninitialized, 1=no, 2=yes private static Trace trace = TraceFactory.getTraceFactory().getTrace(World.class); private boolean errorThreshold; private boolean warningThreshold; /** * A list of RuntimeExceptions containing full stack information for every type we couldn't find. */ private List<RuntimeException> dumpState_cantFindTypeExceptions = null; static { try { String value = System.getProperty("aspectj.overweaving", "false"); if (value.equalsIgnoreCase("true")) { System.out.println("ASPECTJ: aspectj.overweaving=true: overweaving switched ON"); systemPropertyOverWeaving = true; } } catch (Throwable t) { System.err.println("ASPECTJ: Unable to read system properties"); t.printStackTrace(); } } public final Primitive BYTE = new Primitive("B", 1, 0); public final Primitive CHAR = new Primitive("C", 1, 1); public final Primitive DOUBLE = new Primitive("D", 2, 2); public final Primitive FLOAT = new Primitive("F", 1, 3); public final Primitive INT = new Primitive("I", 1, 4); public final Primitive LONG = new Primitive("J", 2, 5); public final Primitive SHORT = new Primitive("S", 1, 6); public final Primitive BOOLEAN = new Primitive("Z", 1, 7); public final Primitive VOID = new Primitive("V", 0, 8); /** * Insert the primitives */ protected World() { super(); // Dump.registerNode(this.getClass(), this); typeMap.put("B", BYTE); typeMap.put("S", SHORT); typeMap.put("I", INT); typeMap.put("J", LONG); typeMap.put("F", FLOAT); typeMap.put("D", DOUBLE); typeMap.put("C", CHAR); typeMap.put("Z", BOOLEAN); typeMap.put("V", VOID); precedenceCalculator = new AspectPrecedenceCalculator(this); } /** * 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 ResolvedType.NONE; } 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); // A TypeVariableReferenceType may look like it is resolved (it extends ResolvedType) but the internal // type variable may not yet have been resolved if (!rty.isTypeVariableReference() || ((TypeVariableReferenceType) rty).isTypeVariableResolved()) { 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 = getWildcard(); typeMap.put("?", something); return something; } // no existing resolved type, create one synchronized (buildingTypeLock) { if (ty.isArray()) { ResolvedType componentType = resolve(ty.getComponentType(), allowMissing); 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 ResolvedType result = typeMap.get(signature); if (result == null && !ret.isMissing()) { ret = ensureRawTypeIfNecessary(ret); typeMap.put(signature, ret); return ret; } if (result == null) { return ret; } else { return result; } } private Object buildingTypeLock = new Object(); // Only need one representation of '?' in a world - can be shared private BoundedReferenceType wildcard; private BoundedReferenceType getWildcard() { if (wildcard == null) { wildcard = new BoundedReferenceType(this); } return wildcard; } /** * 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<RuntimeException>(); } 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) { resolved = ensureRawTypeIfNecessary(ty); typeMap.put(ty.getSignature(), resolved); resolved = ty; } resolved.world = this; return resolved; } /** * When the world is operating in 1.5 mode, the TypeMap should only contain RAW types and never directly generic types. The RAW * type will contain a reference to the generic type. * * @param type a possibly generic type for which the raw needs creating as it is not currently in the world * @return a type suitable for putting into the world */ private ResolvedType ensureRawTypeIfNecessary(ResolvedType type) { if (!isInJava5Mode() || type.isRawType()) { return type; } // Key requirement here is if it is generic, create a RAW entry to be put in the map that points to it if (type instanceof ReferenceType && ((ReferenceType) type).getDelegate() != null && type.isGenericType()) { ReferenceType rawType = new ReferenceType(type.getSignature(), this); rawType.typeKind = UnresolvedType.TypeKind.RAW; ReferenceTypeDelegate delegate = ((ReferenceType) type).getDelegate(); rawType.setDelegate(delegate); rawType.setGenericType((ReferenceType) type); return rawType; } // probably parameterized... return type; } /** * 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 ReferenceType resolveToReferenceType(String name) { return (ReferenceType) resolve(name); } 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 ====================== ResolvedType rt = resolveGenericTypeFor(ty, false); ReferenceType genericType = (ReferenceType) rt; 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; ((ReferenceType) genericType).addDependentType((ReferenceType) rawType); 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 = getWildcard(); } 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); } private boolean allLintIgnored = false; public void setAllLintIgnored() { allLintIgnored = true; } public boolean areAllLintIgnored() { return allLintIgnored; } 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, ResolvedType declaringAspect) { AjAttribute.AdviceAttribute attribute = new AjAttribute.AdviceAttribute(kind, p, extraParameterFlags, loc.getStart(), loc.getEnd(), loc.getSourceContext()); return getWeavingSupport().createAdviceMunger(attribute, p, signature, declaringAspect); } /** * 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<DeclareParents> getDeclareParents() { return crosscuttingMembersSet.getDeclareParents(); } public List<DeclareAnnotation> getDeclareAnnotationOnTypes() { return crosscuttingMembersSet.getDeclareAnnotationOnTypes(); } public List<DeclareAnnotation> getDeclareAnnotationOnFields() { return crosscuttingMembersSet.getDeclareAnnotationOnFields(); } public List<DeclareAnnotation> getDeclareAnnotationOnMethods() { return crosscuttingMembersSet.getDeclareAnnotationOnMethods(); } public List<DeclareTypeErrorOrWarning> getDeclareTypeEows() { return crosscuttingMembersSet.getDeclareTypeEows(); } public List<DeclareSoft> 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 boolean useFinal() { return useFinal; } public boolean isMinimalModel() { ensureAdvancedConfigurationProcessed(); return minimalModel; } public boolean isTargettingRuntime1_6_10() { ensureAdvancedConfigurationProcessed(); return targettingRuntime1_6_10; } public void setBehaveInJava5Way(boolean b) { behaveInJava5Way = b; } /** * Set the timing option (whether to collect timing info), this will also need INFO messages turned on for the message handler * being used. The reportPeriodically flag should be set to false under AJDT so numbers just come out at the end. */ public void setTiming(boolean timersOn, boolean reportPeriodically) { timing = timersOn; timingPeriodically = reportPeriodically; } /** * Set the error and warning threashold which can be taken from CompilerOptions (see bug 129282) * * @param errorThreshold * @param warningThreshold */ public void setErrorAndWarningThreshold(boolean errorThreshold, boolean 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 return errorThreshold||warningThreshold; // 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(); } public boolean areInfoMessagesEnabled() { if (infoMessagesEnabled == 0) { infoMessagesEnabled = (messageHandler.isIgnoring(IMessage.INFO) ? 1 : 2); } return infoMessagesEnabled == 2; } /** * may return null */ public Properties getExtraConfiguration() { return extraConfiguration; } public final static String xsetAVOID_FINAL = "avoidFinal"; // default true 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 xsetTRANSIENT_TJP_FIELDS = "makeTjpFieldsTransient"; // 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 final static String xsetOVERWEAVING = "overWeaving"; public final static String xsetOPTIMIZED_MATCHING = "optimizedMatching"; public final static String xsetTIMERS_PER_JOINPOINT = "timersPerJoinpoint"; public final static String xsetTIMERS_PER_FASTMATCH_CALL = "timersPerFastMatchCall"; public final static String xsetITD_VERSION = "itdVersion"; public final static String xsetITD_VERSION_ORIGINAL = "1"; public final static String xsetITD_VERSION_2NDGEN = "2"; public final static String xsetITD_VERSION_DEFAULT = xsetITD_VERSION_2NDGEN; public final static String xsetMINIMAL_MODEL = "minimalModel"; public final static String xsetTARGETING_RUNTIME_1610 = "targetRuntime1_6_10"; public boolean isInJava5Mode() { return behaveInJava5Way; } public boolean isTimingEnabled() { return timing; } 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). */ public static class TypeMap { // 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 public List<String> addedSinceLastDemote; public List<String> writtenClasses; private static boolean debug = false; public static boolean useExpendableMap = true; // configurable for reliable testing private boolean demotionSystemActive; private boolean debugDemotion = false; public int policy = USE_WEAK_REFS; // Map of types that never get thrown away final Map<String, ResolvedType> tMap = new HashMap<String, ResolvedType>(); // Map of types that may be ejected from the cache if we need space final Map<String, Reference<ResolvedType>> expendableMap = Collections .synchronizedMap(new WeakHashMap<String, Reference<ResolvedType>>()); private final World w; // profiling tools... private boolean memoryProfiling = false; private int maxExpendableMapSize = -1; private int collectedTypes = 0; private final ReferenceQueue<ResolvedType> rq = new ReferenceQueue<ResolvedType>(); // private static Trace trace = TraceFactory.getTraceFactory().getTrace(World.TypeMap.class); TypeMap(World w) { // Demotion activated when switched on and loadtime weaving or in AJDT demotionSystemActive = w.isDemotionActive() && (w.isLoadtimeWeaving() || w.couldIncrementalCompileFollow()); addedSinceLastDemote = new ArrayList<String>(); writtenClasses = new ArrayList<String>(); this.w = w; memoryProfiling = false;// !w.getMessageHandler().isIgnoring(Message. // INFO); } // For testing public Map<String, Reference<ResolvedType>> getExpendableMap() { return expendableMap; } // For testing public Map<String, ResolvedType> getMainMap() { return tMap; } public int demote() { return demote(false); } /** * 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(boolean atEndOfCompile) { if (!demotionSystemActive) { return 0; } if (debugDemotion) { System.out.println("Demotion running " + addedSinceLastDemote); } boolean isLtw = w.isLoadtimeWeaving(); int demotionCounter = 0; if (isLtw) { // Loadtime weaving demotion strategy for (String key : addedSinceLastDemote) { ResolvedType type = tMap.get(key); if (type != null && !type.isAspect() && !type.equals(UnresolvedType.OBJECT) && !type.isPrimitiveType()) { List<ConcreteTypeMunger> typeMungers = type.getInterTypeMungers(); if (typeMungers == null || typeMungers.size() == 0) { tMap.remove(key); insertInExpendableMap(key, type); demotionCounter++; } } } addedSinceLastDemote.clear(); } else { // Compile time demotion strategy List<String> forRemoval = new ArrayList<String>(); for (String key : addedSinceLastDemote) { ResolvedType type = tMap.get(key); if (type == null) { // TODO not 100% sure why it is not there, where did it go? forRemoval.add(key); continue; } if (!writtenClasses.contains(type.getName())) { // COSTLY continue; } if (type != null && !type.isAspect() && !type.equals(UnresolvedType.OBJECT) && !type.isPrimitiveType()) { List<ConcreteTypeMunger> typeMungers = type.getInterTypeMungers(); if (typeMungers == null || typeMungers.size() == 0) { /* * if (type.isNested()) { try { ReferenceType rt = (ReferenceType) w.resolve(type.getOutermostType()); * if (!rt.isMissing()) { ReferenceTypeDelegate delegate = ((ReferenceType) type).getDelegate(); boolean * isWeavable = delegate == null ? false : delegate.isExposedToWeaver(); boolean hasBeenWoven = delegate * == null ? false : delegate.hasBeenWoven(); if (isWeavable && !hasBeenWoven) { // skip demotion of * this inner type for now continue; } } } catch (ClassCastException cce) { cce.printStackTrace(); * System.out.println("outer of " + key + " is not a reftype? " + type.getOutermostType()); // throw new * IllegalStateException(cce); } } */ ReferenceTypeDelegate delegate = ((ReferenceType) type).getDelegate(); boolean isWeavable = delegate == null ? false : delegate.isExposedToWeaver(); boolean hasBeenWoven = delegate == null ? false : delegate.hasBeenWoven(); if (!isWeavable || hasBeenWoven) { if (debugDemotion) { System.out.println("Demoting " + key); } forRemoval.add(key); tMap.remove(key); insertInExpendableMap(key, type); demotionCounter++; } } else { // no need to try this again, it will never be demoted writtenClasses.remove(type.getName()); forRemoval.add(key); } } else { writtenClasses.remove(type.getName()); // no need to try this again, it will never be demoted forRemoval.add(key); } } addedSinceLastDemote.removeAll(forRemoval); } if (debugDemotion) { System.out.println("Demoted " + demotionCounter + " types. Types remaining in fixed set #" + tMap.keySet().size() + ". addedSinceLastDemote size is " + addedSinceLastDemote.size()); System.out.println("writtenClasses.size() = " + writtenClasses.size() + ": " + writtenClasses); } if (atEndOfCompile) { if (debugDemotion) { System.out.println("Clearing writtenClasses"); } writtenClasses.clear(); } return demotionCounter; } private void insertInExpendableMap(String key, ResolvedType type) { if (useExpendableMap) { if (!expendableMap.containsKey(key)) { if (policy == USE_SOFT_REFS) { expendableMap.put(key, new SoftReference<ResolvedType>(type)); } else { expendableMap.put(key, new WeakReference<ResolvedType>(type)); } } } } /** * 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.isCacheable()) { return 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; } // TODO should this be in as a permanent assertion? /* * if ((type instanceof ReferenceType) && type.getWorld().isInJava5Mode() && (((ReferenceType) type).getDelegate() != * null) && type.isGenericType()) { throw new BCException("Attempt to add generic type to typemap " + type.toString() + * " (should be raw)"); } */ if (w.isExpendable(type)) { if (useExpendableMap) { // Dont use reference queue for tracking if not profiling... if (policy == USE_WEAK_REFS) { if (memoryProfiling) { expendableMap.put(key, new WeakReference<ResolvedType>(type, rq)); } else { expendableMap.put(key, new WeakReference<ResolvedType>(type)); } } else if (policy == USE_SOFT_REFS) { if (memoryProfiling) { expendableMap.put(key, new SoftReference<ResolvedType>(type, rq)); } else { expendableMap.put(key, new SoftReference<ResolvedType>(type)); } // } else { // expendableMap.put(key, type); } } if (memoryProfiling && expendableMap.size() > maxExpendableMapSize) { maxExpendableMapSize = expendableMap.size(); } return type; } else { if (demotionSystemActive) { // System.out.println("Added since last demote " + key); addedSinceLastDemote.add(key); } return 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 = tMap.get(key); if (ret == null) { if (policy == USE_WEAK_REFS) { WeakReference<ResolvedType> ref = (WeakReference<ResolvedType>) expendableMap.get(key); if (ref != null) { ret = ref.get(); } } else if (policy == USE_SOFT_REFS) { SoftReference<ResolvedType> ref = (SoftReference<ResolvedType>) expendableMap.get(key); if (ref != null) { ret = ref.get(); } // } else { // return (ResolvedType) expendableMap.get(key); } } return ret; } /** Remove a type from the map */ public ResolvedType remove(String key) { ResolvedType ret = tMap.remove(key); if (ret == null) { if (policy == USE_WEAK_REFS) { WeakReference<ResolvedType> wref = (WeakReference<ResolvedType>) expendableMap.remove(key); if (wref != null) { ret = wref.get(); } } else if (policy == USE_SOFT_REFS) { SoftReference<ResolvedType> wref = (SoftReference<ResolvedType>) expendableMap.remove(key); if (wref != null) { ret = wref.get(); } // } else { // ret = (ResolvedType) expendableMap.remove(key); } } return ret; } public void classWriteEvent(String classname) { // that is a name com.Foo and not a signature Lcom/Foo; boooooooooo! if (demotionSystemActive) { writtenClasses.add(classname); } if (debugDemotion) { System.out.println("Class write event for " + classname); } } public void demote(ResolvedType type) { String key = type.getSignature(); if (debugDemotion) { addedSinceLastDemote.remove(key); } tMap.remove(key); insertInExpendableMap(key, type); } // 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<PrecedenceCacheKey, Integer> cachedResults; public AspectPrecedenceCalculator(World forSomeWorld) { world = forSomeWorld; cachedResults = new HashMap<PrecedenceCacheKey, Integer>(); } /** * 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 (cachedResults.get(key)).intValue(); } else { int order = 0; DeclarePrecedence orderer = null; // Records the declare // precedence statement that // gives the first ordering for (Iterator<Declare> 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 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; } @Override public boolean equals(Object obj) { if (!(obj instanceof PrecedenceCacheKey)) { return false; } PrecedenceCacheKey other = (PrecedenceCacheKey) obj; return (aspect1 == other.aspect1 && aspect2 == other.aspect2); } @Override 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) --- public boolean isDemotionActive() { return true; } // --- 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<Class<?>, TypeVariable[]> workInProgress1 = new HashMap<Class<?>, TypeVariable[]>(); public TypeVariable[] getTypeVariablesCurrentlyBeingProcessed(Class<?> baseClass) { return 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")); } // ITD Versions // 1 is the first version in use up to AspectJ 1.6.8 // 2 is from 1.6.9 onwards s = p.getProperty(xsetITD_VERSION, xsetITD_VERSION_DEFAULT); if (s.equals(xsetITD_VERSION_ORIGINAL)) { itdVersion = 1; } s = p.getProperty(xsetAVOID_FINAL, "false"); if (s.equalsIgnoreCase("true")) { useFinal = false; // if avoidFinal=true, then set useFinal to false } s = p.getProperty(xsetMINIMAL_MODEL, "true"); if (s.equalsIgnoreCase("false")) { minimalModel = false; } s = p.getProperty(xsetTARGETING_RUNTIME_1610, "false"); if (s.equalsIgnoreCase("true")) { targettingRuntime1_6_10 = true; } 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); // default is: ON if (s != null) { boolean b = typeMap.demotionSystemActive; if (b && s.equalsIgnoreCase("false")) { System.out.println("typeDemotion=false: type demotion switched OFF"); typeMap.demotionSystemActive = false; } else if (!b && s.equalsIgnoreCase("true")) { System.out.println("typeDemotion=true: type demotion switched ON"); typeMap.demotionSystemActive = true; } } s = p.getProperty(xsetOVERWEAVING, "false"); if (s.equalsIgnoreCase("true")) { overWeaving = true; } s = p.getProperty(xsetTYPE_DEMOTION_DEBUG, "false"); if (s.equalsIgnoreCase("true")) { typeMap.debugDemotion = true; } s = p.getProperty(xsetTYPE_REFS, "true"); if (s.equalsIgnoreCase("false")) { typeMap.policy = TypeMap.USE_SOFT_REFS; } runMinimalMemorySet = p.getProperty(xsetRUN_MINIMAL_MEMORY) != null; 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(xsetTRANSIENT_TJP_FIELDS,"false"); transientTjpFields = s.equalsIgnoreCase("true"); s = p.getProperty(xsetDEBUG_BRIDGING, "false"); forDEBUG_bridgingCode = s.equalsIgnoreCase("true"); s = p.getProperty(xsetOPTIMIZED_MATCHING, "true"); optimizedMatching = s.equalsIgnoreCase("true"); if (!optimizedMatching) { getMessageHandler().handleMessage(MessageUtil.info("[optimizedMatching=false] optimized matching turned off")); } s = p.getProperty(xsetTIMERS_PER_JOINPOINT, "25000"); try { timersPerJoinpoint = Integer.parseInt(s); } catch (Exception e) { getMessageHandler().handleMessage(MessageUtil.error("unable to process timersPerJoinpoint value of " + s)); timersPerJoinpoint = 25000; } s = p.getProperty(xsetTIMERS_PER_FASTMATCH_CALL, "250"); try { timersPerType = Integer.parseInt(s); } catch (Exception e) { getMessageHandler().handleMessage(MessageUtil.error("unable to process timersPerType value of " + s)); timersPerType = 250; } } try { if (systemPropertyOverWeaving) { overWeaving = true; } String value = null; value = System.getProperty("aspectj.typeDemotion", "false"); if (value.equalsIgnoreCase("true")) { System.out.println("ASPECTJ: aspectj.typeDemotion=true: type demotion switched ON"); typeMap.demotionSystemActive = true; } value = System.getProperty("aspectj.minimalModel", "false"); if (value.equalsIgnoreCase("true")) { System.out.println("ASPECTJ: aspectj.minimalModel=true: minimal model switched ON"); minimalModel = true; } } catch (Throwable t) { System.err.println("ASPECTJ: Unable to read system properties"); t.printStackTrace(); } checkedAdvancedConfiguration = true; } } public boolean isRunMinimalMemory() { ensureAdvancedConfigurationProcessed(); return runMinimalMemory; } public boolean isTransientTjpFields() { ensureAdvancedConfigurationProcessed(); return transientTjpFields; } public boolean isRunMinimalMemorySet() { ensureAdvancedConfigurationProcessed(); return runMinimalMemorySet; } 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<PointcutDesignatorHandler>(); } pointcutDesignators.add(designatorHandler); } public Set<PointcutDesignatorHandler> getRegisteredPointcutHandlers() { if (pointcutDesignators == null) { return Collections.emptySet(); } return pointcutDesignators; } public void reportMatch(ShadowMunger munger, Shadow shadow) { } public boolean isOverWeaving() { return overWeaving; } 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; } /** * Determine if the named aspect requires a particular type around in order to be useful. The type is named in the aop.xml file * against the aspect. * * @return true if there is a type missing that this aspect really needed around */ public boolean hasUnsatisfiedDependency(ResolvedType aspectType) { return false; } public TypePattern getAspectScope(ResolvedType declaringType) { return null; } public Map<String, ResolvedType> getFixed() { return typeMap.tMap; } public Map<String, Reference<ResolvedType>> 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() && !type.isPrimitiveArray(); } // map from aspect > excluded types // memory issue here? private Map<ResolvedType, Set<ResolvedType>> exclusionMap = new HashMap<ResolvedType, Set<ResolvedType>>(); public Map<ResolvedType, Set<ResolvedType>> getExclusionMap() { return exclusionMap; } private TimeCollector timeCollector = null; /** * Record the time spent matching a pointcut - this will accumulate over the lifetime of this world/weaver and be reported every * 25000 join points. */ public void record(Pointcut pointcut, long timetaken) { if (timeCollector == null) { ensureAdvancedConfigurationProcessed(); timeCollector = new TimeCollector(this); } timeCollector.record(pointcut, timetaken); } /** * Record the time spent fastmatching a pointcut - this will accumulate over the lifetime of this world/weaver and be reported * every 250 types. */ public void recordFastMatch(Pointcut pointcut, long timetaken) { if (timeCollector == null) { ensureAdvancedConfigurationProcessed(); timeCollector = new TimeCollector(this); } timeCollector.recordFastMatch(pointcut, timetaken); } public void reportTimers() { if (timeCollector != null && !timingPeriodically) { timeCollector.report(); timeCollector = new TimeCollector(this); } } private static class TimeCollector { private World world; long joinpointCount; long typeCount; long perJoinpointCount; long perTypes; Map<String, Long> joinpointsPerPointcut = new HashMap<String, Long>(); Map<String, Long> timePerPointcut = new HashMap<String, Long>(); Map<String, Long> fastMatchTimesPerPointcut = new HashMap<String, Long>(); Map<String, Long> fastMatchTypesPerPointcut = new HashMap<String, Long>(); TimeCollector(World world) { this.perJoinpointCount = world.timersPerJoinpoint; this.perTypes = world.timersPerType; this.world = world; this.joinpointCount = 0; this.typeCount = 0; this.joinpointsPerPointcut = new HashMap<String, Long>(); this.timePerPointcut = new HashMap<String, Long>(); } public void report() { long totalTime = 0L; for (String p : joinpointsPerPointcut.keySet()) { totalTime += timePerPointcut.get(p); } world.getMessageHandler().handleMessage( MessageUtil.info("Pointcut matching cost (total=" + (totalTime / 1000000) + "ms for " + joinpointCount + " joinpoint match calls):")); for (String p : joinpointsPerPointcut.keySet()) { StringBuffer sb = new StringBuffer(); sb.append("Time:" + (timePerPointcut.get(p) / 1000000) + "ms (jps:#" + joinpointsPerPointcut.get(p) + ") matching against " + p); world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString())); } world.getMessageHandler().handleMessage(MessageUtil.info("---")); totalTime = 0L; for (String p : fastMatchTimesPerPointcut.keySet()) { totalTime += fastMatchTimesPerPointcut.get(p); } world.getMessageHandler().handleMessage( MessageUtil.info("Pointcut fast matching cost (total=" + (totalTime / 1000000) + "ms for " + typeCount + " fast match calls):")); for (String p : fastMatchTimesPerPointcut.keySet()) { StringBuffer sb = new StringBuffer(); sb.append("Time:" + (fastMatchTimesPerPointcut.get(p) / 1000000) + "ms (types:#" + fastMatchTypesPerPointcut.get(p) + ") fast matching against " + p); world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString())); } world.getMessageHandler().handleMessage(MessageUtil.info("---")); } void record(Pointcut pointcut, long timetakenInNs) { joinpointCount++; String pointcutText = pointcut.toString(); Long jpcounter = joinpointsPerPointcut.get(pointcutText); if (jpcounter == null) { jpcounter = 1L; } else { jpcounter++; } joinpointsPerPointcut.put(pointcutText, jpcounter); Long time = timePerPointcut.get(pointcutText); if (time == null) { time = timetakenInNs; } else { time += timetakenInNs; } timePerPointcut.put(pointcutText, time); if (world.timingPeriodically) { if ((joinpointCount % perJoinpointCount) == 0) { long totalTime = 0L; for (String p : joinpointsPerPointcut.keySet()) { totalTime += timePerPointcut.get(p); } world.getMessageHandler().handleMessage( MessageUtil.info("Pointcut matching cost (total=" + (totalTime / 1000000) + "ms for " + joinpointCount + " joinpoint match calls):")); for (String p : joinpointsPerPointcut.keySet()) { StringBuffer sb = new StringBuffer(); sb.append("Time:" + (timePerPointcut.get(p) / 1000000) + "ms (jps:#" + joinpointsPerPointcut.get(p) + ") matching against " + p); world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString())); } world.getMessageHandler().handleMessage(MessageUtil.info("---")); } } } void recordFastMatch(Pointcut pointcut, long timetakenInNs) { typeCount++; String pointcutText = pointcut.toString(); Long typecounter = fastMatchTypesPerPointcut.get(pointcutText); if (typecounter == null) { typecounter = 1L; } else { typecounter++; } fastMatchTypesPerPointcut.put(pointcutText, typecounter); Long time = fastMatchTimesPerPointcut.get(pointcutText); if (time == null) { time = timetakenInNs; } else { time += timetakenInNs; } fastMatchTimesPerPointcut.put(pointcutText, time); if (world.timingPeriodically) { if ((typeCount % perTypes) == 0) { long totalTime = 0L; for (String p : fastMatchTimesPerPointcut.keySet()) { totalTime += fastMatchTimesPerPointcut.get(p); } world.getMessageHandler().handleMessage( MessageUtil.info("Pointcut fast matching cost (total=" + (totalTime / 1000000) + "ms for " + typeCount + " fast match calls):")); for (String p : fastMatchTimesPerPointcut.keySet()) { StringBuffer sb = new StringBuffer(); sb.append("Time:" + (fastMatchTimesPerPointcut.get(p) / 1000000) + "ms (types:#" + fastMatchTypesPerPointcut.get(p) + ") fast matching against " + p); world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString())); } world.getMessageHandler().handleMessage(MessageUtil.info("---")); } } } } public TypeMap getTypeMap() { return typeMap; } public static void reset() { // ResolvedType.resetPrimitives(); } /** * Returns the version of ITD that this world wants to create. The default is the new style (2) but in some cases where there * might be a clash, the old style can be used. It is set through the option -Xset:itdVersion=1 * * @return the ITD version this world wants to create - 1=oldstyle 2=new, transparent style */ public int getItdVersion() { return itdVersion; } // if not loadtime weaving then we are compile time weaving or post-compile time weaving public abstract boolean isLoadtimeWeaving(); public void classWriteEvent(char[][] compoundName) { // override if interested in write events } }
374,964
Bug 374964 Performance - improve pointcut expensiveness calculation
Build Identifier: 1.6.12 I'm able to reduce the AspectJ LTW startup overhead on the app I'm working on, from 95 seconds down to 47 seconds, just by switching the "expensiveness" of THIS_OR_TARGET and CALL in PointcutEvaluationExpenseComparator. It seems to make sense to me that THIS_OR_TARGET is more expensive since it requires type matching (under profiler ExactTypePattern.matchesInstanceof() is what shows up as very expensive), whereas CALL can evaluate very quickly in most cases since it just fails to match on method name. I'm not sure if this is specific to my particular usage, but cutting 50% of the LTW startup is a very nice improvement. If you think this change doesn't make sense for everyone, I can work on a patch that makes this configurable somehow. Thanks. Reproducible: Always
resolved fixed
f85631f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-03-24T01:17:09Z"
"2012-03-21T17:13:20Z"
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 int p1code = p1.hashCode(); int p2code = p2.hashCode(); if (p1code == p2code) { return 0; } else if (p1code < p2code) { return -1; } else { 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 || p instanceof ConcreteCflowPointcut) { 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) { int leftScore = getScore(((AndPointcut) p).getLeft()); int rightScore = getScore(((AndPointcut) p).getRight()); if (leftScore < rightScore) { return leftScore; } else { return rightScore; } } if (p instanceof OrPointcut) { int leftScore = getScore(((OrPointcut) p).getLeft()); int rightScore = getScore(((OrPointcut) p).getRight()); if (leftScore > rightScore) { return leftScore; } else { return rightScore; } } return OTHER; } }
374,964
Bug 374964 Performance - improve pointcut expensiveness calculation
Build Identifier: 1.6.12 I'm able to reduce the AspectJ LTW startup overhead on the app I'm working on, from 95 seconds down to 47 seconds, just by switching the "expensiveness" of THIS_OR_TARGET and CALL in PointcutEvaluationExpenseComparator. It seems to make sense to me that THIS_OR_TARGET is more expensive since it requires type matching (under profiler ExactTypePattern.matchesInstanceof() is what shows up as very expensive), whereas CALL can evaluate very quickly in most cases since it just fails to match on method name. I'm not sure if this is specific to my particular usage, but cutting 50% of the LTW startup is a very nice improvement. If you think this change doesn't make sense for everyone, I can work on a patch that makes this configurable somehow. Thanks. Reproducible: Always
resolved fixed
f85631f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-03-24T01:17:09Z"
"2012-03-21T17:13:20Z"
tests/src/org/aspectj/systemtest/ajc170/Ajc170Tests.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.ajc170; import java.io.File; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.weaver.TypeFactory; import org.aspectj.weaver.UnresolvedType; /** * @author Andy Clement */ public class Ajc170Tests extends org.aspectj.testing.XMLBasedAjcTestCase { /* public void testPublicITDFs_pr73507_1() { runTest("public ITDfs - 1"); } public void testPublicITDFs_pr73507_2() { runTest("public ITDfs - 2"); } public void testPublicITDFs_pr73507_3() { runTest("public ITDfs - 3"); } public void testPublicITDFs_pr73507_4() { runTest("public ITDfs - 4"); } */ public void testBCExceptionAnnoDecp_371998() { runTest("BCException anno decp"); } public void testTransientTjpFields()throws Exception { runTest("transient tjp fields"); JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "Code"); Field[] fs = jc.getFields(); //private static final org.aspectj.lang.JoinPoint$StaticPart ajc$tjp_0 [Synthetic] //private static final org.aspectj.lang.JoinPoint$StaticPart ajc$tjp_1 [Synthetic] for (Field f: fs) { if (!f.isTransient()) { fail("Field should be transient: "+f); } } } public void testGenericsWithTwoTypeParamsOneWildcard() { UnresolvedType ut; ut = TypeFactory.createTypeFromSignature("LFoo<**>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<***>;"); assertEquals(3,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<TP;*+Ljava/lang/String;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<*+Ljava/lang/String;TP;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<*+Ljava/lang/String;TP;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<*TT;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<[I>;"); assertEquals(1,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<[I[Z>;"); assertEquals(2,ut.getTypeParameters().length); } public void testPerThis() { runTest("perthis"); } public void testPerTarget() { runTest("pertarget"); } public void testPerCflow() { runTest("percflow"); } public void testPerTypeWithin() { runTest("pertypewithin"); } // not specifying -1.7 public void testDiamond1() { runTest("diamond 1"); } public void testDiamond2() { runTest("diamond 2"); } public void testDiamondItd1() { runTest("diamond itd 1"); } public void testLiterals1() { runTest("literals 1"); } public void testLiterals2() { runTest("literals 2"); } public void testLiteralsItd1() { runTest("literals itd 1"); } public void testStringSwitch1() { runTest("string switch 1"); } public void testStringSwitch2() { runTest("string switch 2"); } public void testMultiCatch1() { runTest("multi catch 1"); } public void testMultiCatch2() { runTest("multi catch 2"); } public void testMultiCatchWithHandler1() { runTest("multi catch with handler 1"); } public void testMultiCatchAspect1() { runTest("multi catch aspect 1"); } // public void testMultiCatchWithHandler2() { // runTest("multi catch with handler 2"); // } public void testSanity1() { runTest("sanity 1"); } public void testMissingImpl_363979() { runTest("missing impl"); } public void testMissingImpl_363979_2() { runTest("missing impl 2"); } public void testStackOverflow_364380() { runTest("stackoverflow"); } // public void testTryResources1() { // runTest("try resources 1"); // } // // public void testTryResources2() { // runTest("try resources 2"); // } // --- public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc170Tests.class); } @Override protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc170/ajc170.xml"); } }
376,139
Bug 376139 AspectJ throws Nullpointer after its IDE plugin update
Build Identifier: Version: Indigo Service Release 2 Build id: 20120216-1857 java.lang.NullPointerException at org.aspectj.org.eclipse.jdt.internal.compiler.ast.SwitchStatement.analyseCode(SwitchStatement.java:118) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.analyseCode(MethodDeclaration.java:104) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.internalAnalyseCode(TypeDeclaration.java:730) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.analyseC ... oBuildJob.run(AutoBuildJob.java:241) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54) Compile error: NullPointerException thrown: null Reproducible: Always Steps to Reproduce: 1. After updating the eclipse plugin
resolved fixed
62fca9a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-04-05T22:17:56Z"
"2012-04-05T04:26:40Z"
tests/bugs170/pr376139/Code.java
376,139
Bug 376139 AspectJ throws Nullpointer after its IDE plugin update
Build Identifier: Version: Indigo Service Release 2 Build id: 20120216-1857 java.lang.NullPointerException at org.aspectj.org.eclipse.jdt.internal.compiler.ast.SwitchStatement.analyseCode(SwitchStatement.java:118) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.analyseCode(MethodDeclaration.java:104) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.internalAnalyseCode(TypeDeclaration.java:730) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.analyseC ... oBuildJob.run(AutoBuildJob.java:241) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54) Compile error: NullPointerException thrown: null Reproducible: Always Steps to Reproduce: 1. After updating the eclipse plugin
resolved fixed
62fca9a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-04-05T22:17:56Z"
"2012-04-05T04:26:40Z"
tests/src/org/aspectj/systemtest/ajc170/Ajc170Tests.java
/******************************************************************************* * Copyright (c) 2008-2012 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.ajc170; import java.io.File; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.weaver.TypeFactory; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.internal.tools.StandardPointcutExpressionImpl; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.PointcutRewriter; import org.aspectj.weaver.reflect.ReflectionWorld; import org.aspectj.weaver.tools.StandardPointcutParser; /** * @author Andy Clement */ public class Ajc170Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testDecAtFieldOrderingLTW1() { runTest("dec at field ordering ltw 1"); } public void testDecAtFieldOrdering1() { runTest("dec at field ordering 1"); } // public void testDecAtFieldOrdering2() { // runTest("dec at field ordering 2"); // } public void testXmlDefsDeclareAnnoMethod() { runTest("xml defined dec at method"); } // anno not runtime vis public void testXmlDefsDeclareAnnoMethod2() { runTest("xml defined dec at method 2"); } public void testXmlDefsDeclareAnnoField() { runTest("xml defined dec at field"); } public void testXmlDefsDeclareAnnoFieldVariants1() { runTest("xml defined dec anno - variants 1"); } public void testXmlDefsDeclareAnnoFieldVariants2() { runTest("xml defined dec anno - variants 2"); } public void testXmlDefsDeclareAnnoFieldMultipleValues() { runTest("xml defined dec anno - multiple values"); } public void testXmlDefsDeclareAnnoFieldMultipleValuesAndSpaces() { runTest("xml defined dec anno - multiple values and spaces"); } public void testPointcutExpense_374964() { // check a declaring type being specified causes the call() to be considered cheaper than this() World world = new ReflectionWorld(true, getClass().getClassLoader()); StandardPointcutParser pointcutParser = StandardPointcutParser.getPointcutParserSupportingAllPrimitives(world); StandardPointcutExpressionImpl pointcutExpression = (StandardPointcutExpressionImpl)pointcutParser.parsePointcutExpression("call(* *(..)) && this(Object)"); Pointcut pc = pointcutExpression.getUnderlyingPointcut(); Pointcut newp = new PointcutRewriter().rewrite(pc); // no declaring type so this() is considered cheaper assertEquals("(this(java.lang.Object) && call(* *(..)))",newp.toString()); pointcutExpression = (StandardPointcutExpressionImpl)pointcutParser.parsePointcutExpression("call(* String.*(..)) && this(Object)"); pc = pointcutExpression.getUnderlyingPointcut(); newp = new PointcutRewriter().rewrite(pc); // declaring type, so call() is cheaper assertEquals("(call(* java.lang.String.*(..)) && this(java.lang.Object))",newp.toString()); pointcutExpression = (StandardPointcutExpressionImpl)pointcutParser.parsePointcutExpression("this(Object) && call(* *(..)) && call(* String.*(..))"); pc = pointcutExpression.getUnderlyingPointcut(); newp = new PointcutRewriter().rewrite(pc); // more complex example, mix of them assertEquals("((call(* java.lang.String.*(..)) && this(java.lang.Object)) && call(* *(..)))",newp.toString()); } /* public void testPublicITDFs_pr73507_1() { runTest("public ITDfs - 1"); } public void testPublicITDFs_pr73507_2() { runTest("public ITDfs - 2"); } public void testPublicITDFs_pr73507_3() { runTest("public ITDfs - 3"); } public void testPublicITDFs_pr73507_4() { runTest("public ITDfs - 4"); } */ public void testBCExceptionAnnoDecp_371998() { runTest("BCException anno decp"); } public void testTransientTjpFields()throws Exception { runTest("transient tjp fields"); JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "Code"); Field[] fs = jc.getFields(); //private static final org.aspectj.lang.JoinPoint$StaticPart ajc$tjp_0 [Synthetic] //private static final org.aspectj.lang.JoinPoint$StaticPart ajc$tjp_1 [Synthetic] for (Field f: fs) { if (!f.isTransient()) { fail("Field should be transient: "+f); } } } public void testGenericsWithTwoTypeParamsOneWildcard() { UnresolvedType ut; ut = TypeFactory.createTypeFromSignature("LFoo<**>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<***>;"); assertEquals(3,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<TP;*+Ljava/lang/String;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<*+Ljava/lang/String;TP;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<*+Ljava/lang/String;TP;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<*TT;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<[I>;"); assertEquals(1,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<[I[Z>;"); assertEquals(2,ut.getTypeParameters().length); } public void testPerThis() { runTest("perthis"); } public void testPerTarget() { runTest("pertarget"); } public void testPerCflow() { runTest("percflow"); } public void testPerTypeWithin() { runTest("pertypewithin"); } // not specifying -1.7 public void testDiamond1() { runTest("diamond 1"); } public void testDiamond2() { runTest("diamond 2"); } public void testDiamondItd1() { runTest("diamond itd 1"); } public void testLiterals1() { runTest("literals 1"); } public void testLiterals2() { runTest("literals 2"); } public void testLiteralsItd1() { runTest("literals itd 1"); } public void testStringSwitch1() { runTest("string switch 1"); } public void testStringSwitch2() { runTest("string switch 2"); } public void testMultiCatch1() { runTest("multi catch 1"); } public void testMultiCatch2() { runTest("multi catch 2"); } public void testMultiCatchWithHandler1() { runTest("multi catch with handler 1"); } public void testMultiCatchAspect1() { runTest("multi catch aspect 1"); } // public void testMultiCatchWithHandler2() { // runTest("multi catch with handler 2"); // } public void testSanity1() { runTest("sanity 1"); } public void testMissingImpl_363979() { runTest("missing impl"); } public void testMissingImpl_363979_2() { runTest("missing impl 2"); } public void testStackOverflow_364380() { runTest("stackoverflow"); } // public void testTryResources1() { // runTest("try resources 1"); // } // // public void testTryResources2() { // runTest("try resources 2"); // } // --- public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc170Tests.class); } @Override protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc170/ajc170.xml"); } }
376,351
Bug 376351 attribute problems with Java 7 compilation
From the mailing list, this goes wrong: ***R.java*** public class R{ public static void main(String[] args) {System.out.println(new R().getClass().getName());} } ***R1.java*** public class R1 extends R {} ***RAj.aj*** public aspect RAj { private ThreadLocal<Object> inAspect = new ThreadLocal<Object>(); pointcut createR() : execution(R.new()); Object around() : createR() { System.out.println("aspect:" + inAspect.get() + ":" + this); if (inAspect.get() != null) { return proceed(); } else { inAspect.set(this); return new R1(); } } } compile command: /cygdrive/c/Program\ Files/Java/aspectj-1.6.12/bin/ajc.bat -source 1.7 -outxml -outjar araj.jar -classpath "aspectjrt.jar;." RAj.aj run: /cygdrive/c/Program\ Files/Java/aspectj-1.6.12/bin/aj5.bat -classpath ".;./araj.jar" R errors: Apr 06, 2012 1:37:40 PM org.aspectj.weaver.tools.Jdk14Trace error SEVERE: register definition failed java.lang.RuntimeException: Problem processing attributes in RAj at org.aspectj.weaver.bcel.BcelObjectType.ensureAspectJAttributesUnpacked(BcelObjectType.java:385)
resolved fixed
be063b8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-04-09T21:15:55Z"
"2012-04-09T19:33:20Z"
tests/bugs170/pr376351/R.java
376,351
Bug 376351 attribute problems with Java 7 compilation
From the mailing list, this goes wrong: ***R.java*** public class R{ public static void main(String[] args) {System.out.println(new R().getClass().getName());} } ***R1.java*** public class R1 extends R {} ***RAj.aj*** public aspect RAj { private ThreadLocal<Object> inAspect = new ThreadLocal<Object>(); pointcut createR() : execution(R.new()); Object around() : createR() { System.out.println("aspect:" + inAspect.get() + ":" + this); if (inAspect.get() != null) { return proceed(); } else { inAspect.set(this); return new R1(); } } } compile command: /cygdrive/c/Program\ Files/Java/aspectj-1.6.12/bin/ajc.bat -source 1.7 -outxml -outjar araj.jar -classpath "aspectjrt.jar;." RAj.aj run: /cygdrive/c/Program\ Files/Java/aspectj-1.6.12/bin/aj5.bat -classpath ".;./araj.jar" R errors: Apr 06, 2012 1:37:40 PM org.aspectj.weaver.tools.Jdk14Trace error SEVERE: register definition failed java.lang.RuntimeException: Problem processing attributes in RAj at org.aspectj.weaver.bcel.BcelObjectType.ensureAspectJAttributesUnpacked(BcelObjectType.java:385)
resolved fixed
be063b8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-04-09T21:15:55Z"
"2012-04-09T19:33:20Z"
tests/bugs170/pr376351/R1.java
376,351
Bug 376351 attribute problems with Java 7 compilation
From the mailing list, this goes wrong: ***R.java*** public class R{ public static void main(String[] args) {System.out.println(new R().getClass().getName());} } ***R1.java*** public class R1 extends R {} ***RAj.aj*** public aspect RAj { private ThreadLocal<Object> inAspect = new ThreadLocal<Object>(); pointcut createR() : execution(R.new()); Object around() : createR() { System.out.println("aspect:" + inAspect.get() + ":" + this); if (inAspect.get() != null) { return proceed(); } else { inAspect.set(this); return new R1(); } } } compile command: /cygdrive/c/Program\ Files/Java/aspectj-1.6.12/bin/ajc.bat -source 1.7 -outxml -outjar araj.jar -classpath "aspectjrt.jar;." RAj.aj run: /cygdrive/c/Program\ Files/Java/aspectj-1.6.12/bin/aj5.bat -classpath ".;./araj.jar" R errors: Apr 06, 2012 1:37:40 PM org.aspectj.weaver.tools.Jdk14Trace error SEVERE: register definition failed java.lang.RuntimeException: Problem processing attributes in RAj at org.aspectj.weaver.bcel.BcelObjectType.ensureAspectJAttributesUnpacked(BcelObjectType.java:385)
resolved fixed
be063b8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-04-09T21:15:55Z"
"2012-04-09T19:33:20Z"
tests/bugs170/pr376351/RAj.java
376,351
Bug 376351 attribute problems with Java 7 compilation
From the mailing list, this goes wrong: ***R.java*** public class R{ public static void main(String[] args) {System.out.println(new R().getClass().getName());} } ***R1.java*** public class R1 extends R {} ***RAj.aj*** public aspect RAj { private ThreadLocal<Object> inAspect = new ThreadLocal<Object>(); pointcut createR() : execution(R.new()); Object around() : createR() { System.out.println("aspect:" + inAspect.get() + ":" + this); if (inAspect.get() != null) { return proceed(); } else { inAspect.set(this); return new R1(); } } } compile command: /cygdrive/c/Program\ Files/Java/aspectj-1.6.12/bin/ajc.bat -source 1.7 -outxml -outjar araj.jar -classpath "aspectjrt.jar;." RAj.aj run: /cygdrive/c/Program\ Files/Java/aspectj-1.6.12/bin/aj5.bat -classpath ".;./araj.jar" R errors: Apr 06, 2012 1:37:40 PM org.aspectj.weaver.tools.Jdk14Trace error SEVERE: register definition failed java.lang.RuntimeException: Problem processing attributes in RAj at org.aspectj.weaver.bcel.BcelObjectType.ensureAspectJAttributesUnpacked(BcelObjectType.java:385)
resolved fixed
be063b8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-04-09T21:15:55Z"
"2012-04-09T19:33:20Z"
tests/src/org/aspectj/systemtest/ajc170/Ajc170Tests.java
/******************************************************************************* * Copyright (c) 2008-2012 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.ajc170; import java.io.File; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.weaver.TypeFactory; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.internal.tools.StandardPointcutExpressionImpl; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.PointcutRewriter; import org.aspectj.weaver.reflect.ReflectionWorld; import org.aspectj.weaver.tools.StandardPointcutParser; /** * @author Andy Clement */ public class Ajc170Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testSwitchOnEnum() { runTest("switch on enum"); } public void testDecAtFieldOrderingLTW1() { runTest("dec at field ordering ltw 1"); } public void testDecAtFieldOrdering1() { runTest("dec at field ordering 1"); } // public void testDecAtFieldOrdering2() { // runTest("dec at field ordering 2"); // } public void testXmlDefsDeclareAnnoMethod() { runTest("xml defined dec at method"); } // anno not runtime vis public void testXmlDefsDeclareAnnoMethod2() { runTest("xml defined dec at method 2"); } public void testXmlDefsDeclareAnnoField() { runTest("xml defined dec at field"); } public void testXmlDefsDeclareAnnoFieldVariants1() { runTest("xml defined dec anno - variants 1"); } public void testXmlDefsDeclareAnnoFieldVariants2() { runTest("xml defined dec anno - variants 2"); } public void testXmlDefsDeclareAnnoFieldMultipleValues() { runTest("xml defined dec anno - multiple values"); } public void testXmlDefsDeclareAnnoFieldMultipleValuesAndSpaces() { runTest("xml defined dec anno - multiple values and spaces"); } public void testPointcutExpense_374964() { // check a declaring type being specified causes the call() to be considered cheaper than this() World world = new ReflectionWorld(true, getClass().getClassLoader()); StandardPointcutParser pointcutParser = StandardPointcutParser.getPointcutParserSupportingAllPrimitives(world); StandardPointcutExpressionImpl pointcutExpression = (StandardPointcutExpressionImpl)pointcutParser.parsePointcutExpression("call(* *(..)) && this(Object)"); Pointcut pc = pointcutExpression.getUnderlyingPointcut(); Pointcut newp = new PointcutRewriter().rewrite(pc); // no declaring type so this() is considered cheaper assertEquals("(this(java.lang.Object) && call(* *(..)))",newp.toString()); pointcutExpression = (StandardPointcutExpressionImpl)pointcutParser.parsePointcutExpression("call(* String.*(..)) && this(Object)"); pc = pointcutExpression.getUnderlyingPointcut(); newp = new PointcutRewriter().rewrite(pc); // declaring type, so call() is cheaper assertEquals("(call(* java.lang.String.*(..)) && this(java.lang.Object))",newp.toString()); pointcutExpression = (StandardPointcutExpressionImpl)pointcutParser.parsePointcutExpression("this(Object) && call(* *(..)) && call(* String.*(..))"); pc = pointcutExpression.getUnderlyingPointcut(); newp = new PointcutRewriter().rewrite(pc); // more complex example, mix of them assertEquals("((call(* java.lang.String.*(..)) && this(java.lang.Object)) && call(* *(..)))",newp.toString()); } /* public void testPublicITDFs_pr73507_1() { runTest("public ITDfs - 1"); } public void testPublicITDFs_pr73507_2() { runTest("public ITDfs - 2"); } public void testPublicITDFs_pr73507_3() { runTest("public ITDfs - 3"); } public void testPublicITDFs_pr73507_4() { runTest("public ITDfs - 4"); } */ public void testBCExceptionAnnoDecp_371998() { runTest("BCException anno decp"); } public void testTransientTjpFields()throws Exception { runTest("transient tjp fields"); JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "Code"); Field[] fs = jc.getFields(); //private static final org.aspectj.lang.JoinPoint$StaticPart ajc$tjp_0 [Synthetic] //private static final org.aspectj.lang.JoinPoint$StaticPart ajc$tjp_1 [Synthetic] for (Field f: fs) { if (!f.isTransient()) { fail("Field should be transient: "+f); } } } public void testGenericsWithTwoTypeParamsOneWildcard() { UnresolvedType ut; ut = TypeFactory.createTypeFromSignature("LFoo<**>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<***>;"); assertEquals(3,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<TP;*+Ljava/lang/String;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<*+Ljava/lang/String;TP;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<*+Ljava/lang/String;TP;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<*TT;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<[I>;"); assertEquals(1,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<[I[Z>;"); assertEquals(2,ut.getTypeParameters().length); } public void testPerThis() { runTest("perthis"); } public void testPerTarget() { runTest("pertarget"); } public void testPerCflow() { runTest("percflow"); } public void testPerTypeWithin() { runTest("pertypewithin"); } // not specifying -1.7 public void testDiamond1() { runTest("diamond 1"); } public void testDiamond2() { runTest("diamond 2"); } public void testDiamondItd1() { runTest("diamond itd 1"); } public void testLiterals1() { runTest("literals 1"); } public void testLiterals2() { runTest("literals 2"); } public void testLiteralsItd1() { runTest("literals itd 1"); } public void testStringSwitch1() { runTest("string switch 1"); } public void testStringSwitch2() { runTest("string switch 2"); } public void testMultiCatch1() { runTest("multi catch 1"); } public void testMultiCatch2() { runTest("multi catch 2"); } public void testMultiCatchWithHandler1() { runTest("multi catch with handler 1"); } public void testMultiCatchAspect1() { runTest("multi catch aspect 1"); } // public void testMultiCatchWithHandler2() { // runTest("multi catch with handler 2"); // } public void testSanity1() { runTest("sanity 1"); } public void testMissingImpl_363979() { runTest("missing impl"); } public void testMissingImpl_363979_2() { runTest("missing impl 2"); } public void testStackOverflow_364380() { runTest("stackoverflow"); } // public void testTryResources1() { // runTest("try resources 1"); // } // // public void testTryResources2() { // runTest("try resources 2"); // } // --- public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc170Tests.class); } @Override protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc170/ajc170.xml"); } }
376,351
Bug 376351 attribute problems with Java 7 compilation
From the mailing list, this goes wrong: ***R.java*** public class R{ public static void main(String[] args) {System.out.println(new R().getClass().getName());} } ***R1.java*** public class R1 extends R {} ***RAj.aj*** public aspect RAj { private ThreadLocal<Object> inAspect = new ThreadLocal<Object>(); pointcut createR() : execution(R.new()); Object around() : createR() { System.out.println("aspect:" + inAspect.get() + ":" + this); if (inAspect.get() != null) { return proceed(); } else { inAspect.set(this); return new R1(); } } } compile command: /cygdrive/c/Program\ Files/Java/aspectj-1.6.12/bin/ajc.bat -source 1.7 -outxml -outjar araj.jar -classpath "aspectjrt.jar;." RAj.aj run: /cygdrive/c/Program\ Files/Java/aspectj-1.6.12/bin/aj5.bat -classpath ".;./araj.jar" R errors: Apr 06, 2012 1:37:40 PM org.aspectj.weaver.tools.Jdk14Trace error SEVERE: register definition failed java.lang.RuntimeException: Problem processing attributes in RAj at org.aspectj.weaver.bcel.BcelObjectType.ensureAspectJAttributesUnpacked(BcelObjectType.java:385)
resolved fixed
be063b8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-04-09T21:15:55Z"
"2012-04-09T19:33:20Z"
weaver/src/org/aspectj/weaver/bcel/asm/StackMapAdder.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 * ******************************************************************/ package org.aspectj.weaver.bcel.asm; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import aj.org.objectweb.asm.ClassReader; import aj.org.objectweb.asm.ClassWriter; /** * Uses asm to add the stack map attribute to methods in a class. The class is passed in as pure byte data and then a reader/writer * process it. The writer is wired into the world so that types can be resolved and getCommonSuperClass() can be implemented without * class loading using the context class loader. * * @author Andy Clement */ public class StackMapAdder { public static byte[] addStackMaps(World world, byte[] data) { try { ClassReader cr = new ClassReader(data); ClassWriter cw = new AspectJConnectClassWriter(world); cr.accept(cw, 0); return cw.toByteArray(); } catch (Throwable t) { System.err.println("AspectJ Internal Error: unable to add stackmap attributes. " + t.getMessage()); AsmDetector.isAsmAround = false; return data; } } private static class AspectJConnectClassWriter extends ClassWriter { private final World world; public AspectJConnectClassWriter(World w) { super(ClassWriter.COMPUTE_FRAMES); this.world = w; } // Implementation of getCommonSuperClass() that avoids Class.forName() protected String getCommonSuperClass(final String type1, final String type2) { ResolvedType resolvedType1 = world.resolve(UnresolvedType.forName(type1.replace('/', '.'))); ResolvedType resolvedType2 = world.resolve(UnresolvedType.forName(type2.replace('/', '.'))); if (resolvedType1.isAssignableFrom(resolvedType2)) { return type1; } if (resolvedType2.isAssignableFrom(resolvedType1)) { return type2; } if (resolvedType1.isInterface() || resolvedType2.isInterface()) { return "java/lang/Object"; } else { do { resolvedType1 = resolvedType1.getSuperclass(); } while (!resolvedType1.isAssignableFrom(resolvedType2)); return resolvedType1.getName().replace('.', '/'); } } } }
376,990
Bug 376990 iajc does not support source compliance level 1.7
Build Identifier: Version: 3.7.2 Build id: M20120208-0800 I am using AspectJ 1.7.0.M1. I changed the examples build.xml to use a source compliance level of 1.7 and verbose=true as follows: <iajc destdir="${classes.dir}" verbose="true" source="1.7" argfiles="${list}" When I run this using 'ant bean' I get the following line: [iajc] ignored: -source 1.7 at E:\aspectj1.7\doc\examples\build.xml:136: I have tried running the compiler 'ajc' directly specifying -source 1.7 and that works. I am trying to use this on a large development project that uses AspectJ and has been migrated over to Java 7. The project uses ant to do builds so it is critical that iajc support 1.7. The project can't be built if any Java 7 features are used in the source files which defeats the whole purpose of moving to Java 7. Reproducible: Always Steps to Reproduce: 1.Change the examples build.xml to use a source compliance level of 1.7 and verbose=true as follows: <iajc destdir="${classes.dir}" verbose="true" source="1.7" argfiles="${list}" 2.Run using 'ant bean' I get the following line: [iajc] ignored: -source 1.7 at E:\aspectj1.7\doc\examples\build.xml:136:
resolved fixed
89c178f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-04-17T16:39:41Z"
"2012-04-17T16:26:40Z"
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.IMessage.Kind; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IMessageHolder; import org.aspectj.bridge.MessageHandler; import org.aspectj.bridge.MessageUtil; 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=&quot;src&quot;&gt; * &lt;compilerarg compiler=&quot;...&quot; line=&quot;-argfile src/args.lst&quot;/&gt; * &lt;javac&gt; * </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 timers; 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 Path inxmlfiles; 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; inxmlfiles = 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; timers = 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 setXmlConfigured(boolean xmlConfigured) { cmd.addFlag("-xmlConfigured", xmlConfigured); } 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 setTimers(boolean timers) { cmd.addFlag("-timers", timers); this.timers = timers; } 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(); } public void setInxmlref(Reference ref) { createArgfiles().setRefid(ref); } public void setInxml(Path path) { // ajc-only eajc-also docDone inxmlfiles = incPath(inxmlfiles, path); } public Path createInxml() { if (inxmlfiles == null) { inxmlfiles = new Path(project); } return inxmlfiles.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 (inxmlfiles != null) { String[] files = inxmlfiles.list(); for (int i = 0; i < files.length; i++) { File inxmlfile = project.resolveFile(files[i]); if (check(inxmlfile, files[i], false, location)) { list.add("-xmlConfigured"); list.add(inxmlfile.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)) { if (!list.contains(file.getAbsolutePath())) { 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) { } } }
382,723
Bug 382723 An package-level abstract generic privileged aspect, which extends an abstract generic aspect, gives a IlligalStateException on a method call in around advice
Build Identifier: AJDT Version: 2.1.3.e37x-20110628-1900 / AspectJ version: 1.6.12.20110613132200 / eclipse.buildId=M20120208-0800 around advice targetting a generic constructor call in a package visability generic privileged abstract apsect, which extends a abstract generic aspect gives a compiler error when in this around advice a method call is made to a method defined in the aspect, superaspect or abstract defined methods. This only affects around advice and only when the aspect is package-visible and privileged. Workaround: either make the aspect public or remove privileged. Compiler output: Compile error: IllegalStateException thrown: Use generic type, not parameterized type StackTrace: java.lang.IllegalStateException: Use generic type, not parameterized type at org.aspectj.weaver.ResolvedTypeMunger.<init>(ResolvedTypeMunger.java:72) at org.aspectj.weaver.PrivilegedAccessMunger.<init>(PrivilegedAccessMunger.java:31) at org.aspectj.weaver.CrosscuttingMembers.addPrivilegedAccesses(CrosscuttingMembers.java:232) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers(ResolvedType.java:756) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect(CrosscuttingMembersSet.java:89) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect(CrosscuttingMembersSet.java:69) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java:512) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.ensureWeaverInitialized(AjPipeliningCompilerAdapter.java:529) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.weaveQueuedEntries(AjPipeliningCompilerAdapter.java:509) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.queueForWeaving(AjPipeliningCompilerAdapter.java:447) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.afterProcessing(AjPipeliningCompilerAdapter.java:432) 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:1021) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performBuild(AjBuildManager.java:305) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:185) at org.aspectj.ajde.core.internal.AjdeCoreBuildManager.performBuild(AjdeCoreBuildManager.java:127) at org.aspectj.ajde.core.AjCompiler.build(AjCompiler.java:91) at org.eclipse.ajdt.core.builder.AJBuilder.build(AJBuilder.java:257) at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:728) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:199) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:239) at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:292) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:295) at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:351) at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:374) at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:143) at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:241) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54) Session data: eclipse.buildId=M20120208-0800 java.version=1.6.0_22 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=nl_NL Command-line arguments: -data C:\workspace\ -os win32 -ws win32 -arch x86_64 Reproducible: Always Steps to Reproduce: 1. In a empty AspectJ project create the file Foo.java: import java.util.LinkedList; public class Foo { public LinkedList bar() { new LinkedList(); return null; } } 2. Create the file FooAspect.aj containing: import java.util.AbstractList; import java.util.List; abstract aspect FooAspectParent<T extends List> { protected int getNumber(int k) { return -1*k; } } abstract privileged aspect FooAspect<T extends AbstractList> extends FooAspectParent<T> { pointcut pc(): call(T.new()); T around():pc() { //getNumber(1); //<-- method call to superAspect fails //method(); // <-- method call to abstract local defined method fails //localMethod(); //<-- method call to local private method fails Math.random(); //<-- works hashCode(); //<-- works return null; } private void localMethod(){} protected abstract T method(); } 3. Uncomment one or more of the three commentted functions calls in the around advice and the compiler will reproduce the error. (note: this example with List which is a generic object is just for illustration of hierachy, this problem occured on production code when doing the same with non-generic, but hierachal objects. This way was the easiest to issolate and reproduce the bug the fastest.)
resolved fixed
ba9d43c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-15T18:29:35Z"
"2012-06-15T11:33:20Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AccessForInlineVisitor.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.util.Arrays; import java.util.HashMap; import java.util.Map; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.lookup.InlineAccessFieldBinding; import org.aspectj.ajdt.internal.compiler.lookup.InterTypeFieldBinding; import org.aspectj.ajdt.internal.compiler.lookup.InterTypeMethodBinding; import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedFieldBinding; import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedHandler; import org.aspectj.org.eclipse.jdt.internal.compiler.ASTVisitor; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AllocationExpression; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AssertStatement; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BlockScope; 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.ParameterizedMethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ProblemFieldBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.VariableBinding; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ResolvedMember; /** * Walks the body of around advice * * Makes sure that all member accesses are to public members. Will convert to use access methods when needed to ensure that. This * makes it much simpler (and more modular) to inline the body of an around. * * ??? constructors are handled different and require access to the target type. changes to * org.eclipse.jdt.internal.compiler.ast.AllocationExpression would be required to fix this issue. * * @author Jim Hugunin */ public class AccessForInlineVisitor extends ASTVisitor { PrivilegedHandler handler; AspectDeclaration inAspect; EclipseFactory world; // alias for inAspect.world private Map<TypeBinding, Map<FieldBinding, ResolvedMember>> alreadyProcessedReceivers = new HashMap<TypeBinding, Map<FieldBinding, ResolvedMember>>(); // set to true for ClassLiteralAccess and AssertStatement // ??? A better answer would be to transform these into inlinable forms public boolean isInlinable = true; public AccessForInlineVisitor(AspectDeclaration inAspect, PrivilegedHandler handler) { this.inAspect = inAspect; this.world = inAspect.factory; this.handler = handler; } public void endVisit(SingleNameReference ref, BlockScope scope) { if (ref.binding instanceof FieldBinding) { ref.binding = getAccessibleField((FieldBinding) ref.binding, ref.actualReceiverType); } } public void endVisit(QualifiedNameReference ref, BlockScope scope) { if (ref.binding instanceof FieldBinding) { ref.binding = getAccessibleField((FieldBinding) ref.binding, ref.actualReceiverType); } if (ref.otherBindings != null && ref.otherBindings.length > 0) { TypeBinding receiverType; if (ref.binding instanceof FieldBinding) { receiverType = ((FieldBinding) ref.binding).type; } else if (ref.binding instanceof VariableBinding) { receiverType = ((VariableBinding) ref.binding).type; } else { // !!! understand and fix this case later receiverType = ref.otherBindings[0].declaringClass; } boolean cont = true; // don't continue if we come across a problem for (int i = 0, len = ref.otherBindings.length; i < len && cont; i++) { FieldBinding binding = ref.otherBindings[i]; ref.otherBindings[i] = getAccessibleField(binding, receiverType); if (!(binding instanceof ProblemFieldBinding) && binding != null) receiverType = binding.type; // TODO Why is this sometimes null? else cont = false; } } } public void endVisit(FieldReference ref, BlockScope scope) { ref.binding = getAccessibleField(ref.binding, ref.actualReceiverType); } public void endVisit(MessageSend send, BlockScope scope) { if (send instanceof Proceed) return; if (send.binding == null || !send.binding.isValidBinding()) return; if (send.isSuperAccess() && !send.binding.isStatic()) { send.receiver = new ThisReference(send.sourceStart, send.sourceEnd); // send.arguments = AstUtil.insert(new ThisReference(send.sourceStart, send.sourceEnd), send.arguments); MethodBinding superAccessBinding = getSuperAccessMethod(send.binding); AstUtil.replaceMethodBinding(send, superAccessBinding); } else if (!isPublic(send.binding)) { send.syntheticAccessor = getAccessibleMethod(send.binding, send.actualReceiverType); } } public void endVisit(AllocationExpression send, BlockScope scope) { if (send.binding == null || !send.binding.isValidBinding()) return; // XXX TBD if (isPublic(send.binding)) return; makePublic(send.binding.declaringClass); send.binding = handler.getPrivilegedAccessMethod(send.binding, send); } public void endVisit(QualifiedTypeReference ref, BlockScope scope) { makePublic(ref.resolvedType); // getTypeBinding(scope)); //??? might be trouble } public void endVisit(SingleTypeReference ref, BlockScope scope) { makePublic(ref.resolvedType); // getTypeBinding(scope)); //??? might be trouble } private FieldBinding getAccessibleField(FieldBinding binding, TypeBinding receiverType) { // System.err.println("checking field: " + binding); if (binding == null || !binding.isValidBinding()) return binding; makePublic(receiverType); if (isPublic(binding)) return binding; if (binding instanceof PrivilegedFieldBinding) return binding; if (binding instanceof InterTypeFieldBinding) return binding; if (binding.isPrivate() && binding.declaringClass != inAspect.binding) { binding.modifiers = AstUtil.makePackageVisible(binding.modifiers); } // Avoid repeatedly building ResolvedMembers by using info on any done previously in this visitor Map<FieldBinding, ResolvedMember> alreadyResolvedMembers = alreadyProcessedReceivers.get(receiverType); if (alreadyResolvedMembers == null) { alreadyResolvedMembers = new HashMap<FieldBinding, ResolvedMember>(); alreadyProcessedReceivers.put(receiverType, alreadyResolvedMembers); } ResolvedMember m = alreadyResolvedMembers.get(binding); if (m == null) { m = world.makeResolvedMember(binding, receiverType); alreadyResolvedMembers.put(binding, m); } if (inAspect.accessForInline.containsKey(m)) { return (FieldBinding) inAspect.accessForInline.get(m); } FieldBinding ret = new InlineAccessFieldBinding(inAspect, binding, m); inAspect.accessForInline.put(m, ret); return ret; } private MethodBinding getAccessibleMethod(MethodBinding binding, TypeBinding receiverType) { if (!binding.isValidBinding()) return binding; makePublic(receiverType); // ??? if (isPublic(binding)) return binding; if (binding instanceof InterTypeMethodBinding) return binding; if (binding instanceof ParameterizedMethodBinding) { // pr124999 binding = binding.original(); } ResolvedMember m = null; if (binding.isPrivate() && binding.declaringClass != inAspect.binding) { // does this always mean that the aspect is an inner aspect of the bindings // declaring class? After all, the field is private but we can see it from // where we are. binding.modifiers = AstUtil.makePackageVisible(binding.modifiers); m = world.makeResolvedMember(binding); } else { // Sometimes receiverType and binding.declaringClass are *not* the same. // Sometimes receiverType is a subclass of binding.declaringClass. In these situations // we want the generated inline accessor to call the method on the subclass (at // runtime this will be satisfied by the super). m = world.makeResolvedMember(binding, receiverType); } if (inAspect.accessForInline.containsKey(m)) return (MethodBinding) inAspect.accessForInline.get(m); MethodBinding ret = world.makeMethodBinding(AjcMemberMaker.inlineAccessMethodForMethod(inAspect.typeX, m)); inAspect.accessForInline.put(m, ret); return ret; } static class SuperAccessMethodPair { public ResolvedMember originalMethod; public MethodBinding accessMethod; public SuperAccessMethodPair(ResolvedMember originalMethod, MethodBinding accessMethod) { this.originalMethod = originalMethod; this.accessMethod = accessMethod; } } private MethodBinding getSuperAccessMethod(MethodBinding binding) { ResolvedMember m = world.makeResolvedMember(binding); ResolvedMember superAccessMember = AjcMemberMaker.superAccessMethod(inAspect.typeX, m); if (inAspect.superAccessForInline.containsKey(superAccessMember)) { return ((SuperAccessMethodPair) inAspect.superAccessForInline.get(superAccessMember)).accessMethod; } MethodBinding ret = world.makeMethodBinding(superAccessMember); inAspect.superAccessForInline.put(superAccessMember, new SuperAccessMethodPair(m, ret)); return ret; } private boolean isPublic(FieldBinding fieldBinding) { // these are always effectively public to the inliner if (fieldBinding instanceof InterTypeFieldBinding) return true; return fieldBinding.isPublic(); } private boolean isPublic(MethodBinding methodBinding) { // these are always effectively public to the inliner if (methodBinding instanceof InterTypeMethodBinding) return true; return methodBinding.isPublic(); } private void makePublic(TypeBinding binding) { if (binding == null || !binding.isValidBinding()) return; // has already produced an error if (binding instanceof ReferenceBinding) { ReferenceBinding rb = (ReferenceBinding) binding; if (!rb.isPublic()) handler.notePrivilegedTypeAccess(rb, null); // ??? } else if (binding instanceof ArrayBinding) { makePublic(((ArrayBinding) binding).leafComponentType); } else { return; } } public void endVisit(AssertStatement assertStatement, BlockScope scope) { isInlinable = false; } public void endVisit(ClassLiteralAccess classLiteral, BlockScope scope) { isInlinable = false; } public boolean visit(TypeDeclaration localTypeDeclaration, BlockScope scope) { // we don't want to transform any local anonymous classes as they won't be inlined return false; } }
382,723
Bug 382723 An package-level abstract generic privileged aspect, which extends an abstract generic aspect, gives a IlligalStateException on a method call in around advice
Build Identifier: AJDT Version: 2.1.3.e37x-20110628-1900 / AspectJ version: 1.6.12.20110613132200 / eclipse.buildId=M20120208-0800 around advice targetting a generic constructor call in a package visability generic privileged abstract apsect, which extends a abstract generic aspect gives a compiler error when in this around advice a method call is made to a method defined in the aspect, superaspect or abstract defined methods. This only affects around advice and only when the aspect is package-visible and privileged. Workaround: either make the aspect public or remove privileged. Compiler output: Compile error: IllegalStateException thrown: Use generic type, not parameterized type StackTrace: java.lang.IllegalStateException: Use generic type, not parameterized type at org.aspectj.weaver.ResolvedTypeMunger.<init>(ResolvedTypeMunger.java:72) at org.aspectj.weaver.PrivilegedAccessMunger.<init>(PrivilegedAccessMunger.java:31) at org.aspectj.weaver.CrosscuttingMembers.addPrivilegedAccesses(CrosscuttingMembers.java:232) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers(ResolvedType.java:756) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect(CrosscuttingMembersSet.java:89) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect(CrosscuttingMembersSet.java:69) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java:512) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.ensureWeaverInitialized(AjPipeliningCompilerAdapter.java:529) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.weaveQueuedEntries(AjPipeliningCompilerAdapter.java:509) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.queueForWeaving(AjPipeliningCompilerAdapter.java:447) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.afterProcessing(AjPipeliningCompilerAdapter.java:432) 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:1021) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performBuild(AjBuildManager.java:305) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:185) at org.aspectj.ajde.core.internal.AjdeCoreBuildManager.performBuild(AjdeCoreBuildManager.java:127) at org.aspectj.ajde.core.AjCompiler.build(AjCompiler.java:91) at org.eclipse.ajdt.core.builder.AJBuilder.build(AJBuilder.java:257) at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:728) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:199) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:239) at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:292) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:295) at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:351) at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:374) at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:143) at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:241) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54) Session data: eclipse.buildId=M20120208-0800 java.version=1.6.0_22 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=nl_NL Command-line arguments: -data C:\workspace\ -os win32 -ws win32 -arch x86_64 Reproducible: Always Steps to Reproduce: 1. In a empty AspectJ project create the file Foo.java: import java.util.LinkedList; public class Foo { public LinkedList bar() { new LinkedList(); return null; } } 2. Create the file FooAspect.aj containing: import java.util.AbstractList; import java.util.List; abstract aspect FooAspectParent<T extends List> { protected int getNumber(int k) { return -1*k; } } abstract privileged aspect FooAspect<T extends AbstractList> extends FooAspectParent<T> { pointcut pc(): call(T.new()); T around():pc() { //getNumber(1); //<-- method call to superAspect fails //method(); // <-- method call to abstract local defined method fails //localMethod(); //<-- method call to local private method fails Math.random(); //<-- works hashCode(); //<-- works return null; } private void localMethod(){} protected abstract T method(); } 3. Uncomment one or more of the three commentted functions calls in the around advice and the compiler will reproduce the error. (note: this example with List which is a generic object is just for illustration of hierachy, this problem occured on production code when doing the same with non-generic, but hierachal objects. This way was the easiest to issolate and reproduce the bug the fastest.)
resolved fixed
ba9d43c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-15T18:29:35Z"
"2012-06-15T11:33:20Z"
tests/bugs170/pr382723/Foo.java
382,723
Bug 382723 An package-level abstract generic privileged aspect, which extends an abstract generic aspect, gives a IlligalStateException on a method call in around advice
Build Identifier: AJDT Version: 2.1.3.e37x-20110628-1900 / AspectJ version: 1.6.12.20110613132200 / eclipse.buildId=M20120208-0800 around advice targetting a generic constructor call in a package visability generic privileged abstract apsect, which extends a abstract generic aspect gives a compiler error when in this around advice a method call is made to a method defined in the aspect, superaspect or abstract defined methods. This only affects around advice and only when the aspect is package-visible and privileged. Workaround: either make the aspect public or remove privileged. Compiler output: Compile error: IllegalStateException thrown: Use generic type, not parameterized type StackTrace: java.lang.IllegalStateException: Use generic type, not parameterized type at org.aspectj.weaver.ResolvedTypeMunger.<init>(ResolvedTypeMunger.java:72) at org.aspectj.weaver.PrivilegedAccessMunger.<init>(PrivilegedAccessMunger.java:31) at org.aspectj.weaver.CrosscuttingMembers.addPrivilegedAccesses(CrosscuttingMembers.java:232) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers(ResolvedType.java:756) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect(CrosscuttingMembersSet.java:89) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect(CrosscuttingMembersSet.java:69) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java:512) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.ensureWeaverInitialized(AjPipeliningCompilerAdapter.java:529) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.weaveQueuedEntries(AjPipeliningCompilerAdapter.java:509) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.queueForWeaving(AjPipeliningCompilerAdapter.java:447) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.afterProcessing(AjPipeliningCompilerAdapter.java:432) 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:1021) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performBuild(AjBuildManager.java:305) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:185) at org.aspectj.ajde.core.internal.AjdeCoreBuildManager.performBuild(AjdeCoreBuildManager.java:127) at org.aspectj.ajde.core.AjCompiler.build(AjCompiler.java:91) at org.eclipse.ajdt.core.builder.AJBuilder.build(AJBuilder.java:257) at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:728) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:199) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:239) at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:292) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:295) at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:351) at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:374) at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:143) at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:241) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54) Session data: eclipse.buildId=M20120208-0800 java.version=1.6.0_22 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=nl_NL Command-line arguments: -data C:\workspace\ -os win32 -ws win32 -arch x86_64 Reproducible: Always Steps to Reproduce: 1. In a empty AspectJ project create the file Foo.java: import java.util.LinkedList; public class Foo { public LinkedList bar() { new LinkedList(); return null; } } 2. Create the file FooAspect.aj containing: import java.util.AbstractList; import java.util.List; abstract aspect FooAspectParent<T extends List> { protected int getNumber(int k) { return -1*k; } } abstract privileged aspect FooAspect<T extends AbstractList> extends FooAspectParent<T> { pointcut pc(): call(T.new()); T around():pc() { //getNumber(1); //<-- method call to superAspect fails //method(); // <-- method call to abstract local defined method fails //localMethod(); //<-- method call to local private method fails Math.random(); //<-- works hashCode(); //<-- works return null; } private void localMethod(){} protected abstract T method(); } 3. Uncomment one or more of the three commentted functions calls in the around advice and the compiler will reproduce the error. (note: this example with List which is a generic object is just for illustration of hierachy, this problem occured on production code when doing the same with non-generic, but hierachal objects. This way was the easiest to issolate and reproduce the bug the fastest.)
resolved fixed
ba9d43c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-15T18:29:35Z"
"2012-06-15T11:33:20Z"
tests/bugs170/pr382723/FooAspect.java
382,723
Bug 382723 An package-level abstract generic privileged aspect, which extends an abstract generic aspect, gives a IlligalStateException on a method call in around advice
Build Identifier: AJDT Version: 2.1.3.e37x-20110628-1900 / AspectJ version: 1.6.12.20110613132200 / eclipse.buildId=M20120208-0800 around advice targetting a generic constructor call in a package visability generic privileged abstract apsect, which extends a abstract generic aspect gives a compiler error when in this around advice a method call is made to a method defined in the aspect, superaspect or abstract defined methods. This only affects around advice and only when the aspect is package-visible and privileged. Workaround: either make the aspect public or remove privileged. Compiler output: Compile error: IllegalStateException thrown: Use generic type, not parameterized type StackTrace: java.lang.IllegalStateException: Use generic type, not parameterized type at org.aspectj.weaver.ResolvedTypeMunger.<init>(ResolvedTypeMunger.java:72) at org.aspectj.weaver.PrivilegedAccessMunger.<init>(PrivilegedAccessMunger.java:31) at org.aspectj.weaver.CrosscuttingMembers.addPrivilegedAccesses(CrosscuttingMembers.java:232) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers(ResolvedType.java:756) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect(CrosscuttingMembersSet.java:89) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect(CrosscuttingMembersSet.java:69) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java:512) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.ensureWeaverInitialized(AjPipeliningCompilerAdapter.java:529) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.weaveQueuedEntries(AjPipeliningCompilerAdapter.java:509) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.queueForWeaving(AjPipeliningCompilerAdapter.java:447) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.afterProcessing(AjPipeliningCompilerAdapter.java:432) 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:1021) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performBuild(AjBuildManager.java:305) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:185) at org.aspectj.ajde.core.internal.AjdeCoreBuildManager.performBuild(AjdeCoreBuildManager.java:127) at org.aspectj.ajde.core.AjCompiler.build(AjCompiler.java:91) at org.eclipse.ajdt.core.builder.AJBuilder.build(AJBuilder.java:257) at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:728) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:199) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:239) at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:292) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:295) at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:351) at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:374) at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:143) at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:241) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54) Session data: eclipse.buildId=M20120208-0800 java.version=1.6.0_22 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=nl_NL Command-line arguments: -data C:\workspace\ -os win32 -ws win32 -arch x86_64 Reproducible: Always Steps to Reproduce: 1. In a empty AspectJ project create the file Foo.java: import java.util.LinkedList; public class Foo { public LinkedList bar() { new LinkedList(); return null; } } 2. Create the file FooAspect.aj containing: import java.util.AbstractList; import java.util.List; abstract aspect FooAspectParent<T extends List> { protected int getNumber(int k) { return -1*k; } } abstract privileged aspect FooAspect<T extends AbstractList> extends FooAspectParent<T> { pointcut pc(): call(T.new()); T around():pc() { //getNumber(1); //<-- method call to superAspect fails //method(); // <-- method call to abstract local defined method fails //localMethod(); //<-- method call to local private method fails Math.random(); //<-- works hashCode(); //<-- works return null; } private void localMethod(){} protected abstract T method(); } 3. Uncomment one or more of the three commentted functions calls in the around advice and the compiler will reproduce the error. (note: this example with List which is a generic object is just for illustration of hierachy, this problem occured on production code when doing the same with non-generic, but hierachal objects. This way was the easiest to issolate and reproduce the bug the fastest.)
resolved fixed
ba9d43c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-15T18:29:35Z"
"2012-06-15T11:33:20Z"
tests/bugs170/pr382723/FooAspect2.java
382,723
Bug 382723 An package-level abstract generic privileged aspect, which extends an abstract generic aspect, gives a IlligalStateException on a method call in around advice
Build Identifier: AJDT Version: 2.1.3.e37x-20110628-1900 / AspectJ version: 1.6.12.20110613132200 / eclipse.buildId=M20120208-0800 around advice targetting a generic constructor call in a package visability generic privileged abstract apsect, which extends a abstract generic aspect gives a compiler error when in this around advice a method call is made to a method defined in the aspect, superaspect or abstract defined methods. This only affects around advice and only when the aspect is package-visible and privileged. Workaround: either make the aspect public or remove privileged. Compiler output: Compile error: IllegalStateException thrown: Use generic type, not parameterized type StackTrace: java.lang.IllegalStateException: Use generic type, not parameterized type at org.aspectj.weaver.ResolvedTypeMunger.<init>(ResolvedTypeMunger.java:72) at org.aspectj.weaver.PrivilegedAccessMunger.<init>(PrivilegedAccessMunger.java:31) at org.aspectj.weaver.CrosscuttingMembers.addPrivilegedAccesses(CrosscuttingMembers.java:232) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers(ResolvedType.java:756) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect(CrosscuttingMembersSet.java:89) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect(CrosscuttingMembersSet.java:69) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java:512) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.ensureWeaverInitialized(AjPipeliningCompilerAdapter.java:529) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.weaveQueuedEntries(AjPipeliningCompilerAdapter.java:509) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.queueForWeaving(AjPipeliningCompilerAdapter.java:447) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.afterProcessing(AjPipeliningCompilerAdapter.java:432) 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:1021) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performBuild(AjBuildManager.java:305) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:185) at org.aspectj.ajde.core.internal.AjdeCoreBuildManager.performBuild(AjdeCoreBuildManager.java:127) at org.aspectj.ajde.core.AjCompiler.build(AjCompiler.java:91) at org.eclipse.ajdt.core.builder.AJBuilder.build(AJBuilder.java:257) at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:728) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:199) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:239) at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:292) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:295) at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:351) at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:374) at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:143) at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:241) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54) Session data: eclipse.buildId=M20120208-0800 java.version=1.6.0_22 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=nl_NL Command-line arguments: -data C:\workspace\ -os win32 -ws win32 -arch x86_64 Reproducible: Always Steps to Reproduce: 1. In a empty AspectJ project create the file Foo.java: import java.util.LinkedList; public class Foo { public LinkedList bar() { new LinkedList(); return null; } } 2. Create the file FooAspect.aj containing: import java.util.AbstractList; import java.util.List; abstract aspect FooAspectParent<T extends List> { protected int getNumber(int k) { return -1*k; } } abstract privileged aspect FooAspect<T extends AbstractList> extends FooAspectParent<T> { pointcut pc(): call(T.new()); T around():pc() { //getNumber(1); //<-- method call to superAspect fails //method(); // <-- method call to abstract local defined method fails //localMethod(); //<-- method call to local private method fails Math.random(); //<-- works hashCode(); //<-- works return null; } private void localMethod(){} protected abstract T method(); } 3. Uncomment one or more of the three commentted functions calls in the around advice and the compiler will reproduce the error. (note: this example with List which is a generic object is just for illustration of hierachy, this problem occured on production code when doing the same with non-generic, but hierachal objects. This way was the easiest to issolate and reproduce the bug the fastest.)
resolved fixed
ba9d43c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-15T18:29:35Z"
"2012-06-15T11:33:20Z"
tests/bugs170/pr382723/FooAspect3.java
382,723
Bug 382723 An package-level abstract generic privileged aspect, which extends an abstract generic aspect, gives a IlligalStateException on a method call in around advice
Build Identifier: AJDT Version: 2.1.3.e37x-20110628-1900 / AspectJ version: 1.6.12.20110613132200 / eclipse.buildId=M20120208-0800 around advice targetting a generic constructor call in a package visability generic privileged abstract apsect, which extends a abstract generic aspect gives a compiler error when in this around advice a method call is made to a method defined in the aspect, superaspect or abstract defined methods. This only affects around advice and only when the aspect is package-visible and privileged. Workaround: either make the aspect public or remove privileged. Compiler output: Compile error: IllegalStateException thrown: Use generic type, not parameterized type StackTrace: java.lang.IllegalStateException: Use generic type, not parameterized type at org.aspectj.weaver.ResolvedTypeMunger.<init>(ResolvedTypeMunger.java:72) at org.aspectj.weaver.PrivilegedAccessMunger.<init>(PrivilegedAccessMunger.java:31) at org.aspectj.weaver.CrosscuttingMembers.addPrivilegedAccesses(CrosscuttingMembers.java:232) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers(ResolvedType.java:756) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect(CrosscuttingMembersSet.java:89) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect(CrosscuttingMembersSet.java:69) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java:512) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.ensureWeaverInitialized(AjPipeliningCompilerAdapter.java:529) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.weaveQueuedEntries(AjPipeliningCompilerAdapter.java:509) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.queueForWeaving(AjPipeliningCompilerAdapter.java:447) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.afterProcessing(AjPipeliningCompilerAdapter.java:432) 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:1021) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performBuild(AjBuildManager.java:305) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:185) at org.aspectj.ajde.core.internal.AjdeCoreBuildManager.performBuild(AjdeCoreBuildManager.java:127) at org.aspectj.ajde.core.AjCompiler.build(AjCompiler.java:91) at org.eclipse.ajdt.core.builder.AJBuilder.build(AJBuilder.java:257) at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:728) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:199) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:239) at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:292) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:295) at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:351) at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:374) at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:143) at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:241) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54) Session data: eclipse.buildId=M20120208-0800 java.version=1.6.0_22 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=nl_NL Command-line arguments: -data C:\workspace\ -os win32 -ws win32 -arch x86_64 Reproducible: Always Steps to Reproduce: 1. In a empty AspectJ project create the file Foo.java: import java.util.LinkedList; public class Foo { public LinkedList bar() { new LinkedList(); return null; } } 2. Create the file FooAspect.aj containing: import java.util.AbstractList; import java.util.List; abstract aspect FooAspectParent<T extends List> { protected int getNumber(int k) { return -1*k; } } abstract privileged aspect FooAspect<T extends AbstractList> extends FooAspectParent<T> { pointcut pc(): call(T.new()); T around():pc() { //getNumber(1); //<-- method call to superAspect fails //method(); // <-- method call to abstract local defined method fails //localMethod(); //<-- method call to local private method fails Math.random(); //<-- works hashCode(); //<-- works return null; } private void localMethod(){} protected abstract T method(); } 3. Uncomment one or more of the three commentted functions calls in the around advice and the compiler will reproduce the error. (note: this example with List which is a generic object is just for illustration of hierachy, this problem occured on production code when doing the same with non-generic, but hierachal objects. This way was the easiest to issolate and reproduce the bug the fastest.)
resolved fixed
ba9d43c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-15T18:29:35Z"
"2012-06-15T11:33:20Z"
tests/src/org/aspectj/systemtest/ajc170/Ajc170Tests.java
/******************************************************************************* * Copyright (c) 2008-2012 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.ajc170; import java.io.File; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.weaver.TypeFactory; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.internal.tools.StandardPointcutExpressionImpl; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.PointcutRewriter; import org.aspectj.weaver.reflect.ReflectionWorld; import org.aspectj.weaver.tools.StandardPointcutParser; /** * @author Andy Clement */ public class Ajc170Tests extends org.aspectj.testing.XMLBasedAjcTestCase { // public void testLostAnnos_377130() { // runTest("missing annos on priv aspects"); // } // // public void testLostAnnos_377130_2() { // runTest("missing annos on priv aspects - 2"); // } public void testAttributeErrorJ7() { runTest("attribute issue with J7"); } public void testSwitchOnEnum() { runTest("switch on enum"); } public void testDecAtFieldOrderingLTW1() { runTest("dec at field ordering ltw 1"); } public void testDecAtFieldOrdering1() { runTest("dec at field ordering 1"); } // public void testDecAtFieldOrdering2() { // runTest("dec at field ordering 2"); // } public void testXmlDefsDeclareAnnoType() { runTest("xml defined dec anno - type"); } public void testXmlDefsDeclareAnnoMethod() { runTest("xml defined dec at method"); } // anno not runtime vis public void testXmlDefsDeclareAnnoMethod2() { runTest("xml defined dec at method 2"); } public void testXmlDefsDeclareAnnoField() { runTest("xml defined dec at field"); } public void testXmlDefsDeclareAnnoFieldVariants1() { runTest("xml defined dec anno - variants 1"); } public void testXmlDefsDeclareAnnoFieldVariants2() { runTest("xml defined dec anno - variants 2"); } public void testXmlDefsDeclareAnnoFieldMultipleValues() { runTest("xml defined dec anno - multiple values"); } public void testXmlDefsDeclareAnnoFieldMultipleValuesAndSpaces() { runTest("xml defined dec anno - multiple values and spaces"); } public void testPointcutExpense_374964() { // check a declaring type being specified causes the call() to be considered cheaper than this() World world = new ReflectionWorld(true, getClass().getClassLoader()); StandardPointcutParser pointcutParser = StandardPointcutParser.getPointcutParserSupportingAllPrimitives(world); StandardPointcutExpressionImpl pointcutExpression = (StandardPointcutExpressionImpl)pointcutParser.parsePointcutExpression("call(* *(..)) && this(Object)"); Pointcut pc = pointcutExpression.getUnderlyingPointcut(); Pointcut newp = new PointcutRewriter().rewrite(pc); // no declaring type so this() is considered cheaper assertEquals("(this(java.lang.Object) && call(* *(..)))",newp.toString()); pointcutExpression = (StandardPointcutExpressionImpl)pointcutParser.parsePointcutExpression("call(* String.*(..)) && this(Object)"); pc = pointcutExpression.getUnderlyingPointcut(); newp = new PointcutRewriter().rewrite(pc); // declaring type, so call() is cheaper assertEquals("(call(* java.lang.String.*(..)) && this(java.lang.Object))",newp.toString()); pointcutExpression = (StandardPointcutExpressionImpl)pointcutParser.parsePointcutExpression("this(Object) && call(* *(..)) && call(* String.*(..))"); pc = pointcutExpression.getUnderlyingPointcut(); newp = new PointcutRewriter().rewrite(pc); // more complex example, mix of them assertEquals("((call(* java.lang.String.*(..)) && this(java.lang.Object)) && call(* *(..)))",newp.toString()); } /* public void testPublicITDFs_pr73507_1() { runTest("public ITDfs - 1"); } public void testPublicITDFs_pr73507_2() { runTest("public ITDfs - 2"); } public void testPublicITDFs_pr73507_3() { runTest("public ITDfs - 3"); } public void testPublicITDFs_pr73507_4() { runTest("public ITDfs - 4"); } */ public void testBCExceptionAnnoDecp_371998() { runTest("BCException anno decp"); } public void testTransientTjpFields()throws Exception { runTest("transient tjp fields"); JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "Code"); Field[] fs = jc.getFields(); //private static final org.aspectj.lang.JoinPoint$StaticPart ajc$tjp_0 [Synthetic] //private static final org.aspectj.lang.JoinPoint$StaticPart ajc$tjp_1 [Synthetic] for (Field f: fs) { if (!f.isTransient()) { fail("Field should be transient: "+f); } } } public void testGenericsWithTwoTypeParamsOneWildcard() { UnresolvedType ut; ut = TypeFactory.createTypeFromSignature("LFoo<**>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<***>;"); assertEquals(3,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<TP;*+Ljava/lang/String;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<*+Ljava/lang/String;TP;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<*+Ljava/lang/String;TP;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<*TT;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<[I>;"); assertEquals(1,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<[I[Z>;"); assertEquals(2,ut.getTypeParameters().length); } public void testPerThis() { runTest("perthis"); } public void testPerTarget() { runTest("pertarget"); } public void testPerCflow() { runTest("percflow"); } public void testPerTypeWithin() { runTest("pertypewithin"); } // not specifying -1.7 public void testDiamond1() { runTest("diamond 1"); } public void testDiamond2() { runTest("diamond 2"); } public void testDiamondItd1() { runTest("diamond itd 1"); } public void testLiterals1() { runTest("literals 1"); } public void testLiterals2() { runTest("literals 2"); } public void testLiteralsItd1() { runTest("literals itd 1"); } public void testStringSwitch1() { runTest("string switch 1"); } public void testStringSwitch2() { runTest("string switch 2"); } public void testMultiCatch1() { runTest("multi catch 1"); } public void testMultiCatch2() { runTest("multi catch 2"); } public void testMultiCatchWithHandler1() { runTest("multi catch with handler 1"); } public void testMultiCatchAspect1() { runTest("multi catch aspect 1"); } // public void testMultiCatchWithHandler2() { // runTest("multi catch with handler 2"); // } public void testSanity1() { runTest("sanity 1"); } public void testMissingImpl_363979() { runTest("missing impl"); } public void testMissingImpl_363979_2() { runTest("missing impl 2"); } public void testStackOverflow_364380() { runTest("stackoverflow"); } // public void testTryResources1() { // runTest("try resources 1"); // } // // public void testTryResources2() { // runTest("try resources 2"); // } // --- public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc170Tests.class); } @Override protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc170/ajc170.xml"); } }
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
org.aspectj.matcher/src/org/aspectj/weaver/ResolvedType.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; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; 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.Queue; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjAttribute.WeaverVersionInfo; import org.aspectj.weaver.Iterators.Getter; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.PerClause; public abstract class ResolvedType extends UnresolvedType implements AnnotatedElement { public static final ResolvedType[] EMPTY_RESOLVED_TYPE_ARRAY = new ResolvedType[0]; public static final String PARAMETERIZED_TYPE_IDENTIFIER = "P"; // Set temporarily during a type pattern match call - this currently used to hold the // annotations that may be attached to a type when it used as a parameter public ResolvedType[] temporaryAnnotationTypes; private ResolvedType[] resolvedTypeParams; private String binaryPath; protected World world; private int bits; private static int AnnotationBitsInitialized = 0x0001; private static int AnnotationMarkedInherited = 0x0002; private static int MungersAnalyzed = 0x0004; private static int HasParentMunger = 0x0008; private static int TypeHierarchyCompleteBit = 0x0010; private static int GroovyObjectInitialized = 0x0020; private static int IsGroovyObject = 0x0040; protected ResolvedType(String signature, World world) { super(signature); this.world = world; } protected ResolvedType(String signature, String signatureErasure, World world) { super(signature, signatureErasure); this.world = world; } public int getSize() { return 1; } /** * Returns an iterator through ResolvedType objects representing all the direct supertypes of this type. That is, through the * superclass, if any, and all declared interfaces. */ public final Iterator<ResolvedType> getDirectSupertypes() { Iterator<ResolvedType> interfacesIterator = Iterators.array(getDeclaredInterfaces()); ResolvedType superclass = getSuperclass(); if (superclass == null) { return interfacesIterator; } else { return Iterators.snoc(interfacesIterator, superclass); } } public abstract ResolvedMember[] getDeclaredFields(); public abstract ResolvedMember[] getDeclaredMethods(); public abstract ResolvedType[] getDeclaredInterfaces(); public abstract ResolvedMember[] getDeclaredPointcuts(); public boolean isCacheable() { return true; } /** * @return the superclass of this type, or null (if this represents a jlObject, primitive, or void) */ public abstract ResolvedType getSuperclass(); public abstract int getModifiers(); // return true if this resolved type couldn't be found (but we know it's name maybe) public boolean isMissing() { return false; } // FIXME asc I wonder if in some circumstances MissingWithKnownSignature // should not be considered // 'really' missing as some code can continue based solely on the signature public static boolean isMissing(UnresolvedType unresolved) { if (unresolved instanceof ResolvedType) { ResolvedType resolved = (ResolvedType) unresolved; return resolved.isMissing(); } else { return (unresolved == MISSING); } } public ResolvedType[] getAnnotationTypes() { return EMPTY_RESOLVED_TYPE_ARRAY; } public AnnotationAJ getAnnotationOfType(UnresolvedType ofType) { return null; } // public final UnresolvedType getSuperclass(World world) { // return getSuperclass(); // } // This set contains pairs of types whose signatures are concatenated // together, this means with a fast lookup we can tell if two types // are equivalent. protected static Set<String> validBoxing = new HashSet<String>(); static { validBoxing.add("Ljava/lang/Byte;B"); validBoxing.add("Ljava/lang/Character;C"); validBoxing.add("Ljava/lang/Double;D"); validBoxing.add("Ljava/lang/Float;F"); validBoxing.add("Ljava/lang/Integer;I"); validBoxing.add("Ljava/lang/Long;J"); validBoxing.add("Ljava/lang/Short;S"); validBoxing.add("Ljava/lang/Boolean;Z"); validBoxing.add("BLjava/lang/Byte;"); validBoxing.add("CLjava/lang/Character;"); validBoxing.add("DLjava/lang/Double;"); validBoxing.add("FLjava/lang/Float;"); validBoxing.add("ILjava/lang/Integer;"); validBoxing.add("JLjava/lang/Long;"); validBoxing.add("SLjava/lang/Short;"); validBoxing.add("ZLjava/lang/Boolean;"); } // utilities public ResolvedType getResolvedComponentType() { return null; } public World getWorld() { return world; } // ---- things from object @Override public boolean equals(Object other) { if (other instanceof ResolvedType) { return this == other; } else { return super.equals(other); } } // ---- difficult things /** * returns an iterator through all of the fields of this type, in order for checking from JVM spec 2ed 5.4.3.2. This means that * the order is * <p/> * <ul> * <li>fields from current class</li> * <li>recur into direct superinterfaces</li> * <li>recur into superclass</li> * </ul> * <p/> * We keep a hashSet of interfaces that we've visited so we don't spiral out into 2^n land. */ public Iterator<ResolvedMember> getFields() { final Iterators.Filter<ResolvedType> dupFilter = Iterators.dupFilter(); Iterators.Getter<ResolvedType, ResolvedType> typeGetter = new Iterators.Getter<ResolvedType, ResolvedType>() { public Iterator<ResolvedType> get(ResolvedType o) { return dupFilter.filter(o.getDirectSupertypes()); } }; return Iterators.mapOver(Iterators.recur(this, typeGetter), FieldGetterInstance); } /** * returns an iterator through all of the methods of this type, in order for checking from JVM spec 2ed 5.4.3.3. This means that * the order is * <p/> * <ul> * <li>methods from current class</li> * <li>recur into superclass, all the way up, not touching interfaces</li> * <li>recur into all superinterfaces, in some unspecified order (but those 'closest' to this type are first)</li> * </ul> * <p/> * * @param wantGenerics is true if the caller would like all generics information, otherwise those methods are collapsed to their * erasure */ public Iterator<ResolvedMember> getMethods(boolean wantGenerics, boolean wantDeclaredParents) { return Iterators.mapOver(getHierarchy(wantGenerics, wantDeclaredParents), MethodGetterInstance); } public Iterator<ResolvedMember> getMethodsIncludingIntertypeDeclarations(boolean wantGenerics, boolean wantDeclaredParents) { return Iterators.mapOver(getHierarchy(wantGenerics, wantDeclaredParents), MethodGetterWithItdsInstance); } /** * An Iterators.Getter that returns an iterator over all methods declared on some resolved type. */ private static class MethodGetter implements Iterators.Getter<ResolvedType, ResolvedMember> { public Iterator<ResolvedMember> get(ResolvedType type) { return Iterators.array(type.getDeclaredMethods()); } } /** * An Iterators.Getter that returns an iterator over all pointcuts declared on some resolved type. */ private static class PointcutGetter implements Iterators.Getter<ResolvedType, ResolvedMember> { public Iterator<ResolvedMember> get(ResolvedType o) { return Iterators.array(o.getDeclaredPointcuts()); } } // OPTIMIZE could cache the result of discovering ITDs // Getter that returns all declared methods for a type through an iterator - including intertype declarations private static class MethodGetterIncludingItds implements Iterators.Getter<ResolvedType, ResolvedMember> { public Iterator<ResolvedMember> get(ResolvedType type) { ResolvedMember[] methods = type.getDeclaredMethods(); if (type.interTypeMungers != null) { int additional = 0; for (ConcreteTypeMunger typeTransformer : type.interTypeMungers) { ResolvedMember rm = typeTransformer.getSignature(); // BUG won't this include fields? When we are looking for methods if (rm != null) { // new parent type munger can have null signature additional++; } } if (additional > 0) { ResolvedMember[] methods2 = new ResolvedMember[methods.length + additional]; System.arraycopy(methods, 0, methods2, 0, methods.length); additional = methods.length; for (ConcreteTypeMunger typeTransformer : type.interTypeMungers) { ResolvedMember rm = typeTransformer.getSignature(); if (rm != null) { // new parent type munger can have null signature methods2[additional++] = typeTransformer.getSignature(); } } methods = methods2; } } return Iterators.array(methods); } } /** * An Iterators.Getter that returns an iterator over all fields declared on some resolved type. */ private static class FieldGetter implements Iterators.Getter<ResolvedType, ResolvedMember> { public Iterator<ResolvedMember> get(ResolvedType type) { return Iterators.array(type.getDeclaredFields()); } } private final static MethodGetter MethodGetterInstance = new MethodGetter(); private final static MethodGetterIncludingItds MethodGetterWithItdsInstance = new MethodGetterIncludingItds(); private final static PointcutGetter PointcutGetterInstance = new PointcutGetter(); private final static FieldGetter FieldGetterInstance = new FieldGetter(); /** * Return an iterator over the types in this types hierarchy - starting with this type first, then all superclasses up to Object * and then all interfaces (starting with those 'nearest' this type). * * @param wantGenerics true if the caller wants full generic information * @param wantDeclaredParents true if the caller even wants those parents introduced via declare parents * @return an iterator over all types in the hierarchy of this type */ public Iterator<ResolvedType> getHierarchy() { return getHierarchy(false, false); } public Iterator<ResolvedType> getHierarchy(final boolean wantGenerics, final boolean wantDeclaredParents) { final Iterators.Getter<ResolvedType, ResolvedType> interfaceGetter = new Iterators.Getter<ResolvedType, ResolvedType>() { List<String> alreadySeen = new ArrayList<String>(); // Strings are signatures (ResolvedType.getSignature()) public Iterator<ResolvedType> get(ResolvedType type) { ResolvedType[] interfaces = type.getDeclaredInterfaces(); // remove interfaces introduced by declare parents // relatively expensive but hopefully uncommon if (!wantDeclaredParents && type.hasNewParentMungers()) { // Throw away interfaces from that array if they were decp'd onto here List<Integer> forRemoval = new ArrayList<Integer>(); for (ConcreteTypeMunger munger : type.interTypeMungers) { if (munger.getMunger() != null) { ResolvedTypeMunger m = munger.getMunger(); if (m.getKind() == ResolvedTypeMunger.Parent) { ResolvedType newType = ((NewParentTypeMunger) m).getNewParent(); if (!wantGenerics && newType.isParameterizedOrGenericType()) { newType = newType.getRawType(); } for (int ii = 0; ii < interfaces.length; ii++) { ResolvedType iface = interfaces[ii]; if (!wantGenerics && iface.isParameterizedOrGenericType()) { iface = iface.getRawType(); } if (newType.getSignature().equals(iface.getSignature())) { // pr171953 forRemoval.add(ii); } } } } } // Found some to remove from those we are going to iterate over if (forRemoval.size() > 0) { ResolvedType[] interfaces2 = new ResolvedType[interfaces.length - forRemoval.size()]; int p = 0; for (int ii = 0; ii < interfaces.length; ii++) { if (!forRemoval.contains(ii)) { interfaces2[p++] = interfaces[ii]; } } interfaces = interfaces2; } } return new Iterators.ResolvedTypeArrayIterator(interfaces, alreadySeen, wantGenerics); } }; // If this type is an interface, there are only interfaces to walk if (this.isInterface()) { return new SuperInterfaceWalker(interfaceGetter, this); } else { SuperInterfaceWalker superInterfaceWalker = new SuperInterfaceWalker(interfaceGetter); Iterator<ResolvedType> superClassesIterator = new SuperClassWalker(this, superInterfaceWalker, wantGenerics); // append() will check if the second iterator is empty before appending - but the types which the superInterfaceWalker // needs to visit are only accumulated whilst the superClassesIterator is in progress return Iterators.append1(superClassesIterator, superInterfaceWalker); } } /** * Return a list of methods, first those declared on this class, then those declared on the superclass (recurse) and then those * declared on the superinterfaces. This is expensive - use the getMethods() method if you can! */ public List<ResolvedMember> getMethodsWithoutIterator(boolean includeITDs, boolean allowMissing, boolean genericsAware) { List<ResolvedMember> methods = new ArrayList<ResolvedMember>(); Set<String> knowninterfaces = new HashSet<String>(); addAndRecurse(knowninterfaces, methods, this, includeITDs, allowMissing, genericsAware); return methods; } /** * Return a list of the types in the hierarchy of this type, starting with this type. The order in the list is the superclasses * followed by the super interfaces. * * @param genericsAware should the list include parameterized/generic types (if not, they will be collapsed to raw)? * @return list of resolvedtypes in this types hierarchy, including this type first */ public List<ResolvedType> getHierarchyWithoutIterator(boolean includeITDs, boolean allowMissing, boolean genericsAware) { List<ResolvedType> types = new ArrayList<ResolvedType>(); Set<String> visited = new HashSet<String>(); recurseHierarchy(visited, types, this, includeITDs, allowMissing, genericsAware); return types; } private void addAndRecurse(Set<String> knowninterfaces, List<ResolvedMember> collector, ResolvedType resolvedType, boolean includeITDs, boolean allowMissing, boolean genericsAware) { // Add the methods declared on this type collector.addAll(Arrays.asList(resolvedType.getDeclaredMethods())); // now add all the inter-typed members too if (includeITDs && resolvedType.interTypeMungers != null) { for (ConcreteTypeMunger typeTransformer : interTypeMungers) { ResolvedMember rm = typeTransformer.getSignature(); if (rm != null) { // new parent type munger can have null signature collector.add(typeTransformer.getSignature()); } } } // BUG? interface type superclass is Object - is that correct? if (!resolvedType.isInterface() && !resolvedType.equals(ResolvedType.OBJECT)) { ResolvedType superType = resolvedType.getSuperclass(); if (superType != null && !superType.isMissing()) { if (!genericsAware && superType.isParameterizedOrGenericType()) { superType = superType.getRawType(); } // Recurse if we are not at the top addAndRecurse(knowninterfaces, collector, superType, includeITDs, allowMissing, genericsAware); } } // Go through the interfaces on the way back down ResolvedType[] interfaces = resolvedType.getDeclaredInterfaces(); for (int i = 0; i < interfaces.length; i++) { ResolvedType iface = interfaces[i]; if (!genericsAware && iface.isParameterizedOrGenericType()) { iface = iface.getRawType(); } // we need to know if it is an interface from Parent kind munger // as those are used for @AJ ITD and we precisely want to skip those boolean shouldSkip = false; for (int j = 0; j < resolvedType.interTypeMungers.size(); j++) { ConcreteTypeMunger munger = resolvedType.interTypeMungers.get(j); if (munger.getMunger() != null && munger.getMunger().getKind() == ResolvedTypeMunger.Parent && ((NewParentTypeMunger) munger.getMunger()).getNewParent().equals(iface) // pr171953 ) { shouldSkip = true; break; } } // Do not do interfaces more than once if (!shouldSkip && !knowninterfaces.contains(iface.getSignature())) { knowninterfaces.add(iface.getSignature()); if (allowMissing && iface.isMissing()) { if (iface instanceof MissingResolvedTypeWithKnownSignature) { ((MissingResolvedTypeWithKnownSignature) iface).raiseWarningOnMissingInterfaceWhilstFindingMethods(); } } else { addAndRecurse(knowninterfaces, collector, iface, includeITDs, allowMissing, genericsAware); } } } } /** * Recurse up a type hierarchy, first the superclasses then the super interfaces. */ private void recurseHierarchy(Set<String> knowninterfaces, List<ResolvedType> collector, ResolvedType resolvedType, boolean includeITDs, boolean allowMissing, boolean genericsAware) { collector.add(resolvedType); if (!resolvedType.isInterface() && !resolvedType.equals(ResolvedType.OBJECT)) { ResolvedType superType = resolvedType.getSuperclass(); if (superType != null && !superType.isMissing()) { if (!genericsAware && (superType.isParameterizedType() || superType.isGenericType())) { superType = superType.getRawType(); } // Recurse if we are not at the top recurseHierarchy(knowninterfaces, collector, superType, includeITDs, allowMissing, genericsAware); } } // Go through the interfaces on the way back down ResolvedType[] interfaces = resolvedType.getDeclaredInterfaces(); for (int i = 0; i < interfaces.length; i++) { ResolvedType iface = interfaces[i]; if (!genericsAware && (iface.isParameterizedType() || iface.isGenericType())) { iface = iface.getRawType(); } // we need to know if it is an interface from Parent kind munger // as those are used for @AJ ITD and we precisely want to skip those boolean shouldSkip = false; for (int j = 0; j < resolvedType.interTypeMungers.size(); j++) { ConcreteTypeMunger munger = resolvedType.interTypeMungers.get(j); if (munger.getMunger() != null && munger.getMunger().getKind() == ResolvedTypeMunger.Parent && ((NewParentTypeMunger) munger.getMunger()).getNewParent().equals(iface) // pr171953 ) { shouldSkip = true; break; } } // Do not do interfaces more than once if (!shouldSkip && !knowninterfaces.contains(iface.getSignature())) { knowninterfaces.add(iface.getSignature()); if (allowMissing && iface.isMissing()) { if (iface instanceof MissingResolvedTypeWithKnownSignature) { ((MissingResolvedTypeWithKnownSignature) iface).raiseWarningOnMissingInterfaceWhilstFindingMethods(); } } else { recurseHierarchy(knowninterfaces, collector, iface, includeITDs, allowMissing, genericsAware); } } } } public ResolvedType[] getResolvedTypeParameters() { if (resolvedTypeParams == null) { resolvedTypeParams = world.resolve(typeParameters); } return resolvedTypeParams; } /** * described in JVM spec 2ed 5.4.3.2 */ public ResolvedMember lookupField(Member field) { Iterator<ResolvedMember> i = getFields(); while (i.hasNext()) { ResolvedMember resolvedMember = i.next(); if (matches(resolvedMember, field)) { return resolvedMember; } if (resolvedMember.hasBackingGenericMember() && field.getName().equals(resolvedMember.getName())) { // might be worth checking the member behind the parameterized member (see pr137496) if (matches(resolvedMember.getBackingGenericMember(), field)) { return resolvedMember; } } } return null; } /** * described in JVM spec 2ed 5.4.3.3. Doesnt check ITDs. * * <p> * Check the current type for the method. If it is not found, check the super class and any super interfaces. Taking care not to * process interfaces multiple times. */ public ResolvedMember lookupMethod(Member m) { List<ResolvedType> typesTolookat = new ArrayList<ResolvedType>(); typesTolookat.add(this); int pos = 0; while (pos < typesTolookat.size()) { ResolvedType type = typesTolookat.get(pos++); if (!type.isMissing()) { ResolvedMember[] methods = type.getDeclaredMethods(); if (methods != null) { for (int i = 0; i < methods.length; i++) { ResolvedMember method = methods[i]; if (matches(method, m)) { return method; } // might be worth checking the method behind the parameterized method (137496) if (method.hasBackingGenericMember() && m.getName().equals(method.getName())) { if (matches(method.getBackingGenericMember(), m)) { return method; } } } } } // Queue the superclass: ResolvedType superclass = type.getSuperclass(); if (superclass != null) { typesTolookat.add(superclass); } // Queue any interfaces not already checked: ResolvedType[] superinterfaces = type.getDeclaredInterfaces(); if (superinterfaces != null) { for (int i = 0; i < superinterfaces.length; i++) { ResolvedType interf = superinterfaces[i]; if (!typesTolookat.contains(interf)) { typesTolookat.add(interf); } } } } return null; } /** * @param member the member to lookup in intertype declarations affecting this type * @return the real signature defined by any matching intertype declaration, otherwise null */ public ResolvedMember lookupMethodInITDs(Member member) { for (ConcreteTypeMunger typeTransformer : interTypeMungers) { if (matches(typeTransformer.getSignature(), member)) { return typeTransformer.getSignature(); } } return null; } /** * return null if not found */ private ResolvedMember lookupMember(Member m, ResolvedMember[] a) { for (int i = 0; i < a.length; i++) { ResolvedMember f = a[i]; if (matches(f, m)) { return f; } } return null; } // Bug (1) Do callers expect ITDs to be involved in the lookup? or do they do their own walk over ITDs? /** * Looks for the first member in the hierarchy matching aMember. This method differs from lookupMember(Member) in that it takes * into account parameters which are type variables - which clearly an unresolved Member cannot do since it does not know * anything about type variables. */ public ResolvedMember lookupResolvedMember(ResolvedMember aMember, boolean allowMissing, boolean eraseGenerics) { Iterator<ResolvedMember> toSearch = null; ResolvedMember found = null; if ((aMember.getKind() == Member.METHOD) || (aMember.getKind() == Member.CONSTRUCTOR)) { // toSearch = getMethodsWithoutIterator(true, allowMissing, !eraseGenerics).iterator(); toSearch = getMethodsIncludingIntertypeDeclarations(!eraseGenerics, true); } else { assert aMember.getKind() == Member.FIELD; toSearch = getFields(); } while (toSearch.hasNext()) { ResolvedMember candidate = toSearch.next(); if (eraseGenerics) { if (candidate.hasBackingGenericMember()) { candidate = candidate.getBackingGenericMember(); } } // OPTIMIZE speed up matches? optimize order of checks if (candidate.matches(aMember, eraseGenerics)) { found = candidate; break; } } return found; } public static boolean matches(Member m1, Member m2) { if (m1 == null) { return m2 == null; } if (m2 == null) { return false; } // Check the names boolean equalNames = m1.getName().equals(m2.getName()); if (!equalNames) { return false; } // Check the signatures boolean equalSignatures = m1.getSignature().equals(m2.getSignature()); if (equalSignatures) { return true; } // If they aren't the same, we need to allow for covariance ... where // one sig might be ()LCar; and // the subsig might be ()LFastCar; - where FastCar is a subclass of Car boolean equalCovariantSignatures = m1.getParameterSignature().equals(m2.getParameterSignature()); if (equalCovariantSignatures) { return true; } return false; } public static boolean conflictingSignature(Member m1, Member m2) { if (m1 == null || m2 == null) { return false; } if (!m1.getName().equals(m2.getName())) { return false; } if (m1.getKind() != m2.getKind()) { return false; } if (m1.getKind() == Member.FIELD) { return m1.getDeclaringType().equals(m2.getDeclaringType()); } else if (m1.getKind() == Member.POINTCUT) { return true; } UnresolvedType[] p1 = m1.getGenericParameterTypes(); UnresolvedType[] p2 = m2.getGenericParameterTypes(); if (p1 == null) { p1 = m1.getParameterTypes(); } if (p2 == null) { p2 = m2.getParameterTypes(); } int n = p1.length; if (n != p2.length) { return false; } for (int i = 0; i < n; i++) { if (!p1[i].equals(p2[i])) { return false; } } return true; } /** * returns an iterator through all of the pointcuts of this type, in order for checking from JVM spec 2ed 5.4.3.2 (as for * fields). This means that the order is * <p/> * <ul> * <li>pointcuts from current class</li> * <li>recur into direct superinterfaces</li> * <li>recur into superclass</li> * </ul> * <p/> * We keep a hashSet of interfaces that we've visited so we don't spiral out into 2^n land. */ public Iterator<ResolvedMember> getPointcuts() { final Iterators.Filter<ResolvedType> dupFilter = Iterators.dupFilter(); // same order as fields Iterators.Getter<ResolvedType, ResolvedType> typeGetter = new Iterators.Getter<ResolvedType, ResolvedType>() { public Iterator<ResolvedType> get(ResolvedType o) { return dupFilter.filter(o.getDirectSupertypes()); } }; return Iterators.mapOver(Iterators.recur(this, typeGetter), PointcutGetterInstance); } public ResolvedPointcutDefinition findPointcut(String name) { for (Iterator<ResolvedMember> i = getPointcuts(); i.hasNext();) { ResolvedPointcutDefinition f = (ResolvedPointcutDefinition) i.next(); // the ResolvedPointcutDefinition can be null if there are other problems that prevented its resolution if (f != null && name.equals(f.getName())) { return f; } } // pr120521 if (!getOutermostType().equals(this)) { ResolvedType outerType = getOutermostType().resolve(world); ResolvedPointcutDefinition rpd = outerType.findPointcut(name); return rpd; } return null; // should we throw an exception here? } // all about collecting CrosscuttingMembers // ??? collecting data-structure, shouldn't really be a field public CrosscuttingMembers crosscuttingMembers; public CrosscuttingMembers collectCrosscuttingMembers(boolean shouldConcretizeIfNeeded) { crosscuttingMembers = new CrosscuttingMembers(this, shouldConcretizeIfNeeded); if (getPerClause() == null) { return crosscuttingMembers; } crosscuttingMembers.setPerClause(getPerClause()); crosscuttingMembers.addShadowMungers(collectShadowMungers()); // GENERICITDFIX // crosscuttingMembers.addTypeMungers(collectTypeMungers()); crosscuttingMembers.addTypeMungers(getTypeMungers()); // FIXME AV - skip but needed ?? or ?? // crosscuttingMembers.addLateTypeMungers(getLateTypeMungers()); crosscuttingMembers.addDeclares(collectDeclares(!this.doesNotExposeShadowMungers())); crosscuttingMembers.addPrivilegedAccesses(getPrivilegedAccesses()); // System.err.println("collected cc members: " + this + ", " + // collectDeclares()); return crosscuttingMembers; } public final List<Declare> collectDeclares(boolean includeAdviceLike) { if (!this.isAspect()) { return Collections.emptyList(); } List<Declare> ret = new ArrayList<Declare>(); // if (this.isAbstract()) { // for (Iterator i = getDeclares().iterator(); i.hasNext();) { // Declare dec = (Declare) i.next(); // if (!dec.isAdviceLike()) ret.add(dec); // } // // if (!includeAdviceLike) return ret; if (!this.isAbstract()) { // ret.addAll(getDeclares()); final Iterators.Filter<ResolvedType> dupFilter = Iterators.dupFilter(); Iterators.Getter<ResolvedType, ResolvedType> typeGetter = new Iterators.Getter<ResolvedType, ResolvedType>() { public Iterator<ResolvedType> get(ResolvedType o) { return dupFilter.filter((o).getDirectSupertypes()); } }; Iterator<ResolvedType> typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedType ty = typeIterator.next(); // System.out.println("super: " + ty + ", " + ); for (Iterator<Declare> i = ty.getDeclares().iterator(); i.hasNext();) { Declare dec = i.next(); if (dec.isAdviceLike()) { if (includeAdviceLike) { ret.add(dec); } } else { ret.add(dec); } } } } return ret; } private final List<ShadowMunger> collectShadowMungers() { if (!this.isAspect() || this.isAbstract() || this.doesNotExposeShadowMungers()) { return Collections.emptyList(); } List<ShadowMunger> acc = new ArrayList<ShadowMunger>(); final Iterators.Filter<ResolvedType> dupFilter = Iterators.dupFilter(); Iterators.Getter<ResolvedType, ResolvedType> typeGetter = new Iterators.Getter<ResolvedType, ResolvedType>() { public Iterator<ResolvedType> get(ResolvedType o) { return dupFilter.filter((o).getDirectSupertypes()); } }; Iterator<ResolvedType> typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedType ty = typeIterator.next(); acc.addAll(ty.getDeclaredShadowMungers()); } return acc; } public void addParent(ResolvedType newParent) { // Nothing to do for anything except a ReferenceType } protected boolean doesNotExposeShadowMungers() { return false; } public PerClause getPerClause() { return null; } public Collection<Declare> getDeclares() { return Collections.emptyList(); } public Collection<ConcreteTypeMunger> getTypeMungers() { return Collections.emptyList(); } public Collection<ResolvedMember> getPrivilegedAccesses() { return Collections.emptyList(); } // ---- useful things public final boolean isInterface() { return Modifier.isInterface(getModifiers()); } public final boolean isAbstract() { return Modifier.isAbstract(getModifiers()); } public boolean isClass() { return false; } public boolean isAspect() { return false; } public boolean isAnnotationStyleAspect() { return false; } /** * Note: Only overridden by Name subtype. */ public boolean isEnum() { return false; } /** * Note: Only overridden by Name subtype. */ public boolean isAnnotation() { return false; } public boolean isAnonymous() { return false; } public boolean isNested() { return false; } public void addAnnotation(AnnotationAJ annotationX) { throw new RuntimeException("ResolvedType.addAnnotation() should never be called"); } public AnnotationAJ[] getAnnotations() { throw new RuntimeException("ResolvedType.getAnnotations() should never be called"); } /** * Note: Only overridden by ReferenceType subtype */ public boolean canAnnotationTargetType() { return false; } /** * Note: Only overridden by ReferenceType subtype */ public AnnotationTargetKind[] getAnnotationTargetKinds() { return null; } /** * Note: Only overridden by Name subtype. */ public boolean isAnnotationWithRuntimeRetention() { return false; } public boolean isSynthetic() { return signature.indexOf("$ajc") != -1; } public final boolean isFinal() { return Modifier.isFinal(getModifiers()); } protected Map<String, UnresolvedType> getMemberParameterizationMap() { if (!isParameterizedType()) { return Collections.emptyMap(); } TypeVariable[] tvs = getGenericType().getTypeVariables(); Map<String, UnresolvedType> parameterizationMap = new HashMap<String, UnresolvedType>(); for (int i = 0; i < tvs.length; i++) { parameterizationMap.put(tvs[i].getName(), typeParameters[i]); } return parameterizationMap; } public List<ShadowMunger> getDeclaredAdvice() { List<ShadowMunger> l = new ArrayList<ShadowMunger>(); ResolvedMember[] methods = getDeclaredMethods(); if (isParameterizedType()) { methods = getGenericType().getDeclaredMethods(); } Map<String, UnresolvedType> typeVariableMap = getAjMemberParameterizationMap(); for (int i = 0, len = methods.length; i < len; i++) { ShadowMunger munger = methods[i].getAssociatedShadowMunger(); if (munger != null) { if (ajMembersNeedParameterization()) { // munger.setPointcut(munger.getPointcut().parameterizeWith( // typeVariableMap)); munger = munger.parameterizeWith(this, typeVariableMap); if (munger instanceof Advice) { Advice advice = (Advice) munger; // update to use the parameterized signature... UnresolvedType[] ptypes = methods[i].getGenericParameterTypes(); UnresolvedType[] newPTypes = new UnresolvedType[ptypes.length]; for (int j = 0; j < ptypes.length; j++) { if (ptypes[j] instanceof TypeVariableReferenceType) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) ptypes[j]; if (typeVariableMap.containsKey(tvrt.getTypeVariable().getName())) { newPTypes[j] = typeVariableMap.get(tvrt.getTypeVariable().getName()); } else { newPTypes[j] = ptypes[j]; } } else { newPTypes[j] = ptypes[j]; } } advice.setBindingParameterTypes(newPTypes); } } munger.setDeclaringType(this); l.add(munger); } } return l; } public List<ShadowMunger> getDeclaredShadowMungers() { return getDeclaredAdvice(); } // ---- only for testing! public ResolvedMember[] getDeclaredJavaFields() { return filterInJavaVisible(getDeclaredFields()); } public ResolvedMember[] getDeclaredJavaMethods() { return filterInJavaVisible(getDeclaredMethods()); } private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) { List<ResolvedMember> l = new ArrayList<ResolvedMember>(); for (int i = 0, len = ms.length; i < len; i++) { if (!ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) { l.add(ms[i]); } } return l.toArray(new ResolvedMember[l.size()]); } public abstract ISourceContext getSourceContext(); // ---- fields public static final ResolvedType[] NONE = new ResolvedType[0]; public static final ResolvedType[] EMPTY_ARRAY = NONE; public static final Missing MISSING = new Missing(); // ---- types public static ResolvedType makeArray(ResolvedType type, int dim) { if (dim == 0) { return type; } ResolvedType array = new ArrayReferenceType("[" + type.getSignature(), "[" + type.getErasureSignature(), type.getWorld(), type); return makeArray(array, dim - 1); } static class Primitive extends ResolvedType { private final int size; private final int index; Primitive(String signature, int size, int index) { super(signature, null); this.size = size; this.index = index; this.typeKind = TypeKind.PRIMITIVE; } @Override public final int getSize() { return size; } @Override public final int getModifiers() { return Modifier.PUBLIC | Modifier.FINAL; } @Override public final boolean isPrimitiveType() { return true; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } @Override public final boolean isAssignableFrom(ResolvedType other) { if (!other.isPrimitiveType()) { if (!world.isInJava5Mode()) { return false; } return validBoxing.contains(this.getSignature() + other.getSignature()); } return assignTable[((Primitive) other).index][index]; } @Override public final boolean isAssignableFrom(ResolvedType other, boolean allowMissing) { return isAssignableFrom(other); } @Override public final boolean isCoerceableFrom(ResolvedType other) { if (this == other) { return true; } if (!other.isPrimitiveType()) { return false; } if (index > 6 || ((Primitive) other).index > 6) { return false; } return true; } @Override public ResolvedType resolve(World world) { if (this.world != world) { throw new IllegalStateException(); } this.world = world; return super.resolve(world); } @Override public final boolean needsNoConversionFrom(ResolvedType other) { if (!other.isPrimitiveType()) { return false; } return noConvertTable[((Primitive) other).index][index]; } private static final boolean[][] assignTable = {// to: B C D F I J S V Z // from { true, true, true, true, true, true, true, false, false }, // B { false, true, true, true, true, true, false, false, false }, // C { false, false, true, false, false, false, false, false, false }, // D { false, false, true, true, false, false, false, false, false }, // F { false, false, true, true, true, true, false, false, false }, // I { false, false, true, true, false, true, false, false, false }, // J { false, false, true, true, true, true, true, false, false }, // S { false, false, false, false, false, false, false, true, false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; private static final boolean[][] noConvertTable = {// to: B C D F I J S // V Z from { true, true, false, false, true, false, true, false, false }, // B { false, true, false, false, true, false, false, false, false }, // C { false, false, true, false, false, false, false, false, false }, // D { false, false, false, true, false, false, false, false, false }, // F { false, false, false, false, true, false, false, false, false }, // I { false, false, false, false, false, true, false, false, false }, // J { false, false, false, false, true, false, true, false, false }, // S { false, false, false, false, false, false, false, true, false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; // ---- @Override public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } @Override public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } @Override public final ResolvedType[] getDeclaredInterfaces() { return ResolvedType.NONE; } @Override public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } @Override public final ResolvedType getSuperclass() { return null; } @Override public ISourceContext getSourceContext() { return null; } } static class Missing extends ResolvedType { Missing() { super(MISSING_NAME, null); } // public final String toString() { // return "<missing>"; // } @Override public final String getName() { return MISSING_NAME; } @Override public final boolean isMissing() { return true; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } @Override public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } @Override public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } @Override public final ResolvedType[] getDeclaredInterfaces() { return ResolvedType.NONE; } @Override public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } @Override public final ResolvedType getSuperclass() { return null; } @Override public final int getModifiers() { return 0; } @Override public final boolean isAssignableFrom(ResolvedType other) { return false; } @Override public final boolean isAssignableFrom(ResolvedType other, boolean allowMissing) { return false; } @Override public final boolean isCoerceableFrom(ResolvedType other) { return false; } @Override public boolean needsNoConversionFrom(ResolvedType other) { return false; } @Override public ISourceContext getSourceContext() { return null; } } /** * Look up a member, takes into account any ITDs on this type. return null if not found */ public ResolvedMember lookupMemberNoSupers(Member member) { ResolvedMember ret = lookupDirectlyDeclaredMemberNoSupers(member); if (ret == null && interTypeMungers != null) { for (ConcreteTypeMunger tm : interTypeMungers) { if (matches(tm.getSignature(), member)) { return tm.getSignature(); } } } return ret; } public ResolvedMember lookupMemberWithSupersAndITDs(Member member) { ResolvedMember ret = lookupMemberNoSupers(member); if (ret != null) { return ret; } ResolvedType supert = getSuperclass(); while (ret == null && supert != null) { ret = supert.lookupMemberNoSupers(member); if (ret == null) { supert = supert.getSuperclass(); } } return ret; } /** * as lookupMemberNoSupers, but does not include ITDs * * @param member * @return */ public ResolvedMember lookupDirectlyDeclaredMemberNoSupers(Member member) { ResolvedMember ret; if (member.getKind() == Member.FIELD) { ret = lookupMember(member, getDeclaredFields()); } else { // assert member.getKind() == Member.METHOD || member.getKind() == // Member.CONSTRUCTOR ret = lookupMember(member, getDeclaredMethods()); } return ret; } /** * This lookup has specialized behaviour - a null result tells the EclipseTypeMunger that it should make a default * implementation of a method on this type. * * @param member * @return */ public ResolvedMember lookupMemberIncludingITDsOnInterfaces(Member member) { return lookupMemberIncludingITDsOnInterfaces(member, this); } private ResolvedMember lookupMemberIncludingITDsOnInterfaces(Member member, ResolvedType onType) { ResolvedMember ret = onType.lookupMemberNoSupers(member); if (ret != null) { return ret; } else { ResolvedType superType = onType.getSuperclass(); if (superType != null) { ret = lookupMemberIncludingITDsOnInterfaces(member, superType); } if (ret == null) { // try interfaces then, but only ITDs now... ResolvedType[] superInterfaces = onType.getDeclaredInterfaces(); for (int i = 0; i < superInterfaces.length; i++) { ret = superInterfaces[i].lookupMethodInITDs(member); if (ret != null) { return ret; } } } } return ret; } protected List<ConcreteTypeMunger> interTypeMungers = new ArrayList<ConcreteTypeMunger>(); public List<ConcreteTypeMunger> getInterTypeMungers() { return interTypeMungers; } public List<ConcreteTypeMunger> getInterTypeParentMungers() { List<ConcreteTypeMunger> l = new ArrayList<ConcreteTypeMunger>(); for (ConcreteTypeMunger element : interTypeMungers) { if (element.getMunger() instanceof NewParentTypeMunger) { l.add(element); } } return l; } /** * ??? This method is O(N*M) where N = number of methods and M is number of inter-type declarations in my super */ public List<ConcreteTypeMunger> getInterTypeMungersIncludingSupers() { ArrayList<ConcreteTypeMunger> ret = new ArrayList<ConcreteTypeMunger>(); collectInterTypeMungers(ret); return ret; } public List<ConcreteTypeMunger> getInterTypeParentMungersIncludingSupers() { ArrayList<ConcreteTypeMunger> ret = new ArrayList<ConcreteTypeMunger>(); collectInterTypeParentMungers(ret); return ret; } private void collectInterTypeParentMungers(List<ConcreteTypeMunger> collector) { for (Iterator<ResolvedType> iter = getDirectSupertypes(); iter.hasNext();) { ResolvedType superType = iter.next(); superType.collectInterTypeParentMungers(collector); } collector.addAll(getInterTypeParentMungers()); } protected void collectInterTypeMungers(List<ConcreteTypeMunger> collector) { for (Iterator<ResolvedType> iter = getDirectSupertypes(); iter.hasNext();) { ResolvedType superType = iter.next(); if (superType == null) { throw new BCException("UnexpectedProblem: a supertype in the hierarchy for " + this.getName() + " is null"); } superType.collectInterTypeMungers(collector); } outer: for (Iterator<ConcreteTypeMunger> iter1 = collector.iterator(); iter1.hasNext();) { ConcreteTypeMunger superMunger = iter1.next(); if (superMunger.getSignature() == null) { continue; } if (!superMunger.getSignature().isAbstract()) { continue; } for (ConcreteTypeMunger myMunger : getInterTypeMungers()) { if (conflictingSignature(myMunger.getSignature(), superMunger.getSignature())) { iter1.remove(); continue outer; } } if (!superMunger.getSignature().isPublic()) { continue; } for (Iterator<ResolvedMember> iter = getMethods(true, true); iter.hasNext();) { ResolvedMember method = iter.next(); if (conflictingSignature(method, superMunger.getSignature())) { iter1.remove(); continue outer; } } } collector.addAll(getInterTypeMungers()); } /** * Check: 1) That we don't have any abstract type mungers unless this type is abstract. 2) That an abstract ITDM on an interface * is declared public. (Compiler limitation) (PR70794) */ public void checkInterTypeMungers() { if (isAbstract()) { return; } boolean itdProblem = false; for (ConcreteTypeMunger munger : getInterTypeMungersIncludingSupers()) { itdProblem = checkAbstractDeclaration(munger) || itdProblem; // Rule 2 } if (itdProblem) { return; // If the rules above are broken, return right now } for (ConcreteTypeMunger munger : getInterTypeMungersIncludingSupers()) { if (munger.getSignature() != null && munger.getSignature().isAbstract()) { // Rule 1 if (munger.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate2) { // ignore for @AJ ITD as munger.getSignature() is the // interface method hence abstract } else { world.getMessageHandler() .handleMessage( new Message("must implement abstract inter-type declaration: " + munger.getSignature(), "", IMessage.ERROR, getSourceLocation(), null, new ISourceLocation[] { getMungerLocation(munger) })); } } } } /** * See PR70794. This method checks that if an abstract inter-type method declaration is made on an interface then it must also * be public. This is a compiler limitation that could be made to work in the future (if someone provides a worthwhile usecase) * * @return indicates if the munger failed the check */ private boolean checkAbstractDeclaration(ConcreteTypeMunger munger) { if (munger.getMunger() != null && (munger.getMunger() instanceof NewMethodTypeMunger)) { ResolvedMember itdMember = munger.getSignature(); ResolvedType onType = itdMember.getDeclaringType().resolve(world); if (onType.isInterface() && itdMember.isAbstract() && !itdMember.isPublic()) { world.getMessageHandler().handleMessage( new Message(WeaverMessages.format(WeaverMessages.ITD_ABSTRACT_MUST_BE_PUBLIC_ON_INTERFACE, munger.getSignature(), onType), "", Message.ERROR, getSourceLocation(), null, new ISourceLocation[] { getMungerLocation(munger) })); return true; } } return false; } /** * Get a source location for the munger. Until intertype mungers remember where they came from, the source location for the * munger itself is null. In these cases use the source location for the aspect containing the ITD. */ private ISourceLocation getMungerLocation(ConcreteTypeMunger munger) { ISourceLocation sloc = munger.getSourceLocation(); if (sloc == null) { sloc = munger.getAspectType().getSourceLocation(); } return sloc; } /** * Returns a ResolvedType object representing the declaring type of this type, or null if this type does not represent a * non-package-level-type. * <p/> * <strong>Warning</strong>: This is guaranteed to work for all member types. For anonymous/local types, the only guarantee is * given in JLS 13.1, where it guarantees that if you call getDeclaringType() repeatedly, you will eventually get the top-level * class, but it does not say anything about classes in between. * * @return the declaring UnresolvedType object, or null. */ public ResolvedType getDeclaringType() { if (isArray()) { return null; } String name = getName(); int lastDollar = name.lastIndexOf('$'); while (lastDollar > 0) { // allow for classes starting '$' (pr120474) ResolvedType ret = world.resolve(UnresolvedType.forName(name.substring(0, lastDollar)), true); if (!ResolvedType.isMissing(ret)) { return ret; } lastDollar = name.lastIndexOf('$', lastDollar - 1); } return null; } public static boolean isVisible(int modifiers, ResolvedType targetType, ResolvedType fromType) { // System.err.println("mod: " + modifiers + ", " + targetType + " and " // + fromType); if (Modifier.isPublic(modifiers)) { return true; } else if (Modifier.isPrivate(modifiers)) { return targetType.getOutermostType().equals(fromType.getOutermostType()); } else if (Modifier.isProtected(modifiers)) { return samePackage(targetType, fromType) || targetType.isAssignableFrom(fromType); } else { // package-visible return samePackage(targetType, fromType); } } private static boolean samePackage(ResolvedType targetType, ResolvedType fromType) { String p1 = targetType.getPackageName(); String p2 = fromType.getPackageName(); if (p1 == null) { return p2 == null; } if (p2 == null) { return false; } return p1.equals(p2); } /** * Checks if the generic type for 'this' and the generic type for 'other' are the same - it can be passed raw or parameterized * versions and will just compare the underlying generic type. */ private boolean genericTypeEquals(ResolvedType other) { ResolvedType rt = other; if (rt.isParameterizedType() || rt.isRawType()) { rt.getGenericType(); } if (((isParameterizedType() || isRawType()) && getGenericType().equals(rt)) || (this.equals(other))) { return true; } return false; } /** * Look up the actual occurence of a particular type in the hierarchy for 'this' type. The input is going to be a generic type, * and the caller wants to know if it was used in its RAW or a PARAMETERIZED form in this hierarchy. * * returns null if it can't be found. */ public ResolvedType discoverActualOccurrenceOfTypeInHierarchy(ResolvedType lookingFor) { if (!lookingFor.isGenericType()) { throw new BCException("assertion failed: method should only be called with generic type, but " + lookingFor + " is " + lookingFor.typeKind); } if (this.equals(ResolvedType.OBJECT)) { return null; } if (genericTypeEquals(lookingFor)) { return this; } ResolvedType superT = getSuperclass(); if (superT.genericTypeEquals(lookingFor)) { return superT; } ResolvedType[] superIs = getDeclaredInterfaces(); for (int i = 0; i < superIs.length; i++) { ResolvedType superI = superIs[i]; if (superI.genericTypeEquals(lookingFor)) { return superI; } ResolvedType checkTheSuperI = superI.discoverActualOccurrenceOfTypeInHierarchy(lookingFor); if (checkTheSuperI != null) { return checkTheSuperI; } } return superT.discoverActualOccurrenceOfTypeInHierarchy(lookingFor); } /** * Called for all type mungers but only does something if they share type variables with a generic type which they target. When * this happens this routine will check for the target type in the target hierarchy and 'bind' any type parameters as * appropriate. For example, for the ITD "List<T> I<T>.x" against a type like this: "class A implements I<String>" this routine * will return a parameterized form of the ITD "List<String> I.x" */ public ConcreteTypeMunger fillInAnyTypeParameters(ConcreteTypeMunger munger) { boolean debug = false; ResolvedMember member = munger.getSignature(); if (munger.isTargetTypeParameterized()) { if (debug) { System.err.println("Processing attempted parameterization of " + munger + " targetting type " + this); } if (debug) { System.err.println(" This type is " + this + " (" + typeKind + ")"); } // need to tailor this munger instance for the particular target... if (debug) { System.err.println(" Signature that needs parameterizing: " + member); } // Retrieve the generic type ResolvedType onTypeResolved = world.resolve(member.getDeclaringType()); ResolvedType onType = onTypeResolved.getGenericType(); if (onType == null) { // The target is not generic getWorld().getMessageHandler().handleMessage( MessageUtil.error("The target type for the intertype declaration is not generic", munger.getSourceLocation())); return munger; } member.resolve(world); // Ensure all parts of the member are resolved if (debug) { System.err.println(" Actual target ontype: " + onType + " (" + onType.typeKind + ")"); } // quickly find the targettype in the type hierarchy for this type // (it will be either RAW or PARAMETERIZED) ResolvedType actualTarget = discoverActualOccurrenceOfTypeInHierarchy(onType); if (actualTarget == null) { throw new BCException("assertion failed: asked " + this + " for occurrence of " + onType + " in its hierarchy??"); } // only bind the tvars if its a parameterized type or the raw type // (in which case they collapse to bounds) - don't do it // for generic types ;) if (!actualTarget.isGenericType()) { if (debug) { System.err.println("Occurrence in " + this + " is actually " + actualTarget + " (" + actualTarget.typeKind + ")"); // parameterize the signature // ResolvedMember newOne = // member.parameterizedWith(actualTarget.getTypeParameters(), // onType,actualTarget.isParameterizedType()); } } // if (!actualTarget.isRawType()) munger = munger.parameterizedFor(actualTarget); if (debug) { System.err.println("New sig: " + munger.getSignature()); } if (debug) { System.err.println("====================================="); } } return munger; } /** * Add an intertype munger to this type. isDuringCompilation tells us if we should be checking for an error scenario where two * ITD fields are trying to use the same name. When this happens during compilation one of them is altered to get mangled name * but when it happens during weaving it is too late and we need to put out an error asking them to recompile. */ public void addInterTypeMunger(ConcreteTypeMunger munger, boolean isDuringCompilation) { ResolvedMember sig = munger.getSignature(); bits = (bits & ~MungersAnalyzed); // clear the bit - as the mungers have changed if (sig == null || munger.getMunger() == null || munger.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess) { interTypeMungers.add(munger); return; } // ConcreteTypeMunger originalMunger = munger; // we will use the 'parameterized' ITD for all the comparisons but we // say the original // one passed in actually matched as it will be added to the intertype // member finder // for the target type. It is possible we only want to do this if a // generic type // is discovered and the tvar is collapsed to a bound? munger = fillInAnyTypeParameters(munger); sig = munger.getSignature(); // possibly changed when type parms filled in if (sig.getKind() == Member.METHOD) { // OPTIMIZE can this be sped up? if (clashesWithExistingMember(munger, getMethods(true, false))) { // ITDs checked below return; } if (this.isInterface()) { // OPTIMIZE this set of methods are always the same - must we keep creating them as a list? if (clashesWithExistingMember(munger, Arrays.asList(world.getCoreType(OBJECT).getDeclaredMethods()).iterator())) { return; } } } else if (sig.getKind() == Member.FIELD) { if (clashesWithExistingMember(munger, Arrays.asList(getDeclaredFields()).iterator())) { return; } // Cannot cope with two version '2' style mungers for the same field on the same type // Must error and request the user recompile at least one aspect with the // -Xset:itdStyle=1 option if (!isDuringCompilation) { ResolvedTypeMunger thisRealMunger = munger.getMunger(); if (thisRealMunger instanceof NewFieldTypeMunger) { NewFieldTypeMunger newFieldTypeMunger = (NewFieldTypeMunger) thisRealMunger; if (newFieldTypeMunger.version == NewFieldTypeMunger.VersionTwo) { String thisRealMungerSignatureName = newFieldTypeMunger.getSignature().getName(); for (ConcreteTypeMunger typeMunger : interTypeMungers) { if (typeMunger.getMunger() instanceof NewFieldTypeMunger) { if (typeMunger.getSignature().getKind() == Member.FIELD) { NewFieldTypeMunger existing = (NewFieldTypeMunger) typeMunger.getMunger(); if (existing.getSignature().getName().equals(thisRealMungerSignatureName) && existing.version == NewFieldTypeMunger.VersionTwo // this check ensures no problem for a clash with an ITD on an interface && existing.getSignature().getDeclaringType() .equals(newFieldTypeMunger.getSignature().getDeclaringType())) { // report error on the aspect StringBuffer sb = new StringBuffer(); sb.append("Cannot handle two aspects both attempting to use new style ITDs for the same named field "); sb.append("on the same target type. Please recompile at least one aspect with '-Xset:itdVersion=1'."); sb.append(" Aspects involved: " + munger.getAspectType().getName() + " and " + typeMunger.getAspectType().getName() + "."); sb.append(" Field is named '" + existing.getSignature().getName() + "'"); getWorld().getMessageHandler().handleMessage( new Message(sb.toString(), getSourceLocation(), true)); return; } } } } } } } } else { if (clashesWithExistingMember(munger, Arrays.asList(getDeclaredMethods()).iterator())) { return; } } // now compare to existingMungers for (Iterator<ConcreteTypeMunger> i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger existingMunger = i.next(); if (conflictingSignature(existingMunger.getSignature(), munger.getSignature())) { // System.err.println("match " + munger + " with " + // existingMunger); if (isVisible(munger.getSignature().getModifiers(), munger.getAspectType(), existingMunger.getAspectType())) { // System.err.println(" is visible"); int c = compareMemberPrecedence(sig, existingMunger.getSignature()); if (c == 0) { c = getWorld().compareByPrecedenceAndHierarchy(munger.getAspectType(), existingMunger.getAspectType()); } // System.err.println(" compare: " + c); if (c < 0) { // the existing munger dominates the new munger checkLegalOverride(munger.getSignature(), existingMunger.getSignature(), 0x11, null); return; } else if (c > 0) { // the new munger dominates the existing one checkLegalOverride(existingMunger.getSignature(), munger.getSignature(), 0x11, null); i.remove(); break; } else { interTypeConflictError(munger, existingMunger); interTypeConflictError(existingMunger, munger); return; } } } } // System.err.println("adding: " + munger + " to " + this); // we are adding the parameterized form of the ITD to the list of // mungers. Within it, the munger knows the original declared // signature for the ITD so it can be retrieved. interTypeMungers.add(munger); } /** * Compare the type transformer with the existing members. A clash may not be an error (the ITD may be the 'default * implementation') so returning false is not always a sign of an error. * * @return true if there is a clash */ private boolean clashesWithExistingMember(ConcreteTypeMunger typeTransformer, Iterator<ResolvedMember> existingMembers) { ResolvedMember typeTransformerSignature = typeTransformer.getSignature(); // ResolvedType declaringAspectType = munger.getAspectType(); // if (declaringAspectType.isRawType()) declaringAspectType = // declaringAspectType.getGenericType(); // if (declaringAspectType.isGenericType()) { // // ResolvedType genericOnType = // getWorld().resolve(sig.getDeclaringType()).getGenericType(); // ConcreteTypeMunger ctm = // munger.parameterizedFor(discoverActualOccurrenceOfTypeInHierarchy // (genericOnType)); // sig = ctm.getSignature(); // possible sig change when type // } // if (munger.getMunger().hasTypeVariableAliases()) { // ResolvedType genericOnType = // getWorld().resolve(sig.getDeclaringType()).getGenericType(); // ConcreteTypeMunger ctm = // munger.parameterizedFor(discoverActualOccurrenceOfTypeInHierarchy( // genericOnType)); // sig = ctm.getSignature(); // possible sig change when type parameters // filled in // } while (existingMembers.hasNext()) { ResolvedMember existingMember = existingMembers.next(); // don't worry about clashing with bridge methods if (existingMember.isBridgeMethod()) { continue; } if (conflictingSignature(existingMember, typeTransformerSignature)) { // System.err.println("conflict: existingMember=" + // existingMember + " typeMunger=" + munger); // System.err.println(munger.getSourceLocation() + ", " + // munger.getSignature() + ", " + // munger.getSignature().getSourceLocation()); if (isVisible(existingMember.getModifiers(), this, typeTransformer.getAspectType())) { int c = compareMemberPrecedence(typeTransformerSignature, existingMember); // System.err.println(" c: " + c); if (c < 0) { // existingMember dominates munger checkLegalOverride(typeTransformerSignature, existingMember, 0x10, typeTransformer.getAspectType()); return true; } else if (c > 0) { // munger dominates existingMember checkLegalOverride(existingMember, typeTransformerSignature, 0x01, typeTransformer.getAspectType()); // interTypeMungers.add(munger); // ??? might need list of these overridden abstracts continue; } else { // bridge methods can differ solely in return type. // FIXME this whole method seems very hokey - unaware of covariance/varargs/bridging - it // could do with a rewrite ! boolean sameReturnTypes = (existingMember.getReturnType().equals(typeTransformerSignature.getReturnType())); if (sameReturnTypes) { // pr206732 - if the existingMember is due to a // previous application of this same ITD (which can // happen if this is a binary type being brought in // from the aspectpath). The 'better' fix is // to recognize it is from the aspectpath at a // higher level and dont do this, but that is rather // more work. boolean isDuplicateOfPreviousITD = false; ResolvedType declaringRt = existingMember.getDeclaringType().resolve(world); WeaverStateInfo wsi = declaringRt.getWeaverState(); if (wsi != null) { List<ConcreteTypeMunger> mungersAffectingThisType = wsi.getTypeMungers(declaringRt); if (mungersAffectingThisType != null) { for (Iterator<ConcreteTypeMunger> iterator = mungersAffectingThisType.iterator(); iterator .hasNext() && !isDuplicateOfPreviousITD;) { ConcreteTypeMunger ctMunger = iterator.next(); // relatively crude check - is the ITD // for the same as the existingmember // and does it come // from the same aspect if (ctMunger.getSignature().equals(existingMember) && ctMunger.aspectType.equals(typeTransformer.getAspectType())) { isDuplicateOfPreviousITD = true; } } } } if (!isDuplicateOfPreviousITD) { // b275032 - this is OK if it is the default ctor and that default ctor was generated // at compile time, otherwise we cannot overwrite it if (!(typeTransformerSignature.getName().equals("<init>") && existingMember.isDefaultConstructor())) { String aspectName = typeTransformer.getAspectType().getName(); ISourceLocation typeTransformerLocation = typeTransformer.getSourceLocation(); ISourceLocation existingMemberLocation = existingMember.getSourceLocation(); String msg = WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT, aspectName, existingMember); // this isn't quite right really... as I think the errors should only be recorded against // what is currently being processed or they may get lost or reported twice // report error on the aspect getWorld().getMessageHandler().handleMessage(new Message(msg, typeTransformerLocation, true)); // report error on the affected type, if we can if (existingMemberLocation != null) { getWorld().getMessageHandler() .handleMessage(new Message(msg, existingMemberLocation, true)); } return true; // clash - so ignore this itd } } } } } else if (isDuplicateMemberWithinTargetType(existingMember, this, typeTransformerSignature)) { getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT, typeTransformer .getAspectType().getName(), existingMember), typeTransformer.getSourceLocation())); return true; } } } return false; } // we know that the member signature matches, but that the member in the // target type is not visible to the aspect. // this may still be disallowed if it would result in two members within the // same declaring type with the same // signature AND more than one of them is concrete AND they are both visible // within the target type. private boolean isDuplicateMemberWithinTargetType(ResolvedMember existingMember, ResolvedType targetType, ResolvedMember itdMember) { if ((existingMember.isAbstract() || itdMember.isAbstract())) { return false; } UnresolvedType declaringType = existingMember.getDeclaringType(); if (!targetType.equals(declaringType)) { return false; } // now have to test that itdMember is visible from targetType if (Modifier.isPrivate(itdMember.getModifiers())) { return false; } if (itdMember.isPublic()) { return true; } // must be in same package to be visible then... if (!targetType.getPackageName().equals(itdMember.getDeclaringType().getPackageName())) { return false; } // trying to put two members with the same signature into the exact same // type..., and both visible in that type. return true; } /** * @param transformerPosition which parameter is the type transformer (0x10 for first, 0x01 for second, 0x11 for both, 0x00 for * neither) * @param aspectType the declaring type of aspect defining the *first* type transformer * @return true if the override is legal note: calling showMessage with two locations issues TWO messages, not ONE message with * an additional source location. */ public boolean checkLegalOverride(ResolvedMember parent, ResolvedMember child, int transformerPosition, ResolvedType aspectType) { // System.err.println("check: " + child.getDeclaringType() + // " overrides " + parent.getDeclaringType()); if (Modifier.isFinal(parent.getModifiers())) { // If the ITD matching is occurring due to pulling in a BinaryTypeBinding then this check can incorrectly // signal an error because the ITD transformer being examined here will exactly match the member it added // during the first round of compilation. This situation can only occur if the ITD is on an interface whilst // the class is the top most implementor. If the ITD is on the same type that received it during compilation, // this method won't be called as the previous check for precedence level will return 0. if (transformerPosition == 0x10 && aspectType != null) { ResolvedType nonItdDeclaringType = child.getDeclaringType().resolve(world); WeaverStateInfo wsi = nonItdDeclaringType.getWeaverState(); if (wsi != null) { List<ConcreteTypeMunger> transformersOnThisType = wsi.getTypeMungers(nonItdDeclaringType); if (transformersOnThisType != null) { for (ConcreteTypeMunger transformer : transformersOnThisType) { // relatively crude check - is the ITD // for the same as the existingmember // and does it come // from the same aspect if (transformer.aspectType.equals(aspectType)) { if (parent.equalsApartFromDeclaringType(transformer.getSignature())) { return true; } } } } } } world.showMessage(Message.ERROR, WeaverMessages.format(WeaverMessages.CANT_OVERRIDE_FINAL_MEMBER, parent), child.getSourceLocation(), null); return false; } boolean incompatibleReturnTypes = false; // In 1.5 mode, allow for covariance on return type if (world.isInJava5Mode() && parent.getKind() == Member.METHOD) { // Look at the generic types when doing this comparison ResolvedType rtParentReturnType = parent.resolve(world).getGenericReturnType().resolve(world); ResolvedType rtChildReturnType = child.resolve(world).getGenericReturnType().resolve(world); incompatibleReturnTypes = !rtParentReturnType.isAssignableFrom(rtChildReturnType); // For debug, uncomment this bit and we'll repeat the check - stick // a breakpoint on the call // if (incompatibleReturnTypes) { // incompatibleReturnTypes = // !rtParentReturnType.isAssignableFrom(rtChildReturnType); // } } else { incompatibleReturnTypes = !parent.getReturnType().equals(child.getReturnType()); } if (incompatibleReturnTypes) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_RETURN_TYPE_MISMATCH, parent, child), child.getSourceLocation(), parent.getSourceLocation()); return false; } if (parent.getKind() == Member.POINTCUT) { UnresolvedType[] pTypes = parent.getParameterTypes(); UnresolvedType[] cTypes = child.getParameterTypes(); if (!Arrays.equals(pTypes, cTypes)) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_PARAM_TYPE_MISMATCH, parent, child), child.getSourceLocation(), parent.getSourceLocation()); return false; } } // System.err.println("check: " + child.getModifiers() + // " more visible " + parent.getModifiers()); if (isMoreVisible(parent.getModifiers(), child.getModifiers())) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_VISIBILITY_REDUCTION, parent, child), child.getSourceLocation(), parent.getSourceLocation()); return false; } // check declared exceptions ResolvedType[] childExceptions = world.resolve(child.getExceptions()); ResolvedType[] parentExceptions = world.resolve(parent.getExceptions()); ResolvedType runtimeException = world.resolve("java.lang.RuntimeException"); ResolvedType error = world.resolve("java.lang.Error"); outer: for (int i = 0, leni = childExceptions.length; i < leni; i++) { // System.err.println("checking: " + childExceptions[i]); if (runtimeException.isAssignableFrom(childExceptions[i])) { continue; } if (error.isAssignableFrom(childExceptions[i])) { continue; } for (int j = 0, lenj = parentExceptions.length; j < lenj; j++) { if (parentExceptions[j].isAssignableFrom(childExceptions[i])) { continue outer; } } // this message is now better handled my MethodVerifier in JDT core. // world.showMessage(IMessage.ERROR, // WeaverMessages.format(WeaverMessages.ITD_DOESNT_THROW, // childExceptions[i].getName()), // child.getSourceLocation(), null); return false; } boolean parentStatic = Modifier.isStatic(parent.getModifiers()); boolean childStatic = Modifier.isStatic(child.getModifiers()); if (parentStatic && !childStatic) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_OVERRIDDEN_STATIC, child, parent), child.getSourceLocation(), null); return false; } else if (childStatic && !parentStatic) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_OVERIDDING_STATIC, child, parent), child.getSourceLocation(), null); return false; } return true; } private int compareMemberPrecedence(ResolvedMember m1, ResolvedMember m2) { // if (!m1.getReturnType().equals(m2.getReturnType())) return 0; // need to allow for the special case of 'clone' - which is like // abstract but is // not marked abstract. The code below this next line seems to make // assumptions // about what will have gotten through the compiler based on the normal // java rules. clone goes against these... if (Modifier.isProtected(m2.getModifiers()) && m2.getName().charAt(0) == 'c') { UnresolvedType declaring = m2.getDeclaringType(); if (declaring != null) { if (declaring.getName().equals("java.lang.Object") && m2.getName().equals("clone")) { return +1; } } } if (Modifier.isAbstract(m1.getModifiers())) { return -1; } if (Modifier.isAbstract(m2.getModifiers())) { return +1; } if (m1.getDeclaringType().equals(m2.getDeclaringType())) { return 0; } ResolvedType t1 = m1.getDeclaringType().resolve(world); ResolvedType t2 = m2.getDeclaringType().resolve(world); if (t1.isAssignableFrom(t2)) { return -1; } if (t2.isAssignableFrom(t1)) { return +1; } return 0; } public static boolean isMoreVisible(int m1, int m2) { if (Modifier.isPrivate(m1)) { return false; } if (isPackage(m1)) { return Modifier.isPrivate(m2); } if (Modifier.isProtected(m1)) { return /* private package */(Modifier.isPrivate(m2) || isPackage(m2)); } if (Modifier.isPublic(m1)) { return /* private package protected */!Modifier.isPublic(m2); } throw new RuntimeException("bad modifier: " + m1); } private static boolean isPackage(int i) { return (0 == (i & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED))); } private void interTypeConflictError(ConcreteTypeMunger m1, ConcreteTypeMunger m2) { // XXX this works only if we ignore separate compilation issues // XXX dual errors possible if (this instanceof BcelObjectType) return; /* * if (m1.getMunger().getKind() == ResolvedTypeMunger.Field && m2.getMunger().getKind() == ResolvedTypeMunger.Field) { // if * *exactly* the same, it's ok return true; } */ // System.err.println("conflict at " + m2.getSourceLocation()); getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_CONFLICT, m1.getAspectType().getName(), m2.getSignature(), m2 .getAspectType().getName()), m2.getSourceLocation(), getSourceLocation()); // return false; } public ResolvedMember lookupSyntheticMember(Member member) { // ??? horribly inefficient // for (Iterator i = // System.err.println("lookup " + member + " in " + interTypeMungers); for (ConcreteTypeMunger m : interTypeMungers) { ResolvedMember ret = m.getMatchingSyntheticMember(member); if (ret != null) { // System.err.println(" found: " + ret); return ret; } } // Handling members for the new array join point if (world.isJoinpointArrayConstructionEnabled() && this.isArray()) { if (member.getKind() == Member.CONSTRUCTOR) { ResolvedMemberImpl ret = new ResolvedMemberImpl(Member.CONSTRUCTOR, this, Modifier.PUBLIC, UnresolvedType.VOID, "<init>", world.resolve(member.getParameterTypes())); // Give the parameters names - they are going to be the dimensions uses to build the array (dim0 > dimN) int count = ret.getParameterTypes().length; String[] paramNames = new String[count]; for (int i = 0; i < count; i++) { paramNames[i] = new StringBuffer("dim").append(i).toString(); } ret.setParameterNames(paramNames); return ret; } } // if (this.getSuperclass() != ResolvedType.OBJECT && // this.getSuperclass() != null) { // return getSuperclass().lookupSyntheticMember(member); // } return null; } static class SuperClassWalker implements Iterator<ResolvedType> { private ResolvedType curr; private SuperInterfaceWalker iwalker; private boolean wantGenerics; public SuperClassWalker(ResolvedType type, SuperInterfaceWalker iwalker, boolean genericsAware) { this.curr = type; this.iwalker = iwalker; this.wantGenerics = genericsAware; } public boolean hasNext() { return curr != null; } public ResolvedType next() { ResolvedType ret = curr; if (!wantGenerics && ret.isParameterizedOrGenericType()) { ret = ret.getRawType(); } iwalker.push(ret); // tell the interface walker about another class whose interfaces need visiting curr = curr.getSuperclass(); return ret; } public void remove() { throw new UnsupportedOperationException(); } } static class SuperInterfaceWalker implements Iterator<ResolvedType> { private Getter<ResolvedType, ResolvedType> ifaceGetter; Iterator<ResolvedType> delegate = null; public Queue<ResolvedType> toPersue = new LinkedList<ResolvedType>(); public Set<ResolvedType> visited = new HashSet<ResolvedType>(); SuperInterfaceWalker(Iterators.Getter<ResolvedType, ResolvedType> ifaceGetter) { this.ifaceGetter = ifaceGetter; } SuperInterfaceWalker(Iterators.Getter<ResolvedType, ResolvedType> ifaceGetter, ResolvedType interfaceType) { this.ifaceGetter = ifaceGetter; this.delegate = Iterators.one(interfaceType); } public boolean hasNext() { if (delegate == null || !delegate.hasNext()) { // either we set it up or we have run out, is there anything else to look at? if (toPersue.isEmpty()) { return false; } do { ResolvedType next = toPersue.remove(); visited.add(next); delegate = ifaceGetter.get(next); // retrieve interfaces from a class or another interface } while (!delegate.hasNext() && !toPersue.isEmpty()); } return delegate.hasNext(); } public void push(ResolvedType ret) { toPersue.add(ret); } public ResolvedType next() { ResolvedType next = delegate.next(); // BUG should check for generics and erase? // if (!visited.contains(next)) { // visited.add(next); if (visited.add(next)) { toPersue.add(next); // pushes on interfaces already visited? } return next; } public void remove() { throw new UnsupportedOperationException(); } } public void clearInterTypeMungers() { if (isRawType()) { ResolvedType genericType = getGenericType(); if (genericType.isRawType()) { // ERROR SITUATION: PR341926 // For some reason the raw type is pointing to another raw form (possibly itself) System.err.println("DebugFor341926: Type " + this.getName() + " has an incorrect generic form"); } else { genericType.clearInterTypeMungers(); } } // interTypeMungers.clear(); // BUG? Why can't this be clear() instead: 293620 c6 interTypeMungers = new ArrayList<ConcreteTypeMunger>(); } public boolean isTopmostImplementor(ResolvedType interfaceType) { boolean b = true; if (isInterface()) { b = false; } else if (!interfaceType.isAssignableFrom(this, true)) { b = false; } else { ResolvedType superclass = this.getSuperclass(); if (superclass.isMissing()) { b = true; // we don't know anything about supertype, and it can't be exposed to weaver } else if (interfaceType.isAssignableFrom(superclass, true)) { // check that I'm truly the topmost implementor b = false; } } // System.out.println("is " + getName() + " topmostimplementor of " + interfaceType + "? " + b); return b; } public ResolvedType getTopmostImplementor(ResolvedType interfaceType) { if (isInterface()) { return null; } if (!interfaceType.isAssignableFrom(this)) { return null; } // Check if my super class is an implementor? ResolvedType higherType = this.getSuperclass().getTopmostImplementor(interfaceType); if (higherType != null) { return higherType; } return this; } public List<ResolvedMember> getExposedPointcuts() { List<ResolvedMember> ret = new ArrayList<ResolvedMember>(); if (getSuperclass() != null) { ret.addAll(getSuperclass().getExposedPointcuts()); } for (ResolvedType type : getDeclaredInterfaces()) { addPointcutsResolvingConflicts(ret, Arrays.asList(type.getDeclaredPointcuts()), false); } addPointcutsResolvingConflicts(ret, Arrays.asList(getDeclaredPointcuts()), true); for (ResolvedMember member : ret) { ResolvedPointcutDefinition inherited = (ResolvedPointcutDefinition) member; if (inherited != null && inherited.isAbstract()) { if (!this.isAbstract()) { getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.POINCUT_NOT_CONCRETE, inherited, this.getName()), inherited.getSourceLocation(), this.getSourceLocation()); } } } return ret; } private void addPointcutsResolvingConflicts(List<ResolvedMember> acc, List<ResolvedMember> added, boolean isOverriding) { for (Iterator<ResolvedMember> i = added.iterator(); i.hasNext();) { ResolvedPointcutDefinition toAdd = (ResolvedPointcutDefinition) i.next(); for (Iterator<ResolvedMember> j = acc.iterator(); j.hasNext();) { ResolvedPointcutDefinition existing = (ResolvedPointcutDefinition) j.next(); if (toAdd == null || existing == null || existing == toAdd) { continue; } UnresolvedType pointcutDeclaringTypeUT = existing.getDeclaringType(); if (pointcutDeclaringTypeUT != null) { ResolvedType pointcutDeclaringType = pointcutDeclaringTypeUT.resolve(getWorld()); if (!isVisible(existing.getModifiers(), pointcutDeclaringType, this)) { // if they intended to override it but it is not visible, // give them a nicer message if (existing.isAbstract() && conflictingSignature(existing, toAdd)) { getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.POINTCUT_NOT_VISIBLE, existing.getDeclaringType() .getName() + "." + existing.getName() + "()", this.getName()), toAdd.getSourceLocation(), null); j.remove(); } continue; } } if (conflictingSignature(existing, toAdd)) { if (isOverriding) { checkLegalOverride(existing, toAdd, 0x00, null); j.remove(); } else { getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.CONFLICTING_INHERITED_POINTCUTS, this.getName() + toAdd.getSignature()), existing.getSourceLocation(), toAdd.getSourceLocation()); j.remove(); } } } acc.add(toAdd); } } public ISourceLocation getSourceLocation() { return null; } public boolean isExposedToWeaver() { return false; } public WeaverStateInfo getWeaverState() { return null; } /** * Overridden by ReferenceType to return a sensible answer for parameterized and raw types. * * @return */ public ReferenceType getGenericType() { // if (!(isParameterizedType() || isRawType())) // throw new BCException("The type " + getBaseName() + " is not parameterized or raw - it has no generic type"); return null; } @Override public ResolvedType getRawType() { return super.getRawType().resolve(world); } public ResolvedType parameterizedWith(UnresolvedType[] typeParameters) { if (!(isGenericType() || isParameterizedType())) { return this; } return TypeFactory.createParameterizedType(this.getGenericType(), typeParameters, getWorld()); } /** * Iff I am a parameterized type, and any of my parameters are type variable references, return a version with those type * parameters replaced in accordance with the passed bindings. */ @Override public UnresolvedType parameterize(Map<String, UnresolvedType> typeBindings) { if (!isParameterizedType()) { return this;// throw new IllegalStateException( } // "Can't parameterize a type that is not a parameterized type" // ); boolean workToDo = false; for (int i = 0; i < typeParameters.length; i++) { if (typeParameters[i].isTypeVariableReference() || (typeParameters[i] instanceof BoundedReferenceType)) { workToDo = true; } } if (!workToDo) { return this; } else { UnresolvedType[] newTypeParams = new UnresolvedType[typeParameters.length]; for (int i = 0; i < newTypeParams.length; i++) { newTypeParams[i] = typeParameters[i]; if (newTypeParams[i].isTypeVariableReference()) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) newTypeParams[i]; UnresolvedType binding = typeBindings.get(tvrt.getTypeVariable().getName()); if (binding != null) { newTypeParams[i] = binding; } } else if (newTypeParams[i] instanceof BoundedReferenceType) { BoundedReferenceType brType = (BoundedReferenceType) newTypeParams[i]; newTypeParams[i] = brType.parameterize(typeBindings); // brType.parameterize(typeBindings) } } return TypeFactory.createParameterizedType(getGenericType(), newTypeParams, getWorld()); } } // public boolean hasParameterizedSuperType() { // getParameterizedSuperTypes(); // return parameterizedSuperTypes.length > 0; // } // public boolean hasGenericSuperType() { // ResolvedType[] superTypes = getDeclaredInterfaces(); // for (int i = 0; i < superTypes.length; i++) { // if (superTypes[i].isGenericType()) // return true; // } // return false; // } // private ResolvedType[] parameterizedSuperTypes = null; /** * Similar to the above method, but accumulates the super types * * @return */ // public ResolvedType[] getParameterizedSuperTypes() { // if (parameterizedSuperTypes != null) // return parameterizedSuperTypes; // List accumulatedTypes = new ArrayList(); // accumulateParameterizedSuperTypes(this, accumulatedTypes); // ResolvedType[] ret = new ResolvedType[accumulatedTypes.size()]; // parameterizedSuperTypes = (ResolvedType[]) accumulatedTypes.toArray(ret); // return parameterizedSuperTypes; // } // private void accumulateParameterizedSuperTypes(ResolvedType forType, List // parameterizedTypeList) { // if (forType.isParameterizedType()) { // parameterizedTypeList.add(forType); // } // if (forType.getSuperclass() != null) { // accumulateParameterizedSuperTypes(forType.getSuperclass(), // parameterizedTypeList); // } // ResolvedType[] interfaces = forType.getDeclaredInterfaces(); // for (int i = 0; i < interfaces.length; i++) { // accumulateParameterizedSuperTypes(interfaces[i], parameterizedTypeList); // } // } /** * @return true if assignable to java.lang.Exception */ public boolean isException() { return (world.getCoreType(UnresolvedType.JL_EXCEPTION).isAssignableFrom(this)); } /** * @return true if it is an exception and it is a checked one, false otherwise. */ public boolean isCheckedException() { if (!isException()) { return false; } if (world.getCoreType(UnresolvedType.RUNTIME_EXCEPTION).isAssignableFrom(this)) { return false; } return true; } /** * Determines if variables of this type could be assigned values of another with lots of help. java.lang.Object is convertable * from all types. A primitive type is convertable from X iff it's assignable from X. A reference type is convertable from X iff * it's coerceable from X. In other words, X isConvertableFrom Y iff the compiler thinks that _some_ value of Y could be * assignable to a variable of type X without loss of precision. * * @param other the other type * @param world the {@link World} in which the possible assignment should be checked. * @return true iff variables of this type could be assigned values of other with possible conversion */ public final boolean isConvertableFrom(ResolvedType other) { // // version from TypeX // if (this.equals(OBJECT)) return true; // if (this.isPrimitiveType() || other.isPrimitiveType()) return // this.isAssignableFrom(other); // return this.isCoerceableFrom(other); // // version from ResolvedTypeX if (this.equals(OBJECT)) { return true; } if (world.isInJava5Mode()) { if (this.isPrimitiveType() ^ other.isPrimitiveType()) { // If one is // primitive // and the // other // isnt if (validBoxing.contains(this.getSignature() + other.getSignature())) { return true; } } } if (this.isPrimitiveType() || other.isPrimitiveType()) { return this.isAssignableFrom(other); } return this.isCoerceableFrom(other); } /** * Determines if the variables of this type could be assigned values of another type without casting. This still allows for * assignment conversion as per JLS 2ed 5.2. For object types, this means supertypeOrEqual(THIS, OTHER). * * @param other the other type * @param world the {@link World} in which the possible assignment should be checked. * @return true iff variables of this type could be assigned values of other without casting * @throws NullPointerException if other is null */ public abstract boolean isAssignableFrom(ResolvedType other); public abstract boolean isAssignableFrom(ResolvedType other, boolean allowMissing); /** * Determines if values of another type could possibly be cast to this type. The rules followed are from JLS 2ed 5.5, * "Casting Conversion". * <p/> * <p> * This method should be commutative, i.e., for all UnresolvedType a, b and all World w: * <p/> * <blockquote> * * <pre> * a.isCoerceableFrom(b, w) == b.isCoerceableFrom(a, w) * </pre> * * </blockquote> * * @param other the other type * @param world the {@link World} in which the possible coersion should be checked. * @return true iff values of other could possibly be cast to this type. * @throws NullPointerException if other is null. */ public abstract boolean isCoerceableFrom(ResolvedType other); public boolean needsNoConversionFrom(ResolvedType o) { return isAssignableFrom(o); } public String getSignatureForAttribute() { return signature; // Assume if this is being called that it is for a // simple type (eg. void, int, etc) } private FuzzyBoolean parameterizedWithTypeVariable = FuzzyBoolean.MAYBE; /** * return true if the parameterization of this type includes a member type variable. Member type variables occur in generic * methods/ctors. */ public boolean isParameterizedWithTypeVariable() { // MAYBE means we haven't worked it out yet... if (parameterizedWithTypeVariable == FuzzyBoolean.MAYBE) { // if there are no type parameters then we cant be... if (typeParameters == null || typeParameters.length == 0) { parameterizedWithTypeVariable = FuzzyBoolean.NO; return false; } for (int i = 0; i < typeParameters.length; i++) { ResolvedType aType = (ResolvedType) typeParameters[i]; if (aType.isTypeVariableReference() // Changed according to the problems covered in bug 222648 // Don't care what kind of type variable - the fact that there // is one // at all means we can't risk caching it against we get confused // later // by another variation of the parameterization that just // happens to // use the same type variable name // assume the worst - if its definetly not a type declared one, // it could be anything // && ((TypeVariableReference)aType).getTypeVariable(). // getDeclaringElementKind()!=TypeVariable.TYPE ) { parameterizedWithTypeVariable = FuzzyBoolean.YES; return true; } if (aType.isParameterizedType()) { boolean b = aType.isParameterizedWithTypeVariable(); if (b) { parameterizedWithTypeVariable = FuzzyBoolean.YES; return true; } } if (aType.isGenericWildcard()) { BoundedReferenceType boundedRT = (BoundedReferenceType) aType; if (boundedRT.isExtends()) { boolean b = false; UnresolvedType upperBound = boundedRT.getUpperBound(); if (upperBound.isParameterizedType()) { b = ((ResolvedType) upperBound).isParameterizedWithTypeVariable(); } else if (upperBound.isTypeVariableReference() && ((TypeVariableReference) upperBound).getTypeVariable().getDeclaringElementKind() == TypeVariable.METHOD) { b = true; } if (b) { parameterizedWithTypeVariable = FuzzyBoolean.YES; return true; } // FIXME asc need to check additional interface bounds } if (boundedRT.isSuper()) { boolean b = false; UnresolvedType lowerBound = boundedRT.getLowerBound(); if (lowerBound.isParameterizedType()) { b = ((ResolvedType) lowerBound).isParameterizedWithTypeVariable(); } else if (lowerBound.isTypeVariableReference() && ((TypeVariableReference) lowerBound).getTypeVariable().getDeclaringElementKind() == TypeVariable.METHOD) { b = true; } if (b) { parameterizedWithTypeVariable = FuzzyBoolean.YES; return true; } } } } parameterizedWithTypeVariable = FuzzyBoolean.NO; } return parameterizedWithTypeVariable.alwaysTrue(); } protected boolean ajMembersNeedParameterization() { if (isParameterizedType()) { return true; } ResolvedType superclass = getSuperclass(); if (superclass != null && !superclass.isMissing()) { return superclass.ajMembersNeedParameterization(); } return false; } protected Map<String, UnresolvedType> getAjMemberParameterizationMap() { Map<String, UnresolvedType> myMap = getMemberParameterizationMap(); if (myMap.isEmpty()) { // might extend a parameterized aspect that we also need to // consider... if (getSuperclass() != null) { return getSuperclass().getAjMemberParameterizationMap(); } } return myMap; } public void setBinaryPath(String binaryPath) { this.binaryPath = binaryPath; } /** * Returns the path to the jar or class file from which this binary aspect came or null if not a binary aspect */ public String getBinaryPath() { return binaryPath; } /** * Undo any temporary modifications to the type (for example it may be holding annotations temporarily whilst some matching is * occurring - These annotations will be added properly during weaving but sometimes for type completion they need to be held * here for a while). */ public void ensureConsistent() { // Nothing to do for anything except a ReferenceType } /** * For an annotation type, this will return if it is marked with @Inherited */ public boolean isInheritedAnnotation() { ensureAnnotationBitsInitialized(); return (bits & AnnotationMarkedInherited) != 0; } /* * Setup the bitflags if they have not already been done. */ private void ensureAnnotationBitsInitialized() { if ((bits & AnnotationBitsInitialized) == 0) { bits |= AnnotationBitsInitialized; // Is it marked @Inherited? if (hasAnnotation(UnresolvedType.AT_INHERITED)) { bits |= AnnotationMarkedInherited; } } } private boolean hasNewParentMungers() { if ((bits & MungersAnalyzed) == 0) { bits |= MungersAnalyzed; for (ConcreteTypeMunger munger : interTypeMungers) { ResolvedTypeMunger resolvedTypeMunger = munger.getMunger(); if (resolvedTypeMunger != null && resolvedTypeMunger.getKind() == ResolvedTypeMunger.Parent) { bits |= HasParentMunger; } } } return (bits & HasParentMunger) != 0; } public void tagAsTypeHierarchyComplete() { bits |= TypeHierarchyCompleteBit; } public boolean isTypeHierarchyComplete() { return (bits & TypeHierarchyCompleteBit) != 0; } /** * return the weaver version used to build this type - defaults to the most recent version unless discovered otherwise. * * @return the (major) version, {@link WeaverVersionInfo} */ public int getCompilerVersion() { return WeaverVersionInfo.getCurrentWeaverMajorVersion(); } public boolean isPrimitiveArray() { return false; } public boolean isGroovyObject() { if ((bits & GroovyObjectInitialized) == 0) { ResolvedType[] intfaces = getDeclaredInterfaces(); boolean done = false; // TODO do we need to walk more of these? (i.e. the interfaces interfaces and supertypes supertype). Check what groovy // does in the case where a hierarchy is involved and there are types in between GroovyObject/GroovyObjectSupport and // the type if (intfaces != null) { for (ResolvedType intface : intfaces) { if (intface.getName().equals("groovy.lang.GroovyObject")) { bits |= IsGroovyObject; done = true; break; } } } if (!done) { // take a look at the supertype if (getSuperclass().getName().equals("groovy.lang.GroovyObjectSupport")) { bits |= IsGroovyObject; } } bits |= GroovyObjectInitialized; } return (bits & IsGroovyObject) != 0; } }
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/covbug/A.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/covbug/B.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/covbug/SuperA.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/covbug/SuperB.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/covbug/cc/covbug/A.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/covbug/cc/covbug/B.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/covbug/cc/covbug/SuperA.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/covbug/cc/covbug/SuperB.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/covbug/pj/Foo.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/one/A.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/one/B.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/one/SuperA.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/one/SuperB.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/three/A.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/three/B.java