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
timestamp[us, tz=UTC] | report_datetime
timestamp[us, tz=UTC] | updated_file
stringlengths 2
187
| file_content
stringlengths 0
368k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
44,191
|
Bug 44191 Need better error message for "can't find type"
|
I have experienced situations where IAJC outputs a message like this at the end of compilation. [iajc] can't find type org.xxx.SomeTest In my case this was one time highly confusing since I did not expect the class in question to be referred anywhere in the project (I have to date still not located the reference). For such cases, it would be extremely nice if the error message would display WHY it need the class (i.e. the name of the refering class(es) or aspect(es) possibly with a reasonable cutoff as there is seldom need to list all referals). So I would like a message like this: [iajc] can't find type org.xxx.SomeTest referred by org.yyy.SomeClass,org.yy.SomeOtherClass ...
|
resolved fixed
|
061395c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-06T15:04:45Z
| 2003-10-04T23:26:40Z
|
weaver/src/org/aspectj/weaver/patterns/DeclareParents.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.aspectj.bridge.IMessage;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
public class DeclareParents extends Declare {
private TypePattern child;
private TypePatternList parents;
public DeclareParents(TypePattern child, List parents) {
this(child, new TypePatternList(parents));
}
private DeclareParents(TypePattern child, TypePatternList parents) {
this.child = child;
this.parents = parents;
}
public boolean match(ResolvedTypeX typeX) {
if (!child.matchesStatically(typeX)) return false;
if (typeX.getWorld().getLint().typeNotExposedToWeaver.isEnabled() &&
!typeX.isExposedToWeaver())
{
typeX.getWorld().getLint().typeNotExposedToWeaver.signal(typeX.getName(), getSourceLocation());
}
return true;
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("declare parents: ");
buf.append(child);
buf.append(" extends "); //extends and implements are treated equivalently
buf.append(parents);
buf.append(";");
return buf.toString();
}
public boolean equals(Object other) {
if (!(other instanceof DeclareParents)) return false;
DeclareParents o = (DeclareParents)other;
return o.child.equals(child) && o.parents.equals(parents);
}
//??? cache this
public int hashCode() {
int result = 23;
result = 37*result + child.hashCode();
result = 37*result + parents.hashCode();
return result;
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Declare.PARENTS);
child.write(s);
parents.write(s);
writeLocation(s);
}
public static Declare read(DataInputStream s, ISourceContext context) throws IOException {
Declare ret = new DeclareParents(TypePattern.read(s, context), TypePatternList.read(s, context));
ret.readLocation(context, s);
return ret;
}
public void resolve(IScope scope) {
child = child.resolveBindings(scope, Bindings.NONE, false, false);
parents = parents.resolveBindings(scope, Bindings.NONE, false, true);
// for (int i=0; i < parents.size(); i++) {
// parents.get(i).assertExactType(scope.getMessageHandler());
// }
}
public TypePatternList getParents() {
return parents;
}
public TypePattern getChild() {
return child;
}
public boolean isAdviceLike() {
return false;
}
private ResolvedTypeX maybeGetNewParent(ResolvedTypeX targetType, TypePattern typePattern, World world) {
if (typePattern == TypePattern.NO) return null; // already had an error here
TypeX iType = typePattern.getExactType();
ResolvedTypeX parentType = iType.resolve(world);
if (targetType.equals(world.resolve(TypeX.OBJECT))) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.DECP_OBJECT),
this.getSourceLocation(), null);
return null;
}
if (parentType.isAssignableFrom(targetType)) return null; // already a parent
if (targetType.isAssignableFrom(parentType)) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.CANT_EXTEND_SELF,targetType.getName()),
this.getSourceLocation(), null
);
return null;
}
if (parentType.isClass()) {
if (targetType.isInterface()) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.INTERFACE_CANT_EXTEND_CLASS),
this.getSourceLocation(), null
);
return null;
// how to handle xcutting errors???
}
if (!targetType.getSuperclass().isAssignableFrom(parentType)) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.DECP_HIERARCHY_ERROR,
iType.getName(),
targetType.getSuperclass().getName()),
this.getSourceLocation(), null
);
return null;
} else {
return parentType;
}
} else {
return parentType;
}
}
public List/*<ResolvedTypeX>*/ findMatchingNewParents(ResolvedTypeX onType) {
if (!match(onType)) return Collections.EMPTY_LIST;
List ret = new ArrayList();
for (int i=0; i < parents.size(); i++) {
ResolvedTypeX t = maybeGetNewParent(onType, parents.get(i), onType.getWorld());
if (t != null) ret.add(t);
}
return ret;
}
}
|
44,191
|
Bug 44191 Need better error message for "can't find type"
|
I have experienced situations where IAJC outputs a message like this at the end of compilation. [iajc] can't find type org.xxx.SomeTest In my case this was one time highly confusing since I did not expect the class in question to be referred anywhere in the project (I have to date still not located the reference). For such cases, it would be extremely nice if the error message would display WHY it need the class (i.e. the name of the refering class(es) or aspect(es) possibly with a reasonable cutoff as there is seldom need to list all referals). So I would like a message like this: [iajc] can't find type org.xxx.SomeTest referred by org.yyy.SomeClass,org.yy.SomeOtherClass ...
|
resolved fixed
|
061395c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-06T15:04:45Z
| 2003-10-04T23:26:40Z
|
weaver/src/org/aspectj/weaver/patterns/DeclareSoft.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.aspectj.bridge.IMessage;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverMessages;
public class DeclareSoft extends Declare {
private TypePattern exception;
private Pointcut pointcut;
public DeclareSoft(TypePattern exception, Pointcut pointcut) {
this.exception = exception;
this.pointcut = pointcut;
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("declare soft: ");
buf.append(exception);
buf.append(": ");
buf.append(pointcut);
buf.append(";");
return buf.toString();
}
public boolean equals(Object other) {
if (!(other instanceof DeclareSoft)) return false;
DeclareSoft o = (DeclareSoft)other;
return
o.pointcut.equals(pointcut) &&
o.exception.equals(exception);
}
public int hashCode() {
int result = 19;
result = 37*result + pointcut.hashCode();
result = 37*result + exception.hashCode();
return result;
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Declare.SOFT);
exception.write(s);
pointcut.write(s);
writeLocation(s);
}
public static Declare read(DataInputStream s, ISourceContext context) throws IOException {
Declare ret = new DeclareSoft(
TypePattern.read(s, context),
Pointcut.read(s, context)
);
ret.readLocation(context, s);
return ret;
}
public Pointcut getPointcut() {
return pointcut;
}
public TypePattern getException() {
return exception;
}
public void resolve(IScope scope) {
exception = exception.resolveBindings(scope, null, false, true);
TypeX excType = exception.getExactType();
if (excType != ResolvedTypeX.MISSING) {
if (!scope.getWorld().resolve(TypeX.THROWABLE).isAssignableFrom(excType)) {
scope.getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.NOT_THROWABLE,excType.getName()),
exception.getSourceLocation(), null);
pointcut = Pointcut.makeMatchesNothing(Pointcut.RESOLVED);
return;
}
}
pointcut = pointcut.resolve(scope);
}
public boolean isAdviceLike() {
return true;
}
}
|
71,377
|
Bug 71377 Cannot advise private method call in around advice
|
Pointcuts should match call joint points in advice. However AspectJ does not match calls to _private_ methods in around advice. The same applies to get/set pointcuts for _private fields. This is probably because in the testcase below a call to "privateMethod()" in the body of the around advice is a call to an accessor method: ajc$inlineAccessMethod$bug_nnnn_JoinPointInAroundAdvice$bug_nnnn_JoinPointInAro undAdvice$privateMethod("around"); public aspect JoinPointInAroundAdvice { private static Set privateCalls = new HashSet(); private static Set publicCalls = new HashSet(); pointcut internalCall () : call(* JoinPointInAroundAdvice.privateMethod(..)); before () : internalCall () { privateCalls.add(thisJoinPoint); } pointcut externalCall () : call(* JoinPointInAroundAdvice.publicMethod(..)); before () : externalCall () { publicCalls.add(thisJoinPoint); } pointcut execTest () : execution(* JoinPointInAroundAdvice.test()); before () : execTest () { privateMethod("before"); publicMethod("before"); } void around () : execTest () { privateMethod("around"); publicMethod("around"); proceed(); } // void around () : execTest () { // Runnable runnable = new Runnable () { // public void run () { // privateMethod("around closure"); // publicMethod; // proceed(); // } // }; // runnable.run(); // } after () : execTest () { privateMethod("after"); publicMethod("after"); } private static void privateMethod (String from) { System.out.println("? privateMethod() " + from); } public static void publicMethod (String from) { System.out.println("? publicMethod() " + from); } public static void test () { System.out.println("? test()"); privateMethod("test"); publicMethod("test"); } public static void main (String[] args) { test(); if (privateCalls.size() != publicCalls.size()) { throw new RuntimeException("Missing join point"); } else { System.out.println("Success."); } } }
|
resolved fixed
|
851da68
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-09T10:26:53Z
| 2004-08-04T14:33:20Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AspectDeclaration.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import java.lang.reflect.Modifier;
import java.util.*;
import org.aspectj.ajdt.internal.compiler.lookup.*;
import org.aspectj.weaver.*;
import org.aspectj.weaver.patterns.*;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
//import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Clinit;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
//import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.eclipse.jdt.internal.compiler.codegen.Label;
import org.eclipse.jdt.internal.compiler.lookup.*;
//import org.eclipse.jdt.internal.compiler.parser.Parser;
// (we used to...) making all aspects member types avoids a nasty hierarchy pain
// switched from MemberTypeDeclaration to TypeDeclaration
public class AspectDeclaration extends TypeDeclaration {
//public IAjDeclaration[] ajDeclarations;
private AjAttribute.Aspect aspectAttribute;
public PerClause perClause;
public ResolvedMember aspectOfMethod;
public ResolvedMember hasAspectMethod;
public Map accessForInline = new HashMap();
public Map superAccessForInline = new HashMap();
public boolean isPrivileged;
public EclipseSourceType concreteName;
public ResolvedTypeX.Name typeX;
public EclipseFactory factory; //??? should use this consistently
public int adviceCounter = 1; // Used as a part of the generated name for advice methods
// for better error messages in 1.0 to 1.1 transition
public TypePattern dominatesPattern;
public AspectDeclaration(CompilationResult compilationResult) {
super(compilationResult);
//perClause = new PerSingleton();
}
public boolean isAbstract() {
return (modifiers & AccAbstract) != 0;
}
public void resolve() {
if (binding == null) {
ignoreFurtherInvestigation = true;
return;
}
super.resolve();
}
public void checkSpec(ClassScope scope) {
if (ignoreFurtherInvestigation) return;
if (dominatesPattern != null) {
scope.problemReporter().signalError(
dominatesPattern.getStart(), dominatesPattern.getEnd(),
"dominates has changed for 1.1, use 'declare precedence: " +
new String(this.name) + ", " + dominatesPattern.toString() + ";' " +
"in the body of the aspect instead");
}
if (!isAbstract()) {
MethodBinding[] methods = binding.methods();
for (int i=0, len = methods.length; i < len; i++) {
MethodBinding m = methods[i];
if (m.isConstructor()) {
// this make all constructors in aspects invisible and thus uncallable
//XXX this only works for aspects that come from source
methods[i] = new MethodBinding(m, binding) {
public boolean canBeSeenBy(
InvocationSite invocationSite,
Scope scope) {
return false;
}
};
if (m.parameters != null && m.parameters.length != 0) {
scope.problemReporter().signalError(m.sourceStart(), m.sourceEnd(),
"only zero-argument constructors allowed in concrete aspect");
}
}
}
}
if (this.enclosingType != null) {
if (!Modifier.isStatic(modifiers)) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"inner aspects must be static");
ignoreFurtherInvestigation = true;
return;
}
}
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope);
ResolvedTypeX myType = typeX;
//if (myType == null) System.err.println("bad myType for: " + this);
ResolvedTypeX superType = myType.getSuperclass();
// can't be Serializable/Cloneable unless -XserializableAspects
if (!world.isXSerializableAspects()) {
if (world.getWorld().getCoreType(TypeX.SERIALIZABLE).isAssignableFrom(myType)) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"aspects may not implement Serializable");
ignoreFurtherInvestigation = true;
return;
}
if (world.getWorld().getCoreType(TypeX.CLONEABLE).isAssignableFrom(myType)) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"aspects may not implement Cloneable");
ignoreFurtherInvestigation = true;
return;
}
}
if (superType.isAspect()) {
if (!superType.isAbstract()) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"can not extend a concrete aspect");
ignoreFurtherInvestigation = true;
return;
}
}
}
private FieldBinding initFailureField= null;
public void generateCode(ClassFile enclosingClassFile) {
if (ignoreFurtherInvestigation) {
if (binding == null)
return;
ClassFile.createProblemType(
this,
scope.referenceCompilationUnit().compilationResult);
return;
}
// make me and my binding public
this.modifiers = AstUtil.makePublic(this.modifiers);
this.binding.modifiers = AstUtil.makePublic(this.binding.modifiers);
if (!isAbstract()) {
initFailureField = factory.makeFieldBinding(AjcMemberMaker.initFailureCauseField(typeX));
binding.addField(initFailureField);
if (perClause == null) {
// we've already produced an error for this
} else if (perClause.getKind() == PerClause.SINGLETON) {
binding.addField(factory.makeFieldBinding(AjcMemberMaker.perSingletonField(
typeX)));
methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, false, true, initFailureField);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
binding.addField(
factory.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, true, false, null);
} else if (perClause.getKind() == PerClause.PEROBJECT) {
// binding.addField(
// world.makeFieldBinding(
// AjcMemberMaker.perCflowField(
// typeX)));
} else {
throw new RuntimeException("unimplemented");
}
}
if (EclipseFactory.DEBUG) System.out.println(toString());
super.generateCode(enclosingClassFile);
}
public boolean needClassInitMethod() {
return true;
}
protected void generateAttributes(ClassFile classFile) {
if (!isAbstract()) generatePerSupportMembers(classFile);
generateInlineAccessMembers(classFile);
classFile.extraAttributes.add(
new EclipseAttributeAdapter(new AjAttribute.Aspect(perClause)));
if (binding.privilegedHandler != null) {
ResolvedMember[] members = ((PrivilegedHandler)binding.privilegedHandler).getMembers();
classFile.extraAttributes.add(
new EclipseAttributeAdapter(new AjAttribute.PrivilegedAttribute(members)));
}
//XXX need to get this attribute on anyone with a pointcut for good errors
classFile.extraAttributes.add(
new EclipseAttributeAdapter(new AjAttribute.SourceContextAttribute(
new String(compilationResult().getFileName()),
compilationResult().lineSeparatorPositions)));
super.generateAttributes(classFile);
}
private void generateInlineAccessMembers(ClassFile classFile) {
for (Iterator i = superAccessForInline.values().iterator(); i.hasNext(); ) {
AccessForInlineVisitor.SuperAccessMethodPair pair = (AccessForInlineVisitor.SuperAccessMethodPair)i.next();
generateSuperAccessMethod(classFile, pair.accessMethod, pair.originalMethod);
}
for (Iterator i = accessForInline.entrySet().iterator(); i.hasNext(); ) {
Map.Entry e = (Map.Entry)i.next();
generateInlineAccessMethod(classFile, (Binding)e.getValue(), (ResolvedMember)e.getKey());
}
}
private void generatePerSupportMembers(ClassFile classFile) {
if (isAbstract()) return;
//XXX otherwise we need to have this (error handling?)
if (aspectOfMethod == null) return;
if (perClause == null) {
System.err.println("has null perClause: " + this);
return;
}
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
if (perClause.getKind() == PerClause.SINGLETON) {
generatePerSingletonAspectOfMethod(classFile);
generatePerSingletonHasAspectMethod(classFile);
generatePerSingletonAjcClinitMethod(classFile);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
generatePerCflowAspectOfMethod(classFile);
generatePerCflowHasAspectMethod(classFile);
generatePerCflowPushMethod(classFile);
generatePerCflowAjcClinitMethod(classFile);
} else if (perClause.getKind() == PerClause.PEROBJECT) {
TypeBinding interfaceType =
generatePerObjectInterface(classFile);
world.addTypeBinding(interfaceType);
generatePerObjectAspectOfMethod(classFile, interfaceType);
generatePerObjectHasAspectMethod(classFile, interfaceType);
generatePerObjectBindMethod(classFile, interfaceType);
} else {
throw new RuntimeException("unimplemented");
}
}
private static interface BodyGenerator {
public void generate(CodeStream codeStream);
}
private void generateMethod(ClassFile classFile, ResolvedMember member, BodyGenerator gen) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(member), gen);
}
private void generateMethod(ClassFile classFile, MethodBinding methodBinding, BodyGenerator gen) {
// EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
classFile.generateMethodInfoHeader(methodBinding);
int methodAttributeOffset = classFile.contentsOffset;
int attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, AstUtil.getAjSyntheticAttribute());
int codeAttributeOffset = classFile.contentsOffset;
classFile.generateCodeAttributeHeader();
CodeStream codeStream = classFile.codeStream;
// Use reset() rather than init()
// XXX We need a scope to keep reset happy, initializerScope is *not* the right one, but it works !
// codeStream.init(classFile);
// codeStream.initializeMaxLocals(methodBinding);
MethodDeclaration md = AstUtil.makeMethodDeclaration(methodBinding);
md.scope = initializerScope;
codeStream.reset(md,classFile);
// body starts here
gen.generate(codeStream);
// body ends here
classFile.completeCodeAttribute(codeAttributeOffset);
attributeNumber++;
classFile.completeMethodInfo(methodAttributeOffset, attributeNumber);
}
private void generatePerCflowAspectOfMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackPeekInstance()));
codeStream.checkcast(binding);
codeStream.areturn();
// body ends here
}});
}
private void generatePerCflowHasAspectMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackIsValid()));
codeStream.ireturn();
// body ends here
}});
}
private void generatePerCflowPushMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.perCflowPush(
EclipseFactory.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackPushInstance()));
codeStream.return_();
// body ends here
}});
}
private void generatePerCflowAjcClinitMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPreClinitMethod(
EclipseFactory.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.CFLOW_STACK_TYPE));
codeStream.dup();
codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.cflowStackInit()));
codeStream.putstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.return_();
// body ends here
}});
}
private TypeBinding generatePerObjectInterface(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
TypeX interfaceTypeX =
AjcMemberMaker.perObjectInterfaceType(typeX);
HelperInterfaceBinding interfaceType =
new HelperInterfaceBinding(this.binding, interfaceTypeX);
world.addTypeBinding(interfaceType);
interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceGet(typeX));
interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceSet(typeX));
interfaceType.generateClass(compilationResult, classFile);
return interfaceType;
}
private void generatePerObjectAspectOfMethod(
ClassFile classFile,
final TypeBinding interfaceType)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
Label popWrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
codeStream.dup();
codeStream.ifnull(popWrongType);
codeStream.areturn();
popWrongType.place();
codeStream.pop();
wrongType.place();
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
codeStream.invokespecial(world.makeMethodBindingForCall(
AjcMemberMaker.noAspectBoundExceptionInit()
));
codeStream.athrow();
// body ends here
}});
}
private void generatePerObjectHasAspectMethod(ClassFile classFile,
final TypeBinding interfaceType) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
codeStream.ifnull(wrongType);
codeStream.iconst_1();
codeStream.ireturn();
wrongType.place();
codeStream.iconst_0();
codeStream.ireturn();
// body ends here
}});
}
private void generatePerObjectBindMethod(
ClassFile classFile,
final TypeBinding interfaceType)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, AjcMemberMaker.perObjectBind(EclipseFactory.fromBinding(binding)),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType); //XXX this case might call for screaming
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
//XXX should do a check for null here and throw a NoAspectBound
codeStream.ifnonnull(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceSet(typeX)));
wrongType.place();
codeStream.return_();
// body ends here
}});
}
private void generatePerSingletonAspectOfMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// Old style aspectOf() method which confused decompilers
// // body starts here
// codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField(
// typeX)));
// Label isNull = new Label(codeStream);
// codeStream.dup();
// codeStream.ifnull(isNull);
// codeStream.areturn();
// isNull.place();
//
// codeStream.incrStackSize(+1); // the dup trick above confuses the stack counter
// codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
// codeStream.dup();
// codeStream.ldc(typeX.getNameAsIdentifier());
// codeStream.getstatic(initFailureField);
// codeStream.invokespecial(world.makeMethodBindingForCall(
// AjcMemberMaker.noAspectBoundExceptionInitWithCause()
// ));
// codeStream.athrow();
// // body ends here
// The stuff below generates code that looks like this:
/*
* if (ajc$perSingletonInstance == null)
* throw new NoAspectBoundException("A", ajc$initFailureCause);
* else
* return ajc$perSingletonInstance;
*/
// body starts here (see end of each line for what it is doing!)
FieldBinding fb = world.makeFieldBinding(AjcMemberMaker.perSingletonField(typeX));
codeStream.getstatic(fb); // GETSTATIC
Label isNonNull = new Label(codeStream);
codeStream.ifnonnull(isNonNull); // IFNONNULL
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); // NEW
codeStream.dup(); // DUP
codeStream.ldc(typeX.getNameAsIdentifier()); // LDC
codeStream.getstatic(initFailureField); // GETSTATIC
codeStream.invokespecial(world.makeMethodBindingForCall(
AjcMemberMaker.noAspectBoundExceptionInitWithCause())); // INVOKESPECIAL
codeStream.athrow(); // ATHROW
isNonNull.place();
codeStream.getstatic(fb); // GETSTATIC
codeStream.areturn(); // ARETURN
// body ends here
}});
}
private void generatePerSingletonHasAspectMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField(
typeX)));
Label isNull = new Label(codeStream);
codeStream.ifnull(isNull);
codeStream.iconst_1();
codeStream.ireturn();
isNull.place();
codeStream.iconst_0();
codeStream.ireturn();
// body ends here
}});
}
private void generatePerSingletonAjcClinitMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPostClinitMethod(
EclipseFactory.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.putstatic(
world.makeFieldBinding(
AjcMemberMaker.perSingletonField(
typeX)));
codeStream.return_();
// body ends here
}});
}
private void generateSuperAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) {
generateMethod(classFile, accessMethod,
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.aload_0();
AstUtil.generateParameterLoads(accessMethod.parameters, codeStream);
codeStream.invokespecial(
factory.makeMethodBinding(method));
AstUtil.generateReturn(accessMethod.returnType, codeStream);
// body ends here
}});
}
private void generateInlineAccessMethod(ClassFile classFile, final Binding binding, final ResolvedMember member) {
if (binding instanceof InlineAccessFieldBinding) {
generateInlineAccessors(classFile, (InlineAccessFieldBinding)binding, member);
} else {
generateInlineAccessMethod(classFile, (MethodBinding)binding, member);
}
}
private void generateInlineAccessors(ClassFile classFile, final InlineAccessFieldBinding accessField, final ResolvedMember field) {
final FieldBinding fieldBinding = factory.makeFieldBinding(field);
generateMethod(classFile, accessField.reader,
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
if (field.isStatic()) {
codeStream.getstatic(fieldBinding);
} else {
codeStream.aload_0();
codeStream.getfield(fieldBinding);
}
AstUtil.generateReturn(accessField.reader.returnType, codeStream);
// body ends here
}});
generateMethod(classFile, accessField.writer,
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
if (field.isStatic()) {
codeStream.load(fieldBinding.type, 0);
codeStream.putstatic(fieldBinding);
} else {
codeStream.aload_0();
codeStream.load(fieldBinding.type, 1);
codeStream.putfield(fieldBinding);
}
codeStream.return_();
// body ends here
}});
}
private void generateInlineAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) {
generateMethod(classFile, accessMethod,
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
AstUtil.generateParameterLoads(accessMethod.parameters, codeStream);
if (method.isStatic()) {
codeStream.invokestatic(factory.makeMethodBinding(method));
} else {
codeStream.invokevirtual(factory.makeMethodBinding(method));
}
AstUtil.generateReturn(accessMethod.returnType, codeStream);
// body ends here
}});
}
private PerClause.Kind lookupPerClauseKind(ReferenceBinding binding) {
PerClause perClause;
if (binding instanceof BinaryTypeBinding) {
ResolvedTypeX superTypeX = factory.fromEclipse(binding);
perClause = superTypeX.getPerClause();
} else if (binding instanceof SourceTypeBinding ) {
SourceTypeBinding sourceSc = (SourceTypeBinding)binding;
if (sourceSc.scope.referenceContext instanceof AspectDeclaration) {
perClause = ((AspectDeclaration)sourceSc.scope.referenceContext).perClause;
} else {
return null;
}
} else {
//XXX need to handle this too
return null;
}
if (perClause == null) {
return lookupPerClauseKind(binding.superclass());
} else {
return perClause.getKind();
}
}
private void buildPerClause(ClassScope scope) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope);
if (perClause == null) {
PerClause.Kind kind = lookupPerClauseKind(binding.superclass);
if (kind == null) {
perClause = new PerSingleton();
} else {
perClause = new PerFromSuper(kind);
}
}
aspectAttribute = new AjAttribute.Aspect(perClause);
if (ignoreFurtherInvestigation) return; //???
if (!isAbstract()) {
if (perClause.getKind() == PerClause.SINGLETON) {
aspectOfMethod = AjcMemberMaker.perSingletonAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perSingletonHasAspectMethod(typeX);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
aspectOfMethod = AjcMemberMaker.perCflowAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perCflowHasAspectMethod(typeX);
} else if (perClause.getKind() == PerClause.PEROBJECT) {
aspectOfMethod = AjcMemberMaker.perObjectAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perObjectHasAspectMethod(typeX);
} else {
throw new RuntimeException("bad per clause: " + perClause);
}
binding.addMethod(world.makeMethodBinding(aspectOfMethod));
binding.addMethod(world.makeMethodBinding(hasAspectMethod));
}
resolvePerClause(); //XXX might be too soon for some error checking
}
private PerClause resolvePerClause() {
EclipseScope iscope = new EclipseScope(new FormalBinding[0], scope);
perClause.resolve(iscope);
return perClause;
}
public void buildInterTypeAndPerClause(ClassScope classScope) {
factory = EclipseFactory.fromScopeLookupEnvironment(scope);
if (isPrivileged) {
binding.privilegedHandler = new PrivilegedHandler(this);
}
checkSpec(classScope);
if (ignoreFurtherInvestigation) return;
buildPerClause(scope);
if (methods != null) {
for (int i = 0; i < methods.length; i++) {
if (methods[i] instanceof InterTypeDeclaration) {
EclipseTypeMunger m = ((InterTypeDeclaration)methods[i]).build(classScope);
if (m != null) concreteName.typeMungers.add(m);
} else if (methods[i] instanceof DeclareDeclaration) {
Declare d = ((DeclareDeclaration)methods[i]).build(classScope);
if (d != null) concreteName.declares.add(d);
}
}
}
concreteName.getDeclaredPointcuts();
}
// public String toString(int tab) {
// return tabString(tab) + toStringHeader() + toStringBody(tab);
// }
//
// public String toStringBody(int tab) {
//
// String s = " {"; //$NON-NLS-1$
//
//
// if (memberTypes != null) {
// for (int i = 0; i < memberTypes.length; i++) {
// if (memberTypes[i] != null) {
// s += "\n" + memberTypes[i].toString(tab + 1); //$NON-NLS-1$
// }
// }
// }
// if (fields != null) {
// for (int fieldI = 0; fieldI < fields.length; fieldI++) {
// if (fields[fieldI] != null) {
// s += "\n" + fields[fieldI].toString(tab + 1); //$NON-NLS-1$
// if (fields[fieldI].isField())
// s += ";"; //$NON-NLS-1$
// }
// }
// }
// if (methods != null) {
// for (int i = 0; i < methods.length; i++) {
// if (methods[i] != null) {
// s += "\n" + methods[i].toString(tab + 1); //$NON-NLS-1$
// }
// }
// }
// s += "\n" + tabString(tab) + "}"; //$NON-NLS-2$ //$NON-NLS-1$
// return s;
// }
public StringBuffer printHeader(int indent, StringBuffer output) {
printModifiers(this.modifiers, output);
output.append("aspect " );
output.append(name);
if (superclass != null) {
output.append(" extends "); //$NON-NLS-1$
superclass.print(0, output);
}
if (superInterfaces != null && superInterfaces.length > 0) {
output.append(isInterface() ? " extends " : " implements ");//$NON-NLS-2$ //$NON-NLS-1$
for (int i = 0; i < superInterfaces.length; i++) {
if (i > 0) output.append( ", "); //$NON-NLS-1$
superInterfaces[i].print(0, output);
}
}
return output;
//XXX we should append the per-clause
}
}
|
71,377
|
Bug 71377 Cannot advise private method call in around advice
|
Pointcuts should match call joint points in advice. However AspectJ does not match calls to _private_ methods in around advice. The same applies to get/set pointcuts for _private fields. This is probably because in the testcase below a call to "privateMethod()" in the body of the around advice is a call to an accessor method: ajc$inlineAccessMethod$bug_nnnn_JoinPointInAroundAdvice$bug_nnnn_JoinPointInAro undAdvice$privateMethod("around"); public aspect JoinPointInAroundAdvice { private static Set privateCalls = new HashSet(); private static Set publicCalls = new HashSet(); pointcut internalCall () : call(* JoinPointInAroundAdvice.privateMethod(..)); before () : internalCall () { privateCalls.add(thisJoinPoint); } pointcut externalCall () : call(* JoinPointInAroundAdvice.publicMethod(..)); before () : externalCall () { publicCalls.add(thisJoinPoint); } pointcut execTest () : execution(* JoinPointInAroundAdvice.test()); before () : execTest () { privateMethod("before"); publicMethod("before"); } void around () : execTest () { privateMethod("around"); publicMethod("around"); proceed(); } // void around () : execTest () { // Runnable runnable = new Runnable () { // public void run () { // privateMethod("around closure"); // publicMethod; // proceed(); // } // }; // runnable.run(); // } after () : execTest () { privateMethod("after"); publicMethod("after"); } private static void privateMethod (String from) { System.out.println("? privateMethod() " + from); } public static void publicMethod (String from) { System.out.println("? publicMethod() " + from); } public static void test () { System.out.println("? test()"); privateMethod("test"); publicMethod("test"); } public static void main (String[] args) { test(); if (privateCalls.size() != publicCalls.size()) { throw new RuntimeException("Missing join point"); } else { System.out.println("Success."); } } }
|
resolved fixed
|
851da68
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-09T10:26:53Z
| 2004-08-04T14:33:20Z
|
tests/bugs/AroundAdviceJPs/FieldGetJoinPointsInAroundAdvice.java
| |
71,377
|
Bug 71377 Cannot advise private method call in around advice
|
Pointcuts should match call joint points in advice. However AspectJ does not match calls to _private_ methods in around advice. The same applies to get/set pointcuts for _private fields. This is probably because in the testcase below a call to "privateMethod()" in the body of the around advice is a call to an accessor method: ajc$inlineAccessMethod$bug_nnnn_JoinPointInAroundAdvice$bug_nnnn_JoinPointInAro undAdvice$privateMethod("around"); public aspect JoinPointInAroundAdvice { private static Set privateCalls = new HashSet(); private static Set publicCalls = new HashSet(); pointcut internalCall () : call(* JoinPointInAroundAdvice.privateMethod(..)); before () : internalCall () { privateCalls.add(thisJoinPoint); } pointcut externalCall () : call(* JoinPointInAroundAdvice.publicMethod(..)); before () : externalCall () { publicCalls.add(thisJoinPoint); } pointcut execTest () : execution(* JoinPointInAroundAdvice.test()); before () : execTest () { privateMethod("before"); publicMethod("before"); } void around () : execTest () { privateMethod("around"); publicMethod("around"); proceed(); } // void around () : execTest () { // Runnable runnable = new Runnable () { // public void run () { // privateMethod("around closure"); // publicMethod; // proceed(); // } // }; // runnable.run(); // } after () : execTest () { privateMethod("after"); publicMethod("after"); } private static void privateMethod (String from) { System.out.println("? privateMethod() " + from); } public static void publicMethod (String from) { System.out.println("? publicMethod() " + from); } public static void test () { System.out.println("? test()"); privateMethod("test"); publicMethod("test"); } public static void main (String[] args) { test(); if (privateCalls.size() != publicCalls.size()) { throw new RuntimeException("Missing join point"); } else { System.out.println("Success."); } } }
|
resolved fixed
|
851da68
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-09T10:26:53Z
| 2004-08-04T14:33:20Z
|
tests/bugs/AroundAdviceJPs/FieldJoinPointsInAroundAdvice.java
| |
71,377
|
Bug 71377 Cannot advise private method call in around advice
|
Pointcuts should match call joint points in advice. However AspectJ does not match calls to _private_ methods in around advice. The same applies to get/set pointcuts for _private fields. This is probably because in the testcase below a call to "privateMethod()" in the body of the around advice is a call to an accessor method: ajc$inlineAccessMethod$bug_nnnn_JoinPointInAroundAdvice$bug_nnnn_JoinPointInAro undAdvice$privateMethod("around"); public aspect JoinPointInAroundAdvice { private static Set privateCalls = new HashSet(); private static Set publicCalls = new HashSet(); pointcut internalCall () : call(* JoinPointInAroundAdvice.privateMethod(..)); before () : internalCall () { privateCalls.add(thisJoinPoint); } pointcut externalCall () : call(* JoinPointInAroundAdvice.publicMethod(..)); before () : externalCall () { publicCalls.add(thisJoinPoint); } pointcut execTest () : execution(* JoinPointInAroundAdvice.test()); before () : execTest () { privateMethod("before"); publicMethod("before"); } void around () : execTest () { privateMethod("around"); publicMethod("around"); proceed(); } // void around () : execTest () { // Runnable runnable = new Runnable () { // public void run () { // privateMethod("around closure"); // publicMethod; // proceed(); // } // }; // runnable.run(); // } after () : execTest () { privateMethod("after"); publicMethod("after"); } private static void privateMethod (String from) { System.out.println("? privateMethod() " + from); } public static void publicMethod (String from) { System.out.println("? publicMethod() " + from); } public static void test () { System.out.println("? test()"); privateMethod("test"); publicMethod("test"); } public static void main (String[] args) { test(); if (privateCalls.size() != publicCalls.size()) { throw new RuntimeException("Missing join point"); } else { System.out.println("Success."); } } }
|
resolved fixed
|
851da68
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-09T10:26:53Z
| 2004-08-04T14:33:20Z
|
tests/bugs/AroundAdviceJPs/JoinPointInAroundAdvice.java
| |
71,377
|
Bug 71377 Cannot advise private method call in around advice
|
Pointcuts should match call joint points in advice. However AspectJ does not match calls to _private_ methods in around advice. The same applies to get/set pointcuts for _private fields. This is probably because in the testcase below a call to "privateMethod()" in the body of the around advice is a call to an accessor method: ajc$inlineAccessMethod$bug_nnnn_JoinPointInAroundAdvice$bug_nnnn_JoinPointInAro undAdvice$privateMethod("around"); public aspect JoinPointInAroundAdvice { private static Set privateCalls = new HashSet(); private static Set publicCalls = new HashSet(); pointcut internalCall () : call(* JoinPointInAroundAdvice.privateMethod(..)); before () : internalCall () { privateCalls.add(thisJoinPoint); } pointcut externalCall () : call(* JoinPointInAroundAdvice.publicMethod(..)); before () : externalCall () { publicCalls.add(thisJoinPoint); } pointcut execTest () : execution(* JoinPointInAroundAdvice.test()); before () : execTest () { privateMethod("before"); publicMethod("before"); } void around () : execTest () { privateMethod("around"); publicMethod("around"); proceed(); } // void around () : execTest () { // Runnable runnable = new Runnable () { // public void run () { // privateMethod("around closure"); // publicMethod; // proceed(); // } // }; // runnable.run(); // } after () : execTest () { privateMethod("after"); publicMethod("after"); } private static void privateMethod (String from) { System.out.println("? privateMethod() " + from); } public static void publicMethod (String from) { System.out.println("? publicMethod() " + from); } public static void test () { System.out.println("? test()"); privateMethod("test"); publicMethod("test"); } public static void main (String[] args) { test(); if (privateCalls.size() != publicCalls.size()) { throw new RuntimeException("Missing join point"); } else { System.out.println("Success."); } } }
|
resolved fixed
|
851da68
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-09T10:26:53Z
| 2004-08-04T14:33:20Z
|
tests/src/org/aspectj/systemtest/ajc121/Ajc121Tests.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.systemtest.ajc121;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc121Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc121Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc121/ajc121.xml");
}
public void test001(){
runTest("false ambigous binding error (introduced in 1.2rc2)");
}
public void test002(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test003(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test004(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test005(){
runTest("compiler aborts with 'conflicting dominates orders' with circular declare precedences");
}
public void test006(){
runTest("'can't bind type' message has $ for . in type name for declare soft");
}
public void test007(){
runTest("Hiding of Instance Methods by static methods");
}
public void test008(){
runTest("if(false) optimisation");
}
public void test009(){
runTest("if(true) optimisation");
}
public void test010(){
runTest("java.lang.NullPointerException in WeaverMessageHandler class");
}
public void test011(){
runTest("ClassCastException at BcelRenderer.java:169");
}
public void test012(){
runTest("Front-end bug, shouldn't allow patterns of the form foo.., should be foo..*");
}
public void test013() {
runTest("Nullpointer-Exception when defining a withincode() pointcut");
}
public void test014() {
runTest("NPE, Incorrect XLint:unmatchedSuperTypeInCall warning");
}
public void test015_invalidXlint() { // keywords: "laurie hendren"
runTest("invalid warning indicating no match when a match really occurs");
}
public void test016_ByteConversionInstructions() {
runTest("RuntimeException thrown: Could not find instruction: org.apache.bcel.generic.B2I");
String output = getLastRunResult().getStdErr();
assertTrue("Expected to find [b2] in this output but didn't:"+output,output.indexOf("[b2]")!=-1);
assertTrue("Expected to find [b127] in this output but didn't:"+output,output.indexOf("[b127]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
assertTrue("Expected to find [c65] in this output but didn't:"+output,output.indexOf("[c65]")!=-1);
assertTrue("Expected to find [c66] in this output but didn't:"+output,output.indexOf("[c66]")!=-1);
assertTrue("Expected to find [c67] in this output but didn't:"+output,output.indexOf("[c67]")!=-1);
assertTrue("Expected to find [s1] in this output but didn't:"+output,output.indexOf("[s1]")!=-1);
assertTrue("Expected to find [s32767] in this output but didn't:"+output,output.indexOf("[s32767]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
}
}
|
71,377
|
Bug 71377 Cannot advise private method call in around advice
|
Pointcuts should match call joint points in advice. However AspectJ does not match calls to _private_ methods in around advice. The same applies to get/set pointcuts for _private fields. This is probably because in the testcase below a call to "privateMethod()" in the body of the around advice is a call to an accessor method: ajc$inlineAccessMethod$bug_nnnn_JoinPointInAroundAdvice$bug_nnnn_JoinPointInAro undAdvice$privateMethod("around"); public aspect JoinPointInAroundAdvice { private static Set privateCalls = new HashSet(); private static Set publicCalls = new HashSet(); pointcut internalCall () : call(* JoinPointInAroundAdvice.privateMethod(..)); before () : internalCall () { privateCalls.add(thisJoinPoint); } pointcut externalCall () : call(* JoinPointInAroundAdvice.publicMethod(..)); before () : externalCall () { publicCalls.add(thisJoinPoint); } pointcut execTest () : execution(* JoinPointInAroundAdvice.test()); before () : execTest () { privateMethod("before"); publicMethod("before"); } void around () : execTest () { privateMethod("around"); publicMethod("around"); proceed(); } // void around () : execTest () { // Runnable runnable = new Runnable () { // public void run () { // privateMethod("around closure"); // publicMethod; // proceed(); // } // }; // runnable.run(); // } after () : execTest () { privateMethod("after"); publicMethod("after"); } private static void privateMethod (String from) { System.out.println("? privateMethod() " + from); } public static void publicMethod (String from) { System.out.println("? publicMethod() " + from); } public static void test () { System.out.println("? test()"); privateMethod("test"); publicMethod("test"); } public static void main (String[] args) { test(); if (privateCalls.size() != publicCalls.size()) { throw new RuntimeException("Missing join point"); } else { System.out.println("Success."); } } }
|
resolved fixed
|
851da68
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-09T10:26:53Z
| 2004-08-04T14:33:20Z
|
weaver/src/org/aspectj/weaver/bcel/LazyClassGen.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
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 org.apache.bcel.Constants;
import org.apache.bcel.classfile.Attribute;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.classfile.Unknown;
import org.apache.bcel.generic.ClassGen;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.FieldGen;
import org.apache.bcel.generic.InstructionConstants;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.PUSH;
import org.apache.bcel.generic.RETURN;
import org.apache.bcel.generic.Type;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.util.CollectionUtil;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.World;
public final class LazyClassGen {
// ---- JSR 45 info
int highestLineNumber = 0;
private SortedMap /* <String, InlinedSourceFileInfo> */ inlinedFiles = new TreeMap();
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 (Iterator iter = inlinedFiles.values().iterator(); iter.hasNext();) {
InlinedSourceFileInfo element = (InlinedSourceFileInfo) iter.next();
element.offset = i;
i = roundUpToHundreds(i + element.highestLineNumber);
}
}
private static int roundUpToHundreds(int i) {
return ((i / 100) + 1) * 100;
}
int getSourceDebugExtensionOffset(String fullpath) {
return ((InlinedSourceFileInfo) inlinedFiles.get(fullpath)).offset;
}
private Unknown getSourceDebugExtensionAttribute() {
int nameIndex = constantPoolGen.addUtf8("SourceDebugExtension");
String data = getSourceDebugExtensionString();
//System.err.println(data);
byte[] bytes = Utility.stringToUTF(data);
int length = bytes.length;
return new Unknown(nameIndex, length, bytes, constantPoolGen.getConstantPool());
}
// 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);
LazyClassGen clazz = new LazyClassGen(BcelWorld.getBcelObjectType(world.resolve(name)));
clazz.print(out);
out.println();
}
private BcelObjectType myType; // XXX is not set for types we create
private ClassGen myGen;
private ConstantPoolGen constantPoolGen;
private List /*LazyMethodGen*/
methodGens = new ArrayList();
private List /*LazyClassGen*/
classGens = new ArrayList();
private int childCounter = 0;
public int getNewGeneratedNameTag() {
return childCounter++;
}
private InstructionFactory fact;
private boolean isSerializable = false;
private boolean hasSerialVersionUIDField = false;
private boolean hasClinit = false;
// ----
public LazyClassGen(
String class_name,
String super_class_name,
String file_name,
int access_flags,
String[] interfaces)
{
myGen = new ClassGen(class_name, super_class_name, file_name, access_flags, interfaces);
constantPoolGen = myGen.getConstantPool();
fact = new InstructionFactory(myGen, constantPoolGen);
}
//Non child type, so it comes from a real type in the world.
public LazyClassGen(BcelObjectType myType) {
myGen = new ClassGen(myType.getJavaClass());
constantPoolGen = myGen.getConstantPool();
fact = new InstructionFactory(myGen, constantPoolGen);
this.myType = myType;
/* Does this class support serialization */
if (TypeX.SERIALIZABLE.isAssignableFrom(getType(),getType().getWorld())) {
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(ResolvedTypeX.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>")) {
hasClinit = true;
}
}
}
Method[] methods = myGen.getMethods();
for (int i = 0; i < methods.length; i++) {
addMethodGen(new LazyMethodGen(methods[i], this));
}
}
public static boolean hasSerialVersionUIDField (ResolvedTypeX type) {
ResolvedMember[] fields = type.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
ResolvedMember field = fields[i];
if (field.getName().equals("serialVersionUID")
&& field.isStatic() && field.getType().equals(ResolvedTypeX.LONG)) {
return true;
}
}
return false;
}
// public void addAttribute(Attribute i) {
// myGen.addAttribute(i);
// }
// ----
public String getInternalClassName() {
return getConstantPoolGen().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();
}
}
public File getPackagePath(File root) {
String str = getInternalClassName();
int index = str.lastIndexOf('/');
if (index == -1)
return root;
return new File(root, str.substring(0, index));
}
public String getClassId() {
String str = getInternalClassName();
int index = str.lastIndexOf('/');
if (index == -1)
return str;
return str.substring(index + 1);
}
public void addMethodGen(LazyMethodGen gen) {
//assert gen.getClassName() == super.getClassName();
methodGens.add(gen);
if (highestLineNumber < gen.highestLineNumber) highestLineNumber = gen.highestLineNumber;
}
public void addMethodGen(LazyMethodGen gen, ISourceLocation sourceLocation) {
addMethodGen(gen);
if (!gen.getMethod().isPrivate()) {
warnOnAddedMethod(gen.getMethod(),sourceLocation);
}
}
public void errorOnAddedField (Field field, ISourceLocation sourceLocation) {
if (isSerializable && !hasSerialVersionUIDField) {
getWorld().getLint().serialVersionUIDBroken.signal(
new String[] {
myType.getResolvedTypeX().getName().toString(),
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 myType.getResolvedTypeX().getWorld();
}
public List getMethodGens() {
return methodGens; //???Collections.unmodifiableList(methodGens);
}
private void writeBack(BcelWorld world) {
if (myType != null && myType.getWeaverState() != null) {
myGen.addAttribute(BcelAttributes.bcelAttribute(
new AjAttribute.WeaverState(myType.getWeaverState()),
getConstantPoolGen()));
}
addAjcInitializers();
int len = methodGens.size();
myGen.setMethods(new Method[0]);
calculateSourceDebugExtensionOffsets();
for (int i = 0; i < len; i++) {
LazyMethodGen gen = (LazyMethodGen) methodGens.get(i);
// we skip empty clinits
if (isEmptyClinit(gen)) continue;
myGen.addMethod(gen.getMethod());
}
if (inlinedFiles.size() != 0) {
if (hasSourceDebugExtensionAttribute(myGen)) {
world.showMessage(
IMessage.WARNING,
WeaverMessages.format(WeaverMessages.OVERWRITE_JSR45,getFileName()),
null,
null);
}
myGen.addAttribute(getSourceDebugExtensionAttribute());
}
}
private static boolean hasSourceDebugExtensionAttribute(ClassGen gen) {
ConstantPoolGen pool = gen.getConstantPool();
Attribute[] attrs = gen.getAttributes();
for (int i = 0; i < attrs.length; i++) {
if ("SourceDebugExtension"
.equals(((ConstantUtf8) pool.getConstant(attrs[i].getNameIndex())).getBytes())) {
return true;
}
}
return false;
}
public JavaClass getJavaClass(BcelWorld world) {
writeBack(world);
return myGen.getJavaClass();
}
public void addGeneratedInner(LazyClassGen newClass) {
classGens.add(newClass);
}
public void addInterface(TypeX typeX, ISourceLocation sourceLocation) {
myGen.addInterface(typeX.getName());
warnOnAddedInterface(typeX.getName(),sourceLocation);
}
public void setSuperClass(TypeX typeX) {
myGen.setSuperclassName(typeX.getName());
}
// non-recursive, may be a bug, ha ha.
private List getClassGens() {
List ret = new ArrayList();
ret.add(this);
ret.addAll(classGens);
return ret;
}
public List getChildClasses(BcelWorld world) {
if (classGens.isEmpty()) return Collections.EMPTY_LIST;
List ret = new ArrayList();
for (Iterator i = classGens.iterator(); i.hasNext();) {
LazyClassGen clazz = (LazyClassGen) i.next();
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;
}
public String toString() {
return toShortString();
}
public String toShortString() {
String s =
org.apache.bcel.classfile.Utility.accessToString(myGen.getAccessFlags(), true);
if (s != "")
s += " ";
s += org.apache.bcel.classfile.Utility.classOrInterface(myGen.getAccessFlags());
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 classGens = getClassGens();
for (Iterator iter = classGens.iterator(); iter.hasNext();) {
LazyClassGen element = (LazyClassGen) iter.next();
element.printOne(out);
if (iter.hasNext()) out.println();
}
}
private void printOne(PrintStream out) {
out.print(toShortString());
out.print(" extends ");
out.print(
org.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 methodGens = getMethodGens();
for (Iterator iter = methodGens.iterator(); iter.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) iter.next();
// we skip empty clinits
if (isEmptyClinit(gen)) continue;
gen.print(out);
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() instanceof RETURN)) {
start = start.getNext();
} else {
return false;
}
}
return true;
}
public ConstantPoolGen getConstantPoolGen() {
return constantPoolGen;
}
public String getName() {
return myGen.getClassName();
}
public boolean isWoven() {
return myType.getWeaverState() != null;
}
public boolean isReweavable() {
if (myType.getWeaverState()==null) return false;
return myType.getWeaverState().isReweavable();
}
public Set getAspectsAffectingType() {
if (myType.getWeaverState()==null) return null;
return myType.getWeaverState().getAspectsAffectingType();
}
public WeaverStateInfo getOrCreateWeaverStateInfo() {
WeaverStateInfo ret = myType.getWeaverState();
if (ret != null) return ret;
ret = new WeaverStateInfo();
myType.setWeaverState(ret);
return ret;
}
public InstructionFactory getFactory() {
return fact;
}
public LazyMethodGen getStaticInitializer() {
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) i.next();
if (gen.getName().equals("<clinit>")) return gen;
}
LazyMethodGen clinit = new LazyMethodGen(
Modifier.STATIC,
Type.VOID,
"<clinit>",
new Type[0],
CollectionUtil.NO_STRINGS,
this);
clinit.getBody().insert(InstructionConstants.RETURN);
methodGens.add(clinit);
return clinit;
}
public LazyMethodGen getAjcPreClinit() {
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) i.next();
if (gen.getName().equals(NameMangler.AJC_PRE_CLINIT_NAME)) return gen;
}
LazyMethodGen ajcClinit = new LazyMethodGen(
Modifier.STATIC,
Type.VOID,
NameMangler.AJC_PRE_CLINIT_NAME,
new Type[0],
CollectionUtil.NO_STRINGS,
this);
ajcClinit.getBody().insert(InstructionConstants.RETURN);
methodGens.add(ajcClinit);
getStaticInitializer().getBody().insert(Utility.createInvoke(getFactory(), ajcClinit));
return ajcClinit;
}
// reflective thisJoinPoint support
Map/*BcelShadow, Field*/ tjpFields = new HashMap();
public static final ObjectType tjpType =
new ObjectType("org.aspectj.lang.JoinPoint");
public static final ObjectType staticTjpType =
new ObjectType("org.aspectj.lang.JoinPoint$StaticPart");
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) {
Field ret = (Field)tjpFields.get(shadow);
if (ret != null) return ret;
int modifiers = Modifier.STATIC | Modifier.FINAL;
if (getType().isInterface()) {
modifiers |= Modifier.PUBLIC;
}
else {
modifiers |= Modifier.PRIVATE;
}
ret = new FieldGen(modifiers,
staticTjpType,
"ajc$tjp_" + tjpFields.size(),
getConstantPoolGen()).getField();
addField(ret);
tjpFields.put(shadow, ret);
return ret;
}
private void addAjcInitializers() {
if (tjpFields.size() == 0) return;
InstructionList il = initializeAllTjps();
getStaticInitializer().getBody().insert(il);
}
private InstructionList initializeAllTjps() {
InstructionList list = new InstructionList();
InstructionFactory fact = getFactory();
// make a new factory
list.append(fact.createNew(factoryType));
list.append(InstructionFactory.createDup(1));
list.append(new PUSH(getConstantPoolGen(), getFileName()));
// load the current Class object
//XXX check that this works correctly for inners/anonymous
list.append(new PUSH(getConstantPoolGen(), getClassName()));
//XXX do we need to worry about the fact the theorectically this could throw
//a ClassNotFoundException
list.append(fact.createInvoke("java.lang.Class", "forName", classType,
new Type[] {Type.STRING}, Constants.INVOKESTATIC));
list.append(fact.createInvoke(factoryType.getClassName(), "<init>",
Type.VOID, new Type[] {Type.STRING, classType},
Constants.INVOKESPECIAL));
list.append(InstructionFactory.createStore(factoryType, 0));
List entries = new ArrayList(tjpFields.entrySet());
Collections.sort(entries, new Comparator() {
public int compare(Object a, Object b) {
Map.Entry ae = (Map.Entry) a;
Map.Entry be = (Map.Entry) b;
return ((Field) ae.getValue())
.getName()
.compareTo(((Field)be.getValue()).getName());
}
});
for (Iterator i = entries.iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry)i.next();
initializeTjp(fact, list, (Field)entry.getValue(), (BcelShadow)entry.getKey());
}
return list;
}
private void initializeTjp(InstructionFactory fact, InstructionList list,
Field field, BcelShadow shadow)
{
Member sig = shadow.getSignature();
//ResolvedMember mem = shadow.getSignature().resolve(shadow.getWorld());
// load the factory
list.append(InstructionFactory.createLoad(factoryType, 0));
// load the kind
list.append(new PUSH(getConstantPoolGen(), shadow.getKind().getName()));
// create the signature
list.append(InstructionFactory.createLoad(factoryType, 0));
list.append(new PUSH(getConstantPoolGen(), sig.getSignatureString(shadow.getWorld())));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING },
Constants.INVOKEVIRTUAL));
//XXX should load source location from shadow
list.append(Utility.createConstant(fact, shadow.getSourceLine()));
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));
}
public ResolvedTypeX getType() {
if (myType == null) return null;
return myType.getResolvedTypeX();
}
public BcelObjectType getBcelObjectType() {
return myType;
}
public String getFileName() {
return myGen.getFileName();
}
private void addField(Field field) {
myGen.addField(field);
}
public void addField(Field 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 LazyMethodGen getLazyMethodGen(Member m) {
return getLazyMethodGen(m.getName(), m.getSignature());
}
public LazyMethodGen getLazyMethodGen(String name, String signature) {
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) i.next();
if (gen.getName().equals(name) && gen.getSignature().equals(signature))
return gen;
}
throw new BCException("Class " + this.getName() + " does not have a method "
+ name + " with signature " + signature);
}
public void forcePublic() {
myGen.setAccessFlags(Utility.makePublic(myGen.getAccessFlags()));
}
}
|
67,592
|
Bug 67592 value in the args[] array of thisjoinpoint can be changed by one advice decl and updated values seen in another advice decl
|
In ajc a use of thisJoinPoint corresponds to an object of type JoinPoint, where a JoinPoint object has four components, which can be retrieved using accessor methods. this getThis() target getTarget() args getArgs() staticJoinPoint getStaticPart() In the case of args, the object returned is an Object array. This means that an advice decl can overwrite the args, and then another advice which shares the same JoinPoint will see the changed args. Here is a small example. In this aspect the before advice changes arg[0] to always be "Laurie" and then the after advice will always say that "Laurie won a million pounds". Is this the behaviour that is intended? I would have thought that the interface to args[] should be such that the values can only be read. Otherwise very strange interactions between advice decls could occur. --------------------------------------------------------------------- public class Main { public static Main v = new Main(); void lottery ( String arg ) { System.out.println("The arg in lottery is " + arg); } public static void main (String args[]) { v.lottery("Oege"); v.lottery("Ganesh"); } } --------------------------------------------------------------------- public aspect Aspect { // This pair of advice decls demonstrates that an advice can change to // the args of a join point. before () : call(* lottery(java.lang.String)) && !within(Aspect) { System.out.println("BEFORE " + thisJoinPoint + " at " + thisJoinPointStaticPart.getSourceLocation()); Object args[] = thisJoinPoint.getArgs(); System.out.println("arg[0] is " + args[0]); args[0] = "Laurie"; System.out.println("... now it is " + thisJoinPoint.getArgs()[0]); } after () : call(* lottery(java.lang.String)) && !within(Aspect) { System.out.println("AFTER " + thisJoinPoint + " at " + thisJoinPointStaticPart.getSourceLocation()); if (thisJoinPoint.getArgs()[0].equals("Laurie")) System.out.println("Laurie wins 1 million pounds!"); } }
|
resolved fixed
|
f6436e3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-09T12:48:11Z
| 2004-06-17T08:13:20Z
|
runtime/src/org/aspectj/runtime/reflect/JoinPointImpl.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.runtime.reflect;
import org.aspectj.lang.*;
import org.aspectj.lang.reflect.SourceLocation;
class JoinPointImpl implements JoinPoint {
static class StaticPartImpl implements JoinPoint.StaticPart {
String kind;
Signature signature;
SourceLocation sourceLocation;
public StaticPartImpl(String kind, Signature signature, SourceLocation sourceLocation) {
this.kind = kind;
this.signature = signature;
this.sourceLocation = sourceLocation;
}
public String getKind() { return kind; }
public Signature getSignature() { return signature; }
public SourceLocation getSourceLocation() { return sourceLocation; }
String toString(StringMaker sm) {
StringBuffer buf = new StringBuffer();
buf.append(sm.makeKindName(getKind()));
buf.append("(");
buf.append(((SignatureImpl)getSignature()).toString(sm));
buf.append(")");
return buf.toString();
}
public final String toString() { return toString(StringMaker.middleStringMaker); }
public final String toShortString() { return toString(StringMaker.shortStringMaker); }
public final String toLongString() { return toString(StringMaker.longStringMaker); }
}
Object _this;
Object target;
Object[] args;
org.aspectj.lang.JoinPoint.StaticPart staticPart;
public JoinPointImpl(org.aspectj.lang.JoinPoint.StaticPart staticPart, Object _this, Object target, Object[] args) {
this.staticPart = staticPart;
this._this = _this;
this.target = target;
this.args = args;
}
public Object getThis() { return _this; }
public Object getTarget() { return target; }
public Object[] getArgs() { return args; }
public org.aspectj.lang.JoinPoint.StaticPart getStaticPart() { return staticPart; }
public String getKind() { return staticPart.getKind(); }
public Signature getSignature() { return staticPart.getSignature(); }
public SourceLocation getSourceLocation() { return staticPart.getSourceLocation(); }
public final String toString() { return staticPart.toString(); }
public final String toShortString() { return staticPart.toShortString(); }
public final String toLongString() { return staticPart.toLongString(); }
}
|
67,592
|
Bug 67592 value in the args[] array of thisjoinpoint can be changed by one advice decl and updated values seen in another advice decl
|
In ajc a use of thisJoinPoint corresponds to an object of type JoinPoint, where a JoinPoint object has four components, which can be retrieved using accessor methods. this getThis() target getTarget() args getArgs() staticJoinPoint getStaticPart() In the case of args, the object returned is an Object array. This means that an advice decl can overwrite the args, and then another advice which shares the same JoinPoint will see the changed args. Here is a small example. In this aspect the before advice changes arg[0] to always be "Laurie" and then the after advice will always say that "Laurie won a million pounds". Is this the behaviour that is intended? I would have thought that the interface to args[] should be such that the values can only be read. Otherwise very strange interactions between advice decls could occur. --------------------------------------------------------------------- public class Main { public static Main v = new Main(); void lottery ( String arg ) { System.out.println("The arg in lottery is " + arg); } public static void main (String args[]) { v.lottery("Oege"); v.lottery("Ganesh"); } } --------------------------------------------------------------------- public aspect Aspect { // This pair of advice decls demonstrates that an advice can change to // the args of a join point. before () : call(* lottery(java.lang.String)) && !within(Aspect) { System.out.println("BEFORE " + thisJoinPoint + " at " + thisJoinPointStaticPart.getSourceLocation()); Object args[] = thisJoinPoint.getArgs(); System.out.println("arg[0] is " + args[0]); args[0] = "Laurie"; System.out.println("... now it is " + thisJoinPoint.getArgs()[0]); } after () : call(* lottery(java.lang.String)) && !within(Aspect) { System.out.println("AFTER " + thisJoinPoint + " at " + thisJoinPointStaticPart.getSourceLocation()); if (thisJoinPoint.getArgs()[0].equals("Laurie")) System.out.println("Laurie wins 1 million pounds!"); } }
|
resolved fixed
|
f6436e3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-09T12:48:11Z
| 2004-06-17T08:13:20Z
|
runtime/testsrc/RuntimeModuleTests.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
// default package
import java.io.*;
import org.aspectj.lang.*;
import org.aspectj.runtime.reflect.SignatureTest;
import junit.framework.*;
public class RuntimeModuleTests extends TestCase {
public static TestSuite suite() {
TestSuite suite = new TestSuite(RuntimeModuleTests.class.getName());
suite.addTestSuite(RuntimeModuleTests.class); // minimum 1 test (testNothing)
suite.addTestSuite(SignatureTest.class);
return suite;
}
public RuntimeModuleTests(String name) { super(name); }
public void testNoAspectBoundException() {
RuntimeException fun = new RuntimeException("fun");
NoAspectBoundException nab = new NoAspectBoundException("Foo", fun);
assertEquals(fun,nab.getCause());
}
public void testSoftExceptionPrintStackTrace() {
// let's see
// Throwable t = new Error("xyz");
// new SoftException(t).printStackTrace();
// save to specified PrintStream
ByteArrayOutputStream sink = new ByteArrayOutputStream();
PrintStream out = new PrintStream(sink);
new SoftException(new Error("xyz")).printStackTrace(out);
String s = new String(sink.toByteArray());
out.flush();
checkSoftExceptionString(s);
// save to specified PrintWriter
sink = new ByteArrayOutputStream();
PrintWriter pout = new PrintWriter(sink);
new SoftException(new Error("xyz")).printStackTrace(pout);
pout.flush();
s = new String(sink.toByteArray());
checkSoftExceptionString(s);
// check System.err redirect
PrintStream systemErr = System.err;
try {
sink = new ByteArrayOutputStream();
out = new PrintStream(sink);
System.setErr(out);
new SoftException(new Error("xyz")).printStackTrace();
out.flush();
s = new String(sink.toByteArray());
checkSoftExceptionString(s);
} finally {
System.setErr(systemErr);
}
}
static void checkSoftExceptionString(String s) {
assertTrue(-1 != s.indexOf("SoftException"));
assertTrue(-1 != s.indexOf("Caused by: java.lang.Error"));
assertTrue(-1 != s.indexOf("xyz"));
assertTrue(-1 != s.indexOf("testSoftExceptionPrintStackTrace"));
}
}
|
67,592
|
Bug 67592 value in the args[] array of thisjoinpoint can be changed by one advice decl and updated values seen in another advice decl
|
In ajc a use of thisJoinPoint corresponds to an object of type JoinPoint, where a JoinPoint object has four components, which can be retrieved using accessor methods. this getThis() target getTarget() args getArgs() staticJoinPoint getStaticPart() In the case of args, the object returned is an Object array. This means that an advice decl can overwrite the args, and then another advice which shares the same JoinPoint will see the changed args. Here is a small example. In this aspect the before advice changes arg[0] to always be "Laurie" and then the after advice will always say that "Laurie won a million pounds". Is this the behaviour that is intended? I would have thought that the interface to args[] should be such that the values can only be read. Otherwise very strange interactions between advice decls could occur. --------------------------------------------------------------------- public class Main { public static Main v = new Main(); void lottery ( String arg ) { System.out.println("The arg in lottery is " + arg); } public static void main (String args[]) { v.lottery("Oege"); v.lottery("Ganesh"); } } --------------------------------------------------------------------- public aspect Aspect { // This pair of advice decls demonstrates that an advice can change to // the args of a join point. before () : call(* lottery(java.lang.String)) && !within(Aspect) { System.out.println("BEFORE " + thisJoinPoint + " at " + thisJoinPointStaticPart.getSourceLocation()); Object args[] = thisJoinPoint.getArgs(); System.out.println("arg[0] is " + args[0]); args[0] = "Laurie"; System.out.println("... now it is " + thisJoinPoint.getArgs()[0]); } after () : call(* lottery(java.lang.String)) && !within(Aspect) { System.out.println("AFTER " + thisJoinPoint + " at " + thisJoinPointStaticPart.getSourceLocation()); if (thisJoinPoint.getArgs()[0].equals("Laurie")) System.out.println("Laurie wins 1 million pounds!"); } }
|
resolved fixed
|
f6436e3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-09T12:48:11Z
| 2004-06-17T08:13:20Z
|
runtime/testsrc/org/aspectj/runtime/reflect/JoinPointImplTest.java
| |
59,208
|
Bug 59208 Weaver fails in BCEL for large classes
| null |
resolved fixed
|
44a92e1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-10T11:08:56Z
| 2004-04-20T08:33:20Z
|
tests/bugs/pr59208/Foo.java
| |
59,208
|
Bug 59208 Weaver fails in BCEL for large classes
| null |
resolved fixed
|
44a92e1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-10T11:08:56Z
| 2004-04-20T08:33:20Z
|
tests/bugs/pr59208/FooProducer.java
| |
59,208
|
Bug 59208 Weaver fails in BCEL for large classes
| null |
resolved fixed
|
44a92e1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-10T11:08:56Z
| 2004-04-20T08:33:20Z
|
tests/src/org/aspectj/systemtest/ajc121/Ajc121Tests.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.systemtest.ajc121;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc121Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc121Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc121/ajc121.xml");
}
public void test001(){
runTest("false ambiguous binding error (introduced in 1.2rc2)");
}
public void test002(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test003(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test004(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test005(){
runTest("compiler aborts with 'conflicting dominates orders' with circular declare precedences");
}
public void test006(){
runTest("'can't bind type' message has $ for . in type name for declare soft");
}
public void test007(){
runTest("Hiding of Instance Methods by static methods");
}
public void test008(){
runTest("if(false) optimisation");
}
public void test009(){
runTest("if(true) optimisation");
}
public void test010(){
runTest("java.lang.NullPointerException in WeaverMessageHandler class");
}
public void test011(){
runTest("ClassCastException at BcelRenderer.java:169");
}
public void test012(){
runTest("Front-end bug, shouldn't allow patterns of the form foo.., should be foo..*");
}
public void test013() {
runTest("Nullpointer-Exception when defining a withincode() pointcut");
}
public void test014() {
runTest("NPE, Incorrect XLint:unmatchedSuperTypeInCall warning");
}
public void test015_invalidXlint() { // keywords: "laurie hendren"
runTest("invalid warning indicating no match when a match really occurs");
}
public void test016_ByteConversionInstructions() {
runTest("RuntimeException thrown: Could not find instruction: org.apache.bcel.generic.B2I");
String output = getLastRunResult().getStdErr();
assertTrue("Expected to find [b2] in this output but didn't:"+output,output.indexOf("[b2]")!=-1);
assertTrue("Expected to find [b127] in this output but didn't:"+output,output.indexOf("[b127]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
assertTrue("Expected to find [c65] in this output but didn't:"+output,output.indexOf("[c65]")!=-1);
assertTrue("Expected to find [c66] in this output but didn't:"+output,output.indexOf("[c66]")!=-1);
assertTrue("Expected to find [c67] in this output but didn't:"+output,output.indexOf("[c67]")!=-1);
assertTrue("Expected to find [s1] in this output but didn't:"+output,output.indexOf("[s1]")!=-1);
assertTrue("Expected to find [s32767] in this output but didn't:"+output,output.indexOf("[s32767]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
}
public void test017_PrivateMethodCallsInAroundAdvice() {
runTest("Cannot advise private method call in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test018_PrivateFieldSetsInAroundAdvice() {
runTest("Cannot advise private field sets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test019_PrivateFieldGetsInAroundAdvice() {
runTest("Cannot advise private field gets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
// test takes over 5 minutes to run, so not included in normal suite run
// public void test020_branchTargetOffsetTooLargeForShort() {
// runTest("Branch target offset too large for short");
// }
}
|
59,208
|
Bug 59208 Weaver fails in BCEL for large classes
| null |
resolved fixed
|
44a92e1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-10T11:08:56Z
| 2004-04-20T08:33:20Z
|
weaver/src/org/aspectj/weaver/WeaverMessages.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.aspectj.weaver;
import java.text.MessageFormat;
import java.util.ResourceBundle;
public class WeaverMessages {
private static ResourceBundle bundle = ResourceBundle.getBundle("org.aspectj.weaver.weaver-messages");
public static final String ARGS_IN_DECLARE = "argsInDeclare";
public static final String CFLOW_IN_DECLARE = "cflowInDeclare";
public static final String IF_IN_DECLARE = "ifInDeclare";
public static final String THIS_OR_TARGET_IN_DECLARE = "thisOrTargetInDeclare";
public static final String ABSTRACT_POINTCUT = "abstractPointcut";
public static final String POINCUT_NOT_CONCRETE = "abstractPointcutNotMadeConcrete";
public static final String CONFLICTING_INHERITED_POINTCUTS = "conflictingInheritedPointcuts";
public static final String CIRCULAR_POINTCUT = "circularPointcutDeclaration";
public static final String CANT_FIND_POINTCUT = "cantFindPointcut";
public static final String EXACT_TYPE_PATTERN_REQD = "exactTypePatternRequired";
public static final String CANT_BIND_TYPE = "cantBindType";
public static final String WILDCARD_NOT_ALLOWED = "wildcardTypePatternNotAllowed";
public static final String DECP_OBJECT = "decpObject";
public static final String CANT_EXTEND_SELF="cantExtendSelf";
public static final String INTERFACE_CANT_EXTEND_CLASS="interfaceExtendClass";
public static final String DECP_HIERARCHY_ERROR = "decpHierarchy";
public static final String MULTIPLE_MATCHES_IN_PRECEDENCE = "multipleMatchesInPrecedence";
public static final String TWO_STARS_IN_PRECEDENCE = "circularityInPrecedenceStar";
public static final String CLASSES_IN_PRECEDENCE = "nonAspectTypesInPrecedence";
public static final String TWO_PATTERN_MATCHES_IN_PRECEDENCE = "circularityInPrecedenceTwo";
public static final String NOT_THROWABLE = "notThrowable";
public static final String ITD_CONS_ON_ASPECT = "itdConsOnAspect";
public static final String ITD_RETURN_TYPE_MISMATCH = "returnTypeMismatch";
public static final String ITD_PARAM_TYPE_MISMATCH = "paramTypeMismatch";
public static final String ITD_VISIBILITY_REDUCTION = "visibilityReduction";
public static final String ITD_DOESNT_THROW = "doesntThrow";
public static final String ITD_OVERRIDDEN_STATIC = "overriddenStatic";
public static final String ITD_OVERIDDING_STATIC = "overridingStatic";
public static final String ITD_CONFLICT = "itdConflict";
public static final String ITD_MEMBER_CONFLICT = "itdMemberConflict";
public static final String NON_VOID_RETURN = "nonVoidReturn";
public static final String INCOMPATIBLE_RETURN_TYPE="incompatibleReturnType";
public static final String CANT_THROW_CHECKED = "cantThrowChecked";
public static final String CIRCULAR_DEPENDENCY = "circularDependency";
public static final String MISSING_PER_CLAUSE = "missingPerClause";
public static final String WRONG_PER_CLAUSE = "wrongPerClause";
public static final String ALREADY_WOVEN = "alreadyWoven";
public static final String REWEAVABLE_MODE = "reweavableMode";
public static final String PROCESSING_REWEAVABLE = "processingReweavable";
public static final String MISSING_REWEAVABLE_TYPE = "missingReweavableType";
public static final String VERIFIED_REWEAVABLE_TYPE = "verifiedReweavableType";
public static final String ASPECT_NEEDED = "aspectNeeded";
public static final String CANT_FIND_TYPE = "cantFindType";
public static final String CANT_FIND_CORE_TYPE = "cantFindCoreType";
public static final String CANT_FIND_TYPE_WITHINPCD = "cantFindTypeWithinpcd";
public static final String DECP_BINARY_LIMITATION = "decpBinaryLimitation";
public static final String OVERWRITE_JSR45 = "overwriteJSR45";
public static final String IF_IN_PERCLAUSE = "ifInPerClause";
public static final String IF_LEXICALLY_IN_CFLOW = "ifLexicallyInCflow";
public static final String ONLY_BEFORE_ON_HANDLER = "onlyBeforeOnHandler";
public static final String AROUND_ON_PREINIT = "aroundOnPreInit";
public static final String AROUND_ON_INIT = "aroundOnInit";
public static final String AROUND_ON_INTERFACE_STATICINIT = "aroundOnInterfaceStaticInit";
public static final String PROBLEM_GENERATING_METHOD = "problemGeneratingMethod";
public static final String ZIPFILE_ENTRY_MISSING = "zipfileEntryMissing";
public static final String ZIPFILE_ENTRY_INVALID = "zipfileEntryInvalid";
public static final String DIRECTORY_ENTRY_MISSING = "directoryEntryMissing";
public static final String XLINT_LOAD_ERROR = "problemLoadingXLint";
public static final String XLINTDEFAULT_LOAD_ERROR = "unableToLoadXLintDefault";
public static final String XLINTDEFAULT_LOAD_PROBLEM = "errorLoadingXLintDefault";
public static final String XLINT_KEY_ERROR = "invalidXLintKey";
public static final String XLINT_VALUE_ERROR = "invalidXLintMessageKind";
public static String format(String key) {
return bundle.getString(key);
}
public static String format(String key, Object insert) {
return MessageFormat.format(bundle.getString(key),new Object[] {insert});
}
public static String format(String key, Object insert1, Object insert2) {
return MessageFormat.format(bundle.getString(key),new Object[] {insert1,insert2});
}
public static String format(String key, Object insert1, Object insert2, Object insert3) {
return MessageFormat.format(bundle.getString(key),new Object[] {insert1, insert2, insert3});
}
}
|
59,208
|
Bug 59208 Weaver fails in BCEL for large classes
| null |
resolved fixed
|
44a92e1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-10T11:08:56Z
| 2004-04-20T08:33:20Z
|
weaver/src/org/aspectj/weaver/bcel/LazyClassGen.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
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 org.apache.bcel.Constants;
import org.apache.bcel.classfile.Attribute;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.classfile.Unknown;
import org.apache.bcel.generic.ClassGen;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.FieldGen;
import org.apache.bcel.generic.InstructionConstants;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.PUSH;
import org.apache.bcel.generic.RETURN;
import org.apache.bcel.generic.Type;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.util.CollectionUtil;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.World;
public final class LazyClassGen {
// ---- JSR 45 info
int highestLineNumber = 0;
private SortedMap /* <String, InlinedSourceFileInfo> */ inlinedFiles = new TreeMap();
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 (Iterator iter = inlinedFiles.values().iterator(); iter.hasNext();) {
InlinedSourceFileInfo element = (InlinedSourceFileInfo) iter.next();
element.offset = i;
i = roundUpToHundreds(i + element.highestLineNumber);
}
}
private static int roundUpToHundreds(int i) {
return ((i / 100) + 1) * 100;
}
int getSourceDebugExtensionOffset(String fullpath) {
return ((InlinedSourceFileInfo) inlinedFiles.get(fullpath)).offset;
}
private Unknown getSourceDebugExtensionAttribute() {
int nameIndex = constantPoolGen.addUtf8("SourceDebugExtension");
String data = getSourceDebugExtensionString();
//System.err.println(data);
byte[] bytes = Utility.stringToUTF(data);
int length = bytes.length;
return new Unknown(nameIndex, length, bytes, constantPoolGen.getConstantPool());
}
// 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);
LazyClassGen clazz = new LazyClassGen(BcelWorld.getBcelObjectType(world.resolve(name)));
clazz.print(out);
out.println();
}
private BcelObjectType myType; // XXX is not set for types we create
private ClassGen myGen;
private ConstantPoolGen constantPoolGen;
private List /*LazyMethodGen*/
methodGens = new ArrayList();
private List /*LazyClassGen*/
classGens = new ArrayList();
private int childCounter = 0;
public int getNewGeneratedNameTag() {
return childCounter++;
}
private InstructionFactory fact;
private boolean isSerializable = false;
private boolean hasSerialVersionUIDField = false;
private boolean hasClinit = false;
// ----
public LazyClassGen(
String class_name,
String super_class_name,
String file_name,
int access_flags,
String[] interfaces)
{
myGen = new ClassGen(class_name, super_class_name, file_name, access_flags, interfaces);
constantPoolGen = myGen.getConstantPool();
fact = new InstructionFactory(myGen, constantPoolGen);
}
//Non child type, so it comes from a real type in the world.
public LazyClassGen(BcelObjectType myType) {
myGen = new ClassGen(myType.getJavaClass());
constantPoolGen = myGen.getConstantPool();
fact = new InstructionFactory(myGen, constantPoolGen);
this.myType = myType;
/* Does this class support serialization */
if (TypeX.SERIALIZABLE.isAssignableFrom(getType(),getType().getWorld())) {
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(ResolvedTypeX.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>")) {
hasClinit = true;
}
}
}
Method[] methods = myGen.getMethods();
for (int i = 0; i < methods.length; i++) {
addMethodGen(new LazyMethodGen(methods[i], this));
}
}
public static boolean hasSerialVersionUIDField (ResolvedTypeX type) {
ResolvedMember[] fields = type.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
ResolvedMember field = fields[i];
if (field.getName().equals("serialVersionUID")
&& field.isStatic() && field.getType().equals(ResolvedTypeX.LONG)) {
return true;
}
}
return false;
}
// public void addAttribute(Attribute i) {
// myGen.addAttribute(i);
// }
// ----
public String getInternalClassName() {
return getConstantPoolGen().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();
}
}
public File getPackagePath(File root) {
String str = getInternalClassName();
int index = str.lastIndexOf('/');
if (index == -1)
return root;
return new File(root, str.substring(0, index));
}
public String getClassId() {
String str = getInternalClassName();
int index = str.lastIndexOf('/');
if (index == -1)
return str;
return str.substring(index + 1);
}
public void addMethodGen(LazyMethodGen gen) {
//assert gen.getClassName() == super.getClassName();
methodGens.add(gen);
if (highestLineNumber < gen.highestLineNumber) highestLineNumber = gen.highestLineNumber;
}
public void addMethodGen(LazyMethodGen gen, ISourceLocation sourceLocation) {
addMethodGen(gen);
if (!gen.getMethod().isPrivate()) {
warnOnAddedMethod(gen.getMethod(),sourceLocation);
}
}
public void errorOnAddedField (Field field, ISourceLocation sourceLocation) {
if (isSerializable && !hasSerialVersionUIDField) {
getWorld().getLint().serialVersionUIDBroken.signal(
new String[] {
myType.getResolvedTypeX().getName().toString(),
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 myType.getResolvedTypeX().getWorld();
}
public List getMethodGens() {
return methodGens; //???Collections.unmodifiableList(methodGens);
}
private void writeBack(BcelWorld world) {
if (myType != null && myType.getWeaverState() != null) {
myGen.addAttribute(BcelAttributes.bcelAttribute(
new AjAttribute.WeaverState(myType.getWeaverState()),
getConstantPoolGen()));
}
addAjcInitializers();
int len = methodGens.size();
myGen.setMethods(new Method[0]);
calculateSourceDebugExtensionOffsets();
for (int i = 0; i < len; i++) {
LazyMethodGen gen = (LazyMethodGen) methodGens.get(i);
// we skip empty clinits
if (isEmptyClinit(gen)) continue;
myGen.addMethod(gen.getMethod());
}
if (inlinedFiles.size() != 0) {
if (hasSourceDebugExtensionAttribute(myGen)) {
world.showMessage(
IMessage.WARNING,
WeaverMessages.format(WeaverMessages.OVERWRITE_JSR45,getFileName()),
null,
null);
}
myGen.addAttribute(getSourceDebugExtensionAttribute());
}
}
private static boolean hasSourceDebugExtensionAttribute(ClassGen gen) {
ConstantPoolGen pool = gen.getConstantPool();
Attribute[] attrs = gen.getAttributes();
for (int i = 0; i < attrs.length; i++) {
if ("SourceDebugExtension"
.equals(((ConstantUtf8) pool.getConstant(attrs[i].getNameIndex())).getBytes())) {
return true;
}
}
return false;
}
public JavaClass getJavaClass(BcelWorld world) {
writeBack(world);
return myGen.getJavaClass();
}
public void addGeneratedInner(LazyClassGen newClass) {
classGens.add(newClass);
}
public void addInterface(TypeX typeX, ISourceLocation sourceLocation) {
myGen.addInterface(typeX.getName());
warnOnAddedInterface(typeX.getName(),sourceLocation);
}
public void setSuperClass(TypeX typeX) {
myGen.setSuperclassName(typeX.getName());
}
// non-recursive, may be a bug, ha ha.
private List getClassGens() {
List ret = new ArrayList();
ret.add(this);
ret.addAll(classGens);
return ret;
}
public List getChildClasses(BcelWorld world) {
if (classGens.isEmpty()) return Collections.EMPTY_LIST;
List ret = new ArrayList();
for (Iterator i = classGens.iterator(); i.hasNext();) {
LazyClassGen clazz = (LazyClassGen) i.next();
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;
}
public String toString() {
return toShortString();
}
public String toShortString() {
String s =
org.apache.bcel.classfile.Utility.accessToString(myGen.getAccessFlags(), true);
if (s != "")
s += " ";
s += org.apache.bcel.classfile.Utility.classOrInterface(myGen.getAccessFlags());
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 classGens = getClassGens();
for (Iterator iter = classGens.iterator(); iter.hasNext();) {
LazyClassGen element = (LazyClassGen) iter.next();
element.printOne(out);
if (iter.hasNext()) out.println();
}
}
private void printOne(PrintStream out) {
out.print(toShortString());
out.print(" extends ");
out.print(
org.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 methodGens = getMethodGens();
for (Iterator iter = methodGens.iterator(); iter.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) iter.next();
// we skip empty clinits
if (isEmptyClinit(gen)) continue;
gen.print(out);
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() instanceof RETURN)) {
start = start.getNext();
} else {
return false;
}
}
return true;
}
public ConstantPoolGen getConstantPoolGen() {
return constantPoolGen;
}
public String getName() {
return myGen.getClassName();
}
public boolean isWoven() {
return myType.getWeaverState() != null;
}
public boolean isReweavable() {
if (myType.getWeaverState()==null) return false;
return myType.getWeaverState().isReweavable();
}
public Set getAspectsAffectingType() {
if (myType.getWeaverState()==null) return null;
return myType.getWeaverState().getAspectsAffectingType();
}
public WeaverStateInfo getOrCreateWeaverStateInfo() {
WeaverStateInfo ret = myType.getWeaverState();
if (ret != null) return ret;
ret = new WeaverStateInfo();
myType.setWeaverState(ret);
return ret;
}
public InstructionFactory getFactory() {
return fact;
}
public LazyMethodGen getStaticInitializer() {
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) i.next();
if (gen.getName().equals("<clinit>")) return gen;
}
LazyMethodGen clinit = new LazyMethodGen(
Modifier.STATIC,
Type.VOID,
"<clinit>",
new Type[0],
CollectionUtil.NO_STRINGS,
this);
clinit.getBody().insert(InstructionConstants.RETURN);
methodGens.add(clinit);
return clinit;
}
public LazyMethodGen getAjcPreClinit() {
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) i.next();
if (gen.getName().equals(NameMangler.AJC_PRE_CLINIT_NAME)) return gen;
}
LazyMethodGen ajcClinit = new LazyMethodGen(
Modifier.STATIC,
Type.VOID,
NameMangler.AJC_PRE_CLINIT_NAME,
new Type[0],
CollectionUtil.NO_STRINGS,
this);
ajcClinit.getBody().insert(InstructionConstants.RETURN);
methodGens.add(ajcClinit);
getStaticInitializer().getBody().insert(Utility.createInvoke(getFactory(), ajcClinit));
return ajcClinit;
}
// reflective thisJoinPoint support
Map/*BcelShadow, Field*/ tjpFields = new HashMap();
public static final ObjectType tjpType =
new ObjectType("org.aspectj.lang.JoinPoint");
public static final ObjectType staticTjpType =
new ObjectType("org.aspectj.lang.JoinPoint$StaticPart");
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) {
Field ret = (Field)tjpFields.get(shadow);
if (ret != null) return ret;
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;
}
ret = new FieldGen(modifiers,
staticTjpType,
"ajc$tjp_" + tjpFields.size(),
getConstantPoolGen()).getField();
addField(ret);
tjpFields.put(shadow, ret);
return ret;
}
private void addAjcInitializers() {
if (tjpFields.size() == 0) return;
InstructionList il = initializeAllTjps();
getStaticInitializer().getBody().insert(il);
}
private InstructionList initializeAllTjps() {
InstructionList list = new InstructionList();
InstructionFactory fact = getFactory();
// make a new factory
list.append(fact.createNew(factoryType));
list.append(InstructionFactory.createDup(1));
list.append(new PUSH(getConstantPoolGen(), getFileName()));
// load the current Class object
//XXX check that this works correctly for inners/anonymous
list.append(new PUSH(getConstantPoolGen(), getClassName()));
//XXX do we need to worry about the fact the theorectically this could throw
//a ClassNotFoundException
list.append(fact.createInvoke("java.lang.Class", "forName", classType,
new Type[] {Type.STRING}, Constants.INVOKESTATIC));
list.append(fact.createInvoke(factoryType.getClassName(), "<init>",
Type.VOID, new Type[] {Type.STRING, classType},
Constants.INVOKESPECIAL));
list.append(InstructionFactory.createStore(factoryType, 0));
List entries = new ArrayList(tjpFields.entrySet());
Collections.sort(entries, new Comparator() {
public int compare(Object a, Object b) {
Map.Entry ae = (Map.Entry) a;
Map.Entry be = (Map.Entry) b;
return ((Field) ae.getValue())
.getName()
.compareTo(((Field)be.getValue()).getName());
}
});
for (Iterator i = entries.iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry)i.next();
initializeTjp(fact, list, (Field)entry.getValue(), (BcelShadow)entry.getKey());
}
return list;
}
private void initializeTjp(InstructionFactory fact, InstructionList list,
Field field, BcelShadow shadow)
{
Member sig = shadow.getSignature();
//ResolvedMember mem = shadow.getSignature().resolve(shadow.getWorld());
// load the factory
list.append(InstructionFactory.createLoad(factoryType, 0));
// load the kind
list.append(new PUSH(getConstantPoolGen(), shadow.getKind().getName()));
// create the signature
list.append(InstructionFactory.createLoad(factoryType, 0));
list.append(new PUSH(getConstantPoolGen(), sig.getSignatureString(shadow.getWorld())));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING },
Constants.INVOKEVIRTUAL));
//XXX should load source location from shadow
list.append(Utility.createConstant(fact, shadow.getSourceLine()));
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));
}
public ResolvedTypeX getType() {
if (myType == null) return null;
return myType.getResolvedTypeX();
}
public BcelObjectType getBcelObjectType() {
return myType;
}
public String getFileName() {
return myGen.getFileName();
}
private void addField(Field field) {
myGen.addField(field);
}
public void addField(Field 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 LazyMethodGen getLazyMethodGen(Member m) {
return getLazyMethodGen(m.getName(), m.getSignature());
}
public LazyMethodGen getLazyMethodGen(String name, String signature) {
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) i.next();
if (gen.getName().equals(name) && gen.getSignature().equals(signature))
return gen;
}
throw new BCException("Class " + this.getName() + " does not have a method "
+ name + " with signature " + signature);
}
public void forcePublic() {
myGen.setAccessFlags(Utility.makePublic(myGen.getAccessFlags()));
}
}
|
53,981
|
Bug 53981 proceed used as method name in around advice
|
Using a method named proceed(..) in around advice confuses the compiler (in at least the 2-3 ways shown below). True of the current tree (untested in 1.1.1). Workaround for now is to rename the method. ---- first problem: NPE in compiler java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.ast.MakeDeclsPublicVisitor.endVisit(MakeDeclsPublicVisitor.java:44) public class Proceeding { public static void main(String[] args) { } static aspect A { interface IProceed { void proceed(Runnable next); } IProceed decorator; void around() : execution(void main(String[])) { decorator.proceed(new Runnable() { public void run() { proceed(); } }); } } } ---- second problem: incorrect error wrt number of arguments public class Proceeding { public static void main(String[] args) { } static aspect A { void around() : execution(void main(String[])) { Proceeding.proceed(null); // BUG: treated as proceed(Object); } } static void proceed(Object o) {} } ---- third hypothetical: we should document how ambiguity is resolved public class Proceeding { public static void main(String[] args) { } static aspect A { void around() : execution(void main(String[])) { proceed(); // special form or Proceeding.proceed()? } } void proceed() {} }
|
resolved fixed
|
05dabd1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-10T13:22:08Z
| 2004-03-07T03:26:40Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/Proceed.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import org.aspectj.weaver.AdviceKind;
import org.eclipse.jdt.internal.compiler.ast.Expression;
import org.eclipse.jdt.internal.compiler.ast.MessageSend;
import org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.lookup.MethodScope;
import org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
/**
* Used to represent any method call to a method named <code>proceed</code>. During
* <code>resolvedType</code> it will be determined if this is actually in the body
* of an <code>around</code> advice and if not this will be treated like any other
* MessageSend.
*
* @author Jim Hugunin
*/
public class Proceed extends MessageSend {
public boolean inInner = false;
public Proceed(MessageSend parent) {
super();
this.receiver = parent.receiver;
this.selector = parent.selector;
this.arguments = parent.arguments;
this.binding = parent.binding;
this.codegenBinding = parent.codegenBinding;
this.nameSourcePosition = parent.nameSourcePosition;
this.receiverType = parent.receiverType;
this.qualifyingType = parent.qualifyingType;
this.sourceStart = parent.sourceStart;
this.sourceEnd = parent.sourceEnd;
}
public TypeBinding resolveType(BlockScope scope) {
// find out if I'm really in an around body or not
//??? this could in theory be done by the parser, but that appears to be hard
AdviceDeclaration aroundDecl = findEnclosingAround(scope);
if (aroundDecl == null) {
return super.resolveType(scope);
}
constant = NotAConstant;
binding = codegenBinding = aroundDecl.proceedMethodBinding;
this.qualifyingType = this.receiverType = binding.declaringClass;
int baseArgCount = 0;
if (arguments != null) {
baseArgCount = arguments.length;
Expression[] newArguments = new Expression[baseArgCount + 1];
System.arraycopy(arguments, 0, newArguments, 0, baseArgCount);
arguments = newArguments;
} else {
arguments = new Expression[1];
}
arguments[baseArgCount] = AstUtil.makeLocalVariableReference(aroundDecl.extraArgument.binding);
int declaredParameterCount = aroundDecl.getDeclaredParameterCount();
if (baseArgCount < declaredParameterCount) {
scope.problemReporter().signalError(this.sourceStart, this.sourceEnd,
"too few arguments to proceed, expected " + declaredParameterCount);
aroundDecl.ignoreFurtherInvestigation = true;
return null; //binding.returnType;
}
if (baseArgCount > declaredParameterCount) {
scope.problemReporter().signalError(this.sourceStart, this.sourceEnd,
"too many arguments to proceed, expected " + declaredParameterCount);
aroundDecl.ignoreFurtherInvestigation = true;
return null; //binding.returnType;
}
for (int i=0, len=arguments.length; i < len; i++) {
Expression arg = arguments[i];
TypeBinding argType = arg.resolveType(scope);
if (argType != null) {
TypeBinding paramType = binding.parameters[i];
if (!argType.isCompatibleWith(paramType)) {
scope.problemReporter().typeMismatchError(argType, paramType, arg);
}
arg.implicitWidening(binding.parameters[i], argType);
}
}
return binding.returnType;
}
private AdviceDeclaration findEnclosingAround(Scope scope) {
if (scope == null) return null;
if (scope instanceof MethodScope) {
MethodScope methodScope = (MethodScope)scope;
ReferenceContext context = methodScope.referenceContext;
if (context instanceof AdviceDeclaration) {
AdviceDeclaration adviceDecl = (AdviceDeclaration)context;
if (adviceDecl.kind == AdviceKind.Around) {
adviceDecl.proceedCalls.add(this);
return adviceDecl;
} else {
return null;
}
}
} else if (scope instanceof ClassScope) {
inInner = true;
}
return findEnclosingAround(scope.parent);
}
}
|
53,981
|
Bug 53981 proceed used as method name in around advice
|
Using a method named proceed(..) in around advice confuses the compiler (in at least the 2-3 ways shown below). True of the current tree (untested in 1.1.1). Workaround for now is to rename the method. ---- first problem: NPE in compiler java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.ast.MakeDeclsPublicVisitor.endVisit(MakeDeclsPublicVisitor.java:44) public class Proceeding { public static void main(String[] args) { } static aspect A { interface IProceed { void proceed(Runnable next); } IProceed decorator; void around() : execution(void main(String[])) { decorator.proceed(new Runnable() { public void run() { proceed(); } }); } } } ---- second problem: incorrect error wrt number of arguments public class Proceeding { public static void main(String[] args) { } static aspect A { void around() : execution(void main(String[])) { Proceeding.proceed(null); // BUG: treated as proceed(Object); } } static void proceed(Object o) {} } ---- third hypothetical: we should document how ambiguity is resolved public class Proceeding { public static void main(String[] args) { } static aspect A { void around() : execution(void main(String[])) { proceed(); // special form or Proceeding.proceed()? } } void proceed() {} }
|
resolved fixed
|
05dabd1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-10T13:22:08Z
| 2004-03-07T03:26:40Z
|
tests/src/org/aspectj/systemtest/ajc121/Ajc121Tests.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.systemtest.ajc121;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc121Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc121Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc121/ajc121.xml");
}
public void test001(){
runTest("false ambiguous binding error (introduced in 1.2rc2)");
}
public void test002(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test003(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test004(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test005(){
runTest("compiler aborts with 'conflicting dominates orders' with circular declare precedences");
}
public void test006(){
runTest("'can't bind type' message has $ for . in type name for declare soft");
}
public void test007(){
runTest("Hiding of Instance Methods by static methods");
}
public void test008(){
runTest("if(false) optimisation");
}
public void test009(){
runTest("if(true) optimisation");
}
public void test010(){
runTest("java.lang.NullPointerException in WeaverMessageHandler class");
}
public void test011(){
runTest("ClassCastException at BcelRenderer.java:169");
}
public void test012(){
runTest("Front-end bug, shouldn't allow patterns of the form foo.., should be foo..*");
}
public void test013() {
runTest("Nullpointer-Exception when defining a withincode() pointcut");
}
public void test014() {
runTest("NPE, Incorrect XLint:unmatchedSuperTypeInCall warning");
}
public void test015_invalidXlint() { // keywords: "laurie hendren"
runTest("invalid warning indicating no match when a match really occurs");
}
public void test016_ByteConversionInstructions() {
runTest("RuntimeException thrown: Could not find instruction: org.apache.bcel.generic.B2I");
String output = getLastRunResult().getStdErr();
assertTrue("Expected to find [b2] in this output but didn't:"+output,output.indexOf("[b2]")!=-1);
assertTrue("Expected to find [b127] in this output but didn't:"+output,output.indexOf("[b127]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
assertTrue("Expected to find [c65] in this output but didn't:"+output,output.indexOf("[c65]")!=-1);
assertTrue("Expected to find [c66] in this output but didn't:"+output,output.indexOf("[c66]")!=-1);
assertTrue("Expected to find [c67] in this output but didn't:"+output,output.indexOf("[c67]")!=-1);
assertTrue("Expected to find [s1] in this output but didn't:"+output,output.indexOf("[s1]")!=-1);
assertTrue("Expected to find [s32767] in this output but didn't:"+output,output.indexOf("[s32767]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
}
public void test017_PrivateMethodCallsInAroundAdvice() {
runTest("Cannot advise private method call in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test018_PrivateFieldSetsInAroundAdvice() {
runTest("Cannot advise private field sets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test019_PrivateFieldGetsInAroundAdvice() {
runTest("Cannot advise private field gets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
// test takes over 5 minutes to run, so not included in normal suite run
// public void test020_branchTargetOffsetTooLargeForShort() {
// runTest("Branch target offset too large for short");
// }
// public void test021_BcelFailureWithVeryLargeClasses() {
// runTest("Weaver fails in BCEL for large classes");
// }
//
// public void test022_BcelFailureWithVeryLargeClasses_Binary() {
// runTest("Weaver fails in BCEL for large classes (binary)");
// }
}
|
65,319
|
Bug 65319 ajc crashes when compiling the following program (binding this() and target())
|
class Test { public static void main(String args[]) { new Test().method(); } public void method() { new Test2().method2(); } } class Test2 { public void method2() {} } aspect Plain { before(Test x): call(void *.* (..)) && (this(x) || target(x)) { } }
|
resolved fixed
|
b75cd93
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-10T16:22:01Z
| 2004-06-02T15:26:40Z
|
tests/bugs/oxford/PR65319.java
| |
65,319
|
Bug 65319 ajc crashes when compiling the following program (binding this() and target())
|
class Test { public static void main(String args[]) { new Test().method(); } public void method() { new Test2().method2(); } } class Test2 { public void method2() {} } aspect Plain { before(Test x): call(void *.* (..)) && (this(x) || target(x)) { } }
|
resolved fixed
|
b75cd93
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-10T16:22:01Z
| 2004-06-02T15:26:40Z
|
tests/src/org/aspectj/systemtest/ajc121/Ajc121Tests.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.systemtest.ajc121;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc121Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc121Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc121/ajc121.xml");
}
public void test001(){
runTest("false ambiguous binding error (introduced in 1.2rc2)");
}
public void test002(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test003(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test004(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test005(){
runTest("compiler aborts with 'conflicting dominates orders' with circular declare precedences");
}
public void test006(){
runTest("'can't bind type' message has $ for . in type name for declare soft");
}
public void test007(){
runTest("Hiding of Instance Methods by static methods");
}
public void test008(){
runTest("if(false) optimisation");
}
public void test009(){
runTest("if(true) optimisation");
}
public void test010(){
runTest("java.lang.NullPointerException in WeaverMessageHandler class");
}
public void test011(){
runTest("ClassCastException at BcelRenderer.java:169");
}
public void test012(){
runTest("Front-end bug, shouldn't allow patterns of the form foo.., should be foo..*");
}
public void test013() {
runTest("Nullpointer-Exception when defining a withincode() pointcut");
}
public void test014() {
runTest("NPE, Incorrect XLint:unmatchedSuperTypeInCall warning");
}
public void test015_invalidXlint() { // keywords: "laurie hendren"
runTest("invalid warning indicating no match when a match really occurs");
}
public void test016_ByteConversionInstructions() {
runTest("RuntimeException thrown: Could not find instruction: org.apache.bcel.generic.B2I");
String output = getLastRunResult().getStdErr();
assertTrue("Expected to find [b2] in this output but didn't:"+output,output.indexOf("[b2]")!=-1);
assertTrue("Expected to find [b127] in this output but didn't:"+output,output.indexOf("[b127]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
assertTrue("Expected to find [c65] in this output but didn't:"+output,output.indexOf("[c65]")!=-1);
assertTrue("Expected to find [c66] in this output but didn't:"+output,output.indexOf("[c66]")!=-1);
assertTrue("Expected to find [c67] in this output but didn't:"+output,output.indexOf("[c67]")!=-1);
assertTrue("Expected to find [s1] in this output but didn't:"+output,output.indexOf("[s1]")!=-1);
assertTrue("Expected to find [s32767] in this output but didn't:"+output,output.indexOf("[s32767]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
}
public void test017_PrivateMethodCallsInAroundAdvice() {
runTest("Cannot advise private method call in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test018_PrivateFieldSetsInAroundAdvice() {
runTest("Cannot advise private field sets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test019_PrivateFieldGetsInAroundAdvice() {
runTest("Cannot advise private field gets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
// test takes over 5 minutes to run, so not included in normal suite run
// public void test020_branchTargetOffsetTooLargeForShort() {
// runTest("Branch target offset too large for short");
// }
// public void test021_BcelFailureWithVeryLargeClasses() {
// runTest("Weaver fails in BCEL for large classes");
// }
//
// public void test022_BcelFailureWithVeryLargeClasses_Binary() {
// runTest("Weaver fails in BCEL for large classes (binary)");
// }
public void test023_proceedInAround1() {
runTest("proceed used as method name in around advice (1)");
}
public void test024_proceedInAround2() {
runTest("proceed used as method name in around advice (2)");
}
public void test025_proceedInAround3() {
runTest("proceed used as method name in around advice (3)");
}
}
|
65,319
|
Bug 65319 ajc crashes when compiling the following program (binding this() and target())
|
class Test { public static void main(String args[]) { new Test().method(); } public void method() { new Test2().method2(); } } class Test2 { public void method2() {} } aspect Plain { before(Test x): call(void *.* (..)) && (this(x) || target(x)) { } }
|
resolved fixed
|
b75cd93
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-10T16:22:01Z
| 2004-06-02T15:26:40Z
|
weaver/src/org/aspectj/weaver/bcel/BcelAdvice.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
import org.aspectj.weaver.patterns.ExactTypePattern;
import org.aspectj.weaver.patterns.ExposedState;
import org.aspectj.weaver.patterns.Pointcut;
/**
* Advice implemented for bcel.
*
* @author Erik Hilsdale
* @author Jim Hugunin
*/
public class BcelAdvice extends Advice {
private Test pointcutTest;
private ExposedState exposedState;
public BcelAdvice(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature,
ResolvedTypeX concreteAspect)
{
super(attribute, pointcut, signature);
this.concreteAspect = concreteAspect;
}
// !!! must only be used for testing
public BcelAdvice(AdviceKind kind, Pointcut pointcut, Member signature,
int extraArgumentFlags,
int start, int end, ISourceContext sourceContext, ResolvedTypeX concreteAspect)
{
this(new AjAttribute.AdviceAttribute(kind, pointcut, extraArgumentFlags, start, end, sourceContext),
pointcut, signature, concreteAspect);
thrownExceptions = Collections.EMPTY_LIST; //!!! interaction with unit tests
}
// ---- implementations of ShadowMunger's methods
public void specializeOn(Shadow shadow) {
if (getKind() == AdviceKind.Around) {
((BcelShadow)shadow).initializeForAroundClosure();
}
//XXX this case is just here for supporting lazy test code
if (getKind() == null) {
exposedState = new ExposedState(0);
return;
}
if (getKind().isPerEntry()) {
exposedState = new ExposedState(0);
} else if (getKind().isCflow()) {
exposedState = new ExposedState(nFreeVars);
} else if (getSignature() != null) {
exposedState = new ExposedState(getSignature());
} else {
exposedState = new ExposedState(0);
return; //XXX this case is just here for supporting lazy test code
}
pointcutTest = getPointcut().findResidue(shadow, exposedState);
// these initializations won't be performed by findResidue, but need to be
// so that the joinpoint is primed for weaving
if (getKind() == AdviceKind.PerThisEntry) {
shadow.getThisVar();
} else if (getKind() == AdviceKind.PerTargetEntry) {
shadow.getTargetVar();
}
// make sure thisJoinPoint parameters are initialized
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
((BcelShadow)shadow).getThisJoinPointStaticPartVar();
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
((BcelShadow)shadow).requireThisJoinPoint(pointcutTest != Literal.TRUE && getKind() != AdviceKind.Around);
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
((BcelShadow)shadow).getThisEnclosingJoinPointStaticPartVar();
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
}
private boolean canInline(Shadow s) {
if (attribute.isProceedInInners()) return false;
//XXX this guard seems to only be needed for bad test cases
if (concreteAspect == null || concreteAspect == ResolvedTypeX.MISSING) return false;
if (concreteAspect.getWorld().isXnoInline()) return false;
//System.err.println("isWoven? " + ((BcelObjectType)concreteAspect).getLazyClassGen().getWeaverState());
return BcelWorld.getBcelObjectType(concreteAspect).getLazyClassGen().isWoven();
}
public void implementOn(Shadow s) {
BcelShadow shadow = (BcelShadow) s;
if (getKind() == AdviceKind.Before) {
shadow.weaveBefore(this);
} else if (getKind() == AdviceKind.AfterReturning) {
shadow.weaveAfterReturning(this);
} else if (getKind() == AdviceKind.AfterThrowing) {
TypeX catchType =
hasExtraParameter()
? getExtraParameterType()
: TypeX.THROWABLE;
shadow.weaveAfterThrowing(this, catchType);
} else if (getKind() == AdviceKind.After) {
shadow.weaveAfter(this);
} else if (getKind() == AdviceKind.Around) {
if (!canInline(s)) {
shadow.weaveAroundClosure(this, hasDynamicTests());
} else {
shadow.weaveAroundInline(this, hasDynamicTests());
}
} else if (getKind() == AdviceKind.InterInitializer) {
shadow.weaveAfterReturning(this);
} else if (getKind().isCflow()) {
shadow.weaveCflowEntry(this, getSignature());
} else if (getKind() == AdviceKind.PerThisEntry) {
shadow.weavePerObjectEntry(this, (BcelVar)shadow.getThisVar());
} else if (getKind() == AdviceKind.PerTargetEntry) {
shadow.weavePerObjectEntry(this, (BcelVar)shadow.getTargetVar());
} else if (getKind() == AdviceKind.Softener) {
shadow.weaveSoftener(this, ((ExactTypePattern)exceptionType).getType());
} else {
throw new BCException("unimplemented kind: " + getKind());
}
}
// ---- implementations
private Collection collectCheckedExceptions(TypeX[] excs) {
if (excs == null || excs.length == 0) return Collections.EMPTY_LIST;
Collection ret = new ArrayList();
World world = concreteAspect.getWorld();
ResolvedTypeX runtimeException = world.getCoreType(TypeX.RUNTIME_EXCEPTION);
ResolvedTypeX error = world.getCoreType(TypeX.ERROR);
for (int i=0, len=excs.length; i < len; i++) {
ResolvedTypeX t = world.resolve(excs[i]);
if (!(runtimeException.isAssignableFrom(t) || error.isAssignableFrom(t))) {
ret.add(t);
}
}
return ret;
}
private Collection thrownExceptions = null;
public Collection getThrownExceptions() {
if (thrownExceptions == null) {
//??? can we really lump in Around here, how does this interact with Throwable
if (concreteAspect != null && concreteAspect.getWorld() != null && // null tests for test harness
(getKind().isAfter() || getKind() == AdviceKind.Before || getKind() == AdviceKind.Around))
{
World world = concreteAspect.getWorld();
ResolvedMember m = world.resolve(signature);
if (m == null) {
thrownExceptions = Collections.EMPTY_LIST;
} else {
thrownExceptions = collectCheckedExceptions(m.getExceptions());
}
} else {
thrownExceptions = Collections.EMPTY_LIST;
}
}
return thrownExceptions;
}
// only call me after prepare has been called
public boolean hasDynamicTests() {
// if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) {
// TypeX extraParameterType = getExtraParameterType();
// if (! extraParameterType.equals(TypeX.OBJECT)
// && ! extraParameterType.isPrimitive())
// return true;
// }
return pointcutTest != null &&
!(pointcutTest == Literal.TRUE);// || pointcutTest == Literal.NO_TEST);
}
/**
* get the instruction list for the really simple version of this advice.
* Is broken apart
* for other advice, but if you want it in one block, this is the method to call.
*
* @param s The shadow around which these instructions will eventually live.
* @param extraArgVar The var that will hold the return value or thrown exception
* for afterX advice
* @param ifNoAdvice The instructionHandle to jump to if the dynamic
* tests for this munger fails.
*/
InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice)
{
BcelShadow shadow = (BcelShadow) s;
InstructionFactory fact = shadow.getFactory();
BcelWorld world = shadow.getWorld();
InstructionList il = new InstructionList();
// we test to see if we have the right kind of thing...
// after throwing does this just by the exception mechanism.
if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) {
TypeX extraParameterType = getExtraParameterType();
if (! extraParameterType.equals(TypeX.OBJECT)
&& ! extraParameterType.isPrimitive()) {
il.append(
BcelRenderer.renderTest(
fact,
world,
Test.makeInstanceof(
extraArgVar, getExtraParameterType().resolve(world)),
null,
ifNoAdvice,
null));
}
}
il.append(getAdviceArgSetup(shadow, extraArgVar, null));
il.append(getNonTestAdviceInstructions(shadow));
InstructionHandle ifYesAdvice = il.getStart();
il.insert(getTestInstructions(shadow, ifYesAdvice, ifNoAdvice, ifYesAdvice));
return il;
}
public InstructionList getAdviceArgSetup(
BcelShadow shadow,
BcelVar extraVar,
InstructionList closureInstantiation)
{
InstructionFactory fact = shadow.getFactory();
BcelWorld world = shadow.getWorld();
InstructionList il = new InstructionList();
// if (targetAspectField != null) {
// il.append(fact.createFieldAccess(
// targetAspectField.getDeclaringType().getName(),
// targetAspectField.getName(),
// BcelWorld.makeBcelType(targetAspectField.getType()),
// Constants.GETSTATIC));
// }
//
//System.err.println("BcelAdvice: " + exposedState);
if (exposedState.getAspectInstance() != null) {
il.append(
BcelRenderer.renderExpr(fact, world, exposedState.getAspectInstance()));
}
for (int i = 0, len = exposedState.size(); i < len; i++) {
BcelVar v = (BcelVar) exposedState.get(i);
if (v == null) continue;
TypeX desiredTy = getSignature().getParameterTypes()[i];
v.appendLoadAndConvert(il, fact, desiredTy.resolve(world));
}
if (getKind() == AdviceKind.Around) {
il.append(closureInstantiation);
} else if (hasExtraParameter()) {
extraVar.appendLoadAndConvert(
il,
fact,
getExtraParameterType().resolve(world));
}
// handle thisJoinPoint parameters
// these need to be in that same order as parameters in
// org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
il.append(shadow.loadThisJoinPoint());
}
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
return il;
}
public InstructionList getNonTestAdviceInstructions(BcelShadow shadow) {
return new InstructionList(
Utility.createInvoke(shadow.getFactory(), shadow.getWorld(), getSignature()));
}
public InstructionList getTestInstructions(
BcelShadow shadow,
InstructionHandle sk,
InstructionHandle fk,
InstructionHandle next)
{
//System.err.println("test: " + pointcutTest);
return BcelRenderer.renderTest(
shadow.getFactory(),
shadow.getWorld(),
pointcutTest,
sk,
fk,
next);
}
public int compareTo(Object other) {
if (!(other instanceof BcelAdvice)) return 0;
BcelAdvice o = (BcelAdvice)other;
//System.err.println("compareTo: " + this + ", " + o);
if (kind.getPrecedence() != o.kind.getPrecedence()) {
if (kind.getPrecedence() > o.kind.getPrecedence()) return +1;
else return -1;
}
if (kind.isCflow()) {
// System.err.println("sort: " + this + " innerCflowEntries " + innerCflowEntries);
// System.err.println(" " + o + " innerCflowEntries " + o.innerCflowEntries);
boolean isBelow = (kind == AdviceKind.CflowBelowEntry);
if (this.innerCflowEntries.contains(o)) return isBelow ? +1 : -1;
else if (o.innerCflowEntries.contains(this)) return isBelow ? -1 : +1;
else return 0;
}
if (kind.isPerEntry() || kind == AdviceKind.Softener) {
return 0;
}
//System.out.println("compare: " + this + " with " + other);
World world = concreteAspect.getWorld();
int ret =
concreteAspect.getWorld().compareByDominates(
concreteAspect,
o.concreteAspect);
if (ret != 0) return ret;
ResolvedTypeX declaringAspect = getDeclaringAspect().resolve(world);
ResolvedTypeX o_declaringAspect = o.getDeclaringAspect().resolve(world);
if (declaringAspect == o_declaringAspect) {
if (kind.isAfter() || o.kind.isAfter()) {
return this.getStart() < o.getStart() ? -1: +1;
} else {
return this.getStart()< o.getStart() ? +1: -1;
}
} else if (declaringAspect.isAssignableFrom(o_declaringAspect)) {
return -1;
} else if (o_declaringAspect.isAssignableFrom(declaringAspect)) {
return +1;
} else {
return 0;
}
}
public BcelVar[] getExposedStateAsBcelVars() {
//System.out.println("vars: " + Arrays.asList(exposedState.vars));
if (exposedState == null) return BcelVar.NONE;
int len = exposedState.vars.length;
BcelVar[] ret = new BcelVar[len];
for (int i=0; i < len; i++) {
ret[i] = (BcelVar)exposedState.vars[i];
}
return ret; //(BcelVar[]) exposedState.vars;
}
}
|
65,319
|
Bug 65319 ajc crashes when compiling the following program (binding this() and target())
|
class Test { public static void main(String args[]) { new Test().method(); } public void method() { new Test2().method2(); } } class Test2 { public void method2() {} } aspect Plain { before(Test x): call(void *.* (..)) && (this(x) || target(x)) { } }
|
resolved fixed
|
b75cd93
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-10T16:22:01Z
| 2004-06-02T15:26:40Z
|
weaver/src/org/aspectj/weaver/patterns/ArgsPointcut.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.CodeSignature;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.BetaException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
/**
* args(arguments)
*
* @author Erik Hilsdale
* @author Jim Hugunin
*/
public class ArgsPointcut extends NameBindingPointcut {
TypePatternList arguments;
public ArgsPointcut(TypePatternList arguments) {
this.arguments = arguments;
}
public FuzzyBoolean fastMatch(FastMatchInfo type) {
return FuzzyBoolean.MAYBE;
}
public FuzzyBoolean match(Shadow shadow) {
FuzzyBoolean ret =
arguments.matches(shadow.getIWorld().resolve(shadow.getArgTypes()), TypePattern.DYNAMIC);
return ret;
}
public FuzzyBoolean match(JoinPoint jp, JoinPoint.StaticPart jpsp) {
FuzzyBoolean ret = arguments.matches(jp.getArgs(),TypePattern.DYNAMIC);
// this may have given a false match (e.g. args(int) may have matched a call to doIt(Integer x)) due to boxing
// check for this...
if (ret == FuzzyBoolean.YES) {
// are the sigs compatible too...
CodeSignature sig = (CodeSignature)jp.getSignature();
Class[] pTypes = sig.getParameterTypes();
Collection tps = arguments.getExactTypes();
int sigIndex = 0;
for (Iterator iter = tps.iterator(); iter.hasNext();) {
TypeX tp = (TypeX) iter.next();
Class lookForClass = getPossiblyBoxed(tp);
if (lookForClass != null) {
boolean foundMatchInSig = false;
while (sigIndex < pTypes.length && !foundMatchInSig) {
if (pTypes[sigIndex++] == lookForClass) foundMatchInSig = true;
}
if (!foundMatchInSig) {
ret = FuzzyBoolean.NO;
break;
}
}
}
}
return ret;
}
private Class getPossiblyBoxed(TypeX tp) {
Class ret = (Class) ExactTypePattern.primitiveTypesMap.get(tp.getName());
if (ret == null) ret = (Class) ExactTypePattern.boxedPrimitivesMap.get(tp.getName());
return ret;
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.ARGS);
arguments.write(s);
writeLocation(s);
}
public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException {
ArgsPointcut ret = new ArgsPointcut(TypePatternList.read(s, context));
ret.readLocation(context, s);
return ret;
}
public boolean equals(Object other) {
if (!(other instanceof ArgsPointcut)) return false;
ArgsPointcut o = (ArgsPointcut)other;
return o.arguments.equals(this.arguments);
}
public int hashCode() {
return arguments.hashCode();
}
public void resolveBindings(IScope scope, Bindings bindings) {
arguments.resolveBindings(scope, bindings, true, true);
if (arguments.ellipsisCount > 1) {
scope.message(IMessage.ERROR, this,
"uses more than one .. in args (compiler limitation)");
}
}
public void resolveBindingsFromRTTI() {
arguments.resolveBindingsFromRTTI(true, true);
if (arguments.ellipsisCount > 1) {
throw new UnsupportedOperationException("uses more than one .. in args (compiler limitation)");
}
}
public void postRead(ResolvedTypeX enclosingType) {
arguments.postRead(enclosingType);
}
public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) {
if (isDeclare(bindings.getEnclosingAdvice())) {
// Enforce rule about which designators are supported in declare
inAspect.getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ARGS_IN_DECLARE),
bindings.getEnclosingAdvice().getSourceLocation(), null);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
TypePatternList args = arguments.resolveReferences(bindings);
if (inAspect.crosscuttingMembers != null) {
inAspect.crosscuttingMembers.exposeTypes(args.getExactTypes());
}
return new ArgsPointcut(args);
}
private Test findResidueNoEllipsis(Shadow shadow, ExposedState state, TypePattern[] patterns) {
int len = shadow.getArgCount();
//System.err.println("boudn to : " + len + ", " + patterns.length);
if (patterns.length != len) {
return Literal.FALSE;
}
Test ret = Literal.TRUE;
for (int i=0; i < len; i++) {
TypeX argType = shadow.getArgType(i);
TypePattern type = patterns[i];
if (!(type instanceof BindingTypePattern)) {
if (type.matchesInstanceof(shadow.getIWorld().resolve(argType)).alwaysTrue()) {
continue;
}
} else {
BindingTypePattern btp = (BindingTypePattern)type;
// Check if we have already bound something to this formal
if (state.get(btp.getFormalIndex())!=null) {
ISourceLocation isl = getSourceLocation();
Message errorMessage = new Message(
"Ambiguous binding of type "+type.getExactType().toString()+
" using args(..) at this line. Use one args(..) per matched join point,"+"" +
" see secondary source location for location of extraneous args(..)",
shadow.getSourceLocation(),true,new ISourceLocation[]{getSourceLocation()});
shadow.getIWorld().getMessageHandler().handleMessage(errorMessage);
}
}
ret = Test.makeAnd(ret,
exposeStateForVar(shadow.getArgVar(i), type, state,shadow.getIWorld()));
}
return ret;
}
public Test findResidue(Shadow shadow, ExposedState state) {
if (arguments.matches(shadow.getIWorld().resolve(shadow.getArgTypes()), TypePattern.DYNAMIC).alwaysFalse()) {
return Literal.FALSE;
}
int ellipsisCount = arguments.ellipsisCount;
if (ellipsisCount == 0) {
return findResidueNoEllipsis(shadow, state, arguments.getTypePatterns());
} else if (ellipsisCount == 1) {
TypePattern[] patternsWithEllipsis = arguments.getTypePatterns();
TypePattern[] patternsWithoutEllipsis = new TypePattern[shadow.getArgCount()];
int lenWithEllipsis = patternsWithEllipsis.length;
int lenWithoutEllipsis = patternsWithoutEllipsis.length;
// l1+1 >= l0
int indexWithEllipsis = 0;
int indexWithoutEllipsis = 0;
while (indexWithoutEllipsis < lenWithoutEllipsis) {
TypePattern p = patternsWithEllipsis[indexWithEllipsis++];
if (p == TypePattern.ELLIPSIS) {
int newLenWithoutEllipsis =
lenWithoutEllipsis - (lenWithEllipsis-indexWithEllipsis);
while (indexWithoutEllipsis < newLenWithoutEllipsis) {
patternsWithoutEllipsis[indexWithoutEllipsis++] = TypePattern.ANY;
}
} else {
patternsWithoutEllipsis[indexWithoutEllipsis++] = p;
}
}
return findResidueNoEllipsis(shadow, state, patternsWithoutEllipsis);
} else {
throw new BetaException("unimplemented");
}
}
public String toString() {
return "args" + arguments.toString() + "";
}
}
|
65,319
|
Bug 65319 ajc crashes when compiling the following program (binding this() and target())
|
class Test { public static void main(String args[]) { new Test().method(); } public void method() { new Test2().method2(); } } class Test2 { public void method2() {} } aspect Plain { before(Test x): call(void *.* (..)) && (this(x) || target(x)) { } }
|
resolved fixed
|
b75cd93
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-10T16:22:01Z
| 2004-06-02T15:26:40Z
|
weaver/src/org/aspectj/weaver/patterns/ExposedState.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.util.Arrays;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ast.Expr;
import org.aspectj.weaver.ast.Var;
public class ExposedState {
public Var[] vars;
private Expr aspectInstance;
public ExposedState(int size) {
super();
vars = new Var[size];
}
public ExposedState(Member signature) {
// XXX there maybe something about target for non-static sigs
this(signature.getParameterTypes().length);
}
public void set(int i, Var var) {
//XXX add sanity checks
// Check (1) added to call of set(), verifies we aren't binding twice to the same formal
vars[i] = var;
}
public Var get(int i) {
return vars[i];
}
public int size() {
return vars.length;
}
public Expr getAspectInstance() {
return aspectInstance;
}
public void setAspectInstance(Expr aspectInstance) {
this.aspectInstance = aspectInstance;
}
public String toString() {
return "ExposedState(" + Arrays.asList(vars) + ", " + aspectInstance + ")";
}
}
|
65,319
|
Bug 65319 ajc crashes when compiling the following program (binding this() and target())
|
class Test { public static void main(String args[]) { new Test().method(); } public void method() { new Test2().method2(); } } class Test2 { public void method2() {} } aspect Plain { before(Test x): call(void *.* (..)) && (this(x) || target(x)) { } }
|
resolved fixed
|
b75cd93
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-10T16:22:01Z
| 2004-06-02T15:26:40Z
|
weaver/src/org/aspectj/weaver/patterns/ThisOrTargetPointcut.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.aspectj.bridge.IMessage;
import org.aspectj.lang.JoinPoint;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
import org.aspectj.weaver.ast.Var;
//
/**
* Corresponds to target or this pcd.
*
* <p>type is initially a WildTypePattern. If it stays that way, it's a this(Foo)
* type deal.
* however, the resolveBindings method may convert it to a BindingTypePattern,
* in which
* case, it's a this(foo) type deal.
*
* @author Erik Hilsdale
* @author Jim Hugunin
*/
public class ThisOrTargetPointcut extends NameBindingPointcut {
private boolean isThis;
private TypePattern type;
public ThisOrTargetPointcut(boolean isThis, TypePattern type) {
this.isThis = isThis;
this.type = type;
}
public FuzzyBoolean fastMatch(FastMatchInfo type) {
return FuzzyBoolean.MAYBE;
}
private boolean couldMatch(Shadow shadow) {
return isThis ? shadow.hasThis() : shadow.hasTarget();
}
public FuzzyBoolean match(Shadow shadow) {
if (!couldMatch(shadow)) return FuzzyBoolean.NO;
TypeX typeToMatch = isThis ? shadow.getThisType() : shadow.getTargetType();
//if (typeToMatch == ResolvedTypeX.MISSING) return FuzzyBoolean.NO;
return type.matches(typeToMatch.resolve(shadow.getIWorld()), TypePattern.DYNAMIC);
}
public FuzzyBoolean match(JoinPoint jp, JoinPoint.StaticPart encJP) {
Object toMatch = isThis ? jp.getThis() : jp.getTarget();
if (toMatch == null) return FuzzyBoolean.NO;
return type.matches(toMatch.getClass(), TypePattern.DYNAMIC);
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.THIS_OR_TARGET);
s.writeBoolean(isThis);
type.write(s);
writeLocation(s);
}
public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException {
boolean isThis = s.readBoolean();
TypePattern type = TypePattern.read(s, context);
ThisOrTargetPointcut ret = new ThisOrTargetPointcut(isThis, type);
ret.readLocation(context, s);
return ret;
}
public void resolveBindings(IScope scope, Bindings bindings) {
type = type.resolveBindings(scope, bindings, true, true);
// ??? handle non-formal
}
public void resolveBindingsFromRTTI() {
type = type.resolveBindingsFromRTTI(true,true);
}
public void postRead(ResolvedTypeX enclosingType) {
type.postRead(enclosingType);
}
public boolean equals(Object other) {
if (!(other instanceof ThisOrTargetPointcut)) return false;
ThisOrTargetPointcut o = (ThisOrTargetPointcut)other;
return o.isThis == this.isThis && o.type.equals(this.type);
}
public int hashCode() {
int result = 17;
result = 37*result + (isThis ? 0 : 1);
result = 37*result + type.hashCode();
return result;
}
public String toString() {
return (isThis ? "this(" : "target(") + type + ")";
}
public Test findResidue(Shadow shadow, ExposedState state) {
if (!couldMatch(shadow)) return Literal.FALSE;
if (type == TypePattern.ANY) return Literal.TRUE;
Var var = isThis ? shadow.getThisVar() : shadow.getTargetVar();
return exposeStateForVar(var, type, state, shadow.getIWorld());
}
public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) {
if (isDeclare(bindings.getEnclosingAdvice())) {
// Enforce rule about which designators are supported in declare
inAspect.getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.THIS_OR_TARGET_IN_DECLARE,isThis?"this":"target"),
bindings.getEnclosingAdvice().getSourceLocation(), null);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
TypePattern newType = type.remapAdviceFormals(bindings);
if (inAspect.crosscuttingMembers != null) {
inAspect.crosscuttingMembers.exposeType(newType.getExactType());
}
return new ThisOrTargetPointcut(isThis, newType);
}
}
|
68,991
|
Bug 68991 intertype initialisers should match field set pointcuts
|
/* initialisers of intertype fields should match field set pointcuts. In the example below, the output should be set field set(int C.n) set field set(int C.m) get field get(int C.n) set field set(int C.n) but the first field set (of C.n) is not picked up. */ aspect Aspect { private int C.n = 13; before() : get(* C.*) { System.out.println("get field "+thisJoinPointStaticPart); } before() : set(* C.*) { System.out.println("set field "+thisJoinPointStaticPart); } public void C.foo() { n++; } } class C { int m = 20; } public class ITFieldsAdvice { public static void main(String[] args) { C c = new C(); c.foo(); } }
|
resolved fixed
|
64183c3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-11T12:24:27Z
| 2004-06-30T12:53:20Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/InterTypeFieldDeclaration.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import java.lang.reflect.Modifier;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseTypeMunger;
import org.aspectj.weaver.*;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.*;
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.eclipse.jdt.internal.compiler.lookup.*;
import org.eclipse.jdt.internal.compiler.parser.Parser;
/**
* An inter-type field declaration.
*
* returnType encodes the type of the field
* selector encodes the name
* statements is null until resolution when it is filled in from the initializer
*
* @author Jim Hugunin
*/
public class InterTypeFieldDeclaration extends InterTypeDeclaration {
public Expression initialization;
//public InterTypeFieldBinding interBinding;
public InterTypeFieldDeclaration(CompilationResult result, TypeReference onType) {
super(result, onType);
}
public void parseStatements(Parser parser, CompilationUnitDeclaration unit) {
//we don't have a body to parse
}
public void resolveOnType(ClassScope classScope) {
super.resolveOnType(classScope);
if (ignoreFurtherInvestigation) return;
if (Modifier.isStatic(declaredModifiers) && onTypeBinding.isInterface()) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"static inter-type field on interface not supported");
ignoreFurtherInvestigation = true;
}
}
public void resolve(ClassScope upperScope) {
if (munger == null) ignoreFurtherInvestigation = true;
if (ignoreFurtherInvestigation) return;
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(upperScope);
ResolvedMember sig = munger.getSignature();
TypeX aspectType = EclipseFactory.fromBinding(upperScope.referenceContext.binding);
if (sig.getReturnType() == ResolvedTypeX.VOID ||
(sig.getReturnType().isArray() && (sig.getReturnType().getComponentType() == ResolvedTypeX.VOID)))
{
upperScope.problemReporter().signalError(sourceStart, sourceEnd,
"field type can not be void");
}
//
// System.err.println("sig: " + sig);
// System.err.println("field: " + world.makeFieldBinding(
// AjcMemberMaker.interFieldClassField(sig, aspectType)));
if (initialization != null && initialization instanceof ArrayInitializer) {
//System.err.println("got initializer: " + initialization);
ArrayAllocationExpression aae = new ArrayAllocationExpression();
aae.initializer = (ArrayInitializer)initialization;
ArrayBinding arrayType = (ArrayBinding)world.makeTypeBinding(sig.getReturnType());
aae.type = AstUtil.makeTypeReference(arrayType.leafComponentType());
aae.sourceStart = initialization.sourceStart;
aae.sourceEnd = initialization.sourceEnd;
aae.dimensions = new Expression[arrayType.dimensions];
initialization = aae;
}
if (initialization == null) {
this.statements = new Statement[] {
new ReturnStatement(null, 0, 0),
};
} else if (!onTypeBinding.isInterface()) {
FieldBinding interField = world.makeFieldBinding(
AjcMemberMaker.interFieldClassField(sig, aspectType));
Reference ref = new KnownFieldReference(interField, 0);
this.statements = new Statement[] {
new Assignment(ref, initialization, initialization.sourceEnd),
};
} else {
//XXX something is broken about this logic. Can we write to static interface fields?
MethodBinding writeMethod = world.makeMethodBinding(
AjcMemberMaker.interFieldInterfaceSetter(sig, sig.getDeclaringType().resolve(world.getWorld()), aspectType));
if (Modifier.isStatic(declaredModifiers)) {
this.statements = new Statement[] {
new KnownMessageSend(writeMethod,
AstUtil.makeNameReference(writeMethod.declaringClass),
new Expression[] {initialization}),
};
} else {
this.statements = new Statement[] {
new KnownMessageSend(writeMethod,
AstUtil.makeLocalVariableReference(arguments[0].binding),
new Expression[] {initialization}),
};
}
}
super.resolve(upperScope);
}
public void setInitialization(Expression initialization) {
this.initialization = initialization;
}
public EclipseTypeMunger build(ClassScope classScope) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope);
resolveOnType(classScope);
if (ignoreFurtherInvestigation) return null;
binding = classScope.referenceContext.binding.resolveTypesFor(binding);
if (ignoreFurtherInvestigation) return null;
if (!Modifier.isStatic(declaredModifiers)) {
super.binding.parameters = new TypeBinding[] {
onTypeBinding,
};
this.arguments = new Argument[] {
AstUtil.makeFinalArgument("ajc$this_".toCharArray(), onTypeBinding),
};
}
//System.err.println("type: " + binding.returnType + ", " + returnType);
ResolvedMember sig =
new ResolvedMember(Member.FIELD, EclipseFactory.fromBinding(onTypeBinding),
declaredModifiers, EclipseFactory.fromBinding(binding.returnType),
new String(declaredSelector), TypeX.NONE);
NewFieldTypeMunger myMunger = new NewFieldTypeMunger(sig, null);
setMunger(myMunger);
ResolvedTypeX aspectType = world.fromEclipse(classScope.referenceContext.binding);
ResolvedMember me =
myMunger.getInitMethod(aspectType);
this.selector = binding.selector = me.getName().toCharArray();
this.binding.returnType = TypeBinding.VoidBinding;
//??? all other pieces should already match
return new EclipseTypeMunger(world, myMunger, aspectType, this);
}
private AjAttribute makeAttribute() {
return new AjAttribute.TypeMunger(munger);
}
public void generateCode(ClassScope classScope, ClassFile classFile) {
if (ignoreFurtherInvestigation) return;
classFile.extraAttributes.add(new EclipseAttributeAdapter(makeAttribute()));
super.generateCode(classScope, classFile);
generateDispatchMethods(classScope, classFile);
// interBinding.reader.generateMethod(this, classScope, classFile);
// interBinding.writer.generateMethod(this, classScope, classFile);
}
private void generateDispatchMethods(ClassScope classScope, ClassFile classFile) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope);
ResolvedMember sig = munger.getSignature();
TypeX aspectType = EclipseFactory.fromBinding(classScope.referenceContext.binding);
generateDispatchMethod(world, sig, aspectType, classScope, classFile, true);
generateDispatchMethod(world, sig, aspectType, classScope, classFile, false);
}
private void generateDispatchMethod(
EclipseFactory world,
ResolvedMember sig,
TypeX aspectType,
ClassScope classScope,
ClassFile classFile,
boolean isGetter)
{
MethodBinding binding;
if (isGetter) {
binding = world.makeMethodBinding(AjcMemberMaker.interFieldGetDispatcher(sig, aspectType));
} else {
binding = world.makeMethodBinding(AjcMemberMaker.interFieldSetDispatcher(sig, aspectType));
}
classFile.generateMethodInfoHeader(binding);
int methodAttributeOffset = classFile.contentsOffset;
int attributeNumber = classFile.generateMethodInfoAttribute(binding,
makeEffectiveSignatureAttribute(sig, isGetter ? Shadow.FieldGet : Shadow.FieldSet, false));
int codeAttributeOffset = classFile.contentsOffset;
classFile.generateCodeAttributeHeader();
CodeStream codeStream = classFile.codeStream;
codeStream.reset(this, classFile);
FieldBinding classField = world.makeFieldBinding(
AjcMemberMaker.interFieldClassField(sig, aspectType));
codeStream.initializeMaxLocals(binding);
if (isGetter) {
if (onTypeBinding.isInterface()) {
MethodBinding readMethod = world.makeMethodBinding(
AjcMemberMaker.interFieldInterfaceGetter(
sig, world.getWorld().resolve(sig.getDeclaringType()), aspectType));
generateInterfaceReadBody(binding, readMethod, codeStream);
} else {
generateClassReadBody(binding, classField, codeStream);
}
} else {
if (onTypeBinding.isInterface()) {
MethodBinding writeMethod = world.makeMethodBinding(
AjcMemberMaker.interFieldInterfaceSetter(
sig, world.getWorld().resolve(sig.getDeclaringType()), aspectType));
generateInterfaceWriteBody(binding, writeMethod, codeStream);
} else {
generateClassWriteBody(binding, classField, codeStream);
}
}
AstUtil.generateReturn(binding.returnType, codeStream);
classFile.completeCodeAttribute(codeAttributeOffset);
attributeNumber++;
classFile.completeMethodInfo(methodAttributeOffset, attributeNumber);
}
private void generateInterfaceReadBody(MethodBinding binding, MethodBinding readMethod, CodeStream codeStream) {
codeStream.aload_0();
codeStream.invokeinterface(readMethod);
}
private void generateInterfaceWriteBody(MethodBinding binding, MethodBinding writeMethod, CodeStream codeStream) {
codeStream.aload_0();
codeStream.load(writeMethod.parameters[0], 1);
codeStream.invokeinterface(writeMethod);
}
private void generateClassReadBody(MethodBinding binding, FieldBinding field, CodeStream codeStream) {
if (field.isStatic()) {
codeStream.getstatic(field);
} else {
codeStream.aload_0();
codeStream.getfield(field);
}
}
private void generateClassWriteBody(MethodBinding binding, FieldBinding field, CodeStream codeStream) {
if (field.isStatic()) {
codeStream.load(field.type, 0);
codeStream.putstatic(field);
} else {
codeStream.aload_0();
codeStream.load(field.type, 1);
codeStream.putfield(field);
}
}
protected Shadow.Kind getShadowKindForBody() {
return null;
}
}
|
68,991
|
Bug 68991 intertype initialisers should match field set pointcuts
|
/* initialisers of intertype fields should match field set pointcuts. In the example below, the output should be set field set(int C.n) set field set(int C.m) get field get(int C.n) set field set(int C.n) but the first field set (of C.n) is not picked up. */ aspect Aspect { private int C.n = 13; before() : get(* C.*) { System.out.println("get field "+thisJoinPointStaticPart); } before() : set(* C.*) { System.out.println("set field "+thisJoinPointStaticPart); } public void C.foo() { n++; } } class C { int m = 20; } public class ITFieldsAdvice { public static void main(String[] args) { C c = new C(); c.foo(); } }
|
resolved fixed
|
64183c3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-11T12:24:27Z
| 2004-06-30T12:53:20Z
|
tests/bugs/PR68991/Oxford.java
| |
68,991
|
Bug 68991 intertype initialisers should match field set pointcuts
|
/* initialisers of intertype fields should match field set pointcuts. In the example below, the output should be set field set(int C.n) set field set(int C.m) get field get(int C.n) set field set(int C.n) but the first field set (of C.n) is not picked up. */ aspect Aspect { private int C.n = 13; before() : get(* C.*) { System.out.println("get field "+thisJoinPointStaticPart); } before() : set(* C.*) { System.out.println("set field "+thisJoinPointStaticPart); } public void C.foo() { n++; } } class C { int m = 20; } public class ITFieldsAdvice { public static void main(String[] args) { C c = new C(); c.foo(); } }
|
resolved fixed
|
64183c3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-11T12:24:27Z
| 2004-06-30T12:53:20Z
|
tests/bugs/PR68991/Simple.java
| |
68,991
|
Bug 68991 intertype initialisers should match field set pointcuts
|
/* initialisers of intertype fields should match field set pointcuts. In the example below, the output should be set field set(int C.n) set field set(int C.m) get field get(int C.n) set field set(int C.n) but the first field set (of C.n) is not picked up. */ aspect Aspect { private int C.n = 13; before() : get(* C.*) { System.out.println("get field "+thisJoinPointStaticPart); } before() : set(* C.*) { System.out.println("set field "+thisJoinPointStaticPart); } public void C.foo() { n++; } } class C { int m = 20; } public class ITFieldsAdvice { public static void main(String[] args) { C c = new C(); c.foo(); } }
|
resolved fixed
|
64183c3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-11T12:24:27Z
| 2004-06-30T12:53:20Z
|
tests/src/org/aspectj/systemtest/ajc121/Ajc121Tests.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.systemtest.ajc121;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc121Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc121Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc121/ajc121.xml");
}
public void test001(){
runTest("false ambiguous binding error (introduced in 1.2rc2)");
}
public void test002(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test003(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test004(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test005(){
runTest("compiler aborts with 'conflicting dominates orders' with circular declare precedences");
}
public void test006(){
runTest("'can't bind type' message has $ for . in type name for declare soft");
}
public void test007(){
runTest("Hiding of Instance Methods by static methods");
}
public void test008(){
runTest("if(false) optimisation");
}
public void test009(){
runTest("if(true) optimisation");
}
public void test010(){
runTest("java.lang.NullPointerException in WeaverMessageHandler class");
}
public void test011(){
runTest("ClassCastException at BcelRenderer.java:169");
}
public void test012(){
runTest("Front-end bug, shouldn't allow patterns of the form foo.., should be foo..*");
}
public void test013() {
runTest("Nullpointer-Exception when defining a withincode() pointcut");
}
public void test014() {
runTest("NPE, Incorrect XLint:unmatchedSuperTypeInCall warning");
}
public void test015_invalidXlint() { // keywords: "laurie hendren"
runTest("invalid warning indicating no match when a match really occurs");
}
public void test016_ByteConversionInstructions() {
runTest("RuntimeException thrown: Could not find instruction: org.apache.bcel.generic.B2I");
String output = getLastRunResult().getStdErr();
assertTrue("Expected to find [b2] in this output but didn't:"+output,output.indexOf("[b2]")!=-1);
assertTrue("Expected to find [b127] in this output but didn't:"+output,output.indexOf("[b127]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
assertTrue("Expected to find [c65] in this output but didn't:"+output,output.indexOf("[c65]")!=-1);
assertTrue("Expected to find [c66] in this output but didn't:"+output,output.indexOf("[c66]")!=-1);
assertTrue("Expected to find [c67] in this output but didn't:"+output,output.indexOf("[c67]")!=-1);
assertTrue("Expected to find [s1] in this output but didn't:"+output,output.indexOf("[s1]")!=-1);
assertTrue("Expected to find [s32767] in this output but didn't:"+output,output.indexOf("[s32767]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
}
public void test017_PrivateMethodCallsInAroundAdvice() {
runTest("Cannot advise private method call in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test018_PrivateFieldSetsInAroundAdvice() {
runTest("Cannot advise private field sets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test019_PrivateFieldGetsInAroundAdvice() {
runTest("Cannot advise private field gets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
// test takes over 5 minutes to run, so not included in normal suite run
// public void test020_branchTargetOffsetTooLargeForShort() {
// runTest("Branch target offset too large for short");
// }
// public void test021_BcelFailureWithVeryLargeClasses() {
// runTest("Weaver fails in BCEL for large classes");
// }
//
// public void test022_BcelFailureWithVeryLargeClasses_Binary() {
// runTest("Weaver fails in BCEL for large classes (binary)");
// }
public void test023_proceedInAround1() {
runTest("proceed used as method name in around advice (1)");
}
public void test024_proceedInAround2() {
runTest("proceed used as method name in around advice (2)");
}
public void test025_proceedInAround3() {
runTest("proceed used as method name in around advice (3)");
}
public void test026_bindingThisAndTargetToTheSameFormal() {
runTest("ajc crashes when compiling the following program (binding this() and target())");
}
public void test027_itdsOnInnerClassesAsStatic() {
runTest("ITDs on inner classes should be static context");
}
// public void test028_itdsAndInitializers() {
// runTest("resolution of IT field inits");
// }
public void test029_falseInvalidAbsoluteTypeName() {
runTest("Valid but inaccessible type names should not be flagged by XLint:invalidAbsoluteTypeName");
}
}
|
54,421
|
Bug 54421 Compile time declarations (warning and error) do not accept string concatenation (with +)
|
The following code does not compile because the message uses string concatenation (the + operator). public class WarningSample { public void method() {} public void anotherMethod() { this.method(); } } aspect WarningAspect { pointcut illegalCall(): call(* WarningSample.method()) && within(WarningSample); // the same thing happens with declare error declare warning: illegalCall() : "Hey, don't " + "do that, that is not nice. You should do something else"; }
|
resolved fixed
|
d43a391
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-11T13:18:24Z
| 2004-03-11T07:26:40Z
|
tests/bugs/decwStrings.java
| |
54,421
|
Bug 54421 Compile time declarations (warning and error) do not accept string concatenation (with +)
|
The following code does not compile because the message uses string concatenation (the + operator). public class WarningSample { public void method() {} public void anotherMethod() { this.method(); } } aspect WarningAspect { pointcut illegalCall(): call(* WarningSample.method()) && within(WarningSample); // the same thing happens with declare error declare warning: illegalCall() : "Hey, don't " + "do that, that is not nice. You should do something else"; }
|
resolved fixed
|
d43a391
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-11T13:18:24Z
| 2004-03-11T07:26:40Z
|
tests/bugs/decwStringsErroneous.java
| |
54,421
|
Bug 54421 Compile time declarations (warning and error) do not accept string concatenation (with +)
|
The following code does not compile because the message uses string concatenation (the + operator). public class WarningSample { public void method() {} public void anotherMethod() { this.method(); } } aspect WarningAspect { pointcut illegalCall(): call(* WarningSample.method()) && within(WarningSample); // the same thing happens with declare error declare warning: illegalCall() : "Hey, don't " + "do that, that is not nice. You should do something else"; }
|
resolved fixed
|
d43a391
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-11T13:18:24Z
| 2004-03-11T07:26:40Z
|
tests/src/org/aspectj/systemtest/ajc121/Ajc121Tests.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.systemtest.ajc121;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc121Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc121Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc121/ajc121.xml");
}
public void test001(){
runTest("false ambiguous binding error (introduced in 1.2rc2)");
}
public void test002(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test003(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test004(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test005(){
runTest("compiler aborts with 'conflicting dominates orders' with circular declare precedences");
}
public void test006(){
runTest("'can't bind type' message has $ for . in type name for declare soft");
}
public void test007(){
runTest("Hiding of Instance Methods by static methods");
}
public void test008(){
runTest("if(false) optimisation");
}
public void test009(){
runTest("if(true) optimisation");
}
public void test010(){
runTest("java.lang.NullPointerException in WeaverMessageHandler class");
}
public void test011(){
runTest("ClassCastException at BcelRenderer.java:169");
}
public void test012(){
runTest("Front-end bug, shouldn't allow patterns of the form foo.., should be foo..*");
}
public void test013() {
runTest("Nullpointer-Exception when defining a withincode() pointcut");
}
public void test014() {
runTest("NPE, Incorrect XLint:unmatchedSuperTypeInCall warning");
}
public void test015_invalidXlint() { // keywords: "laurie hendren"
runTest("invalid warning indicating no match when a match really occurs");
}
public void test016_ByteConversionInstructions() {
runTest("RuntimeException thrown: Could not find instruction: org.apache.bcel.generic.B2I");
String output = getLastRunResult().getStdErr();
assertTrue("Expected to find [b2] in this output but didn't:"+output,output.indexOf("[b2]")!=-1);
assertTrue("Expected to find [b127] in this output but didn't:"+output,output.indexOf("[b127]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
assertTrue("Expected to find [c65] in this output but didn't:"+output,output.indexOf("[c65]")!=-1);
assertTrue("Expected to find [c66] in this output but didn't:"+output,output.indexOf("[c66]")!=-1);
assertTrue("Expected to find [c67] in this output but didn't:"+output,output.indexOf("[c67]")!=-1);
assertTrue("Expected to find [s1] in this output but didn't:"+output,output.indexOf("[s1]")!=-1);
assertTrue("Expected to find [s32767] in this output but didn't:"+output,output.indexOf("[s32767]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
}
public void test017_PrivateMethodCallsInAroundAdvice() {
runTest("Cannot advise private method call in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test018_PrivateFieldSetsInAroundAdvice() {
runTest("Cannot advise private field sets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test019_PrivateFieldGetsInAroundAdvice() {
runTest("Cannot advise private field gets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
// test takes over 5 minutes to run, so not included in normal suite run
// public void test020_branchTargetOffsetTooLargeForShort() {
// runTest("Branch target offset too large for short");
// }
// public void test021_BcelFailureWithVeryLargeClasses() {
// runTest("Weaver fails in BCEL for large classes");
// }
//
// public void test022_BcelFailureWithVeryLargeClasses_Binary() {
// runTest("Weaver fails in BCEL for large classes (binary)");
// }
public void test023_proceedInAround1() {
runTest("proceed used as method name in around advice (1)");
}
public void test024_proceedInAround2() {
runTest("proceed used as method name in around advice (2)");
}
public void test025_proceedInAround3() {
runTest("proceed used as method name in around advice (3)");
}
public void test026_bindingThisAndTargetToTheSameFormal() {
runTest("ajc crashes when compiling the following program (binding this() and target())");
}
public void test027_itdsOnInnerClassesAsStatic() {
runTest("ITDs on inner classes should be static context");
}
// public void test028_itdsAndInitializers() {
// runTest("resolution of IT field inits");
// }
public void test029_falseInvalidAbsoluteTypeName() {
runTest("Valid but inaccessible type names should not be flagged by XLint:invalidAbsoluteTypeName");
}
public void test030_privateITDinitialisersBeingMatched() {
runTest("intertype initialisers should match field set pointcuts");
}
public void test031_privateITDinitialisersBeingMatched_OxfordTest() {
runTest("intertype initialisers should match field set pointcuts (oxford testcase)");
//System.err.println(">"+getLastRunResult().getStdErr());
String exp = ":set field set(int C.n):set field set(int C.m):get field get(int C.n):set field set(int C.n)";
assertTrue("Expected output '"+exp+"' but got "+getLastRunResult().getStdErr(),
getLastRunResult().getStdErr().equals(exp));
}
}
|
54,421
|
Bug 54421 Compile time declarations (warning and error) do not accept string concatenation (with +)
|
The following code does not compile because the message uses string concatenation (the + operator). public class WarningSample { public void method() {} public void anotherMethod() { this.method(); } } aspect WarningAspect { pointcut illegalCall(): call(* WarningSample.method()) && within(WarningSample); // the same thing happens with declare error declare warning: illegalCall() : "Hey, don't " + "do that, that is not nice. You should do something else"; }
|
resolved fixed
|
d43a391
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-11T13:18:24Z
| 2004-03-11T07:26:40Z
|
weaver/src/org/aspectj/weaver/patterns/PatternParser.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.util.ArrayList;
import java.util.List;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.Shadow;
//XXX doesn't handle errors for extra tokens very well (sometimes ignores)
public class PatternParser {
private ITokenSource tokenSource;
private ISourceContext sourceContext;
/**
* Constructor for PatternParser.
*/
public PatternParser(ITokenSource tokenSource) {
super();
this.tokenSource = tokenSource;
this.sourceContext = tokenSource.getSourceContext();
}
public PerClause maybeParsePerClause() {
IToken tok = tokenSource.peek();
if (tok == IToken.EOF) return null;
if (tok.isIdentifier()) {
String name = tok.getString();
if (name.equals("issingleton")) {
return parsePerSingleton();
} else if (name.equals("perthis")) {
return parsePerObject(true);
} else if (name.equals("pertarget")) {
return parsePerObject(false);
} else if (name.equals("percflow")) {
return parsePerCflow(false);
} else if (name.equals("percflowbelow")) {
return parsePerCflow(true);
} else {
return null;
}
}
return null;
}
private PerClause parsePerCflow(boolean isBelow) {
parseIdentifier();
eat("(");
Pointcut entry = parsePointcut();
eat(")");
return new PerCflow(entry, isBelow);
}
private PerClause parsePerObject(boolean isThis) {
parseIdentifier();
eat("(");
Pointcut entry = parsePointcut();
eat(")");
return new PerObject(entry, isThis);
}
private PerClause parsePerSingleton() {
parseIdentifier();
eat("(");
eat(")");
return new PerSingleton();
}
public Declare parseDeclare() {
int startPos = tokenSource.peek().getStart();
eatIdentifier("declare");
String kind = parseIdentifier();
eat(":");
Declare ret;
//XXX beta add soft, dominates
if (kind.equals("error")) {
ret = parseErrorOrWarning(true);
} else if (kind.equals("warning")) {
ret = parseErrorOrWarning(false);
} else if (kind.equals("precedence")) {
ret = parseDominates();
} else if (kind.equals("dominates")) {
throw new ParserException("name changed to declare precedence", tokenSource.peek(-2));
} else if (kind.equals("parents")) {
ret = parseParents();
} else if (kind.equals("soft")) {
ret = parseSoft();
} else {
throw new ParserException("expected one of error, warning, parents, soft, dominates",
tokenSource.peek(-1));
}
int endPos = tokenSource.peek(-1).getEnd();
ret.setLocation(sourceContext, startPos, endPos);
return ret;
}
public DeclarePrecedence parseDominates() {
List l = new ArrayList();
do {
l.add(parseTypePattern());
} while (maybeEat(","));
return new DeclarePrecedence(l);
}
private Declare parseParents() {
TypePattern p = parseTypePattern();
IToken t = tokenSource.next();
if (!(t.getString().equals("extends") || t.getString().equals("implements"))) {
throw new ParserException("extends or implements", t);
}
List l = new ArrayList();
do {
l.add(parseTypePattern());
} while (maybeEat(","));
//XXX somewhere in the chain we need to enforce that we have only ExactTypePatterns
return new DeclareParents(p, l);
}
private Declare parseSoft() {
TypePattern p = parseTypePattern();
eat(":");
Pointcut pointcut = parsePointcut();
return new DeclareSoft(p, pointcut);
}
private Declare parseErrorOrWarning(boolean isError) {
Pointcut pointcut = parsePointcut();
eat(":");
String message = parseStringLiteral();
return new DeclareErrorOrWarning(isError, pointcut, message);
}
public Pointcut parsePointcut() {
Pointcut p = parseAtomicPointcut();
if (maybeEat("&&")) {
p = new AndPointcut(p, parseNotOrPointcut());
}
if (maybeEat("||")) {
p = new OrPointcut(p, parsePointcut());
}
return p;
}
private Pointcut parseNotOrPointcut() {
Pointcut p = parseAtomicPointcut();
if (maybeEat("&&")) {
p = new AndPointcut(p, parsePointcut());
}
return p;
}
private Pointcut parseAtomicPointcut() {
if (maybeEat("!")) {
int startPos = tokenSource.peek(-1).getStart();
Pointcut p = new NotPointcut(parseAtomicPointcut(), startPos);
return p;
}
if (maybeEat("(")) {
Pointcut p = parsePointcut();
eat(")");
return p;
}
int startPos = tokenSource.peek().getStart();
Pointcut p = parseSinglePointcut();
int endPos = tokenSource.peek(-1).getEnd();
p.setLocation(sourceContext, startPos, endPos);
return p;
}
public Pointcut parseSinglePointcut() {
int start = tokenSource.getIndex();
IToken t = tokenSource.peek();
Pointcut p = t.maybeGetParsedPointcut();
if (p != null) {
tokenSource.next();
return p;
}
String kind = parseIdentifier();
tokenSource.setIndex(start);
if (kind.equals("execution") || kind.equals("call") ||
kind.equals("get") || kind.equals("set")) {
return parseKindedPointcut();
} else if (kind.equals("args")) {
return parseArgsPointcut();
} else if (kind.equals("this") || kind.equals("target")) {
return parseThisOrTargetPointcut();
} else if (kind.equals("within")) {
return parseWithinPointcut();
} else if (kind.equals("withincode")) {
return parseWithinCodePointcut();
} else if (kind.equals("cflow")) {
return parseCflowPointcut(false);
} else if (kind.equals("cflowbelow")) {
return parseCflowPointcut(true);
} else if (kind.equals("adviceexecution")) {
parseIdentifier(); eat("(");
eat(")");
return new KindedPointcut(Shadow.AdviceExecution,
new SignaturePattern(Member.ADVICE, ModifiersPattern.ANY,
TypePattern.ANY, TypePattern.ANY, NamePattern.ANY,
TypePatternList.ANY,
ThrowsPattern.ANY));
} else if (kind.equals("handler")) {
parseIdentifier(); eat("(");
TypePattern typePat = parseTypePattern();
eat(")");
return new HandlerPointcut(typePat);
} else if (kind.equals("initialization")) {
parseIdentifier(); eat("(");
SignaturePattern sig = parseConstructorSignaturePattern();
eat(")");
return new KindedPointcut(Shadow.Initialization, sig);
} else if (kind.equals("staticinitialization")) {
parseIdentifier(); eat("(");
TypePattern typePat = parseTypePattern();
eat(")");
return new KindedPointcut(Shadow.StaticInitialization,
new SignaturePattern(Member.STATIC_INITIALIZATION, ModifiersPattern.ANY,
TypePattern.ANY, typePat, NamePattern.ANY, TypePatternList.EMPTY,
ThrowsPattern.ANY));
} else if (kind.equals("preinitialization")) {
parseIdentifier(); eat("(");
SignaturePattern sig = parseConstructorSignaturePattern();
eat(")");
return new KindedPointcut(Shadow.PreInitialization, sig);
} else {
return parseReferencePointcut();
}
}
private SignaturePattern parseConstructorSignaturePattern() {
SignaturePattern ret = parseMethodOrConstructorSignaturePattern();
if (ret.getKind() == Member.CONSTRUCTOR) return ret;
throw new ParserException("constructor pattern required, found method pattern",
ret);
}
private Pointcut parseWithinCodePointcut() {
parseIdentifier();
eat("(");
SignaturePattern sig = parseMethodOrConstructorSignaturePattern();
eat(")");
return new WithincodePointcut(sig);
}
private Pointcut parseCflowPointcut(boolean isBelow) {
parseIdentifier();
eat("(");
Pointcut entry = parsePointcut();
eat(")");
return new CflowPointcut(entry, isBelow, null);
}
/**
* Method parseWithinPointcut.
* @return Pointcut
*/
private Pointcut parseWithinPointcut() {
parseIdentifier();
eat("(");
TypePattern type = parseTypePattern();
eat(")");
return new WithinPointcut(type);
}
/**
* Method parseThisOrTargetPointcut.
* @return Pointcut
*/
private Pointcut parseThisOrTargetPointcut() {
String kind = parseIdentifier();
eat("(");
TypePattern type = parseTypePattern();
eat(")");
return new ThisOrTargetPointcut(kind.equals("this"), type);
}
/**
* Method parseArgsPointcut.
* @return Pointcut
*/
private Pointcut parseArgsPointcut() {
parseIdentifier();
TypePatternList arguments = parseArgumentsPattern();
return new ArgsPointcut(arguments);
}
private Pointcut parseReferencePointcut() {
TypePattern onType = parseTypePattern();
NamePattern name = tryToExtractName(onType);
if (name == null) {
throw new ParserException("name pattern", tokenSource.peek());
}
if (onType.toString().equals("")) {
onType = null;
}
TypePatternList arguments = parseArgumentsPattern();
return new ReferencePointcut(onType, name.maybeGetSimpleName(), arguments);
}
public List parseDottedIdentifier() {
List ret = new ArrayList();
ret.add(parseIdentifier());
while (maybeEat(".")) {
ret.add(parseIdentifier());
}
return ret;
}
private KindedPointcut parseKindedPointcut() {
String kind = parseIdentifier();
eat("(");
SignaturePattern sig;
Shadow.Kind shadowKind = null;
if (kind.equals("execution")) {
sig = parseMethodOrConstructorSignaturePattern();
if (sig.getKind() == Member.METHOD) {
shadowKind = Shadow.MethodExecution;
} else if (sig.getKind() == Member.CONSTRUCTOR) {
shadowKind = Shadow.ConstructorExecution;
}
} else if (kind.equals("call")) {
sig = parseMethodOrConstructorSignaturePattern();
if (sig.getKind() == Member.METHOD) {
shadowKind = Shadow.MethodCall;
} else if (sig.getKind() == Member.CONSTRUCTOR) {
shadowKind = Shadow.ConstructorCall;
}
} else if (kind.equals("get")) {
sig = parseFieldSignaturePattern();
shadowKind = Shadow.FieldGet;
} else if (kind.equals("set")) {
sig = parseFieldSignaturePattern();
shadowKind = Shadow.FieldSet;
} else {
throw new ParserException("bad kind: " + kind, tokenSource.peek());
}
eat(")");
return new KindedPointcut(shadowKind, sig);
}
public TypePattern parseTypePattern() {
TypePattern p = parseAtomicTypePattern();
if (maybeEat("&&")) {
p = new AndTypePattern(p, parseNotOrTypePattern());
}
if (maybeEat("||")) {
p = new OrTypePattern(p, parseTypePattern());
}
return p;
}
private TypePattern parseNotOrTypePattern() {
TypePattern p = parseAtomicTypePattern();
if (maybeEat("&&")) {
p = new AndTypePattern(p, parseTypePattern());
}
return p;
}
private TypePattern parseAtomicTypePattern() {
if (maybeEat("!")) {
//int startPos = tokenSource.peek(-1).getStart();
//??? we lose source location for true start of !type
TypePattern p = new NotTypePattern(parseAtomicTypePattern());
return p;
}
if (maybeEat("(")) {
TypePattern p = parseTypePattern();
eat(")");
return p;
}
int startPos = tokenSource.peek().getStart();
TypePattern p = parseSingleTypePattern();
int endPos = tokenSource.peek(-1).getEnd();
p.setLocation(sourceContext, startPos, endPos);
return p;
}
public TypePattern parseSingleTypePattern() {
List names = parseDottedNamePattern();
// new ArrayList();
// NamePattern p1 = parseNamePattern();
// names.add(p1);
// while (maybeEat(".")) {
// if (maybeEat(".")) {
// names.add(NamePattern.ELLIPSIS);
// }
// NamePattern p2 = parseNamePattern();
// names.add(p2);
// }
int dim = 0;
while (maybeEat("[")) {
eat("]");
dim++;
}
boolean includeSubtypes = maybeEat("+");
int endPos = tokenSource.peek(-1).getEnd();
//??? what about the source location of any's????
if (names.size() == 1 && ((NamePattern)names.get(0)).isAny() && dim == 0) return TypePattern.ANY;
return new WildTypePattern(names, includeSubtypes, dim, endPos);
}
public List parseDottedNamePattern() {
List names = new ArrayList();
StringBuffer buf = new StringBuffer();
IToken previous = null;
boolean justProcessedEllipsis = false; // Remember if we just dealt with an ellipsis (PR61536)
boolean justProcessedDot = false;
boolean onADot = false;
while (true) {
IToken tok = null;
int startPos = tokenSource.peek().getStart();
String afterDot = null;
while (true) {
if (previous !=null && previous.getString().equals(".")) justProcessedDot = true;
tok = tokenSource.peek();
onADot = (tok.getString().equals("."));
if (previous != null) {
if (!isAdjacent(previous, tok)) break;
}
if (tok.getString() == "*" || tok.isIdentifier()) {
buf.append(tok.getString());
} else if (tok.getLiteralKind() != null) {
//System.err.println("literal kind: " + tok.getString());
String s = tok.getString();
int dot = s.indexOf('.');
if (dot != -1) {
buf.append(s.substring(0, dot));
afterDot = s.substring(dot+1);
previous = tokenSource.next();
break;
}
buf.append(s); // ??? so-so
} else {
break;
}
previous = tokenSource.next();
//XXX need to handle floats and other fun stuff
}
int endPos = tokenSource.peek(-1).getEnd();
if (buf.length() == 0 && names.isEmpty()) {
throw new ParserException("expected name pattern", tok);
}
if (buf.length() == 0 && justProcessedEllipsis) {
throw new ParserException("name pattern cannot finish with ..", tok);
}
if (buf.length() == 0 && justProcessedDot && !onADot) {
throw new ParserException("name pattern cannot finish with .", tok);
}
if (buf.length() == 0) {
names.add(NamePattern.ELLIPSIS);
justProcessedEllipsis = true;
} else {
checkLegalName(buf.toString(), previous);
NamePattern ret = new NamePattern(buf.toString());
ret.setLocation(sourceContext, startPos, endPos);
names.add(ret);
justProcessedEllipsis = false;
}
if (afterDot == null) {
buf.setLength(0);
if (!maybeEat(".")) break;
else previous = tokenSource.peek(-1);
} else {
buf.setLength(0);
buf.append(afterDot);
afterDot = null;
}
}
//System.err.println("parsed: " + names);
return names;
}
public NamePattern parseNamePattern() {
StringBuffer buf = new StringBuffer();
IToken previous = null;
IToken tok;
int startPos = tokenSource.peek().getStart();
while (true) {
tok = tokenSource.peek();
if (previous != null) {
if (!isAdjacent(previous, tok)) break;
}
if (tok.getString() == "*" || tok.isIdentifier()) {
buf.append(tok.getString());
} else if (tok.getLiteralKind() != null) {
//System.err.println("literal kind: " + tok.getString());
String s = tok.getString();
if (s.indexOf('.') != -1) break;
buf.append(s); // ??? so-so
} else {
break;
}
previous = tokenSource.next();
//XXX need to handle floats and other fun stuff
}
int endPos = tokenSource.peek(-1).getEnd();
if (buf.length() == 0) {
throw new ParserException("expected name pattern", tok);
}
checkLegalName(buf.toString(), previous);
NamePattern ret = new NamePattern(buf.toString());
ret.setLocation(sourceContext, startPos, endPos);
return ret;
}
private void checkLegalName(String s, IToken tok) {
char ch = s.charAt(0);
if (!(ch == '*' || Character.isJavaIdentifierStart(ch))) {
throw new ParserException("illegal identifier start (" + ch + ")", tok);
}
for (int i=1, len=s.length(); i < len; i++) {
ch = s.charAt(i);
if (!(ch == '*' || Character.isJavaIdentifierPart(ch))) {
throw new ParserException("illegal identifier character (" + ch + ")", tok);
}
}
}
private boolean isAdjacent(IToken first, IToken second) {
return first.getEnd() == second.getStart()-1;
}
public ModifiersPattern parseModifiersPattern() {
int requiredFlags = 0;
int forbiddenFlags = 0;
int start;
while (true) {
start = tokenSource.getIndex();
boolean isForbidden = false;
isForbidden = maybeEat("!");
IToken t = tokenSource.next();
int flag = ModifiersPattern.getModifierFlag(t.getString());
if (flag == -1) break;
if (isForbidden) forbiddenFlags |= flag;
else requiredFlags |= flag;
}
tokenSource.setIndex(start);
if (requiredFlags == 0 && forbiddenFlags == 0) {
return ModifiersPattern.ANY;
} else {
return new ModifiersPattern(requiredFlags, forbiddenFlags);
}
}
public TypePatternList parseArgumentsPattern() {
List patterns = new ArrayList();
eat("(");
if (maybeEat(")")) {
return new TypePatternList();
}
do {
if (maybeEat(".")) {
eat(".");
patterns.add(TypePattern.ELLIPSIS);
} else {
patterns.add(parseTypePattern());
}
} while (maybeEat(","));
eat(")");
return new TypePatternList(patterns);
}
public ThrowsPattern parseOptionalThrowsPattern() {
IToken t = tokenSource.peek();
if (t.isIdentifier() && t.getString().equals("throws")) {
tokenSource.next();
List required = new ArrayList();
List forbidden = new ArrayList();
do {
boolean isForbidden = maybeEat("!");
//???might want an error for a second ! without a paren
TypePattern p = parseTypePattern();
if (isForbidden) forbidden.add(p);
else required.add(p);
} while (maybeEat(","));
return new ThrowsPattern(new TypePatternList(required), new TypePatternList(forbidden));
}
return ThrowsPattern.ANY;
}
public SignaturePattern parseMethodOrConstructorSignaturePattern() {
int startPos = tokenSource.peek().getStart();
ModifiersPattern modifiers = parseModifiersPattern();
TypePattern returnType = parseTypePattern();
TypePattern declaringType;
NamePattern name = null;
Member.Kind kind;
// here we can check for 'new'
if (maybeEatNew(returnType)) {
kind = Member.CONSTRUCTOR;
if (returnType.toString().length() == 0) {
declaringType = TypePattern.ANY;
} else {
declaringType = returnType;
}
returnType = TypePattern.ANY;
name = NamePattern.ANY;
} else {
kind = Member.METHOD;
declaringType = parseTypePattern();
if (maybeEat(".")) {
name = parseNamePattern();
} else {
name = tryToExtractName(declaringType);
if (name == null) {
throw new ParserException("name pattern", tokenSource.peek());
}
String simpleName = name.maybeGetSimpleName();
//XXX should add check for any Java keywords
if (simpleName != null && simpleName.equals("new")) {
throw new ParserException("constructor patterns have no return type",
tokenSource.peek());
}
if (declaringType.toString().equals("")) {
declaringType = TypePattern.ANY;
}
}
}
TypePatternList parameterTypes = parseArgumentsPattern();
ThrowsPattern throwsPattern = parseOptionalThrowsPattern();
SignaturePattern ret = new SignaturePattern(kind, modifiers, returnType, declaringType, name, parameterTypes, throwsPattern);
int endPos = tokenSource.peek(-1).getEnd();
ret.setLocation(sourceContext, startPos, endPos);
return ret;
}
private boolean maybeEatNew(TypePattern returnType) {
if (returnType instanceof WildTypePattern) {
WildTypePattern p = (WildTypePattern)returnType;
if (p.maybeExtractName("new")) return true;
}
int start = tokenSource.getIndex();
if (maybeEat(".")) {
String id = maybeEatIdentifier();
if (id != null && id.equals("new")) return true;
tokenSource.setIndex(start);
}
return false;
}
public SignaturePattern parseFieldSignaturePattern() {
int startPos = tokenSource.peek().getStart();
ModifiersPattern modifiers = parseModifiersPattern();
TypePattern returnType = parseTypePattern();
TypePattern declaringType = parseTypePattern();
NamePattern name;
//System.err.println("parsed field: " + declaringType.toString());
if (maybeEat(".")) {
name = parseNamePattern();
} else {
name = tryToExtractName(declaringType);
if (declaringType.toString().equals("")) {
declaringType = TypePattern.ANY;
}
}
SignaturePattern ret = new SignaturePattern(Member.FIELD, modifiers, returnType,
declaringType, name, TypePatternList.ANY, ThrowsPattern.ANY);
int endPos = tokenSource.peek(-1).getEnd();
ret.setLocation(sourceContext, startPos, endPos);
return ret;
}
private NamePattern tryToExtractName(TypePattern nextType) {
if (nextType == TypePattern.ANY) {
return NamePattern.ANY;
} else if (nextType instanceof WildTypePattern) {
WildTypePattern p = (WildTypePattern)nextType;
return p.extractName();
} else {
return null;
}
}
public String parseStringLiteral() {
IToken token = tokenSource.next();
String literalKind = token.getLiteralKind();
if (literalKind == "string") {
return token.getString();
}
throw new ParserException("string", token);
}
public String parseIdentifier() {
IToken token = tokenSource.next();
if (token.isIdentifier()) return token.getString();
throw new ParserException("identifier", token);
}
public void eatIdentifier(String expectedValue) {
IToken next = tokenSource.next();
if (!next.getString().equals(expectedValue)) {
throw new ParserException(expectedValue, next);
}
}
public boolean maybeEatIdentifier(String expectedValue) {
IToken next = tokenSource.peek();
if (next.getString().equals(expectedValue)) {
tokenSource.next();
return true;
} else {
return false;
}
}
public void eat(String expectedValue) {
IToken next = tokenSource.next();
if (next.getString() != expectedValue) {
throw new ParserException(expectedValue, next);
}
}
public boolean maybeEat(String token) {
IToken next = tokenSource.peek();
if (next.getString() == token) {
tokenSource.next();
return true;
} else {
return false;
}
}
public String maybeEatIdentifier() {
IToken next = tokenSource.peek();
if (next.isIdentifier()) {
tokenSource.next();
return next.getString();
} else {
return null;
}
}
public boolean peek(String token) {
IToken next = tokenSource.peek();
return next.getString() == token;
}
public PatternParser(String data) {
this(BasicTokenSource.makeTokenSource(data));
}
}
|
61,768
|
Bug 61768 scope for intertype methods
|
/* According to the documentation, the scope rules for intertype method declarations are interpreted from the originating aspect. The only exceptions (I thought) are the use of "this" and "super" which refer to the target type. According to that interpretation, the program below is type correct, but ajc generates two error messages, shown in comments at the relevant lines. Note that it's ok to access private static fields of the aspect, but not to use private classes of the aspect. If this is a feature and not a bug, what are the precise scope rules for intertype method declarations? */ aspect Aspect { private static int y = 5; private class A { int x = 3; } private static void B.happy() { System.out.println(y); // happy accessing private field y } private static void B.foo(A z) { System.out.println(z.x); // ERROR: The type Aspect.A is not visible } public void B.bar() { B.foo(new A()); // ERROR: The type A is not visible } } class B { } public class IT { public static void main(String[] args) { new B().bar(); } }
|
resolved fixed
|
8c5d743
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-11T16:51:24Z
| 2004-05-11T18:26:40Z
|
tests/bugs/oxford/PR61768.java
| |
61,768
|
Bug 61768 scope for intertype methods
|
/* According to the documentation, the scope rules for intertype method declarations are interpreted from the originating aspect. The only exceptions (I thought) are the use of "this" and "super" which refer to the target type. According to that interpretation, the program below is type correct, but ajc generates two error messages, shown in comments at the relevant lines. Note that it's ok to access private static fields of the aspect, but not to use private classes of the aspect. If this is a feature and not a bug, what are the precise scope rules for intertype method declarations? */ aspect Aspect { private static int y = 5; private class A { int x = 3; } private static void B.happy() { System.out.println(y); // happy accessing private field y } private static void B.foo(A z) { System.out.println(z.x); // ERROR: The type Aspect.A is not visible } public void B.bar() { B.foo(new A()); // ERROR: The type A is not visible } } class B { } public class IT { public static void main(String[] args) { new B().bar(); } }
|
resolved fixed
|
8c5d743
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-11T16:51:24Z
| 2004-05-11T18:26:40Z
|
tests/bugs/oxford/PR62475.java
|
/*
Intertype field initialisers should be resolved in the aspect
(lexical scope), for consistency with intertype method and
constructor bodies.
The program below compiles without warning, however, binding z
to the z field of the target class.
*/
aspect Aspect {
public int A.x = z; // CE L14 error: z not visible.
}
class A {
int z = 0;
}
public class PR62475 {
public static void main(String[] args) {
System.out.println(new A().x);
}
}
|
61,768
|
Bug 61768 scope for intertype methods
|
/* According to the documentation, the scope rules for intertype method declarations are interpreted from the originating aspect. The only exceptions (I thought) are the use of "this" and "super" which refer to the target type. According to that interpretation, the program below is type correct, but ajc generates two error messages, shown in comments at the relevant lines. Note that it's ok to access private static fields of the aspect, but not to use private classes of the aspect. If this is a feature and not a bug, what are the precise scope rules for intertype method declarations? */ aspect Aspect { private static int y = 5; private class A { int x = 3; } private static void B.happy() { System.out.println(y); // happy accessing private field y } private static void B.foo(A z) { System.out.println(z.x); // ERROR: The type Aspect.A is not visible } public void B.bar() { B.foo(new A()); // ERROR: The type A is not visible } } class B { } public class IT { public static void main(String[] args) { new B().bar(); } }
|
resolved fixed
|
8c5d743
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-11T16:51:24Z
| 2004-05-11T18:26:40Z
|
tests/src/org/aspectj/systemtest/ajc121/Ajc121Tests.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.systemtest.ajc121;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc121Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc121Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc121/ajc121.xml");
}
public void test001(){
runTest("false ambiguous binding error (introduced in 1.2rc2)");
}
public void test002(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test003(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test004(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test005(){
runTest("compiler aborts with 'conflicting dominates orders' with circular declare precedences");
}
public void test006(){
runTest("'can't bind type' message has $ for . in type name for declare soft");
}
public void test007(){
runTest("Hiding of Instance Methods by static methods");
}
public void test008(){
runTest("if(false) optimisation");
}
public void test009(){
runTest("if(true) optimisation");
}
public void test010(){
runTest("java.lang.NullPointerException in WeaverMessageHandler class");
}
public void test011(){
runTest("ClassCastException at BcelRenderer.java:169");
}
public void test012(){
runTest("Front-end bug, shouldn't allow patterns of the form foo.., should be foo..*");
}
public void test013() {
runTest("Nullpointer-Exception when defining a withincode() pointcut");
}
public void test014() {
runTest("NPE, Incorrect XLint:unmatchedSuperTypeInCall warning");
}
public void test015_invalidXlint() { // keywords: "laurie hendren"
runTest("invalid warning indicating no match when a match really occurs");
}
public void test016_ByteConversionInstructions() {
runTest("RuntimeException thrown: Could not find instruction: org.apache.bcel.generic.B2I");
String output = getLastRunResult().getStdErr();
assertTrue("Expected to find [b2] in this output but didn't:"+output,output.indexOf("[b2]")!=-1);
assertTrue("Expected to find [b127] in this output but didn't:"+output,output.indexOf("[b127]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
assertTrue("Expected to find [c65] in this output but didn't:"+output,output.indexOf("[c65]")!=-1);
assertTrue("Expected to find [c66] in this output but didn't:"+output,output.indexOf("[c66]")!=-1);
assertTrue("Expected to find [c67] in this output but didn't:"+output,output.indexOf("[c67]")!=-1);
assertTrue("Expected to find [s1] in this output but didn't:"+output,output.indexOf("[s1]")!=-1);
assertTrue("Expected to find [s32767] in this output but didn't:"+output,output.indexOf("[s32767]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
}
public void test017_PrivateMethodCallsInAroundAdvice() {
runTest("Cannot advise private method call in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test018_PrivateFieldSetsInAroundAdvice() {
runTest("Cannot advise private field sets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test019_PrivateFieldGetsInAroundAdvice() {
runTest("Cannot advise private field gets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
// test takes over 5 minutes to run, so not included in normal suite run
// public void test020_branchTargetOffsetTooLargeForShort() {
// runTest("Branch target offset too large for short");
// }
// public void test021_BcelFailureWithVeryLargeClasses() {
// runTest("Weaver fails in BCEL for large classes");
// }
//
// public void test022_BcelFailureWithVeryLargeClasses_Binary() {
// runTest("Weaver fails in BCEL for large classes (binary)");
// }
public void test023_proceedInAround1() {
runTest("proceed used as method name in around advice (1)");
}
public void test024_proceedInAround2() {
runTest("proceed used as method name in around advice (2)");
}
public void test025_proceedInAround3() {
runTest("proceed used as method name in around advice (3)");
}
public void test026_bindingThisAndTargetToTheSameFormal() {
runTest("ajc crashes when compiling the following program (binding this() and target())");
}
public void test027_itdsOnInnerClassesAsStatic() {
runTest("ITDs on inner classes should be static context");
}
// public void test028_itdsAndInitializers() {
// runTest("resolution of IT field inits");
// }
public void test029_falseInvalidAbsoluteTypeName() {
runTest("Valid but inaccessible type names should not be flagged by XLint:invalidAbsoluteTypeName");
}
public void test030_privateITDinitialisersBeingMatched() {
runTest("intertype initialisers should match field set pointcuts");
}
public void test031_privateITDinitialisersBeingMatched_OxfordTest() {
runTest("intertype initialisers should match field set pointcuts (oxford testcase)");
//System.err.println(">"+getLastRunResult().getStdErr());
String exp = ":set field set(int C.n):set field set(int C.m):get field get(int C.n):set field set(int C.n)";
assertTrue("Expected output '"+exp+"' but got "+getLastRunResult().getStdErr(),
getLastRunResult().getStdErr().equals(exp));
}
public void test032_stringConcatForDEOW() {
runTest("Compile time declarations (warning and error) do not accept string concatenation (with +)");
}
public void test033_stringConcatForDEOWErrorCase() {
runTest("Compile time declarations (warning and error) do not accept string concatenation (with +) (2)");
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/BcelAdvice.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
import org.aspectj.weaver.patterns.ExactTypePattern;
import org.aspectj.weaver.patterns.ExposedState;
import org.aspectj.weaver.patterns.Pointcut;
/**
* Advice implemented for bcel.
*
* @author Erik Hilsdale
* @author Jim Hugunin
*/
public class BcelAdvice extends Advice {
private Test pointcutTest;
private ExposedState exposedState;
public BcelAdvice(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature,
ResolvedTypeX concreteAspect)
{
super(attribute, pointcut, signature);
this.concreteAspect = concreteAspect;
}
// !!! must only be used for testing
public BcelAdvice(AdviceKind kind, Pointcut pointcut, Member signature,
int extraArgumentFlags,
int start, int end, ISourceContext sourceContext, ResolvedTypeX concreteAspect)
{
this(new AjAttribute.AdviceAttribute(kind, pointcut, extraArgumentFlags, start, end, sourceContext),
pointcut, signature, concreteAspect);
thrownExceptions = Collections.EMPTY_LIST; //!!! interaction with unit tests
}
// ---- implementations of ShadowMunger's methods
public void specializeOn(Shadow shadow) {
if (getKind() == AdviceKind.Around) {
((BcelShadow)shadow).initializeForAroundClosure();
}
//XXX this case is just here for supporting lazy test code
if (getKind() == null) {
exposedState = new ExposedState(0);
return;
}
if (getKind().isPerEntry()) {
exposedState = new ExposedState(0);
} else if (getKind().isCflow()) {
exposedState = new ExposedState(nFreeVars);
} else if (getSignature() != null) {
exposedState = new ExposedState(getSignature());
} else {
exposedState = new ExposedState(0);
return; //XXX this case is just here for supporting lazy test code
}
pointcutTest = getPointcut().findResidue(shadow, exposedState);
// these initializations won't be performed by findResidue, but need to be
// so that the joinpoint is primed for weaving
if (getKind() == AdviceKind.PerThisEntry) {
shadow.getThisVar();
} else if (getKind() == AdviceKind.PerTargetEntry) {
shadow.getTargetVar();
}
// make sure thisJoinPoint parameters are initialized
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
((BcelShadow)shadow).getThisJoinPointStaticPartVar();
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
((BcelShadow)shadow).requireThisJoinPoint(pointcutTest != Literal.TRUE && getKind() != AdviceKind.Around);
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
((BcelShadow)shadow).getThisEnclosingJoinPointStaticPartVar();
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
}
private boolean canInline(Shadow s) {
if (attribute.isProceedInInners()) return false;
//XXX this guard seems to only be needed for bad test cases
if (concreteAspect == null || concreteAspect == ResolvedTypeX.MISSING) return false;
if (concreteAspect.getWorld().isXnoInline()) return false;
//System.err.println("isWoven? " + ((BcelObjectType)concreteAspect).getLazyClassGen().getWeaverState());
return BcelWorld.getBcelObjectType(concreteAspect).getLazyClassGen().isWoven();
}
public void implementOn(Shadow s) {
BcelShadow shadow = (BcelShadow) s;
if (getKind() == AdviceKind.Before) {
shadow.weaveBefore(this);
} else if (getKind() == AdviceKind.AfterReturning) {
shadow.weaveAfterReturning(this);
} else if (getKind() == AdviceKind.AfterThrowing) {
TypeX catchType =
hasExtraParameter()
? getExtraParameterType()
: TypeX.THROWABLE;
shadow.weaveAfterThrowing(this, catchType);
} else if (getKind() == AdviceKind.After) {
shadow.weaveAfter(this);
} else if (getKind() == AdviceKind.Around) {
if (!canInline(s)) {
shadow.weaveAroundClosure(this, hasDynamicTests());
} else {
shadow.weaveAroundInline(this, hasDynamicTests());
}
} else if (getKind() == AdviceKind.InterInitializer) {
shadow.weaveAfterReturning(this);
} else if (getKind().isCflow()) {
shadow.weaveCflowEntry(this, getSignature());
} else if (getKind() == AdviceKind.PerThisEntry) {
shadow.weavePerObjectEntry(this, (BcelVar)shadow.getThisVar());
} else if (getKind() == AdviceKind.PerTargetEntry) {
shadow.weavePerObjectEntry(this, (BcelVar)shadow.getTargetVar());
} else if (getKind() == AdviceKind.Softener) {
shadow.weaveSoftener(this, ((ExactTypePattern)exceptionType).getType());
} else {
throw new BCException("unimplemented kind: " + getKind());
}
}
// ---- implementations
private Collection collectCheckedExceptions(TypeX[] excs) {
if (excs == null || excs.length == 0) return Collections.EMPTY_LIST;
Collection ret = new ArrayList();
World world = concreteAspect.getWorld();
ResolvedTypeX runtimeException = world.getCoreType(TypeX.RUNTIME_EXCEPTION);
ResolvedTypeX error = world.getCoreType(TypeX.ERROR);
for (int i=0, len=excs.length; i < len; i++) {
ResolvedTypeX t = world.resolve(excs[i]);
if (!(runtimeException.isAssignableFrom(t) || error.isAssignableFrom(t))) {
ret.add(t);
}
}
return ret;
}
private Collection thrownExceptions = null;
public Collection getThrownExceptions() {
if (thrownExceptions == null) {
//??? can we really lump in Around here, how does this interact with Throwable
if (concreteAspect != null && concreteAspect.getWorld() != null && // null tests for test harness
(getKind().isAfter() || getKind() == AdviceKind.Before || getKind() == AdviceKind.Around))
{
World world = concreteAspect.getWorld();
ResolvedMember m = world.resolve(signature);
if (m == null) {
thrownExceptions = Collections.EMPTY_LIST;
} else {
thrownExceptions = collectCheckedExceptions(m.getExceptions());
}
} else {
thrownExceptions = Collections.EMPTY_LIST;
}
}
return thrownExceptions;
}
// only call me after prepare has been called
public boolean hasDynamicTests() {
// if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) {
// TypeX extraParameterType = getExtraParameterType();
// if (! extraParameterType.equals(TypeX.OBJECT)
// && ! extraParameterType.isPrimitive())
// return true;
// }
return pointcutTest != null &&
!(pointcutTest == Literal.TRUE);// || pointcutTest == Literal.NO_TEST);
}
/**
* get the instruction list for the really simple version of this advice.
* Is broken apart
* for other advice, but if you want it in one block, this is the method to call.
*
* @param s The shadow around which these instructions will eventually live.
* @param extraArgVar The var that will hold the return value or thrown exception
* for afterX advice
* @param ifNoAdvice The instructionHandle to jump to if the dynamic
* tests for this munger fails.
*/
InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice)
{
BcelShadow shadow = (BcelShadow) s;
InstructionFactory fact = shadow.getFactory();
BcelWorld world = shadow.getWorld();
InstructionList il = new InstructionList();
// we test to see if we have the right kind of thing...
// after throwing does this just by the exception mechanism.
if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) {
TypeX extraParameterType = getExtraParameterType();
if (! extraParameterType.equals(TypeX.OBJECT)
&& ! extraParameterType.isPrimitive()) {
il.append(
BcelRenderer.renderTest(
fact,
world,
Test.makeInstanceof(
extraArgVar, getExtraParameterType().resolve(world)),
null,
ifNoAdvice,
null));
}
}
il.append(getAdviceArgSetup(shadow, extraArgVar, null));
il.append(getNonTestAdviceInstructions(shadow));
InstructionHandle ifYesAdvice = il.getStart();
il.insert(getTestInstructions(shadow, ifYesAdvice, ifNoAdvice, ifYesAdvice));
return il;
}
public InstructionList getAdviceArgSetup(
BcelShadow shadow,
BcelVar extraVar,
InstructionList closureInstantiation)
{
InstructionFactory fact = shadow.getFactory();
BcelWorld world = shadow.getWorld();
InstructionList il = new InstructionList();
// if (targetAspectField != null) {
// il.append(fact.createFieldAccess(
// targetAspectField.getDeclaringType().getName(),
// targetAspectField.getName(),
// BcelWorld.makeBcelType(targetAspectField.getType()),
// Constants.GETSTATIC));
// }
//
//System.err.println("BcelAdvice: " + exposedState);
if (exposedState.getAspectInstance() != null) {
il.append(
BcelRenderer.renderExpr(fact, world, exposedState.getAspectInstance()));
}
for (int i = 0, len = exposedState.size(); i < len; i++) {
if (exposedState.isErroneousVar(i)) continue; // Erroneous vars have already had error msgs reported!
BcelVar v = (BcelVar) exposedState.get(i);
if (v == null) continue;
TypeX desiredTy = getSignature().getParameterTypes()[i];
v.appendLoadAndConvert(il, fact, desiredTy.resolve(world));
}
if (getKind() == AdviceKind.Around) {
il.append(closureInstantiation);
} else if (hasExtraParameter()) {
extraVar.appendLoadAndConvert(
il,
fact,
getExtraParameterType().resolve(world));
}
// handle thisJoinPoint parameters
// these need to be in that same order as parameters in
// org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
il.append(shadow.loadThisJoinPoint());
}
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
return il;
}
public InstructionList getNonTestAdviceInstructions(BcelShadow shadow) {
return new InstructionList(
Utility.createInvoke(shadow.getFactory(), shadow.getWorld(), getSignature()));
}
public InstructionList getTestInstructions(
BcelShadow shadow,
InstructionHandle sk,
InstructionHandle fk,
InstructionHandle next)
{
//System.err.println("test: " + pointcutTest);
return BcelRenderer.renderTest(
shadow.getFactory(),
shadow.getWorld(),
pointcutTest,
sk,
fk,
next);
}
public int compareTo(Object other) {
if (!(other instanceof BcelAdvice)) return 0;
BcelAdvice o = (BcelAdvice)other;
//System.err.println("compareTo: " + this + ", " + o);
if (kind.getPrecedence() != o.kind.getPrecedence()) {
if (kind.getPrecedence() > o.kind.getPrecedence()) return +1;
else return -1;
}
if (kind.isCflow()) {
// System.err.println("sort: " + this + " innerCflowEntries " + innerCflowEntries);
// System.err.println(" " + o + " innerCflowEntries " + o.innerCflowEntries);
boolean isBelow = (kind == AdviceKind.CflowBelowEntry);
if (this.innerCflowEntries.contains(o)) return isBelow ? +1 : -1;
else if (o.innerCflowEntries.contains(this)) return isBelow ? -1 : +1;
else return 0;
}
if (kind.isPerEntry() || kind == AdviceKind.Softener) {
return 0;
}
//System.out.println("compare: " + this + " with " + other);
World world = concreteAspect.getWorld();
int ret =
concreteAspect.getWorld().compareByDominates(
concreteAspect,
o.concreteAspect);
if (ret != 0) return ret;
ResolvedTypeX declaringAspect = getDeclaringAspect().resolve(world);
ResolvedTypeX o_declaringAspect = o.getDeclaringAspect().resolve(world);
if (declaringAspect == o_declaringAspect) {
if (kind.isAfter() || o.kind.isAfter()) {
return this.getStart() < o.getStart() ? -1: +1;
} else {
return this.getStart()< o.getStart() ? +1: -1;
}
} else if (declaringAspect.isAssignableFrom(o_declaringAspect)) {
return -1;
} else if (o_declaringAspect.isAssignableFrom(declaringAspect)) {
return +1;
} else {
return 0;
}
}
public BcelVar[] getExposedStateAsBcelVars() {
//System.out.println("vars: " + Arrays.asList(exposedState.vars));
if (exposedState == null) return BcelVar.NONE;
int len = exposedState.vars.length;
BcelVar[] ret = new BcelVar[len];
for (int i=0; i < len; i++) {
ret[i] = (BcelVar)exposedState.vars[i];
}
return ret; //(BcelVar[]) exposedState.vars;
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/BcelAttributes.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.util.ArrayList;
import java.util.List;
import org.apache.bcel.classfile.Attribute;
import org.apache.bcel.classfile.Unknown;
import org.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.ISourceContext;
// this is a class o' static methods for reading attributes. It's pretty much a bridge from
// bcel to AjAttribute.
class BcelAttributes {
public static List readAjAttributes(Attribute[] as, ISourceContext context) {
List l = new ArrayList();
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.startsWith(AjAttribute.AttributePrefix)) {
l.add(AjAttribute.read(name, u.getBytes(), context));
}
}
}
return l;
}
public static Attribute bcelAttribute(AjAttribute a, ConstantPoolGen pool) {
int nameIndex = pool.addUtf8(a.getNameString());
byte[] bytes = a.getBytes();
int length = bytes.length;
return new Unknown(nameIndex, length, bytes, pool.getConstantPool());
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/BcelCflowAccessVar.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import org.apache.bcel.Constants;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.Type;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedTypeX;
/**
* XXX Erik and I need to discuss this hierarchy. Having FieldRef
* extend Var is convenient, but hopefully there's a better design.
*
* This is always a static reference.
*/
public class BcelCflowAccessVar extends BcelVar {
private Member stackField;
private int index;
/**
* @param type The type to convert to from Object
* @param stackField the member containing the CFLOW_STACK_TYPE
* @param index yeah yeah
*/
public BcelCflowAccessVar(ResolvedTypeX type, Member stackField, int index) {
super(type, 0);
this.stackField = stackField;
this.index = index;
}
public String toString() {
return "BcelCflowAccessVar(" + getType() + " " + stackField + "." + index + ")";
}
public Instruction createLoad(InstructionFactory fact) {
throw new RuntimeException("unimplemented");
}
public Instruction createStore(InstructionFactory fact) {
throw new RuntimeException("unimplemented");
}
public InstructionList createCopyFrom(InstructionFactory fact, int oldSlot) {
throw new RuntimeException("unimplemented");
}
public void appendLoad(InstructionList il, InstructionFactory fact) {
il.append(createLoadInstructions(getType(), fact));
}
public InstructionList createLoadInstructions(ResolvedTypeX toType, InstructionFactory fact) {
InstructionList il = new InstructionList();
il.append(Utility.createGet(fact, stackField));
il.append(Utility.createConstant(fact, index));
il.append(
fact.createInvoke(
NameMangler.CFLOW_STACK_TYPE, "get",
Type.OBJECT, new Type[] { Type.INT },
Constants.INVOKEVIRTUAL));
il.append(Utility.createConversion(fact, Type.OBJECT, BcelWorld.makeBcelType(toType)));
return il;
}
public void appendLoadAndConvert(
InstructionList il,
InstructionFactory fact,
ResolvedTypeX toType) {
il.append(createLoadInstructions(toType, fact));
}
public void insertLoad(InstructionList il, InstructionFactory fact) {
il.insert(createLoadInstructions(getType(), fact));
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/BcelCflowStackFieldAdder.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.generic.FieldGen;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.Type;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
public class BcelCflowStackFieldAdder extends BcelTypeMunger {
private ResolvedMember cflowStackField;
public BcelCflowStackFieldAdder(ResolvedMember cflowStackField) {
super(null,(ResolvedTypeX)cflowStackField.getDeclaringType());
this.cflowStackField = cflowStackField;
}
public boolean munge(BcelClassWeaver weaver) {
LazyClassGen gen = weaver.getLazyClassGen();
if (!gen.getType().equals(cflowStackField.getDeclaringType())) return false;
Field f = new FieldGen(cflowStackField.getModifiers(),
BcelWorld.makeBcelType(cflowStackField.getReturnType()),
cflowStackField.getName(),
gen.getConstantPoolGen()).getField();
gen.addField(f,getSourceLocation());
LazyMethodGen clinit = gen.getAjcPreClinit(); //StaticInitializer();
InstructionList setup = new InstructionList();
InstructionFactory fact = gen.getFactory();
setup.append(fact.createNew(new ObjectType(NameMangler.CFLOW_STACK_TYPE)));
setup.append(InstructionFactory.createDup(1));
setup.append(fact.createInvoke(
NameMangler.CFLOW_STACK_TYPE,
"<init>",
Type.VOID,
new Type[0],
Constants.INVOKESPECIAL));
setup.append(Utility.createSet(fact, cflowStackField));
clinit.getBody().insert(setup);
return true;
}
public ResolvedMember getMatchingSyntheticMember(Member member) {
return null;
}
public ResolvedMember getSignature() {
return cflowStackField;
}
public boolean matches(ResolvedTypeX onType) {
return onType.equals(cflowStackField.getDeclaringType());
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40: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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-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.List;
import java.util.Map;
import java.util.Set;
import org.apache.bcel.Constants;
import org.apache.bcel.generic.BranchInstruction;
import org.apache.bcel.generic.CPInstruction;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.FieldInstruction;
import org.apache.bcel.generic.INVOKESPECIAL;
import org.apache.bcel.generic.IndexedInstruction;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionConstants;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.InstructionTargeter;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.LocalVariableInstruction;
import org.apache.bcel.generic.NEW;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.PUTFIELD;
import org.apache.bcel.generic.PUTSTATIC;
import org.apache.bcel.generic.RET;
import org.apache.bcel.generic.ReturnInstruction;
import org.apache.bcel.generic.Select;
import org.apache.bcel.generic.Type;
import org.aspectj.bridge.IMessage;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.util.PartialOrder;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AjcMemberMaker;
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.WeaverMetrics;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.Shadow.Kind;
import org.aspectj.weaver.patterns.FastMatchInfo;
class BcelClassWeaver implements IClassWeaver {
/**
* This is called from {@link BcelWeaver} to perform the per-class weaving process.
*/
public static boolean weave(
BcelWorld world,
LazyClassGen clazz,
List shadowMungers,
List typeMungers)
{
boolean b = new BcelClassWeaver(world, clazz, shadowMungers, typeMungers).weave();
//System.out.println(clazz.getClassName() + ", " + clazz.getType().getWeaverState());
//clazz.print();
return b;
}
// --------------------------------------------
private final LazyClassGen clazz;
private final List shadowMungers;
private final List typeMungers;
private final BcelObjectType ty; // alias of clazz.getType()
private final BcelWorld world; // alias of ty.getWorld()
private final ConstantPoolGen cpg; // alias of clazz.getConstantPoolGen()
private final InstructionFactory fact; // alias of clazz.getFactory();
private final List addedLazyMethodGens = new ArrayList();
private final Set addedDispatchTargets = new HashSet();
// Static setting across BcelClassWeavers
private static boolean inReweavableMode = false;
private static boolean compressReweavableAttributes = false;
private List addedSuperInitializersAsList = null; // List<IfaceInitList>
private final Map addedSuperInitializers = new HashMap(); // Interface -> IfaceInitList
private List addedThisInitializers = new ArrayList(); // List<NewFieldMunger>
private List addedClassInitializers = new ArrayList(); // List<NewFieldMunger>
private BcelShadow clinitShadow = null;
/**
* This holds the initialization and pre-initialization shadows for this class
* that were actually matched by mungers (if no match, then we don't even create the
* shadows really).
*/
private final List initializationShadows = new ArrayList(1);
private BcelClassWeaver(
BcelWorld world,
LazyClassGen clazz,
List shadowMungers,
List typeMungers)
{
super();
// assert world == clazz.getType().getWorld()
this.world = world;
this.clazz = clazz;
this.shadowMungers = shadowMungers;
this.typeMungers = typeMungers;
this.ty = clazz.getBcelObjectType();
this.cpg = clazz.getConstantPoolGen();
this.fact = clazz.getFactory();
fastMatchShadowMungers(shadowMungers);
initializeSuperInitializerMap(ty.getResolvedTypeX());
}
private List[] perKindShadowMungers;
private boolean canMatchBodyShadows = false;
private boolean canMatchInitialization = false;
private void fastMatchShadowMungers(List shadowMungers) {
perKindShadowMungers = new List[Shadow.MAX_SHADOW_KIND+1];
for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) {
Shadow.Kind kind = Shadow.SHADOW_KINDS[i];
ArrayList mungers = new ArrayList(0);
perKindShadowMungers[kind.getKey()] = mungers;
fastMatchShadowMungers(shadowMungers, mungers, kind);
if (mungers.isEmpty()) {
perKindShadowMungers[kind.getKey()] = null;
} else {
if (kind == Shadow.Initialization) {
canMatchInitialization = true;
} else if (!kind.isEnclosingKind()) {
canMatchBodyShadows = true;
}
}
}
}
private boolean canMatch(Shadow.Kind kind) {
return perKindShadowMungers[kind.getKey()] != null;
}
private void fastMatchShadowMungers(List shadowMungers, ArrayList mungers, Kind kind) {
FastMatchInfo info = new FastMatchInfo(clazz.getType(), kind);
for (Iterator i = shadowMungers.iterator(); i.hasNext();) {
ShadowMunger munger = (ShadowMunger) i.next();
FuzzyBoolean fb = munger.getPointcut().fastMatch(info);
WeaverMetrics.recordFastMatchResult(fb);// Could pass: munger.getPointcut().toString()
if (fb.maybeTrue()) mungers.add(munger);
}
}
private void initializeSuperInitializerMap(ResolvedTypeX child) {
ResolvedTypeX[] superInterfaces = child.getDeclaredInterfaces();
for (int i=0, len=superInterfaces.length; i < len; i++) {
if (ty.getResolvedTypeX().isTopmostImplementor(superInterfaces[i])) {
if (addSuperInitializer(superInterfaces[i])) {
initializeSuperInitializerMap(superInterfaces[i]);
}
}
}
}
private boolean addSuperInitializer(ResolvedTypeX onType) {
IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType);
if (l != null) return false;
l = new IfaceInitList(onType);
addedSuperInitializers.put(onType, l);
return true;
}
public void addInitializer(ConcreteTypeMunger cm) {
NewFieldTypeMunger m = (NewFieldTypeMunger) cm.getMunger();
ResolvedTypeX onType = m.getSignature().getDeclaringType().resolve(world);
if (m.getSignature().isStatic()) {
addedClassInitializers.add(cm);
} else {
if (onType == ty.getResolvedTypeX()) {
addedThisInitializers.add(cm);
} else {
IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType);
l.list.add(cm);
}
}
}
private static class IfaceInitList implements PartialOrder.PartialComparable {
final ResolvedTypeX onType;
List list = new ArrayList();
IfaceInitList(ResolvedTypeX onType) {
this.onType = onType;
}
public int compareTo(Object other) {
IfaceInitList o = (IfaceInitList)other;
if (onType.isAssignableFrom(o.onType)) return +1;
else if (o.onType.isAssignableFrom(onType)) return -1;
else return 0;
}
public int fallbackCompareTo(Object other) {
return 0;
}
}
// XXX this is being called, but the result doesn't seem to be being used
public boolean addDispatchTarget(ResolvedMember m) {
return addedDispatchTargets.add(m);
}
public void addLazyMethodGen(LazyMethodGen gen) {
addedLazyMethodGens.add(gen);
}
public void addOrReplaceLazyMethodGen(LazyMethodGen mg) {
if (alreadyDefined(clazz, mg)) return;
for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) {
LazyMethodGen existing = (LazyMethodGen)i.next();
if (signaturesMatch(mg, existing)) {
if (existing.definingType == null) {
// this means existing was introduced on the class itself
return;
} else if (mg.definingType.isAssignableFrom(existing.definingType)) {
// existing is mg's subtype and dominates mg
return;
} else if (existing.definingType.isAssignableFrom(mg.definingType)) {
// mg is existing's subtype and dominates existing
i.remove();
addedLazyMethodGens.add(mg);
return;
} else {
throw new BCException("conflict between: " + mg + " and " + existing);
}
}
}
addedLazyMethodGens.add(mg);
}
private boolean alreadyDefined(LazyClassGen clazz, LazyMethodGen mg) {
for (Iterator i = clazz.getMethodGens().iterator(); i.hasNext(); ) {
LazyMethodGen existing = (LazyMethodGen)i.next();
if (signaturesMatch(mg, existing)) {
if (!mg.isAbstract() && existing.isAbstract()) {
i.remove();
return false;
}
return true;
}
}
return false;
}
private boolean signaturesMatch(LazyMethodGen mg, LazyMethodGen existing) {
return mg.getName().equals(existing.getName()) &&
mg.getSignature().equals(existing.getSignature());
}
// ----
public boolean weave() {
if (clazz.isWoven() && !clazz.isReweavable()) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ALREADY_WOVEN,clazz.getType().getName()),
ty.getSourceLocation(), null);
return false;
}
Set aspectsAffectingType = null;
if (inReweavableMode) aspectsAffectingType = new HashSet();
boolean isChanged = false;
// we want to "touch" all aspects
if (clazz.getType().isAspect()) isChanged = true;
// start by munging all typeMungers
for (Iterator i = typeMungers.iterator(); i.hasNext(); ) {
Object o = i.next();
if ( !(o instanceof BcelTypeMunger) ) {
//???System.err.println("surprising: " + o);
continue;
}
BcelTypeMunger munger = (BcelTypeMunger)o;
boolean typeMungerAffectedType = munger.munge(this);
if (typeMungerAffectedType) {
isChanged = true;
if (inReweavableMode) aspectsAffectingType.add(munger.getAspectType().getName());
}
}
// XXX do major sort of stuff
// sort according to: Major: type hierarchy
// within each list: dominates
// don't forget to sort addedThisInitialiers according to dominates
addedSuperInitializersAsList = new ArrayList(addedSuperInitializers.values());
addedSuperInitializersAsList = PartialOrder.sort(addedSuperInitializersAsList);
if (addedSuperInitializersAsList == null) {
throw new BCException("circularity in inter-types");
}
// this will create a static initializer if there isn't one
// this is in just as bad taste as NOPs
LazyMethodGen staticInit = clazz.getStaticInitializer();
staticInit.getBody().insert(genInitInstructions(addedClassInitializers, true));
// now go through each method, and match against each method. This
// sets up each method's {@link LazyMethodGen#matchedShadows} field,
// and it also possibly adds to {@link #initializationShadows}.
List methodGens = new ArrayList(clazz.getMethodGens());
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen)i.next();
//mg.getBody();
if (! mg.hasBody()) continue;
boolean shadowMungerMatched = match(mg);
if (shadowMungerMatched) {
// For matching mungers, add their declaring aspects to the list that affected this type
if (inReweavableMode) aspectsAffectingType.addAll(findAspectsForMungers(mg));
isChanged = true;
}
}
if (! isChanged) return false;
// now we weave all but the initialization shadows
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen)i.next();
if (! mg.hasBody()) continue;
implement(mg);
}
// if we matched any initialization shadows, we inline and weave
if (! initializationShadows.isEmpty()) {
// Repeat next step until nothing left to inline...cant go on
// infinetly as compiler will have detected and reported
// "Recursive constructor invocation"
while (inlineSelfConstructors(methodGens));
positionAndImplement(initializationShadows);
}
// finally, if we changed, we add in the introduced methods.
if (isChanged) {
clazz.getOrCreateWeaverStateInfo();
weaveInAddedMethods();
}
if (inReweavableMode) {
WeaverStateInfo wsi = clazz.getOrCreateWeaverStateInfo();
wsi.addAspectsAffectingType(aspectsAffectingType);
wsi.setUnwovenClassFileData(ty.getJavaClass().getBytes());
wsi.setReweavable(true,compressReweavableAttributes);
} else {
clazz.getOrCreateWeaverStateInfo().setReweavable(false,false);
}
return isChanged;
}
private Set findAspectsForMungers(LazyMethodGen mg) {
Set aspectsAffectingType = new HashSet();
for (Iterator iter = mg.matchedShadows.iterator(); iter.hasNext();) {
BcelShadow aShadow = (BcelShadow) iter.next();
// Mungers in effect on that shadow
for (Iterator iter2 = aShadow.getMungers().iterator();iter2.hasNext();) {
ShadowMunger aMunger = (ShadowMunger) iter2.next();
if (aMunger instanceof BcelAdvice) {
BcelAdvice bAdvice = (BcelAdvice)aMunger;
aspectsAffectingType.add(bAdvice.getConcreteAspect().getName());
} else {
// It is a 'Checker' - we don't need to remember aspects that only contributed Checkers...
}
}
}
return aspectsAffectingType;
}
private boolean inlineSelfConstructors(List methodGens) {
boolean inlinedSomething = false;
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen) i.next();
if (! mg.getName().equals("<init>")) continue;
InstructionHandle ih = findSuperOrThisCall(mg);
if (ih != null && isThisCall(ih)) {
LazyMethodGen donor = getCalledMethod(ih);
inlineMethod(donor, mg, ih);
inlinedSomething = true;
}
}
return inlinedSomething;
}
private void positionAndImplement(List initializationShadows) {
for (Iterator i = initializationShadows.iterator(); i.hasNext(); ) {
BcelShadow s = (BcelShadow) i.next();
positionInitializationShadow(s);
//s.getEnclosingMethod().print();
s.implement();
}
}
private void positionInitializationShadow(BcelShadow s) {
LazyMethodGen mg = s.getEnclosingMethod();
InstructionHandle call = findSuperOrThisCall(mg);
InstructionList body = mg.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow((BcelShadow) s);
if (s.getKind() == Shadow.PreInitialization) {
// XXX assert first instruction is an ALOAD_0.
// a pre shadow goes from AFTER the first instruction (which we believe to
// be an ALOAD_0) to just before the call to super
r.associateWithTargets(
Range.genStart(body, body.getStart().getNext()),
Range.genEnd(body, call.getPrev()));
} else {
// assert s.getKind() == Shadow.Initialization
r.associateWithTargets(
Range.genStart(body, call.getNext()),
Range.genEnd(body));
}
}
private boolean isThisCall(InstructionHandle ih) {
INVOKESPECIAL inst = (INVOKESPECIAL) ih.getInstruction();
return inst.getClassName(cpg).equals(clazz.getName());
}
/** inline a particular call in bytecode.
*
* @param donor the method we want to inline
* @param recipient the method containing the call we want to inline
* @param call the instructionHandle in recipient's body holding the call we want to
* inline.
*/
public static void inlineMethod(
LazyMethodGen donor,
LazyMethodGen recipient,
InstructionHandle call)
{
// assert recipient.contains(call)
/* Implementation notes:
*
* We allocate two slots for every tempvar so we don't screw up
* longs and doubles which may share space. This could be conservatively avoided
* (no reference to a long/double instruction, don't do it) or packed later.
* Right now we don't bother to pack.
*
* Allocate a new var for each formal param of the inlined. Fill with stack
* contents. Then copy the inlined instructions in with the appropriate remap
* table. Any framelocs used by locals in inlined are reallocated to top of
* frame,
*/
final InstructionFactory fact = recipient.getEnclosingClass().getFactory();
IntMap frameEnv = new IntMap();
// this also sets up the initial environment
InstructionList argumentStores =
genArgumentStores(donor, recipient, frameEnv, fact);
InstructionList inlineInstructions =
genInlineInstructions(donor, recipient, frameEnv, fact, false);
inlineInstructions.insert(argumentStores);
recipient.getBody().append(call, inlineInstructions);
Utility.deleteInstruction(call, recipient);
}
/** generate the instructions to be inlined.
*
* @param donor the method from which we will copy (and adjust frame and jumps)
* instructions.
* @param recipient the method the instructions will go into. Used to get the frame
* size so we can allocate new frame locations for locals in donor.
* @param frameEnv an environment to map from donor frame to recipient frame,
* initially populated with argument locations.
* @param fact an instruction factory for recipient
*/
static InstructionList genInlineInstructions(
LazyMethodGen donor,
LazyMethodGen recipient,
IntMap frameEnv,
InstructionFactory fact,
boolean keepReturns)
{
InstructionList footer = new InstructionList();
InstructionHandle end = footer.append(InstructionConstants.NOP);
InstructionList ret = new InstructionList();
InstructionList sourceList = donor.getBody();
Map srcToDest = new HashMap();
ConstantPoolGen donorCpg = donor.getEnclosingClass().getConstantPoolGen();
ConstantPoolGen recipientCpg = recipient.getEnclosingClass().getConstantPoolGen();
boolean isAcrossClass = donorCpg != recipientCpg;
// first pass: copy the instructions directly, populate the srcToDest map,
// fix frame instructions
for (InstructionHandle src = sourceList.getStart();
src != null;
src = src.getNext())
{
Instruction fresh = Utility.copyInstruction(src.getInstruction());
InstructionHandle dest;
if (fresh instanceof CPInstruction) {
// need to reset index to go to new constant pool. This is totally
// a computation leak... we're testing this LOTS of times. Sigh.
if (isAcrossClass) {
CPInstruction cpi = (CPInstruction) fresh;
cpi.setIndex(
recipientCpg.addConstant(
donorCpg.getConstant(cpi.getIndex()),
donorCpg));
}
}
if (src.getInstruction() == Range.RANGEINSTRUCTION) {
dest = ret.append(Range.RANGEINSTRUCTION);
} else if (fresh instanceof ReturnInstruction) {
if (keepReturns) {
dest = ret.append(fresh);
} else {
dest =
ret.append(InstructionFactory.createBranchInstruction(Constants.GOTO, end));
}
} else if (fresh instanceof BranchInstruction) {
dest = ret.append((BranchInstruction) fresh);
} else if (
fresh instanceof LocalVariableInstruction || fresh instanceof RET) {
IndexedInstruction indexed = (IndexedInstruction) fresh;
int oldIndex = indexed.getIndex();
int freshIndex;
if (!frameEnv.hasKey(oldIndex)) {
freshIndex = recipient.allocateLocal(2);
frameEnv.put(oldIndex, freshIndex);
} else {
freshIndex = frameEnv.get(oldIndex);
}
indexed.setIndex(freshIndex);
dest = ret.append(fresh);
} else {
dest = ret.append(fresh);
}
srcToDest.put(src, dest);
}
// second pass: retarget branch instructions, copy ranges and tags
Map tagMap = new HashMap();
Map shadowMap = new HashMap();
for (InstructionHandle dest = ret.getStart(), src = sourceList.getStart();
dest != null;
dest = dest.getNext(), src = src.getNext()) {
Instruction inst = dest.getInstruction();
// retarget branches
if (inst instanceof BranchInstruction) {
BranchInstruction branch = (BranchInstruction) inst;
InstructionHandle oldTarget = branch.getTarget();
InstructionHandle newTarget =
(InstructionHandle) srcToDest.get(oldTarget);
if (newTarget == null) {
// assert this is a GOTO
// this was a return instruction we previously replaced
} else {
branch.setTarget(newTarget);
if (branch instanceof Select) {
Select select = (Select) branch;
InstructionHandle[] oldTargets = select.getTargets();
for (int k = oldTargets.length - 1; k >= 0; k--) {
select.setTarget(
k,
(InstructionHandle) srcToDest.get(oldTargets[k]));
}
}
}
}
//copy over tags and range attributes
InstructionTargeter[] srcTargeters = src.getTargeters();
if (srcTargeters != null) {
for (int j = srcTargeters.length - 1; j >= 0; j--) {
InstructionTargeter old = srcTargeters[j];
if (old instanceof Tag) {
Tag oldTag = (Tag) old;
Tag fresh = (Tag) tagMap.get(oldTag);
if (fresh == null) {
fresh = oldTag.copy();
tagMap.put(oldTag, fresh);
}
dest.addTargeter(fresh);
} else if (old instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) old;
if (er.getStart() == src) {
ExceptionRange freshEr =
new ExceptionRange(
recipient.getBody(),
er.getCatchType(),
er.getPriority());
freshEr.associateWithTargets(
dest,
(InstructionHandle)srcToDest.get(er.getEnd()),
(InstructionHandle)srcToDest.get(er.getHandler()));
}
} else if (old instanceof ShadowRange) {
ShadowRange oldRange = (ShadowRange) old;
if (oldRange.getStart() == src) {
BcelShadow oldShadow = oldRange.getShadow();
BcelShadow freshEnclosing =
oldShadow.getEnclosingShadow() == null
? null
: (BcelShadow) shadowMap.get(oldShadow.getEnclosingShadow());
BcelShadow freshShadow =
oldShadow.copyInto(recipient, freshEnclosing);
ShadowRange freshRange = new ShadowRange(recipient.getBody());
freshRange.associateWithShadow(freshShadow);
freshRange.associateWithTargets(
dest,
(InstructionHandle) srcToDest.get(oldRange.getEnd()));
shadowMap.put(oldRange, freshRange);
//recipient.matchedShadows.add(freshShadow);
// XXX should go through the NEW copied shadow and update
// the thisVar, targetVar, and argsVar
// ??? Might want to also go through at this time and add
// "extra" vars to the shadow.
}
}
}
}
}
if (!keepReturns) ret.append(footer);
return ret;
}
/** generate the argument stores in preparation for inlining.
*
* @param donor the method we will inline from. Used to get the signature.
* @param recipient the method we will inline into. Used to get the frame size
* so we can allocate fresh locations.
* @param frameEnv an empty environment we populate with a map from donor frame to
* recipient frame.
* @param fact an instruction factory for recipient
*/
private static InstructionList genArgumentStores(
LazyMethodGen donor,
LazyMethodGen recipient,
IntMap frameEnv,
InstructionFactory fact)
{
InstructionList ret = new InstructionList();
int donorFramePos = 0;
// writing ret back to front because we're popping.
if (! donor.isStatic()) {
int targetSlot = recipient.allocateLocal(Type.OBJECT);
ret.insert(InstructionFactory.createStore(Type.OBJECT, targetSlot));
frameEnv.put(donorFramePos, targetSlot);
donorFramePos += 1;
}
Type[] argTypes = donor.getArgumentTypes();
for (int i = 0, len = argTypes.length; i < len; i++) {
Type argType = argTypes[i];
int argSlot = recipient.allocateLocal(argType);
ret.insert(InstructionFactory.createStore(argType, argSlot));
frameEnv.put(donorFramePos, argSlot);
donorFramePos += argType.getSize();
}
return ret;
}
/** get a called method: Assumes the called method is in this class,
* and the reference to it is exact (a la INVOKESPECIAL).
*
* @param ih The InvokeInstruction instructionHandle pointing to the called method.
*/
private LazyMethodGen getCalledMethod(
InstructionHandle ih)
{
InvokeInstruction inst = (InvokeInstruction) ih.getInstruction();
String methodName = inst.getName(cpg);
String signature = inst.getSignature(cpg);
return clazz.getLazyMethodGen(methodName, signature);
}
private void weaveInAddedMethods() {
Collections.sort(addedLazyMethodGens,
new Comparator() {
public int compare(Object a, Object b) {
LazyMethodGen aa = (LazyMethodGen) a;
LazyMethodGen bb = (LazyMethodGen) b;
int i = aa.getName().compareTo(bb.getName());
if (i != 0) return i;
return aa.getSignature().compareTo(bb.getSignature());
}
}
);
for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) {
clazz.addMethodGen((LazyMethodGen)i.next());
}
}
void addPerSingletonField(Member field) {
ObjectType aspectType = (ObjectType) BcelWorld.makeBcelType(field.getReturnType());
String aspectName = field.getReturnType().getName();
LazyMethodGen clinit = clazz.getStaticInitializer();
InstructionList setup = new InstructionList();
InstructionFactory fact = clazz.getFactory();
setup.append(fact.createNew(aspectType));
setup.append(InstructionFactory.createDup(1));
setup.append(fact.createInvoke(
aspectName,
"<init>",
Type.VOID,
new Type[0],
Constants.INVOKESPECIAL));
setup.append(
fact.createFieldAccess(
aspectName,
field.getName(),
aspectType,
Constants.PUTSTATIC));
clinit.getBody().insert(setup);
}
/**
* Returns null if this is not a Java constructor, and then we won't
* weave into it at all
*/
private InstructionHandle findSuperOrThisCall(LazyMethodGen mg) {
int depth = 1;
InstructionHandle start = mg.getBody().getStart();
while (true) {
if (start == null) return null;
Instruction inst = start.getInstruction();
if (inst instanceof INVOKESPECIAL
&& ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) {
depth--;
if (depth == 0) return start;
} else if (inst instanceof NEW) {
depth++;
}
start = start.getNext();
}
}
// ----
private boolean match(LazyMethodGen mg) {
BcelShadow enclosingShadow;
List shadowAccumulator = new ArrayList();
// we want to match ajsynthetic constructors...
if (mg.getName().equals("<init>")) {
return matchInit(mg, shadowAccumulator);
} else if (!shouldWeaveBody(mg)) { //.isAjSynthetic()) {
return false;
} else {
if (mg.getName().equals("<clinit>")) {
clinitShadow = enclosingShadow = BcelShadow.makeStaticInitialization(world, mg);
//System.err.println(enclosingShadow);
} else if (mg.isAdviceMethod()) {
enclosingShadow = BcelShadow.makeAdviceExecution(world, mg);
} else {
AjAttribute.EffectiveSignatureAttribute effective = mg.getEffectiveSignature();
if (effective == null) {
enclosingShadow = BcelShadow.makeMethodExecution(world, mg, !canMatchBodyShadows);
} else if (effective.isWeaveBody()) {
enclosingShadow =
BcelShadow.makeShadowForMethod(
world,
mg,
effective.getShadowKind(),
effective.getEffectiveSignature());
} else {
return false;
}
}
if (canMatchBodyShadows) {
for (InstructionHandle h = mg.getBody().getStart();
h != null;
h = h.getNext()) {
match(mg, h, enclosingShadow, shadowAccumulator);
}
}
if (match(enclosingShadow, shadowAccumulator)) {
enclosingShadow.init();
}
mg.matchedShadows = shadowAccumulator;
return !shadowAccumulator.isEmpty();
}
}
private boolean matchInit(LazyMethodGen mg, List shadowAccumulator) {
BcelShadow enclosingShadow;
// XXX the enclosing join point is wrong for things before ignoreMe.
InstructionHandle superOrThisCall = findSuperOrThisCall(mg);
// we don't walk bodies of things where it's a wrong constructor thingie
if (superOrThisCall == null) return false;
enclosingShadow = BcelShadow.makeConstructorExecution(world, mg, superOrThisCall);
// 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);
}
}
match(enclosingShadow, shadowAccumulator);
}
// XXX we don't do pre-inits of interfaces
// now add interface inits
if (superOrThisCall != null && ! isThisCall(superOrThisCall)) {
InstructionHandle curr = enclosingShadow.getRange().getStart();
for (Iterator i = addedSuperInitializersAsList.iterator(); i.hasNext(); ) {
IfaceInitList l = (IfaceInitList) i.next();
Member ifaceInitSig = AjcMemberMaker.interfaceConstructor(l.onType);
BcelShadow initShadow =
BcelShadow.makeIfaceInitialization(world, mg, ifaceInitSig);
// insert code in place
InstructionList inits = genInitInstructions(l.list, false);
if (match(initShadow, shadowAccumulator) || !inits.isEmpty()) {
initShadow.initIfaceInitializer(curr);
initShadow.getRange().insert(inits, Range.OutsideBefore);
}
}
// now we add our initialization code
InstructionList inits = genInitInstructions(addedThisInitializers, false);
enclosingShadow.getRange().insert(inits, Range.OutsideBefore);
}
// actually, you only need to inline the self constructors that are
// in a particular group (partition the constructors into groups where members
// call or are called only by those in the group). Then only inline
// constructors
// in groups where at least one initialization jp matched. Future work.
boolean addedInitialization =
match(
BcelShadow.makeUnfinishedInitialization(world, mg),
initializationShadows);
addedInitialization |=
match(
BcelShadow.makeUnfinishedPreinitialization(world, mg),
initializationShadows);
mg.matchedShadows = shadowAccumulator;
return addedInitialization || !shadowAccumulator.isEmpty();
}
private boolean shouldWeaveBody(LazyMethodGen mg) {
if (mg.isAjSynthetic()) return mg.getName().equals("<clinit>");
AjAttribute.EffectiveSignatureAttribute a = mg.getEffectiveSignature();
if (a != null) return a.isWeaveBody();
return true;
}
/**
* first sorts the mungers, then gens the initializers in the right order
*/
private InstructionList genInitInstructions(List list, boolean isStatic) {
list = PartialOrder.sort(list);
if (list == null) {
throw new BCException("circularity in inter-types");
}
InstructionList ret = new InstructionList();
for (Iterator i = list.iterator(); i.hasNext();) {
ConcreteTypeMunger cmunger = (ConcreteTypeMunger) i.next();
NewFieldTypeMunger munger = (NewFieldTypeMunger) cmunger.getMunger();
ResolvedMember initMethod = munger.getInitMethod(cmunger.getAspectType());
if (!isStatic) ret.append(InstructionConstants.ALOAD_0);
ret.append(Utility.createInvoke(fact, world, initMethod));
}
return ret;
}
private void match(
LazyMethodGen mg,
InstructionHandle ih,
BcelShadow enclosingShadow,
List shadowAccumulator)
{
Instruction i = ih.getInstruction();
if (i instanceof FieldInstruction) {
FieldInstruction fi = (FieldInstruction) i;
if (fi instanceof PUTFIELD || fi instanceof PUTSTATIC) {
// check for sets of constant fields. We first check the previous
// instruction. If the previous instruction is a LD_WHATEVER (push
// constant on the stack) then we must resolve the field to determine
// if it's final. If it is final, then we don't generate a shadow.
InstructionHandle prevHandle = ih.getPrev();
Instruction prevI = prevHandle.getInstruction();
if (Utility.isConstantPushInstruction(prevI)) {
Member field = BcelWorld.makeFieldSignature(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 {
matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else {
matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else {
matchGetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else if (i instanceof InvokeInstruction) {
InvokeInstruction ii = (InvokeInstruction) i;
if (ii.getMethodName(clazz.getConstantPoolGen()).equals("<init>")) {
match(
BcelShadow.makeConstructorCall(world, mg, ih, enclosingShadow),
shadowAccumulator);
} else if (ii instanceof INVOKESPECIAL) {
String onTypeName = ii.getClassName(cpg);
if (onTypeName.equals(mg.getEnclosingClass().getName())) {
// we are private
matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator);
} else {
// we are a super call, and this is not a join point in AspectJ-1.{0,1}
}
} else {
matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator);
}
}
// performance optimization... we only actually care about ASTORE instructions,
// since that's what every javac type thing ever uses to start a handler, but for
// now we'll do this for everybody.
if (Range.isRangeHandle(ih)) return;
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters != null) {
for (int j = 0; j < targeters.length; j++) {
InstructionTargeter t = targeters[j];
if (t instanceof ExceptionRange) {
// assert t.getHandler() == ih
ExceptionRange er = (ExceptionRange) t;
if (er.getCatchType() == null) continue;
if (isInitFailureHandler(ih)) return;
match(
BcelShadow.makeExceptionHandler(
world,
er,
mg, ih, enclosingShadow),
shadowAccumulator);
}
}
}
}
private boolean isInitFailureHandler(InstructionHandle ih) {
// Skip the astore_0 and aload_0 at the start of the handler and
// then check if the instruction following these is
// 'putstatic ajc$initFailureCause'. If it is then we are
// in the handler we created in AspectClinit.generatePostSyntheticCode()
InstructionHandle twoInstructionsAway = ih.getNext().getNext();
if (twoInstructionsAway.getInstruction() instanceof PUTSTATIC) {
String name = ((PUTSTATIC)twoInstructionsAway.getInstruction()).getFieldName(cpg);
if (name.equals(NameMangler.INITFAILURECAUSE_FIELD_NAME)) return true;
}
return false;
}
private void matchSetInstruction(
LazyMethodGen mg,
InstructionHandle ih,
BcelShadow enclosingShadow,
List shadowAccumulator) {
FieldInstruction fi = (FieldInstruction) ih.getInstruction();
Member field = BcelWorld.makeFieldSignature(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 {
match(
BcelShadow.makeFieldSet(world, mg, ih, enclosingShadow),
shadowAccumulator);
}
}
private void matchGetInstruction(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) {
FieldInstruction fi = (FieldInstruction) ih.getInstruction();
Member field = BcelWorld.makeFieldSignature(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 {
match(BcelShadow.makeFieldGet(world, mg, ih, enclosingShadow), shadowAccumulator);
}
}
private void matchInvokeInstruction(LazyMethodGen mg,
InstructionHandle ih,
InvokeInstruction invoke,
BcelShadow enclosingShadow,
List shadowAccumulator)
{
String methodName = invoke.getName(cpg);
if (methodName.startsWith(NameMangler.PREFIX)) {
Member method =
BcelWorld.makeMethodSignature(clazz, invoke);
ResolvedMember declaredSig = method.resolve(world);
//System.err.println(method + ", declaredSig: " +declaredSig);
if (declaredSig == null) return;
if (declaredSig.getKind() == Member.FIELD) {
Shadow.Kind kind;
if (method.getReturnType().equals(ResolvedTypeX.VOID)) {
kind = Shadow.FieldSet;
} else {
kind = Shadow.FieldGet;
}
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;
match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow,
effectiveSig.getShadowKind(), effectiveSig.getEffectiveSignature()),
shadowAccumulator);
}
} else {
match(
BcelShadow.makeMethodCall(world, mg, ih, enclosingShadow),
shadowAccumulator);
}
}
private boolean match(BcelShadow shadow, List shadowAccumulator) {
//System.err.println("match: " + shadow);
boolean isMatched = false;
for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) {
ShadowMunger munger = (ShadowMunger)i.next();
if (munger.match(shadow, world)) {
WeaverMetrics.recordMatchResult(true);// Could pass: munger
shadow.addMunger(munger);
isMatched = true;
if (shadow.getKind() == Shadow.StaticInitialization) {
clazz.warnOnAddedStaticInitializer(shadow,munger.getSourceLocation());
}
} else {
WeaverMetrics.recordMatchResult(false); // Could pass: munger
}
}
if (isMatched) shadowAccumulator.add(shadow);
return isMatched;
}
// ----
private void implement(LazyMethodGen mg) {
List shadows = mg.matchedShadows;
if (shadows == null) return;
// We depend on a partial order such that inner shadows are earlier on the list
// than outer shadows. That's fine. This order is preserved if:
// A preceeds B iff B.getStart() is LATER THAN A.getStart().
for (Iterator i = shadows.iterator(); i.hasNext(); ) {
BcelShadow shadow = (BcelShadow)i.next();
shadow.implement();
}
mg.matchedShadows = null;
}
// ----
public LazyClassGen getLazyClassGen() {
return clazz;
}
public List getShadowMungers() {
return shadowMungers;
}
public BcelWorld getWorld() {
return world;
}
// Called by the BcelWeaver to let us know all BcelClassWeavers need to collect reweavable info
public static void setReweavableMode(boolean mode,boolean compress) {
inReweavableMode = mode;
compressReweavableAttributes = compress;
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/BcelField.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.util.Iterator;
import java.util.List;
import org.apache.bcel.classfile.Attribute;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.Synthetic;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.World;
final class BcelField extends ResolvedMember {
private Field field;
private boolean isAjSynthetic;
private boolean isSynthetic = false;
BcelField(BcelObjectType declaringType, Field field) {
super(
FIELD,
declaringType.getResolvedTypeX(),
field.getAccessFlags(),
field.getName(),
field.getSignature());
this.field = field;
unpackAttributes(declaringType.getResolvedTypeX().getWorld());
checkedExceptions = TypeX.NONE;
}
// ----
private void unpackAttributes(World world) {
Attribute[] attrs = field.getAttributes();
List as = BcelAttributes.readAjAttributes(attrs, getSourceContext(world));
for (Iterator iter = as.iterator(); iter.hasNext();) {
AjAttribute a = (AjAttribute) iter.next();
if (a instanceof AjAttribute.AjSynthetic) {
isAjSynthetic = true;
} else {
throw new BCException("weird field attribute " + a);
}
}
isAjSynthetic = false;
for (int i = attrs.length - 1; i >= 0; i--) {
if (attrs[i] instanceof Synthetic) isSynthetic = true;
}
}
public boolean isAjSynthetic() {
return isAjSynthetic; // || getName().startsWith(NameMangler.PREFIX);
}
public boolean isSynthetic() {
return isSynthetic;
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/BcelFieldRef.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import org.apache.bcel.Constants;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionList;
import org.aspectj.weaver.ResolvedTypeX;
/**
* XXX Erik and I need to discuss this hierarchy. Having FieldRef
* extend Var is convenient, but hopefully there's a better design.
*
* This is always a static reference.
*/
public class BcelFieldRef extends BcelVar {
private String className, fieldName;
public BcelFieldRef(ResolvedTypeX type, String className, String fieldName) {
super(type, 0);
this.className = className;
this.fieldName = fieldName;
}
public String toString() {
return "BcelFieldRef(" + getType() + " " + className + "." + fieldName + ")";
}
//public int getSlot() { return slot; }
public Instruction createLoad(InstructionFactory fact) {
return fact.createFieldAccess(className, fieldName,
BcelWorld.makeBcelType(getType()), Constants.GETSTATIC);
}
public Instruction createStore(InstructionFactory fact) {
return fact.createFieldAccess(className, fieldName,
BcelWorld.makeBcelType(getType()), Constants.PUTSTATIC);
}
public InstructionList createCopyFrom(InstructionFactory fact, int oldSlot) {
throw new RuntimeException("unimplemented");
}
// this is an array var
// void appendConvertableArrayLoad(
// InstructionList il,
// InstructionFactory fact,
// int index,
// ResolvedTypeX convertTo)
// {
// ResolvedTypeX convertFromType = getType().getResolvedComponentType();
// appendLoad(il, fact);
// il.append(Utility.createConstant(fact, index));
// il.append(fact.createArrayLoad(BcelWorld.makeBcelType(convertFromType)));
// Utility.appendConversion(il, fact, convertFromType, convertTo);
// }
//
// void appendConvertableArrayStore(
// InstructionList il,
// InstructionFactory fact,
// int index,
// BcelFieldRef storee)
// {
// ResolvedTypeX convertToType = getType().getResolvedComponentType();
// appendLoad(il, fact);
// il.append(Utility.createConstant(fact, index));
// storee.appendLoad(il, fact);
// Utility.appendConversion(il, fact, storee.getType(), convertToType);
// il.append(fact.createArrayStore(BcelWorld.makeBcelType(convertToType)));
// }
//
// InstructionList createConvertableArrayStore(
// InstructionFactory fact,
// int index,
// BcelFieldRef storee)
// {
// InstructionList il = new InstructionList();
// appendConvertableArrayStore(il, fact, index, storee);
// return il;
// }
// InstructionList createConvertableArrayLoad(
// InstructionFactory fact,
// int index,
// ResolvedTypeX convertTo)
// {
// InstructionList il = new InstructionList();
// appendConvertableArrayLoad(il, fact, index, convertTo);
// return il;
// }
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/BcelMethod.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.Iterator;
import java.util.List;
import org.apache.bcel.classfile.ExceptionTable;
import org.apache.bcel.classfile.LocalVariable;
import org.apache.bcel.classfile.LocalVariableTable;
import org.apache.bcel.classfile.Method;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.World;
final class BcelMethod extends ResolvedMember {
private Method method;
private boolean isAjSynthetic;
private ShadowMunger associatedShadowMunger;
private AjAttribute.EffectiveSignatureAttribute effectiveSignature;
BcelMethod(BcelObjectType declaringType, Method method) {
super(
method.getName().equals("<init>") ? CONSTRUCTOR :
(method.getName().equals("<clinit>") ? STATIC_INITIALIZATION : METHOD),
declaringType.getResolvedTypeX(),
declaringType.isInterface()
? method.getAccessFlags() | Modifier.INTERFACE
: method.getAccessFlags(),
method.getName(),
method.getSignature());
this.method = method;
unpackAjAttributes(declaringType.getResolvedTypeX().getWorld());
unpackJavaAttributes();
}
// ----
private void unpackJavaAttributes() {
ExceptionTable exnTable = method.getExceptionTable();
checkedExceptions = (exnTable == null)
? TypeX.NONE
: TypeX.forNames(exnTable.getExceptionNames());
LocalVariableTable varTable = method.getLocalVariableTable();
int len = getArity();
if (varTable == null) {
this.parameterNames = Utility.makeArgNames(len);
} else {
TypeX[] paramTypes = getParameterTypes();
String[] paramNames = new String[len];
int index = isStatic() ? 0 : 1;
for (int i = 0; i < len; i++) {
LocalVariable lv = varTable.getLocalVariable(index);
if (lv == null) {
paramNames[i] = "arg" + i;
} else {
paramNames[i] = lv.getName();
}
index += paramTypes[i].getSize();
}
this.parameterNames = paramNames;
}
}
private void unpackAjAttributes(World world) {
List as = BcelAttributes.readAjAttributes(method.getAttributes(), getSourceContext(world));
//System.out.println("unpack: " + this + ", " + as);
for (Iterator iter = as.iterator(); iter.hasNext();) {
AjAttribute a = (AjAttribute) iter.next();
if (a instanceof AjAttribute.AdviceAttribute) {
associatedShadowMunger = ((AjAttribute.AdviceAttribute)a).reify(this, world);
return;
} else if (a instanceof AjAttribute.AjSynthetic) {
isAjSynthetic = true;
} else if (a instanceof AjAttribute.EffectiveSignatureAttribute) {
//System.out.println("found effective: " + this);
effectiveSignature = (AjAttribute.EffectiveSignatureAttribute)a;
} else {
throw new BCException("weird method attribute " + a);
}
}
associatedShadowMunger = null;
}
public boolean isAjSynthetic() {
return isAjSynthetic; // || getName().startsWith(NameMangler.PREFIX);
}
//FIXME needs an isSynthetic method
public ShadowMunger getAssociatedShadowMunger() {
return associatedShadowMunger;
}
public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() {
return effectiveSignature;
}
public Kind getKind() {
if (associatedShadowMunger != null) {
return ADVICE;
} else {
return super.getKind();
}
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/BcelObjectType.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.patterns.PerClause;
// ??? exposed for testing
public class BcelObjectType extends ResolvedTypeX.ConcreteName {
private JavaClass javaClass;
private boolean isObject = false; // set upon construction
private LazyClassGen lazyClassGen = null; // set lazily if it's an aspect
// lazy, for no particular reason I can discern
private ResolvedTypeX[] interfaces = null;
private ResolvedTypeX superClass = null;
private ResolvedMember[] fields = null;
private ResolvedMember[] methods = null;
// strangely non-lazy
private ResolvedPointcutDefinition[] pointcuts = null;
private PerClause perClause = null;
private WeaverStateInfo weaverState = null;
private List typeMungers = Collections.EMPTY_LIST;
private List declares = Collections.EMPTY_LIST;
private ResolvedMember[] privilegedAccess = null;
public Collection getTypeMungers() {
return typeMungers;
}
public Collection getDeclares() {
return declares;
}
public Collection getPrivilegedAccesses() {
if (privilegedAccess == null) return Collections.EMPTY_LIST;
return Arrays.asList(privilegedAccess);
}
// IMPORTANT! THIS DOESN'T do real work on the java class, just stores it away.
BcelObjectType(ResolvedTypeX.Name resolvedTypeX, JavaClass javaClass, boolean exposedToWeaver) {
super(resolvedTypeX, exposedToWeaver);
this.javaClass = javaClass;
if (resolvedTypeX.getSourceContext() == null) {
resolvedTypeX.setSourceContext(new BcelSourceContext(this));
}
// this should only ever be java.lang.Object which is
// the only class in Java-1.4 with no superclasses
isObject = (javaClass.getSuperclassNameIndex() == 0);
unpackAspectAttributes();
}
// repeat initialization
public void setJavaClass(JavaClass newclass) {
this.javaClass = newclass;
resetState();
}
public int getModifiers() {
return javaClass.getAccessFlags();
}
public ResolvedTypeX getSuperclass() {
if (isObject) return null;
if (superClass == null) {
superClass = getResolvedTypeX().getWorld().resolve(TypeX.forName(javaClass.getSuperclassName()));
}
return superClass;
}
public ResolvedTypeX[] getDeclaredInterfaces() {
if (interfaces == null) {
String[] ifaceNames = javaClass.getInterfaceNames();
interfaces = new ResolvedTypeX[ifaceNames.length];
for (int i = 0, len = ifaceNames.length; i < len; i++) {
interfaces[i] = getResolvedTypeX().getWorld().resolve(TypeX.forName(ifaceNames[i]));
}
}
return interfaces;
}
public ResolvedMember[] getDeclaredMethods() {
if (methods == null) {
Method[] ms = javaClass.getMethods();
ResolvedMember[] ret = new ResolvedMember[ms.length];
for (int i = ms.length - 1; i >= 0; i--) {
ret[i] = new BcelMethod(this, ms[i]);
}
methods = ret;
}
return methods;
}
public ResolvedMember[] getDeclaredFields() {
if (fields == null) {
Field[] fs = javaClass.getFields();
ResolvedMember[] ret = new ResolvedMember[fs.length];
for (int i = 0, len = fs.length; i < len; i++) {
ret[i] = new BcelField(this, fs[i]);
}
fields = ret;
}
return fields;
}
// ----
// fun based on the aj attributes
public ResolvedMember[] getDeclaredPointcuts() {
return pointcuts;
}
//??? method only used for testing
public void addPointcutDefinition(ResolvedPointcutDefinition d) {
int len = pointcuts.length;
ResolvedPointcutDefinition[] ret = new ResolvedPointcutDefinition[len+1];
System.arraycopy(pointcuts, 0, ret, 0, len);
ret[len] = d;
pointcuts = ret;
}
public boolean isAspect() {
return perClause != null;
}
private void unpackAspectAttributes() {
List pointcuts = new ArrayList();
typeMungers = new ArrayList();
declares = new ArrayList();
List l = BcelAttributes.readAjAttributes(javaClass.getAttributes(), getResolvedTypeX().getSourceContext());
for (Iterator iter = l.iterator(); iter.hasNext();) {
AjAttribute a = (AjAttribute) iter.next();
//System.err.println("unpacking: " + this + " and " + a);
if (a instanceof AjAttribute.Aspect) {
perClause = ((AjAttribute.Aspect)a).reify(this.getResolvedTypeX());
} else if (a instanceof AjAttribute.PointcutDeclarationAttribute) {
pointcuts.add(((AjAttribute.PointcutDeclarationAttribute)a).reify());
} else if (a instanceof AjAttribute.WeaverState) {
weaverState = ((AjAttribute.WeaverState)a).reify();
} else if (a instanceof AjAttribute.TypeMunger) {
typeMungers.add(((AjAttribute.TypeMunger)a).reify(getResolvedTypeX().getWorld(), getResolvedTypeX()));
} else if (a instanceof AjAttribute.DeclareAttribute) {
declares.add(((AjAttribute.DeclareAttribute)a).getDeclare());
} else if (a instanceof AjAttribute.PrivilegedAttribute) {
privilegedAccess = ((AjAttribute.PrivilegedAttribute)a).getAccessedMembers();
} else if (a instanceof AjAttribute.SourceContextAttribute) {
if (getResolvedTypeX().getSourceContext() instanceof BcelSourceContext) {
((BcelSourceContext)getResolvedTypeX().getSourceContext()).addAttributeInfo((AjAttribute.SourceContextAttribute)a);
}
} else {
throw new BCException("bad attribute " + a);
}
}
this.pointcuts = (ResolvedPointcutDefinition[])
pointcuts.toArray(new ResolvedPointcutDefinition[pointcuts.size()]);
// this.typeMungers = (BcelTypeMunger[])
// typeMungers.toArray(new BcelTypeMunger[typeMungers.size()]);
// this.declares = (Declare[])
// declares.toArray(new Declare[declares.size()]);
}
public PerClause getPerClause() {
return perClause;
}
JavaClass getJavaClass() {
return javaClass;
}
public void resetState() {
this.interfaces = null;
this.superClass = null;
this.fields = null;
this.methods = null;
this.pointcuts = null;
this.perClause = null;
this.weaverState = null;
this.lazyClassGen = null;
isObject = (javaClass.getSuperclassNameIndex() == 0);
unpackAspectAttributes();
}
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 isInterface() {
return javaClass.isInterface();
}
public boolean isSynthetic() {
return getResolvedTypeX().isSynthetic();
}
public ISourceLocation getSourceLocation() {
return getResolvedTypeX().getSourceContext().makeSourceLocation(0); //FIXME, we can do better than this
}
public void addParent(ResolvedTypeX newParent) {
if (newParent.isClass()) {
superClass = newParent;
} else {
ResolvedTypeX[] oldInterfaceNames = getDeclaredInterfaces();
int len = oldInterfaceNames.length;
ResolvedTypeX[] newInterfaceNames = new ResolvedTypeX[len+1];
System.arraycopy(oldInterfaceNames, 0, newInterfaceNames, 0, len);
newInterfaceNames[len] = newParent;
interfaces = newInterfaceNames;
}
//System.err.println("javaClass: " + Arrays.asList(javaClass.getInterfaceNames()) + " super " + javaClass.getSuperclassName());
//if (lazyClassGen != null) lazyClassGen.print();
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/BcelRenderer.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import org.apache.bcel.Constants;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.ReferenceType;
import org.apache.bcel.generic.Type;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ast.And;
import org.aspectj.weaver.ast.Call;
import org.aspectj.weaver.ast.CallExpr;
import org.aspectj.weaver.ast.Expr;
import org.aspectj.weaver.ast.FieldGet;
import org.aspectj.weaver.ast.FieldGetCall;
import org.aspectj.weaver.ast.IExprVisitor;
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;
// we generate right to left, btw.
public class BcelRenderer implements ITestVisitor, IExprVisitor {
private InstructionList instructions;
private InstructionFactory fact;
private BcelWorld world;
InstructionHandle sk, fk, next = null;
private BcelRenderer(InstructionFactory fact, BcelWorld world) {
super();
this.fact = fact;
this.world = world;
this.instructions = new InstructionList();
}
// ---- renderers
public static InstructionList renderExpr(
InstructionFactory fact,
BcelWorld world,
Expr e)
{
BcelRenderer renderer = new BcelRenderer(fact, world);
e.accept(renderer);
return renderer.instructions;
}
public static InstructionList renderExpr(
InstructionFactory fact,
BcelWorld world,
Expr e,
Type desiredType)
{
BcelRenderer renderer = new BcelRenderer(fact, world);
e.accept(renderer);
InstructionList il = renderer.instructions;
il.append(Utility.createConversion(fact, BcelWorld.makeBcelType(e.getType()), desiredType));
return il;
}
public static InstructionList renderExprs(
InstructionFactory fact,
BcelWorld world,
Expr[] es)
{
BcelRenderer renderer = new BcelRenderer(fact, world);
for (int i = es.length - 1; i >= 0; i--) {
es[i].accept(renderer);
}
return renderer.instructions;
}
/*
* Get the instructions representing this test.
*
* @param e test to render
* @param sk instructionHandle to jump to if our rendered check succeeds (typically start of advice)
* @param fk instructionHandle to jump to if our rendered check fails (typically after end of advice)
* @param next instructionHandle that will follow this generated code. Passing in null will generate
* one unnecessary GOTO instruction.
*
* @returns the instruction list representing this expression
*/
public static InstructionList renderTest(
InstructionFactory fact,
BcelWorld world,
Test e,
InstructionHandle sk,
InstructionHandle fk,
InstructionHandle next)
{
BcelRenderer renderer = new BcelRenderer(fact, world);
renderer.recur(e, sk, fk, next);
return renderer.instructions;
}
/*
* Get the instructions representing this test.
*
* @param e test to render
* @param sk instructionHandle to jump to if our rendered check succeeds (typically start of advice)
* @param fk instructionHandle to jump to if our rendered check fails (typically after end of advice)
*
* @returns the instruction list representing this expression
*/
public static InstructionList renderTest(
InstructionFactory fact,
BcelWorld world,
Test e,
InstructionHandle sk,
InstructionHandle fk)
{
return renderTest(fact, world, e, sk, fk, null);
}
// ---- recurrers
private void recur(
Test e,
InstructionHandle sk,
InstructionHandle fk,
InstructionHandle next)
{
this.sk = sk;
this.fk = fk;
this.next = next;
e.accept(this);
}
// ---- test visitors
public void visit(And e) {
InstructionHandle savedFk = fk;
recur(e.getRight(), sk, fk, next);
InstructionHandle ning = instructions.getStart();
recur(e.getLeft(), ning, savedFk, ning);
}
public void visit(Or e) {
InstructionHandle savedSk = sk;
recur(e.getRight(), sk, fk, next);
recur(e.getLeft(), savedSk, instructions.getStart(), instructions.getStart());
}
public void visit(Not e) {
recur(e.getBody(), fk, sk, next);
}
public void visit(Instanceof i) {
instructions.insert(createJumpBasedOnBooleanOnStack());
instructions.insert(
Utility.createInstanceof(fact, (ReferenceType) BcelWorld.makeBcelType(i.getType())));
i.getVar().accept(this);
}
private InstructionList createJumpBasedOnBooleanOnStack() {
InstructionList il = new InstructionList();
if (sk == fk) {
// don't bother generating if it doesn't matter
if (sk != next) {
il.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, sk));
}
return il;
}
if (fk == next) {
il.insert(InstructionFactory.createBranchInstruction(Constants.IFNE, sk));
} else if (sk == next) {
il.insert(InstructionFactory.createBranchInstruction(Constants.IFEQ, fk));
} else {
il.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, sk));
il.insert(InstructionFactory.createBranchInstruction(Constants.IFEQ, fk));
}
return il;
}
public void visit(Literal literal) {
if (literal == Literal.FALSE)
throw new BCException("bad");
}
public void visit(Call call) {
Member method = call.getMethod();
// assert method.isStatic()
Expr[] args = call.getArgs();
//System.out.println("args: " + Arrays.asList(args));
InstructionList callIl = new InstructionList();
for (int i=0, len=args.length; i < len; i++) {
//XXX only correct for static method calls
Type desiredType = BcelWorld.makeBcelType(method.getParameterTypes()[i]);
callIl.append(renderExpr(fact, world, args[i], desiredType));
}
//System.out.println("rendered args: " + callIl);
callIl.append(Utility.createInvoke(fact, world, method));
callIl.append(createJumpBasedOnBooleanOnStack());
instructions.insert(callIl);
}
public void visit(FieldGetCall fieldGetCall) {
Member field = fieldGetCall.getField();
Member method = fieldGetCall.getMethod();
InstructionList il = new InstructionList();
il.append(Utility.createGet(fact, field));
// assert !method.isStatic()
Expr[] args = fieldGetCall.getArgs();
//System.out.println("args: " + Arrays.asList(args));
il.append(renderExprs(fact, world, args));
//System.out.println("rendered args: " + callIl);
il.append(Utility.createInvoke(fact, world, method));
il.append(createJumpBasedOnBooleanOnStack());
instructions.insert(il);
}
// ---- expr visitors
public void visit(Var var) {
BcelVar bvar = (BcelVar) var;
bvar.insertLoad(instructions, fact);
}
public void visit(FieldGet fieldGet) {
Member field = fieldGet.getField();
// assert field.isStatic()
instructions.insert(Utility.createGet(fact, field));
}
public void visit(CallExpr call) {
Member method = call.getMethod();
// assert method.isStatic()
Expr[] args = call.getArgs();
InstructionList callIl = renderExprs(fact, world, args);
callIl.append(Utility.createInvoke(fact, world, method));
instructions.insert(callIl);
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.generic.ACONST_NULL;
import org.apache.bcel.generic.ArrayType;
import org.apache.bcel.generic.BranchInstruction;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.DUP;
import org.apache.bcel.generic.DUP_X1;
import org.apache.bcel.generic.FieldInstruction;
import org.apache.bcel.generic.INVOKESPECIAL;
import org.apache.bcel.generic.INVOKESTATIC;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionConstants;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.InstructionTargeter;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.NEW;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.ReturnInstruction;
import org.apache.bcel.generic.SWAP;
import org.apache.bcel.generic.StoreInstruction;
import org.apache.bcel.generic.TargetLostException;
import org.apache.bcel.generic.Type;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Var;
/*
* Some fun implementation stuff:
*
* * expressionKind advice is non-execution advice
* * may have a target.
* * if the body is extracted, it will be extracted into
* a static method. The first argument to the static
* method is the target
* * advice may expose a this object, but that's the advice's
* consideration, not ours. This object will NOT be cached in another
* local, but will always come from frame zero.
*
* * non-expressionKind advice is execution advice
* * may have a this.
* * target is same as this, and is exposed that way to advice
* (i.e., target will not be cached, will always come from frame zero)
* * if the body is extracted, it will be extracted into a method
* with same static/dynamic modifier as enclosing method. If non-static,
* target of callback call will be this.
*
* * because of these two facts, the setup of the actual arguments (including
* possible target) callback method is the same for both kinds of advice:
* push the targetVar, if it exists (it will not exist for advice on static
* things), then push all the argVars.
*
* Protected things:
*
* * the above is sufficient for non-expressionKind advice for protected things,
* since the target will always be this.
*
* * For expressionKind things, we have to modify the signature of the callback
* method slightly. For non-static expressionKind things, we modify
* the first argument of the callback method NOT to be the type specified
* by the method/field signature (the owner), but rather we type it to
* the currentlyEnclosing type. We are guaranteed this will be fine,
* since the verifier verifies that the target is a subtype of the currently
* enclosingType.
*
* Worries:
*
* * ConstructorCalls will be weirder than all of these, since they
* supposedly don't have a target (according to AspectJ), but they clearly
* do have a target of sorts, just one that needs to be pushed on the stack,
* dupped, and not touched otherwise until the constructor runs.
*
* @author Jim Hugunin
* @author Erik Hilsdale
*
*/
public class BcelShadow extends Shadow {
private ShadowRange range;
private final BcelWorld world;
private final LazyMethodGen enclosingMethod;
private boolean fallsThrough; //XXX not used anymore
// ---- initialization
/**
* 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;
fallsThrough = kind.argsOnStack();
}
// ---- copies all state, including Shadow's mungers...
public BcelShadow copyInto(LazyMethodGen recipient, BcelShadow enclosing) {
BcelShadow s = new BcelShadow(world, getKind(), getSignature(), recipient, enclosing);
List src = mungers;
List dest = s.mungers;
for (Iterator i = src.iterator(); i.hasNext(); ) {
dest.add(i.next());
}
return s;
}
// ---- overridden behaviour
public World getIWorld() {
return world;
}
private void deleteNewAndDup() {
final ConstantPoolGen cpg = getEnclosingClass().getConstantPoolGen();
int depth = 1;
InstructionHandle ih = range.getStart();
while (true) {
Instruction inst = ih.getInstruction();
if (inst instanceof INVOKESPECIAL
&& ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) {
depth++;
} else if (inst instanceof NEW) {
depth--;
if (depth == 0) break;
}
ih = ih.getPrev();
}
// now IH points to the NEW. We're followed by the DUP, and that is followed
// by the actual instruciton we care about.
InstructionHandle newHandle = ih;
InstructionHandle endHandle = newHandle.getNext();
InstructionHandle nextHandle;
if (endHandle.getInstruction() instanceof DUP) {
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else if (endHandle.getInstruction() instanceof DUP_X1) {
InstructionHandle dupHandle = endHandle;
endHandle = endHandle.getNext();
nextHandle = endHandle.getNext();
if (endHandle.getInstruction() instanceof SWAP) {}
else {
// XXX see next XXX comment
throw new RuntimeException("Unhandled kind of new " + endHandle);
}
retargetFrom(newHandle, nextHandle);
retargetFrom(dupHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else {
endHandle = newHandle;
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
// add a POP here... we found a NEW w/o a dup or anything else, so
// we must be in statement context.
getRange().insert(InstructionConstants.POP, Range.OutsideAfter);
}
// assert (dupHandle.getInstruction() instanceof DUP);
try {
range.getBody().delete(newHandle, endHandle);
} catch (TargetLostException e) {
throw new BCException("shouldn't happen");
}
}
private void retargetFrom(InstructionHandle old, InstructionHandle fresh) {
InstructionTargeter[] sources = old.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
sources[i].updateTarget(old, fresh);
}
}
}
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) {
deleteNewAndDup();
initializeArgVars();
} else if (getKind() == ExceptionHandler) {
ShadowRange range = getRange();
InstructionList body = range.getBody();
InstructionHandle start = range.getStart();
InstructionHandle freshIh = body.insert(start, InstructionConstants.NOP);
InstructionTargeter[] targeters = start.getTargeters();
for (int i = 0; i < targeters.length; i++) {
InstructionTargeter t = targeters[i];
if (t instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) t;
er.updateTarget(start, freshIh, body);
}
}
}
// now we ask each munger to request our state
isThisJoinPointLazy = world.isXlazyTjp();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
munger.specializeOn(this);
}
initializeThisJoinPoint();
// 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) {
range.insert(
BcelRenderer.renderExprs(fact, world, argVars),
Range.InsideBefore);
if (targetVar != null) {
range.insert(
BcelRenderer.renderExpr(fact, world, targetVar),
Range.InsideBefore);
}
if (getKind() == ConstructorCall) {
range.insert((Instruction) 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;
}
public int getSourceLine() {
if (range == null) {
if (getEnclosingMethod().hasBody()) {
return Utility.getSourceLine(getEnclosingMethod().getBody().getStart());
} else {
return 0;
}
}
int ret = Utility.getSourceLine(range.getStart());
if (ret < 0) return 0;
return ret;
}
// overrides
public TypeX 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.makeMethodSignature(enclosingMethod),
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().getConstantPoolGen())
.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().getConstantPoolGen()).equals(NameMangler.AJC_POST_CLINIT_NAME)) {
// clinitEnd = clinitEnd.getPrev();
// }
// }
BcelShadow s =
new BcelShadow(
world,
StaticInitialization,
world.makeMethodSignature(enclosingMethod),
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();
TypeX catchType = exceptionRange.getCatchType();
TypeX inType = enclosingMethod.getEnclosingClass().getType();
ResolvedMember sig = Member.makeExceptionHandlerSignature(inType, catchType);
sig.parameterNames = 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() instanceof StoreInstruction &&
startOfHandler.getNext() != null)
{
int slot = ((StoreInstruction)startOfHandler.getInstruction()).getIndex();
//System.out.println("got store: " + startOfHandler.getInstruction() + ", " + index);
InstructionTargeter[] targeters = startOfHandler.getNext().getTargeters();
if (targeters!=null) {
for (int i=targeters.length-1; i >= 0; i--) {
if (targeters[i] instanceof LocalVariableTag) {
LocalVariableTag t = (LocalVariableTag)targeters[i];
if (t.getSlot() == slot) {
return t.getName();
}
//System.out.println("tag: " + targeters[i]);
}
}
}
}
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)
{
InstructionList body = constructor.getBody();
// TypeX 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();
// // TypeX 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)
{
return new BcelShadow(
world,
Initialization,
world.makeMethodSignature(constructor),
constructor,
null);
}
public static BcelShadow makeUnfinishedPreinitialization(
BcelWorld world,
LazyMethodGen constructor)
{
BcelShadow ret = new BcelShadow(
world,
PreInitialization,
world.makeMethodSignature(constructor),
constructor,
null);
ret.fallsThrough = true;
return ret;
}
public static BcelShadow makeMethodExecution(
BcelWorld world,
LazyMethodGen enclosingMethod,
boolean lazyInit)
{
if (!lazyInit) return makeMethodExecution(world, enclosingMethod);
BcelShadow s =
new BcelShadow(
world,
MethodExecution,
enclosingMethod.getMemberView(),
enclosingMethod,
null);
return s;
}
public void init() {
if (range != null) return;
final InstructionList body = enclosingMethod.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(this);
r.associateWithTargets(
Range.genStart(body),
Range.genEnd(body));
}
public static BcelShadow makeMethodExecution(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
return makeShadowForMethod(world, enclosingMethod, MethodExecution,
enclosingMethod.getMemberView()); //world.makeMethodSignature(enclosingMethod));
}
public static BcelShadow makeShadowForMethod(BcelWorld world,
LazyMethodGen enclosingMethod, Shadow.Kind kind, Member sig)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
kind,
sig,
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
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.makeMethodSignature(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 = BcelWorld.makeMethodSignature(
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 makeMethodCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
MethodCall,
BcelWorld.makeMethodSignature(
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,
LazyMethodGen enclosingMethod,
InstructionHandle getHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldGet,
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,
LazyMethodGen enclosingMethod,
InstructionHandle setHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldSet,
BcelWorld.makeFieldSignature(
enclosingMethod.getEnclosingClass(),
(FieldInstruction) setHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, setHandle),
Range.genEnd(body, setHandle));
retargetAllBranches(setHandle, r.getStart());
return s;
}
public static void retargetAllBranches(InstructionHandle from, InstructionHandle to) {
InstructionTargeter[] sources = from.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
InstructionTargeter source = sources[i];
if (source instanceof BranchInstruction) {
source.updateTarget(from, to);
}
}
}
}
// // ---- type access methods
// private ObjectType getTargetBcelType() {
// return (ObjectType) BcelWorld.makeBcelType(getTargetType());
// }
// private Type getArgBcelType(int arg) {
// return BcelWorld.makeBcelType(getArgType(arg));
// }
// ---- kinding
/**
* If the end of my range has no real instructions following then
* my context needs a return at the end.
*/
public boolean terminatesWithReturn() {
return getRange().getRealNext() == null;
}
/**
* Is arg0 occupied with the value of this
*/
public boolean arg0HoldsThis() {
if (getKind().isEnclosingKind()) {
return !getSignature().isStatic();
} else if (enclosingShadow == null) {
//XXX this is mostly right
// this doesn't do the right thing for calls in the pre part of introduced constructors.
return !enclosingMethod.isStatic();
} else {
return ((BcelShadow)enclosingShadow).arg0HoldsThis();
}
}
// ---- argument getting methods
private BcelVar thisVar = null;
private BcelVar targetVar = null;
private BcelVar[] argVars = null;
public Var getThisVar() {
if (!hasThis()) {
throw new IllegalStateException("no this");
}
initializeThisVar();
return thisVar;
}
public Var getTargetVar() {
if (!hasTarget()) {
throw new IllegalStateException("no target");
}
initializeTargetVar();
return targetVar;
}
public Var getArgVar(int i) {
initializeArgVars();
return argVars[i];
}
// reflective thisJoinPoint support
private BcelVar thisJoinPointVar = null;
private boolean isThisJoinPointLazy;
private int lazyTjpConsumers = 0;
private BcelVar thisJoinPointStaticPartVar = null;
// private BcelVar thisEnclosingJoinPointStaticPartVar = null;
public final Var getThisJoinPointStaticPartVar() {
return getThisJoinPointStaticPartBcelVar();
}
public final Var getThisEnclosingJoinPointStaticPartVar() {
return getThisEnclosingJoinPointStaticPartBcelVar();
}
public void requireThisJoinPoint(boolean hasGuardTest) {
if (!hasGuardTest) {
isThisJoinPointLazy = false;
} else {
lazyTjpConsumers++;
}
if (thisJoinPointVar == null) {
thisJoinPointVar = genTempVar(TypeX.forName("org.aspectj.lang.JoinPoint"));
}
}
public Var getThisJoinPointVar() {
requireThisJoinPoint(false);
return thisJoinPointVar;
}
void initializeThisJoinPoint() {
if (thisJoinPointVar == null) return;
if (isThisJoinPointLazy) {
isThisJoinPointLazy = checkLazyTjp();
}
if (isThisJoinPointLazy) {
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 {
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) {
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) {
il.append(createThisJoinPoint());
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 {
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(new ACONST_NULL());
}
if (hasTarget()) {
((BcelVar)getTargetVar()).appendLoad(il, fact);
} else {
il.append(new 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(ResolvedTypeX.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(ResolvedTypeX.OBJECT));
((BcelVar)getArgVar(1)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedTypeX.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;
}
public BcelVar getThisJoinPointStaticPartBcelVar() {
if (thisJoinPointStaticPartVar == null) {
Field field = getEnclosingClass().getTjpField(this);
thisJoinPointStaticPartVar =
new BcelFieldRef(
world.getCoreType(TypeX.forName("org.aspectj.lang.JoinPoint$StaticPart")),
getEnclosingClass().getClassName(),
field.getName());
// getEnclosingClass().warnOnAddedStaticInitializer(this,munger.getSourceLocation());
}
return thisJoinPointStaticPartVar;
}
public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() {
if (enclosingShadow == null) {
// the enclosing of an execution is itself
return getThisJoinPointStaticPartBcelVar();
} else {
return ((BcelShadow)enclosingShadow).getThisJoinPointStaticPartBcelVar();
}
}
//??? need to better understand all the enclosing variants
public Member getEnclosingCodeSignature() {
if (getKind().isEnclosingKind()) {
return getSignature();
} else if (getKind() == Shadow.PreInitialization) {
// PreInit doesn't enclose code but its signature
// is correctly the signature of the ctor.
return getSignature();
} else if (enclosingShadow == null) {
return getEnclosingMethod().getMemberView();
} else {
return enclosingShadow.getSignature();
}
}
private InstructionList makeArgsObjectArray() {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY);
final InstructionList il = new InstructionList();
int alen = getArgCount() ;
il.append(Utility.createConstant(fact, alen));
il.append((Instruction)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
TypeX type = getTargetType();
targetVar = genTempVar(type, "ajc$target");
range.insert(targetVar.createStore(fact), Range.OutsideBefore);
targetVar.setPositionInAroundState(hasThis() ? 1 : 0);
}
}
public void initializeArgVars() {
if (argVars != null) return;
InstructionFactory fact = getFactory();
int len = getArgCount();
argVars = new BcelVar[len];
int positionOffset = (hasTarget() ? 1 : 0) +
((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
if (getKind().argsOnStack()) {
// we move backwards because we're popping off the stack
for (int i = len - 1; i >= 0; i--) {
TypeX 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++) {
TypeX type = getArgType(i);
BcelVar tmp = genTempVar(type, "ajc$arg" + i);
range.insert(tmp.createCopyFrom(fact, index), Range.OutsideBefore);
argVars[i] = tmp;
int position = i;
position += positionOffset;
// System.out.println("set position: " + tmp + ", " + position + " in " + this);
// System.out.println(" hasThis: " + hasThis() + ", hasTarget: " + hasTarget());
tmp.setPositionInAroundState(position);
index += type.getSize();
}
}
}
public void initializeForAroundClosure() {
initializeArgVars();
if (hasTarget()) initializeTargetVar();
if (hasThis()) initializeThisVar();
// System.out.println("initialized: " + this + " thisVar = " + thisVar);
}
// ---- weave methods
void weaveBefore(BcelAdvice munger) {
range.insert(
munger.getAdviceInstructions(this, null, range.getRealStart()),
Range.InsideBefore);
}
public void weaveAfter(BcelAdvice munger) {
weaveAfterThrowing(munger, TypeX.THROWABLE);
weaveAfterReturning(munger);
}
/**
* We guarantee that the return value is on the top of the stack when
* munger.getAdviceInstructions() will be run
* (Unless we have a void return type in which case there's nothing)
*/
public void weaveAfterReturning(BcelAdvice munger) {
// InstructionFactory fact = getFactory();
List returns = new ArrayList();
Instruction ret = null;
for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
if (ih.getInstruction() instanceof ReturnInstruction) {
returns.add(ih);
ret = Utility.copyInstruction(ih.getInstruction());
}
}
InstructionList retList;
InstructionHandle afterAdvice;
if (ret != null) {
retList = new InstructionList(ret);
afterAdvice = retList.getStart();
} else /* if (munger.hasDynamicTests()) */ {
retList = new InstructionList(InstructionConstants.NOP);
afterAdvice = retList.getStart();
// } else {
// retList = new InstructionList();
// afterAdvice = null;
}
InstructionList advice = new InstructionList();
BcelVar tempVar = null;
if (munger.hasExtraParameter()) {
TypeX tempVarType = getReturnType();
if (tempVarType.equals(ResolvedTypeX.VOID)) {
tempVar = genTempVar(TypeX.OBJECT);
advice.append(InstructionConstants.ACONST_NULL);
tempVar.appendStore(advice, getFactory());
} else {
tempVar = genTempVar(tempVarType);
advice.append(InstructionFactory.createDup(tempVarType.getSize()));
tempVar.appendStore(advice, getFactory());
}
}
advice.append(munger.getAdviceInstructions(this, tempVar, afterAdvice));
if (ret != null) {
InstructionHandle gotoTarget = advice.getStart();
for (Iterator i = returns.iterator(); i.hasNext();) {
InstructionHandle ih = (InstructionHandle) i.next();
Utility.replaceInstruction(
ih,
InstructionFactory.createBranchInstruction(
Constants.GOTO,
gotoTarget),
enclosingMethod);
}
range.append(advice);
range.append(retList);
} else {
range.append(advice);
range.append(retList);
}
}
public void weaveAfterThrowing(BcelAdvice munger, TypeX 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);
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, TypeX 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);
// ENH 42743 suggests that we don't soften runtime exceptions.
// To implement that, would need to add instructions into the handler
// stream here to test if exceptionVar is an instanceof RuntimeException,
// and if it is, just re-throw it without softening.
// (Not yet implemented obviously).
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);
InstructionHandle handlerStart = handler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = range.getEnd();//handler.append(fact.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),
// 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);
}
public void weaveCflowEntry(final BcelAdvice munger, final Member cflowStackField) {
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(ResolvedTypeX.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();
BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY);
int alen = cflowStateVars.length;
entrySuccessInstructions.append(Utility.createConstant(fact, alen));
entrySuccessInstructions.append(
(Instruction) 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, cflowStackField));
arrayVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID,
new Type[] { objectArrayType },
Constants.INVOKEVIRTUAL));
}
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
}
// this is the same for both per and non-per
weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) {
public InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice) {
InstructionList exitInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
testResult.appendLoad(exitInstructions, fact);
exitInstructions.append(
InstructionFactory.createBranchInstruction(
Constants.IFEQ,
ifNoAdvice));
}
exitInstructions.append(Utility.createGet(fact, cflowStackField));
exitInstructions
.append(
fact
.createInvoke(
NameMangler.CFLOW_STACK_TYPE,
"pop",
Type.VOID,
new Type[] {
}, Constants.INVOKEVIRTUAL));
return exitInstructions;
}
});
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveAroundInline(
BcelAdvice munger,
boolean hasDynamicTest)
{
/* 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.
*/
// !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...);
Member mungerSig = munger.getSignature();
ResolvedTypeX declaringType = world.resolve(mungerSig.getDeclaringType());
//??? might want some checks here to give better errors
BcelObjectType ot = BcelWorld.getBcelObjectType(declaringType);
LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig);
if (!adviceMethod.getCanInline())
{
weaveAroundClosure(munger, hasDynamicTest);
return;
}
// We can't inline around methods if they have around advice on them, this
// is because the weaving will extract the body and hence the proceed call.
//??? should consider optimizations to recognize simple cases that don't require body extraction
enclosingMethod.setCanInline(false);
// start by exposing various useful things into the frame
final InstructionFactory fact = getFactory();
// now generate the aroundBody method
LazyMethodGen extractedMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
Modifier.PRIVATE,
munger);
// now extract the advice into its own method
String adviceMethodName =
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()) + "$advice";
List argVarList = new ArrayList();
List proceedVarList = new ArrayList();
int extraParamOffset = 0;
// Create the extra parameters that are needed for passing to proceed
// This code is very similar to that found in makeCallToCallback and should
// be rationalized in the future
if (thisVar != null) {
argVarList.add(thisVar);
proceedVarList.add(new BcelVar(thisVar.getType(), extraParamOffset));
extraParamOffset += thisVar.getType().getSize();
}
if (targetVar != null && targetVar != thisVar) {
argVarList.add(targetVar);
proceedVarList.add(new BcelVar(targetVar.getType(), extraParamOffset));
extraParamOffset += targetVar.getType().getSize();
}
for (int i = 0, len = getArgCount(); i < len; i++) {
argVarList.add(argVars[i]);
proceedVarList.add(new BcelVar(argVars[i].getType(), extraParamOffset));
extraParamOffset += argVars[i].getType().getSize();
}
if (thisJoinPointVar != null) {
argVarList.add(thisJoinPointVar);
proceedVarList.add(new BcelVar(thisJoinPointVar.getType(), extraParamOffset));
extraParamOffset += thisJoinPointVar.getType().getSize();
}
Type[] adviceParameterTypes = adviceMethod.getArgumentTypes();
Type[] extractedMethodParameterTypes = extractedMethod.getArgumentTypes();
Type[] parameterTypes =
new Type[extractedMethodParameterTypes.length
+ adviceParameterTypes.length
+ 1];
int parameterIndex = 0;
System.arraycopy(
extractedMethodParameterTypes,
0,
parameterTypes,
parameterIndex,
extractedMethodParameterTypes.length);
parameterIndex += extractedMethodParameterTypes.length;
parameterTypes[parameterIndex++] =
BcelWorld.makeBcelType(adviceMethod.getEnclosingClass().getType());
System.arraycopy(
adviceParameterTypes,
0,
parameterTypes,
parameterIndex,
adviceParameterTypes.length);
LazyMethodGen localAdviceMethod =
new LazyMethodGen(
Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC,
adviceMethod.getReturnType(),
adviceMethodName,
parameterTypes,
new String[0],
getEnclosingClass());
String donorFileName = adviceMethod.getEnclosingClass().getInternalFileName();
String recipientFileName = getEnclosingClass().getInternalFileName();
// System.err.println("donor " + donorFileName);
// System.err.println("recip " + recipientFileName);
if (! donorFileName.equals(recipientFileName)) {
localAdviceMethod.fromFilename = donorFileName;
getEnclosingClass().addInlinedSourceFileInfo(
donorFileName,
adviceMethod.highestLineNumber);
}
getEnclosingClass().addMethodGen(localAdviceMethod);
// create a map that will move all slots in advice method forward by extraParamOffset
// in order to make room for the new proceed-required arguments that are added at
// the beginning of the parameter list
int nVars = adviceMethod.getMaxLocals() + extraParamOffset;
IntMap varMap = IntMap.idMap(nVars);
for (int i=extraParamOffset; i < nVars; i++) {
varMap.put(i-extraParamOffset, i);
}
localAdviceMethod.getBody().insert(
BcelClassWeaver.genInlineInstructions(adviceMethod,
localAdviceMethod, varMap, fact, true));
localAdviceMethod.setMaxLocals(nVars);
//System.err.println(localAdviceMethod);
// the shadow is now empty. First, create a correct call
// to the around advice. This includes both the call (which may involve
// value conversion of the advice arguments) and the return
// (which may involve value conversion of the return value). Right now
// we push a null for the unused closure. It's sad, but there it is.
InstructionList advice = new InstructionList();
// InstructionHandle adviceMethodInvocation;
{
for (Iterator i = argVarList.iterator(); i.hasNext(); ) {
BcelVar var = (BcelVar)i.next();
var.appendLoad(advice, fact);
}
// ??? we don't actually need to push NULL for the closure if we take care
advice.append(
munger.getAdviceArgSetup(
this,
null,
new InstructionList(InstructionConstants.ACONST_NULL)));
// adviceMethodInvocation =
advice.append(
Utility.createInvoke(fact, localAdviceMethod)); //(fact, getWorld(), munger.getSignature()));
advice.append(
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType()),
extractedMethod.getReturnType()));
if (! isFallsThrough()) {
advice.append(InstructionFactory.createReturn(extractedMethod.getReturnType()));
}
}
// now, situate the call inside the possible dynamic tests,
// and actually add the whole mess to the shadow
if (! hasDynamicTest) {
range.append(advice);
} else {
InstructionList afterThingie = new InstructionList(InstructionConstants.NOP);
InstructionList callback = makeCallToCallback(extractedMethod);
if (terminatesWithReturn()) {
callback.append(
InstructionFactory.createReturn(extractedMethod.getReturnType()));
} else {
//InstructionHandle endNop = range.insert(fact.NOP, Range.InsideAfter);
advice.append(
InstructionFactory.createBranchInstruction(
Constants.GOTO,
afterThingie.getStart()));
}
range.append(
munger.getTestInstructions(
this,
advice.getStart(),
callback.getStart(),
advice.getStart()));
range.append(advice);
range.append(callback);
range.append(afterThingie);
}
// now search through the advice, looking for a call to PROCEED.
// Then we replace the call to proceed with some argument setup, and a
// call to the extracted method.
String proceedName =
NameMangler.proceedMethodName(munger.getSignature().getName());
InstructionHandle curr = localAdviceMethod.getBody().getStart();
InstructionHandle end = localAdviceMethod.getBody().getEnd();
ConstantPoolGen cpg = localAdviceMethod.getEnclosingClass().getConstantPoolGen();
while (curr != end) {
InstructionHandle next = curr.getNext();
Instruction inst = curr.getInstruction();
if ((inst instanceof INVOKESTATIC)
&& proceedName.equals(((INVOKESTATIC) inst).getMethodName(cpg))) {
localAdviceMethod.getBody().append(
curr,
getRedoneProceedCall(
fact,
extractedMethod,
munger,
localAdviceMethod,
proceedVarList));
Utility.deleteInstruction(curr, localAdviceMethod);
}
curr = next;
}
// and that's it.
}
private InstructionList getRedoneProceedCall(
InstructionFactory fact,
LazyMethodGen callbackMethod,
BcelAdvice munger,
LazyMethodGen localAdviceMethod,
List argVarList)
{
InstructionList ret = new InstructionList();
// we have on stack all the arguments for the ADVICE call.
// we have in frame somewhere all the arguments for the non-advice call.
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars();
IntMap proceedMap = makeProceedArgumentMap(adviceVars);
// System.out.println(proceedMap + " for " + this);
// System.out.println(argVarList);
ResolvedTypeX[] proceedParamTypes =
world.resolve(munger.getSignature().getParameterTypes());
// remove this*JoinPoint* as arguments to proceed
if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) {
int len = munger.getBaseParameterCount()+1;
ResolvedTypeX[] newTypes = new ResolvedTypeX[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];
ResolvedTypeX 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;
}
public void weaveAroundClosure(
BcelAdvice munger,
boolean hasDynamicTest)
{
InstructionFactory fact = getFactory();
enclosingMethod.setCanInline(false);
// MOVE OUT ALL THE INSTRUCTIONS IN MY SHADOW INTO ANOTHER METHOD!
LazyMethodGen callbackMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
0,
munger);
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars();
String closureClassName =
NameMangler.makeClosureClassName(
getEnclosingClass().getType(),
getEnclosingClass().getNewGeneratedNameTag());
Member constructorSig = new Member(Member.CONSTRUCTOR,
TypeX.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(TypeX.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++) {
stateTempVar.appendConvertableArrayLoad(
returnConversionCode,
fact,
i,
world.resolve(BcelWorld.fromBcel(stateTypes[i])));
}
} else {
returnConversionCode =
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType()),
callbackMethod.getReturnType());
if (!isFallsThrough()) {
returnConversionCode.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
}
}
InstructionList advice = new InstructionList();
advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation));
// advice.append(closureInstantiation);
advice.append(munger.getNonTestAdviceInstructions(this));
advice.append(returnConversionCode);
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(TypeX.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((Instruction)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(new 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 = (BcelVar) 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[] {});
InstructionFactory fact = new InstructionFactory(closureClass.getConstantPoolGen());
// 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(TypeX.OBJECTARRAY.resolve(world), 1);
// int proceedVarIndex = 1;
BcelVar stateVar =
new BcelVar(TypeX.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];
ResolvedTypeX stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
if (proceedMap.hasKey(i)) {
mbody.append(
proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i),
stateTypeX));
} else {
mbody.append(
stateVar.createConvertableArrayLoad(fact, i,
stateTypeX));
}
}
mbody.append(Utility.createInvoke(fact, callbackMethod));
if (getKind() == PreInitialization) {
mbody.append(Utility.createSet(
fact,
AjcMemberMaker.aroundClosurePreInitializationField()));
mbody.append(InstructionConstants.ACONST_NULL);
} else {
mbody.append(
Utility.createConversion(
fact,
callbackMethod.getReturnType(),
Type.OBJECT));
}
mbody.append(InstructionFactory.createReturn(Type.OBJECT));
closureClass.addMethodGen(runMethod);
// class
getEnclosingClass().addGeneratedInner(closureClass);
return constructor;
}
// ---- extraction methods
public LazyMethodGen extractMethod(String newMethodName, int visibilityModifier, ShadowMunger munger) {
LazyMethodGen.assertGoodBody(range.getBody(), newMethodName);
if (!getKind().allowsExtraction()) throw new BCException();
LazyMethodGen freshMethod = createMethodGen(newMethodName,visibilityModifier);
// System.err.println("******");
// System.err.println("ABOUT TO EXTRACT METHOD for" + this);
// enclosingMethod.print(System.err);
// System.err.println("INTO");
// freshMethod.print(System.err);
// System.err.println("WITH REMAP");
// System.err.println(makeRemap());
range.extractInstructionsInto(freshMethod, makeRemap(),
(getKind() != PreInitialization) &&
isFallsThrough());
if (getKind() == PreInitialization) {
addPreInitializationReturnCode(
freshMethod,
getSuperConstructorParameterTypes());
}
getEnclosingClass().addMethodGen(freshMethod,munger.getSourceLocation());
return freshMethod;
}
private void addPreInitializationReturnCode(
LazyMethodGen extractedMethod,
Type[] superConstructorTypes)
{
InstructionList body = extractedMethod.getBody();
final InstructionFactory fact = getFactory();
BcelVar arrayVar = new BcelVar(
world.getCoreType(TypeX.OBJECTARRAY),
extractedMethod.allocateLocal(1));
int len = superConstructorTypes.length;
body.append(Utility.createConstant(fact, len));
body.append((Instruction)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().getConstantPoolGen());
}
/** 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++) {
TypeX type = getArgType(i);
ret.put(oldi, newi);
oldi += type.getSize();
newi += type.getSize();
}
}
// System.err.println("making remap for : " + this);
// if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot());
// if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot());
// System.err.println(ret);
return ret;
}
/**
* The new method always static.
* It may take some extra arguments: this, target.
* If it's argsOnStack, then it must take both this/target
* If it's argsOnFrame, it shares this and target.
* ??? rewrite this to do less array munging, please
*/
private LazyMethodGen createMethodGen(String newMethodName, int visibilityModifier) {
Type[] parameterTypes = BcelWorld.makeBcelTypes(getArgTypes());
int modifiers = Modifier.FINAL | visibilityModifier;
// XXX some bug
// if (! isExpressionKind() && getSignature().isStrict(world)) {
// modifiers |= Modifier.STRICT;
// }
modifiers |= Modifier.STATIC;
if (targetVar != null && targetVar != thisVar) {
TypeX targetType = getTargetType();
ResolvedMember resolvedMember = getSignature().resolve(world);
if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) &&
!samePackage(targetType.getPackageName(), getEnclosingType().getPackageName()))
{
if (!targetType.isAssignableFrom(getThisType(), world)) {
throw new BCException("bad bytecode");
}
targetType = getThisType();
}
parameterTypes = addType(BcelWorld.makeBcelType(targetType), parameterTypes);
}
if (thisVar != null) {
TypeX thisType = getThisType();
parameterTypes = addType(BcelWorld.makeBcelType(thisType), parameterTypes);
}
// We always want to pass down thisJoinPoint in case we have already woven
// some advice in here. If we only have a single piece of around advice on a
// join point, it is unnecessary to accept (and pass) tjp.
if (thisJoinPointVar != null) {
parameterTypes = addTypeToEnd(LazyClassGen.tjpType, parameterTypes);
}
TypeX returnType;
if (getKind() == PreInitialization) {
returnType = TypeX.OBJECTARRAY;
} else {
returnType = getReturnType();
}
return
new LazyMethodGen(
modifiers,
BcelWorld.makeBcelType(returnType),
newMethodName,
parameterTypes,
new String[0],
// XXX again, we need to look up methods!
// TypeX.getNames(getSignature().getExceptions(world)),
getEnclosingClass());
}
private boolean samePackage(String p1, String p2) {
if (p1 == null) return p2 == null;
if (p2 == null) return false;
return p1.equals(p2);
}
private Type[] addType(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[0] = type;
System.arraycopy(types, 0, ret, 1, len);
return ret;
}
private Type[] addTypeToEnd(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[len] = type;
System.arraycopy(types, 0, ret, 0, len);
return ret;
}
public BcelVar genTempVar(TypeX typeX) {
return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize()));
}
// public static final boolean CREATE_TEMP_NAMES = true;
public BcelVar genTempVar(TypeX typeX, String localName) {
BcelVar tv = genTempVar(typeX);
// if (CREATE_TEMP_NAMES) {
// for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
// if (Range.isRangeHandle(ih)) continue;
// ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot()));
// }
// }
return tv;
}
// eh doesn't think we need to garbage collect these (64K is a big number...)
private int genTempVarIndex(int size) {
return enclosingMethod.allocateLocal(size);
}
public InstructionFactory getFactory() {
return getEnclosingClass().getFactory();
}
public ISourceLocation getSourceLocation() {
int sourceLine = getSourceLine();
if (sourceLine == 0 || sourceLine == -1) {
// Thread.currentThread().dumpStack();
// System.err.println(this + ": " + range);
return getEnclosingClass().getType().getSourceLocation();
} else {
return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine);
}
}
public Shadow getEnclosingShadow() {
return enclosingShadow;
}
public LazyMethodGen getEnclosingMethod() {
return enclosingMethod;
}
public boolean isFallsThrough() {
return !terminatesWithReturn(); //fallsThrough;
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.Iterator;
import java.util.Set;
import org.apache.bcel.Constants;
import org.apache.bcel.generic.FieldGen;
import org.apache.bcel.generic.InstructionConstants;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.Type;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.WeaveMessage;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.AsmRelationshipProvider;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewConstructorTypeMunger;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.NewParentTypeMunger;
import org.aspectj.weaver.PerObjectInterfaceTypeMunger;
import org.aspectj.weaver.PrivilegedAccessMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.patterns.Pointcut;
//XXX addLazyMethodGen is probably bad everywhere
public class BcelTypeMunger extends ConcreteTypeMunger {
public BcelTypeMunger(ResolvedTypeMunger munger, ResolvedTypeX aspectType) {
super(munger, aspectType);
}
public String toString() {
return "(BcelTypeMunger " + getMunger() + ")";
}
public boolean munge(BcelClassWeaver weaver) {
boolean changed = false;
boolean worthReporting = true;
if (munger.getKind() == ResolvedTypeMunger.Field) {
changed = mungeNewField(weaver, (NewFieldTypeMunger)munger);
} else if (munger.getKind() == ResolvedTypeMunger.Method) {
changed = mungeNewMethod(weaver, (NewMethodTypeMunger)munger);
} else if (munger.getKind() == ResolvedTypeMunger.PerObjectInterface) {
changed = mungePerObjectInterface(weaver, (PerObjectInterfaceTypeMunger)munger);
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 {
throw new RuntimeException("unimplemented");
}
if (changed && munger.changesPublicSignature()) {
WeaverStateInfo info =
weaver.getLazyClassGen().getOrCreateWeaverStateInfo();
info.addConcreteMunger(this);
}
// Whilst type mungers aren't persisting their source locations, we add this relationship during
// compilation time (see other reference to ResolvedTypeMunger.persist)
if (ResolvedTypeMunger.persistSourceLocation) {
if (changed) {
if (munger.getKind().equals(ResolvedTypeMunger.Parent)) {
AsmRelationshipProvider.addRelationship(weaver.getLazyClassGen().getType(), munger,getAspectType());
} else {
AsmRelationshipProvider.addRelationship(weaver.getLazyClassGen().getType(), munger,getAspectType());
}
}
}
// TAG: WeavingMessage
if (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 will come out of AjLookupEnvironment.addParent if doing a source
// compilation.
NewParentTypeMunger parentTM = (NewParentTypeMunger)munger;
if (parentTM.getNewParent().isInterface()) {
weaver.getWorld().getMessageHandler().handleMessage(WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS,
new String[]{weaver.getLazyClassGen().getType().getName(),
tName,parentTM.getNewParent().getName(),fName}));
} else {
System.err.println("BANG, you need to fix this. BcelTypeMunger");
}
} else {
weaver.getWorld().getMessageHandler().handleMessage(WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ITD,
new String[]{weaver.getLazyClassGen().getType().getName(),
tName,munger.getKind().toString().toLowerCase(),
getAspectType().getName(),
fName+":'"+munger.getSignature()+"'"}));
// ??? If only type mungers knew their originating line numbers ...
}
}
return changed;
}
private String getShortname(String path) {
int takefrom = path.lastIndexOf('/');
if (takefrom == -1) {
takefrom = path.lastIndexOf('\\');
}
return path.substring(takefrom+1);
}
private boolean mungeNewParent(BcelClassWeaver weaver, NewParentTypeMunger munger) {
LazyClassGen gen = weaver.getLazyClassGen();
ResolvedTypeX newParent = munger.getNewParent();
if (newParent.isClass()) {
//gen.setSuperClass(newParent);
} else {
gen.addInterface(newParent,getSourceLocation());
}
return true;
}
private boolean mungePrivilegedAccess(
BcelClassWeaver weaver,
PrivilegedAccessMunger munger)
{
LazyClassGen gen = weaver.getLazyClassGen();
ResolvedMember member = munger.getMember();
ResolvedTypeX onType = weaver.getWorld().resolve(member.getDeclaringType());
//System.out.println("munging: " + gen + " with " + member);
if (onType.equals(gen.getType())) {
if (member.getKind() == Member.FIELD) {
//System.out.println("matched: " + gen);
addFieldGetter(gen, member,
AjcMemberMaker.privilegedAccessMethodForFieldGet(aspectType, member));
addFieldSetter(gen, member,
AjcMemberMaker.privilegedAccessMethodForFieldSet(aspectType, member));
return true;
} else if (member.getKind() == Member.METHOD) {
addMethodDispatch(gen, member,
AjcMemberMaker.privilegedAccessMethodForMethod(aspectType, member));
return true;
} else if (member.getKind() == Member.CONSTRUCTOR) {
for (Iterator i = gen.getMethodGens().iterator(); i.hasNext(); ) {
LazyMethodGen m = (LazyMethodGen)i.next();
if (m.getMemberView() != null
&& m.getMemberView().getKind() == Member.CONSTRUCTOR) {
// m.getMemberView().equals(member)) {
m.forcePublic();
//return true;
}
}
return true;
//throw new BCException("no match for " + member + " in " + gen);
} else if (member.getKind() == Member.STATIC_INITIALIZATION) {
gen.forcePublic();
return true;
} else {
throw new RuntimeException("unimplemented");
}
}
return false;
}
private void addFieldGetter(
LazyClassGen gen,
ResolvedMember field,
ResolvedMember accessMethod)
{
LazyMethodGen mg = makeMethodGen(gen, accessMethod);
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
if (field.isStatic()) {
il.append(fact.createFieldAccess(
gen.getClassName(),
field.getName(),
BcelWorld.makeBcelType(field.getType()), Constants.GETSTATIC));
} else {
il.append(InstructionConstants.ALOAD_0);
il.append(fact.createFieldAccess(
gen.getClassName(),
field.getName(),
BcelWorld.makeBcelType(field.getType()), Constants.GETFIELD));
}
il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(field.getType())));
mg.getBody().insert(il);
gen.addMethodGen(mg,getSignature().getSourceLocation());
}
private void addFieldSetter(
LazyClassGen gen,
ResolvedMember field,
ResolvedMember accessMethod)
{
LazyMethodGen mg = makeMethodGen(gen, accessMethod);
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
Type fieldType = BcelWorld.makeBcelType(field.getType());
if (field.isStatic()) {
il.append(InstructionFactory.createLoad(fieldType, 0));
il.append(fact.createFieldAccess(
gen.getClassName(),
field.getName(),
fieldType, Constants.PUTSTATIC));
} else {
il.append(InstructionConstants.ALOAD_0);
il.append(InstructionFactory.createLoad(fieldType, 1));
il.append(fact.createFieldAccess(
gen.getClassName(),
field.getName(),
fieldType, Constants.PUTFIELD));
}
il.append(InstructionFactory.createReturn(Type.VOID));
mg.getBody().insert(il);
gen.addMethodGen(mg,getSignature().getSourceLocation());
}
private void addMethodDispatch(
LazyClassGen gen,
ResolvedMember method,
ResolvedMember accessMethod)
{
LazyMethodGen mg = makeMethodGen(gen, accessMethod);
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
//Type fieldType = BcelWorld.makeBcelType(field.getType());
Type[] paramTypes = BcelWorld.makeBcelTypes(method.getParameterTypes());
int pos = 0;
if (!method.isStatic()) {
il.append(InstructionConstants.ALOAD_0);
pos++;
}
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
il.append(InstructionFactory.createLoad(paramType, pos));
pos+=paramType.getSize();
}
il.append(Utility.createInvoke(fact, (BcelWorld)aspectType.getWorld(),
method));
il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(method.getReturnType())));
mg.getBody().insert(il);
gen.addMethodGen(mg);
}
private LazyMethodGen makeMethodGen(LazyClassGen gen, ResolvedMember member) {
LazyMethodGen ret = new LazyMethodGen(
member.getModifiers(),
BcelWorld.makeBcelType(member.getReturnType()),
member.getName(),
BcelWorld.makeBcelTypes(member.getParameterTypes()),
TypeX.getNames(member.getExceptions()),
gen);
// 43972 : Static crosscutting makes interfaces unusable for javac
// ret.makeSynthetic();
return ret;
}
private FieldGen makeFieldGen(LazyClassGen gen, ResolvedMember member) {
return new FieldGen(
member.getModifiers(),
BcelWorld.makeBcelType(member.getReturnType()),
member.getName(),
gen.getConstantPoolGen());
}
private boolean mungePerObjectInterface(
BcelClassWeaver weaver,
PerObjectInterfaceTypeMunger munger)
{
LazyClassGen gen = weaver.getLazyClassGen();
if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) {
FieldGen fg = makeFieldGen(gen,
AjcMemberMaker.perObjectField(gen.getType(), aspectType));
gen.addField(fg.getField(),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(),getSourceLocation());
return true;
} else {
return false;
}
}
private boolean couldMatch(
BcelObjectType bcelObjectType,
Pointcut pointcut) {
return !bcelObjectType.isInterface();
}
private boolean mungeNewMethod(BcelClassWeaver weaver, NewMethodTypeMunger munger) {
ResolvedMember signature = munger.getSignature();
ResolvedMember dispatchMethod = munger.getDispatchMethod(aspectType);
LazyClassGen gen = weaver.getLazyClassGen();
ResolvedTypeX onType = weaver.getWorld().resolve(signature.getDeclaringType());
boolean onInterface = onType.isInterface();
if (onType.equals(gen.getType())) {
ResolvedMember introMethod =
AjcMemberMaker.interMethod(signature, aspectType, onInterface);
LazyMethodGen mg = makeMethodGen(gen, introMethod);
if (!onInterface && !Modifier.isAbstract(introMethod.getModifiers())) {
InstructionList body = mg.getBody();
InstructionFactory fact = gen.getFactory();
int pos = 0;
if (!signature.isStatic()) {
body.append(InstructionFactory.createThis());
pos++;
}
Type[] paramTypes = BcelWorld.makeBcelTypes(introMethod.getParameterTypes());
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
body.append(InstructionFactory.createLoad(paramType, pos));
pos+=paramType.getSize();
}
body.append(Utility.createInvoke(fact, weaver.getWorld(), dispatchMethod));
body.append(
InstructionFactory.createReturn(
BcelWorld.makeBcelType(introMethod.getReturnType())));
} else {
//??? this is okay
//if (!(mg.getBody() == null)) throw new RuntimeException("bas");
}
// XXX make sure to check that we set exceptions properly on this guy.
weaver.addLazyMethodGen(mg);
weaver.getLazyClassGen().warnOnAddedMethod(mg.getMethod(),getSignature().getSourceLocation());
addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled());
return true;
} else if (onInterface && gen.getType().isTopmostImplementor(onType) &&
!Modifier.isAbstract(signature.getModifiers()))
{
ResolvedMember introMethod =
AjcMemberMaker.interMethod(signature, aspectType, false);
LazyMethodGen mg = makeMethodGen(gen, introMethod);
Type[] paramTypes = BcelWorld.makeBcelTypes(introMethod.getParameterTypes());
Type returnType = BcelWorld.makeBcelType(introMethod.getReturnType());
InstructionList body = mg.getBody();
InstructionFactory fact = gen.getFactory();
int pos = 0;
if (!introMethod.isStatic()) {
body.append(InstructionFactory.createThis());
pos++;
}
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
body.append(InstructionFactory.createLoad(paramType, pos));
pos+=paramType.getSize();
}
body.append(Utility.createInvoke(fact, weaver.getWorld(), dispatchMethod));
body.append(InstructionFactory.createReturn(returnType));
mg.definingType = onType;
weaver.addOrReplaceLazyMethodGen(mg);
addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled());
return true;
} else {
return false;
}
}
private void addNeededSuperCallMethods(
BcelClassWeaver weaver,
ResolvedTypeX onType,
Set neededSuperCalls)
{
LazyClassGen gen = weaver.getLazyClassGen();
for (Iterator iter = neededSuperCalls.iterator(); iter.hasNext();) {
ResolvedMember superMethod = (ResolvedMember) iter.next();
if (weaver.addDispatchTarget(superMethod)) {
//System.err.println("super type: " + superMethod.getDeclaringType() + ", " + gen.getType());
boolean isSuper = !superMethod.getDeclaringType().equals(gen.getType());
String dispatchName;
if (isSuper)
dispatchName =
NameMangler.superDispatchMethod(onType, superMethod.getName());
else
dispatchName =
NameMangler.protectedDispatchMethod(
onType,
superMethod.getName());
LazyMethodGen dispatcher =
makeDispatcher(
gen,
dispatchName,
superMethod,
weaver.getWorld(),
isSuper);
weaver.addLazyMethodGen(dispatcher);
}
}
}
private boolean mungeNewConstructor(
BcelClassWeaver weaver,
NewConstructorTypeMunger newConstructorTypeMunger)
{
final LazyClassGen currentClass = weaver.getLazyClassGen();
final InstructionFactory fact = currentClass.getFactory();
ResolvedMember newConstructorMember = newConstructorTypeMunger.getSyntheticConstructor();
TypeX onType = newConstructorMember.getDeclaringType();
if (! onType.equals(currentClass.getType())) return false;
ResolvedMember explicitConstructor = newConstructorTypeMunger.getExplicitConstructor();
//int declaredParameterCount = newConstructorTypeMunger.getDeclaredParameterCount();
LazyMethodGen freshConstructor =
makeMethodGen(currentClass, newConstructorMember);
currentClass.addMethodGen(freshConstructor);
//weaver.addLazyMethodGen(freshConstructor);
InstructionList body = freshConstructor.getBody();
// add to body: push arts for call to pre, from actual args starting at 1 (skipping this), going to
// declared argcount + 1
TypeX[] declaredParams = newConstructorTypeMunger.getSignature().getParameterTypes();
Type[] paramTypes = freshConstructor.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 = freshConstructor.allocateLocal(1);
body.append(InstructionFactory.createStore(Type.OBJECT, arraySlot));
// put this on the stack
body.append(InstructionConstants.ALOAD_0);
// unpack pre args onto stack
TypeX[] 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);
TypeX[] 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,
TypeX.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();
ResolvedTypeX onType = weaver.getWorld().resolve(field.getDeclaringType());
boolean onInterface = onType.isInterface();
if (onType.equals(gen.getType())) {
if (onInterface) {
LazyMethodGen mg = makeMethodGen(gen,
AjcMemberMaker.interFieldInterfaceGetter(field, onType, aspectType));
gen.addMethodGen(mg);
LazyMethodGen mg1 = makeMethodGen(gen,
AjcMemberMaker.interFieldInterfaceSetter(field, onType, aspectType));
gen.addMethodGen(mg1);
} else {
weaver.addInitializer(this);
FieldGen fg = makeFieldGen(gen,
AjcMemberMaker.interFieldClassField(field, aspectType));
gen.addField(fg.getField(),getSourceLocation());
}
return true;
} else if (onInterface && gen.getType().isTopmostImplementor(onType)) {
// wew know that we can't be static since we don't allow statics on interfaces
if (field.isStatic()) throw new RuntimeException("unimplemented");
weaver.addInitializer(this);
//System.err.println("impl body on " + gen.getType() + " for " + munger);
Type fieldType = BcelWorld.makeBcelType(field.getType());
FieldGen fg = makeFieldGen(gen,
AjcMemberMaker.interFieldInterfaceField(field, onType, aspectType));
gen.addField(fg.getField(),getSourceLocation());
//this uses a shadow munger to add init method to constructors
//weaver.getShadowMungers().add(makeInitCallShadowMunger(initMethod));
LazyMethodGen mg = makeMethodGen(gen,
AjcMemberMaker.interFieldInterfaceGetter(field, gen.getType(), aspectType));
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
if (field.isStatic()) {
il.append(fact.createFieldAccess(
gen.getClassName(),
fg.getName(),
fieldType, Constants.GETSTATIC));
} else {
il.append(InstructionConstants.ALOAD_0);
il.append(fact.createFieldAccess(
gen.getClassName(),
fg.getName(),
fieldType, Constants.GETFIELD));
}
il.append(InstructionFactory.createReturn(fieldType));
mg.getBody().insert(il);
gen.addMethodGen(mg);
LazyMethodGen mg1 = makeMethodGen(gen,
AjcMemberMaker.interFieldInterfaceSetter(field, gen.getType(), aspectType));
InstructionList il1 = new InstructionList();
if (field.isStatic()) {
il1.append(InstructionFactory.createLoad(fieldType, 0));
il1.append(fact.createFieldAccess(
gen.getClassName(),
fg.getName(),
fieldType, Constants.PUTSTATIC));
} else {
il1.append(InstructionConstants.ALOAD_0);
il1.append(InstructionFactory.createLoad(fieldType, 1));
il1.append(fact.createFieldAccess(
gen.getClassName(),
fg.getName(),
fieldType, Constants.PUTFIELD));
}
il1.append(InstructionFactory.createReturn(Type.VOID));
mg1.getBody().insert(il1);
gen.addMethodGen(mg1);
return true;
} else {
return false;
}
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/BcelVar.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionList;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.ast.Var;
public class BcelVar extends Var {
private int positionInAroundState = -1;
private int slot;
public BcelVar(ResolvedTypeX type, int slot) {
super(type);
this.slot = slot;
}
public String toString() {
return "BcelVar(" + getType() + " " + slot +
((positionInAroundState != -1) ? (" " + positionInAroundState) : "") +
")";
}
public int getSlot() { return slot; }
// fact is used in the subtypes
public Instruction createLoad(InstructionFactory fact) {
return InstructionFactory.createLoad(BcelWorld.makeBcelType(getType()), slot);
}
public Instruction createStore(InstructionFactory fact) {
return InstructionFactory.createStore(BcelWorld.makeBcelType(getType()), slot);
}
public void appendStore(InstructionList il, InstructionFactory fact) {
il.append(createStore(fact));
}
public void appendLoad(InstructionList il, InstructionFactory fact) {
il.append(createLoad(fact));
}
public void appendLoadAndConvert(
InstructionList il,
InstructionFactory fact,
ResolvedTypeX toType) {
il.append(createLoad(fact));
Utility.appendConversion(il, fact, getType(), toType);
}
public void insertLoad(InstructionList il, InstructionFactory fact) {
il.insert(createLoad(fact));
}
public InstructionList createCopyFrom(InstructionFactory fact, int oldSlot) {
InstructionList il = new InstructionList();
il.append(InstructionFactory.createLoad(BcelWorld.makeBcelType(getType()), oldSlot));
il.append(createStore(fact));
return il;
}
// this is an array var
void appendConvertableArrayLoad(
InstructionList il,
InstructionFactory fact,
int index,
ResolvedTypeX convertTo)
{
ResolvedTypeX convertFromType = getType().getResolvedComponentType();
appendLoad(il, fact);
il.append(Utility.createConstant(fact, index));
il.append(InstructionFactory.createArrayLoad(BcelWorld.makeBcelType(convertFromType)));
Utility.appendConversion(il, fact, convertFromType, convertTo);
}
void appendConvertableArrayStore(
InstructionList il,
InstructionFactory fact,
int index,
BcelVar storee)
{
ResolvedTypeX convertToType = getType().getResolvedComponentType();
appendLoad(il, fact);
il.append(Utility.createConstant(fact, index));
storee.appendLoad(il, fact);
Utility.appendConversion(il, fact, storee.getType(), convertToType);
il.append(InstructionFactory.createArrayStore(BcelWorld.makeBcelType(convertToType)));
}
InstructionList createConvertableArrayStore(
InstructionFactory fact,
int index,
BcelVar storee)
{
InstructionList il = new InstructionList();
appendConvertableArrayStore(il, fact, index, storee);
return il;
}
InstructionList createConvertableArrayLoad(
InstructionFactory fact,
int index,
ResolvedTypeX convertTo)
{
InstructionList il = new InstructionList();
appendConvertableArrayLoad(il, fact, index, convertTo);
return il;
}
public int getPositionInAroundState() {
return positionInAroundState;
}
public void setPositionInAroundState(int positionInAroundState) {
this.positionInAroundState = positionInAroundState;
}
// random useful fields
public static final BcelVar[] NONE = new BcelVar[] {};
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/BcelWeaver.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
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.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.jar.Attributes.Name;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.JavaClass;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IProgressListener;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.util.FileUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.CrosscuttingMembersSet;
import org.aspectj.weaver.IClassFileProvider;
import org.aspectj.weaver.IWeaveRequestor;
import org.aspectj.weaver.IWeaver;
import org.aspectj.weaver.NewParentTypeMunger;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.WeaverMetrics;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.patterns.DeclareParents;
import org.aspectj.weaver.patterns.FastMatchInfo;
public class BcelWeaver implements IWeaver {
private BcelWorld world;
private CrosscuttingMembersSet xcutSet;
private IProgressListener progressListener = null;
private double progressMade;
private double progressPerClassFile;
private boolean inReweavableMode = false;
public BcelWeaver(BcelWorld world) {
super();
WeaverMetrics.reset();
this.world = world;
this.xcutSet = world.getCrosscuttingMembersSet();
}
public BcelWeaver() {
this(new BcelWorld());
}
// ---- fields
// private Map sourceJavaClasses = new HashMap(); /* String -> UnwovenClassFile */
private List addedClasses = new ArrayList(); /* List<UnovenClassFile> */
private List deletedTypenames = new ArrayList(); /* List<String> */
// private Map resources = new HashMap(); /* String -> UnwovenClassFile */
private Manifest manifest = null;
private boolean needToReweaveWorld = false;
private List shadowMungerList = null; // setup by prepareForWeave
private List typeMungerList = null; // setup by prepareForWeave
private List declareParentsList = null; // setup by prepareForWeave
private ZipOutputStream zipOutputStream;
// ----
// only called for testing
public void setShadowMungers(List l) {
shadowMungerList = l;
}
public void addLibraryAspect(String aspectName) {
ResolvedTypeX type = world.resolve(aspectName);
//System.out.println("type: " + type + " for " + aspectName);
if (type.isAspect()) {
xcutSet.addOrReplaceAspect(type);
} else {
throw new RuntimeException("unimplemented");
}
}
public void addLibraryJarFile(File inFile) throws IOException {
ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered
List addedAspects = new ArrayList();
while (true) {
ZipEntry entry = inStream.getNextEntry();
if (entry == null) break;
if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
continue;
}
ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName());
JavaClass jc = parser.parse();
inStream.closeEntry();
ResolvedTypeX type = world.addSourceObjectType(jc).getResolvedTypeX();
if (type.isAspect()) {
addedAspects.add(type);
}
}
inStream.close();
for (Iterator i = addedAspects.iterator(); i.hasNext();) {
ResolvedTypeX aspectX = (ResolvedTypeX) i.next();
xcutSet.addOrReplaceAspect(aspectX);
}
}
// // The ANT copy task should be used to copy resources across.
// private final static boolean CopyResourcesFromInpathDirectoriesToOutput=false;
private Set alreadyConfirmedReweavableState;
/**
* Add any .class files in the directory to the outdir. Anything other than .class files in
* the directory (or its subdirectories) are considered resources and are also copied.
*
*/
public List addDirectoryContents(File inFile,File outDir) throws IOException {
List addedClassFiles = new ArrayList();
// Get a list of all files (i.e. everything that isnt a directory)
File[] files = FileUtil.listFiles(inFile,new FileFilter() {
public boolean accept(File f) {
boolean accept = !f.isDirectory();
return accept;
}
});
// For each file, add it either as a real .class file or as a resource
for (int i = 0; i < files.length; i++) {
addedClassFiles.add(addClassFile(files[i],inFile,outDir));
}
return addedClassFiles;
}
/** Adds all class files in the jar
*/
public List addJarFile(File inFile, File outDir, boolean canBeDirectory){
// System.err.println("? addJarFile(" + inFile + ", " + outDir + ")");
List addedClassFiles = new ArrayList();
needToReweaveWorld = true;
JarFile inJar = null;
try {
// Is this a directory we are looking at?
if (inFile.isDirectory() && canBeDirectory) {
addedClassFiles.addAll(addDirectoryContents(inFile,outDir));
} else {
inJar = new JarFile(inFile);
addManifest(inJar.getManifest());
Enumeration entries = inJar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = (JarEntry)entries.nextElement();
InputStream inStream = inJar.getInputStream(entry);
byte[] bytes = FileUtil.readAsByteArray(inStream);
String filename = entry.getName();
// System.out.println("? addJarFile() filename='" + filename + "'");
UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes);
if (filename.endsWith(".class")) {
this.addClassFile(classFile);
addedClassFiles.add(classFile);
}
// else if (!entry.isDirectory()) {
//
// /* bug-44190 Copy meta-data */
// addResource(filename,classFile);
// }
inStream.close();
}
inJar.close();
}
} catch (FileNotFoundException ex) {
IMessage message = new Message(
"Could not find input jar file " + inFile.getPath() + ", ignoring",
new SourceLocation(inFile,0),
false);
world.getMessageHandler().handleMessage(message);
} catch (IOException ex) {
IMessage message = new Message(
"Could not read input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")",
new SourceLocation(inFile,0),
true);
world.getMessageHandler().handleMessage(message);
} finally {
if (inJar != null) {
try {inJar.close();}
catch (IOException ex) {
IMessage message = new Message(
"Could not close input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")",
new SourceLocation(inFile,0),
true);
world.getMessageHandler().handleMessage(message);
}
}
}
return addedClassFiles;
}
// public void addResource(String name, File inPath, File outDir) throws IOException {
//
// /* Eliminate CVS files. Relative paths use "/" */
// if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) {
//// System.err.println("? addResource('" + name + "')");
//// BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(inPath));
//// byte[] bytes = new byte[(int)inPath.length()];
//// inStream.read(bytes);
//// inStream.close();
// byte[] bytes = FileUtil.readAsByteArray(inPath);
// UnwovenClassFile resourceFile = new UnwovenClassFile(new File(outDir, name).getAbsolutePath(), bytes);
// addResource(name,resourceFile);
// }
// }
public boolean needToReweaveWorld() {
return needToReweaveWorld;
}
/** Should be addOrReplace
*/
public void addClassFile(UnwovenClassFile classFile) {
addedClasses.add(classFile);
// if (null != sourceJavaClasses.put(classFile.getClassName(), classFile)) {
//// throw new RuntimeException(classFile.getClassName());
// }
world.addSourceObjectType(classFile.getJavaClass());
}
public UnwovenClassFile addClassFile(File classFile, File inPathDir, File outDir) throws IOException {
FileInputStream fis = new FileInputStream(classFile);
byte[] bytes = FileUtil.readAsByteArray(fis);
// String relativePath = files[i].getPath();
// ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
// or we are in trouble...
String filename = classFile.getAbsolutePath().substring(
inPathDir.getAbsolutePath().length()+1);
UnwovenClassFile ucf = new UnwovenClassFile(new File(outDir,filename).getAbsolutePath(),bytes);
if (filename.endsWith(".class")) {
// System.err.println("BCELWeaver: processing class from input directory "+classFile);
this.addClassFile(ucf);
}
fis.close();
return ucf;
}
public void deleteClassFile(String typename) {
deletedTypenames.add(typename);
// sourceJavaClasses.remove(typename);
world.deleteSourceObjectType(TypeX.forName(typename));
}
// public void addResource (String name, UnwovenClassFile resourceFile) {
// /* bug-44190 Change error to warning and copy first resource */
// if (!resources.containsKey(name)) {
// resources.put(name, resourceFile);
// }
// else {
// world.showMessage(IMessage.WARNING, "duplicate resource: '" + name + "'",
// null, null);
// }
// }
// ---- weave preparation
public void prepareForWeave() {
needToReweaveWorld = false;
// update mungers
for (Iterator i = addedClasses.iterator(); i.hasNext(); ) {
UnwovenClassFile jc = (UnwovenClassFile)i.next();
String name = jc.getClassName();
ResolvedTypeX type = world.resolve(name);
//System.err.println("added: " + type + " aspect? " + type.isAspect());
if (type.isAspect()) {
needToReweaveWorld |= xcutSet.addOrReplaceAspect(type);
}
}
for (Iterator i = deletedTypenames.iterator(); i.hasNext(); ) {
String name = (String)i.next();
if (xcutSet.deleteAspect(TypeX.forName(name))) needToReweaveWorld = true;
}
shadowMungerList = xcutSet.getShadowMungers();
typeMungerList = xcutSet.getTypeMungers();
declareParentsList = xcutSet.getDeclareParents();
//XXX this gets us a stable (but completely meaningless) order
Collections.sort(
shadowMungerList,
new Comparator() {
public int compare(Object o1, Object o2) {
return o1.toString().compareTo(o2.toString());
}
});
}
// public void dumpUnwoven(File file) throws IOException {
// BufferedOutputStream os = FileUtil.makeOutputStream(file);
// this.zipOutputStream = new ZipOutputStream(os);
// dumpUnwoven();
// /* BUG 40943*/
// dumpResourcesToOutJar();
// zipOutputStream.close(); //this flushes and closes the acutal file
// }
//
//
// public void dumpUnwoven() throws IOException {
// Collection filesToDump = new HashSet(sourceJavaClasses.values());
// for (Iterator i = filesToDump.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// dumpUnchanged(classFile);
// }
// }
// public void dumpResourcesToOutPath() throws IOException {
//// System.err.println("? dumpResourcesToOutPath() resources=" + resources.keySet());
// Iterator i = resources.keySet().iterator();
// while (i.hasNext()) {
// UnwovenClassFile res = (UnwovenClassFile)resources.get(i.next());
// dumpUnchanged(res);
// }
// //resources = new HashMap();
// }
//
/* BUG #40943 */
// public void dumpResourcesToOutJar() throws IOException {
//// System.err.println("? dumpResourcesToOutJar() resources=" + resources.keySet());
// Iterator i = resources.keySet().iterator();
// while (i.hasNext()) {
// String name = (String)i.next();
// UnwovenClassFile res = (UnwovenClassFile)resources.get(name);
// writeZipEntry(name,res.getBytes());
// }
// resources = new HashMap();
// }
//
// // halfway house for when the jar is managed outside of the weaver, but the resources
// // to be copied are known in the weaver.
// public void dumpResourcesToOutJar(ZipOutputStream zos) throws IOException {
// this.zipOutputStream = zos;
// dumpResourcesToOutJar();
// }
public void addManifest (Manifest newManifest) {
// System.out.println("? addManifest() newManifest=" + newManifest);
if (manifest == null) {
manifest = newManifest;
}
}
public static final String MANIFEST_NAME = "META-INF/MANIFEST.MF";
private static final String WEAVER_MANIFEST_VERSION = "1.0";
private static final Attributes.Name CREATED_BY = new Name("Created-By");
private static final String WEAVER_CREATED_BY = "AspectJ Compiler";
public Manifest getManifest (boolean shouldCreate) {
if (manifest == null && shouldCreate) {
manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.put(Name.MANIFEST_VERSION,WEAVER_MANIFEST_VERSION);
attributes.put(CREATED_BY,WEAVER_CREATED_BY);
}
return manifest;
}
// ---- weaving
// Used by some test cases only...
public Collection weave(File file) throws IOException {
OutputStream os = FileUtil.makeOutputStream(file);
this.zipOutputStream = new ZipOutputStream(os);
prepareForWeave();
Collection c = weave( new IClassFileProvider() {
public Iterator getClassFileIterator() {
return addedClasses.iterator();
}
public IWeaveRequestor getRequestor() {
return new IWeaveRequestor() {
public void acceptResult(UnwovenClassFile result) {
try {
writeZipEntry(result.filename, result.bytes);
} catch(IOException ex) {}
}
public void processingReweavableState() {}
public void addingTypeMungers() {}
public void weavingAspects() {}
public void weavingClasses() {}
public void weaveCompleted() {}
};
}
});
// /* BUG 40943*/
// dumpResourcesToOutJar();
zipOutputStream.close(); //this flushes and closes the acutal file
return c;
}
// public Collection weave() throws IOException {
// prepareForWeave();
// Collection filesToWeave;
//
// if (needToReweaveWorld) {
// filesToWeave = sourceJavaClasses.values();
// } else {
// filesToWeave = addedClasses;
// }
//
// Collection wovenClassNames = new ArrayList();
// world.showMessage(IMessage.INFO, "might need to weave " + filesToWeave +
// "(world=" + needToReweaveWorld + ")", null, null);
//
//
// //System.err.println("typeMungers: " + typeMungerList);
//
// prepareToProcessReweavableState();
// // clear all state from files we'll be reweaving
// for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// String className = classFile.getClassName();
// BcelObjectType classType = getClassType(className);
// processReweavableStateIfPresent(className, classType);
// }
//
//
//
// //XXX this isn't quite the right place for this...
// for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// String className = classFile.getClassName();
// addTypeMungers(className);
// }
//
// // first weave into aspects
// for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// String className = classFile.getClassName();
// BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
// if (classType.isAspect()) {
// weave(classFile, classType);
// wovenClassNames.add(className);
// }
// }
//
// // then weave into non-aspects
// for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// String className = classFile.getClassName();
// BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
// if (! classType.isAspect()) {
// weave(classFile, classType);
// wovenClassNames.add(className);
// }
// }
//
// if (zipOutputStream != null && !needToReweaveWorld) {
// Collection filesToDump = new HashSet(sourceJavaClasses.values());
// filesToDump.removeAll(filesToWeave);
// for (Iterator i = filesToDump.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// dumpUnchanged(classFile);
// }
// }
//
// addedClasses = new ArrayList();
// deletedTypenames = new ArrayList();
//
// return wovenClassNames;
// }
// variation of "weave" that sources class files from an external source.
public Collection weave(IClassFileProvider input) throws IOException {
Collection wovenClassNames = new ArrayList();
IWeaveRequestor requestor = input.getRequestor();
requestor.processingReweavableState();
prepareToProcessReweavableState();
// clear all state from files we'll be reweaving
for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
String className = classFile.getClassName();
BcelObjectType classType = getClassType(className);
processReweavableStateIfPresent(className, classType);
}
requestor.addingTypeMungers();
//XXX this isn't quite the right place for this...
for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
String className = classFile.getClassName();
addTypeMungers(className);
}
requestor.weavingAspects();
// first weave into aspects
for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
String className = classFile.getClassName();
BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
if (classType.isAspect()) {
weaveAndNotify(classFile, classType,requestor);
wovenClassNames.add(className);
}
}
requestor.weavingClasses();
// then weave into non-aspects
for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
String className = classFile.getClassName();
BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
if (! classType.isAspect()) {
weaveAndNotify(classFile, classType, requestor);
wovenClassNames.add(className);
}
}
addedClasses = new ArrayList();
deletedTypenames = new ArrayList();
requestor.weaveCompleted();
return wovenClassNames;
}
public void prepareToProcessReweavableState() {
if (inReweavableMode)
world.showMessage(IMessage.INFO,
WeaverMessages.format(WeaverMessages.REWEAVABLE_MODE),
null, null);
alreadyConfirmedReweavableState = new HashSet();
}
public void processReweavableStateIfPresent(String className, BcelObjectType classType) {
// If the class is marked reweavable, check any aspects around when it was built are in this world
WeaverStateInfo wsi = classType.getWeaverState();
if (wsi!=null && wsi.isReweavable()) { // Check all necessary types are around!
world.showMessage(IMessage.INFO,
WeaverMessages.format(WeaverMessages.PROCESSING_REWEAVABLE,className,classType.getSourceLocation().getSourceFile()),
null,null);
Set aspectsPreviouslyInWorld = wsi.getAspectsAffectingType();
if (aspectsPreviouslyInWorld!=null) {
for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) {
String requiredTypeName = (String) iter.next();
if (!alreadyConfirmedReweavableState.contains(requiredTypeName)) {
ResolvedTypeX rtx = world.resolve(TypeX.forName(requiredTypeName),true);
boolean exists = rtx!=ResolvedTypeX.MISSING;
if (!exists) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE,requiredTypeName,className),
classType.getSourceLocation(), null);
} else {
if (!world.getMessageHandler().isIgnoring(IMessage.INFO))
world.showMessage(IMessage.INFO,
WeaverMessages.format(WeaverMessages.VERIFIED_REWEAVABLE_TYPE,requiredTypeName,rtx.getSourceLocation().getSourceFile()),
null,null);
alreadyConfirmedReweavableState.add(requiredTypeName);
}
}
}
}
classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData()));
} else {
classType.resetState();
}
}
private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType,
IWeaveRequestor requestor) throws IOException {
LazyClassGen clazz = weaveWithoutDump(classFile,classType);
classType.finishedWith();
//clazz is null if the classfile was unchanged by weaving...
if (clazz != null) {
UnwovenClassFile[] newClasses = getClassFilesFor(clazz);
for (int i = 0; i < newClasses.length; i++) {
requestor.acceptResult(newClasses[i]);
}
} else {
requestor.acceptResult(classFile);
}
}
// helper method
public BcelObjectType getClassType(String forClass) {
return BcelWorld.getBcelObjectType(world.resolve(forClass));
}
public void addTypeMungers(String typeName) {
weave(world.resolve(typeName));
}
public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) {
List childClasses = clazz.getChildClasses(world);
UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()];
ret[0] = new UnwovenClassFile(clazz.getFileName(),clazz.getJavaClass(world).getBytes());
int index = 1;
for (Iterator iter = childClasses.iterator(); iter.hasNext();) {
UnwovenClassFile.ChildClass element = (UnwovenClassFile.ChildClass) iter.next();
UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes);
ret[index++] = childClass;
}
return ret;
}
public void weave(ResolvedTypeX onType) {
onType.clearInterTypeMungers();
// need to do any declare parents before the matching below
for (Iterator i = declareParentsList.iterator(); i.hasNext(); ) {
DeclareParents p = (DeclareParents)i.next();
List newParents = p.findMatchingNewParents(onType);
if (!newParents.isEmpty()) {
BcelObjectType classType = BcelWorld.getBcelObjectType(onType);
//System.err.println("need to do declare parents for: " + onType);
for (Iterator j = newParents.iterator(); j.hasNext(); ) {
ResolvedTypeX newParent = (ResolvedTypeX)j.next();
if (newParent.isClass()) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.DECP_BINARY_LIMITATION,onType.getName()),
p.getSourceLocation(), null);
continue;
}
classType.addParent(newParent);
ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent);
onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p)));
}
}
}
for (Iterator i = typeMungerList.iterator(); i.hasNext(); ) {
ConcreteTypeMunger m = (ConcreteTypeMunger)i.next();
if (m.matches(onType)) {
onType.addInterTypeMunger(m);
}
}
}
// exposed for ClassLoader dynamic weaving
public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
return weave(classFile, classType, false);
}
// non-private for testing
LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
LazyClassGen ret = weave(classFile, classType, true);
if (progressListener != null) {
progressMade += progressPerClassFile;
progressListener.setProgress(progressMade);
progressListener.setText("woven: " + classFile.getFilename());
}
return ret;
}
private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException {
if (classType.isSynthetic()) {
if (dump) dumpUnchanged(classFile);
return null;
}
// JavaClass javaClass = classType.getJavaClass();
List shadowMungers = fastMatch(shadowMungerList, classType.getResolvedTypeX());
List typeMungers = classType.getResolvedTypeX().getInterTypeMungers();
classType.getResolvedTypeX().checkInterTypeMungers();
LazyClassGen clazz = null;
if (shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect()) {
clazz = classType.getLazyClassGen();
//System.err.println("got lazy gen: " + clazz + ", " + clazz.getWeaverState());
try {
boolean isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers);
if (isChanged) {
if (dump) dump(classFile, clazz);
return clazz;
}
} catch (RuntimeException re) {
System.err.println("trouble in: ");
//XXXclazz.print(System.err);
throw re;
} catch (Error re) {
System.err.println("trouble in: ");
clazz.print(System.err);
throw re;
}
}
// this is very odd return behavior trying to keep everyone happy
if (dump) {
dumpUnchanged(classFile);
return clazz;
} else {
return null;
}
}
// ---- writing
private void dumpUnchanged(UnwovenClassFile classFile) throws IOException {
if (zipOutputStream != null) {
writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes());
} else {
classFile.writeUnchangedBytes();
}
}
private String getEntryName(String className) {
//XXX what does bcel's getClassName do for inner names
return className.replace('.', '/') + ".class";
}
private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException {
if (zipOutputStream != null) {
String mainClassName = classFile.getJavaClass().getClassName();
writeZipEntry(getEntryName(mainClassName),
clazz.getJavaClass(world).getBytes());
if (!clazz.getChildClasses(world).isEmpty()) {
for (Iterator i = clazz.getChildClasses(world).iterator(); i.hasNext();) {
UnwovenClassFile.ChildClass c = (UnwovenClassFile.ChildClass) i.next();
writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes);
}
}
} else {
classFile.writeWovenBytes(
clazz.getJavaClass(world).getBytes(),
clazz.getChildClasses(world)
);
}
}
private void writeZipEntry(String name, byte[] bytes) throws IOException {
ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right
zipOutputStream.putNextEntry(newEntry);
zipOutputStream.write(bytes);
zipOutputStream.closeEntry();
}
private List fastMatch(List list, ResolvedTypeX type) {
if (list == null) return Collections.EMPTY_LIST;
// here we do the coarsest grained fast match with no kind constraints
// this will remove all obvious non-matches and see if we need to do any weaving
FastMatchInfo info = new FastMatchInfo(type, null);
List result = new ArrayList();
Iterator iter = list.iterator();
while (iter.hasNext()) {
ShadowMunger munger = (ShadowMunger)iter.next();
FuzzyBoolean fb = munger.getPointcut().fastMatch(info);
WeaverMetrics.recordFastMatchTypeResult(fb); // Could pass: munger.getPointcut().toString(),info
if (fb.maybeTrue()) {
result.add(munger);
}
}
return result;
}
public void setProgressListener(IProgressListener listener, double previousProgress, double progressPerClassFile) {
progressListener = listener;
this.progressMade = previousProgress;
this.progressPerClassFile = progressPerClassFile;
}
public void setReweavableMode(boolean mode,boolean compress) {
inReweavableMode = mode;
WeaverStateInfo.setReweavableModeDefaults(mode,compress);
BcelClassWeaver.setReweavableMode(mode,compress);
}
public boolean isReweavable() {
return inReweavableMode;
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/BcelWorld.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.FieldInstruction;
import org.apache.bcel.generic.GETSTATIC;
import org.apache.bcel.generic.INVOKEINTERFACE;
import org.apache.bcel.generic.INVOKESPECIAL;
import org.apache.bcel.generic.INVOKESTATIC;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.PUTSTATIC;
import org.apache.bcel.generic.Type;
import org.apache.bcel.util.ClassPath;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.ICrossReferenceHandler;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.World;
import org.aspectj.weaver.patterns.FormalBinding;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.SimpleScope;
public class BcelWorld extends World {
private ClassPathManager classPath;
//private ClassPathManager aspectPath = null;
// private List aspectPathEntries;
// ---- constructors
public BcelWorld() {
this("");
}
public BcelWorld(String cp) {
this(makeDefaultClasspath(cp), IMessageHandler.THROW, null);
}
private static List makeDefaultClasspath(String cp) {
List classPath = new ArrayList();
classPath.addAll(getPathEntries(cp));
classPath.addAll(getPathEntries(ClassPath.getClassPath()));
//System.err.println("classpath: " + classPath);
return classPath;
}
private static List getPathEntries(String s) {
List ret = new ArrayList();
StringTokenizer tok = new StringTokenizer(s, File.pathSeparator);
while(tok.hasMoreTokens()) ret.add(tok.nextToken());
return ret;
}
public BcelWorld(List classPath, IMessageHandler handler, ICrossReferenceHandler xrefHandler) {
//this.aspectPath = new ClassPathManager(aspectPath, handler);
this.classPath = new ClassPathManager(classPath, handler);
setMessageHandler(handler);
setXRefHandler(xrefHandler);
}
public BcelWorld(ClassPathManager cpm, IMessageHandler handler, ICrossReferenceHandler xrefHandler) {
this.classPath = cpm;
setMessageHandler(handler);
setXRefHandler(xrefHandler);
}
public void addPath (String name) {
classPath.addPath(name, this.getMessageHandler());
}
/**
* Parse a string into advice.
*
* <blockquote><pre>
* Kind ( Id , ... ) : Pointcut -> MethodSignature
* </pre></blockquote>
*/
public Advice shadowMunger(String str, int extraFlag) {
str = str.trim();
int start = 0;
int i = str.indexOf('(');
AdviceKind kind =
AdviceKind.stringToKind(str.substring(start, i));
start = ++i;
i = str.indexOf(')', i);
String[] ids = parseIds(str.substring(start, i).trim());
//start = ++i;
i = str.indexOf(':', i);
start = ++i;
i = str.indexOf("->", i);
Pointcut pointcut = Pointcut.fromString(str.substring(start, i).trim());
Member m = Member.methodFromString(str.substring(i+2, str.length()).trim());
// now, we resolve
TypeX[] types = m.getParameterTypes();
FormalBinding[] bindings = new FormalBinding[ids.length];
for (int j = 0, len = ids.length; j < len; j++) {
bindings[j] = new FormalBinding(types[j], ids[j], j, 0, 0, "fromString");
}
Pointcut p =
pointcut.resolve(new SimpleScope(this, bindings));
return new BcelAdvice(kind, p, m, extraFlag, 0, 0, null, null);
}
private String[] parseIds(String str) {
if (str.length() == 0) return ZERO_STRINGS;
List l = new ArrayList();
int start = 0;
while (true) {
int i = str.indexOf(',', start);
if (i == -1) {
l.add(str.substring(start).trim());
break;
}
l.add(str.substring(start, i).trim());
start = i+1;
}
return (String[]) l.toArray(new String[l.size()]);
}
// ---- various interactions with bcel
public static Type makeBcelType(TypeX type) {
return Type.getType(type.getSignature());
}
static Type[] makeBcelTypes(TypeX[] types) {
Type[] ret = new Type[types.length];
for (int i = 0, len = types.length; i < len; i++) {
ret[i] = makeBcelType(types[i]);
}
return ret;
}
public static TypeX fromBcel(Type t) {
return TypeX.forSignature(t.getSignature());
}
static TypeX[] fromBcel(Type[] ts) {
TypeX[] ret = new TypeX[ts.length];
for (int i = 0, len = ts.length; i < len; i++) {
ret[i] = fromBcel(ts[i]);
}
return ret;
}
public ResolvedTypeX resolve(Type t) {
return resolve(fromBcel(t));
}
protected ResolvedTypeX.ConcreteName resolveObjectType(ResolvedTypeX.Name ty) {
String name = ty.getName();
JavaClass jc = null;
//UnwovenClassFile classFile = (UnwovenClassFile)sourceJavaClasses.get(name);
//if (classFile != null) jc = classFile.getJavaClass();
// if (jc == null) {
// jc = lookupJavaClass(aspectPath, name);
// }
if (jc == null) {
jc = lookupJavaClass(classPath, name);
}
if (jc == null) {
return null;
} else {
return makeBcelObjectType(ty, jc, false);
}
}
private BcelObjectType makeBcelObjectType(ResolvedTypeX.Name resolvedTypeX, JavaClass jc, boolean exposedToWeaver) {
BcelObjectType ret = new BcelObjectType(resolvedTypeX, jc, exposedToWeaver);
resolvedTypeX.setDelegate(ret);
return ret;
}
private JavaClass lookupJavaClass(ClassPathManager classPath, String name) {
if (classPath == null) return null;
try {
ClassPathManager.ClassFile file = classPath.find(TypeX.forName(name));
if (file == null) return null;
ClassParser parser = new ClassParser(file.getInputStream(), file.getPath());
JavaClass jc = parser.parse();
return jc;
} catch (IOException ioe) {
return null;
}
}
public BcelObjectType addSourceObjectType(JavaClass jc) {
String signature = TypeX.forName(jc.getClassName()).getSignature();
ResolvedTypeX.Name nameTypeX = (ResolvedTypeX.Name)typeMap.get(signature);
if (nameTypeX == null) {
nameTypeX = new ResolvedTypeX.Name(signature, this);
}
BcelObjectType ret = makeBcelObjectType(nameTypeX, jc, true);
nameTypeX.setDelegate(ret);
typeMap.put(signature, nameTypeX);
return ret;
}
void deleteSourceObjectType(TypeX ty) {
typeMap.remove(ty.getSignature());
}
public static Member makeFieldSignature(LazyClassGen cg, FieldInstruction fi) {
ConstantPoolGen cpg = cg.getConstantPoolGen();
return
Member.field(
fi.getClassName(cpg),
(fi instanceof GETSTATIC || fi instanceof PUTSTATIC)
? Modifier.STATIC
: 0,
fi.getName(cpg),
fi.getSignature(cpg));
}
public static Member makeFieldSetSignature(LazyClassGen cg, FieldInstruction fi) {
ConstantPoolGen cpg = cg.getConstantPoolGen();
return
Member.field(
fi.getClassName(cpg),
(fi instanceof GETSTATIC || fi instanceof PUTSTATIC)
? Modifier.STATIC
: 0,
fi.getName(cpg),
"(" + fi.getSignature(cpg) + ")" +fi.getSignature(cpg));
}
public Member makeMethodSignature(LazyMethodGen mg) {
return makeMethodSignature(mg, null);
}
public Member makeMethodSignature(LazyMethodGen mg, Member.Kind kind) {
ResolvedMember ret = mg.getMemberView();
if (ret == null) {
int mods = mg.getAccessFlags();
if (mg.getEnclosingClass().isInterface()) {
mods |= Modifier.INTERFACE;
}
if (kind == null) {
if (mg.getName().equals("<init>")) {
kind = Member.CONSTRUCTOR;
} else if (mg.getName().equals("<clinit>")) {
kind = Member.STATIC_INITIALIZATION;
} else {
kind = Member.METHOD;
}
}
return new ResolvedMember(kind,
TypeX.forName(mg.getClassName()),
mods,
fromBcel(mg.getReturnType()),
mg.getName(),
fromBcel(mg.getArgumentTypes())
);
} else {
return ret;
}
}
public static Member makeMethodSignature(LazyClassGen cg, InvokeInstruction ii) {
ConstantPoolGen cpg = cg.getConstantPoolGen();
String declaring = ii.getClassName(cpg);
String name = ii.getName(cpg);
String signature = ii.getSignature(cpg);
int modifier =
(ii instanceof INVOKEINTERFACE)
? Modifier.INTERFACE
: (ii instanceof INVOKESTATIC)
? Modifier.STATIC
: (ii instanceof INVOKESPECIAL && ! name.equals("<init>"))
? Modifier.PRIVATE
: 0;
return Member.method(TypeX.forName(declaring), modifier, name, signature);
}
public static Member makeMungerMethodSignature(JavaClass javaClass, Method method) {
int mods = 0;
if (method.isStatic()) mods = Modifier.STATIC;
else if (javaClass.isInterface()) mods = Modifier.INTERFACE;
else if (method.isPrivate()) mods = Modifier.PRIVATE;
return Member.method(
TypeX.forName(javaClass.getClassName()), mods, method.getName(), method.getSignature());
}
private static final String[] ZERO_STRINGS = new String[0];
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("BcelWorld(");
//buf.append(shadowMungerMap);
buf.append(")");
return buf.toString();
}
public Advice concreteAdvice(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature)
{
//System.err.println("concrete advice: " + signature + " context " + sourceContext);
return new BcelAdvice(attribute, pointcut, signature, null);
}
public ConcreteTypeMunger concreteTypeMunger(
ResolvedTypeMunger munger, ResolvedTypeX aspectType)
{
return new BcelTypeMunger(munger, aspectType);
}
public ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField) {
return new BcelCflowStackFieldAdder(cflowField);
}
public static BcelObjectType getBcelObjectType(ResolvedTypeX concreteAspect) {
//XXX need error checking
return (BcelObjectType) ((ResolvedTypeX.Name)concreteAspect).getDelegate();
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/ExceptionRange.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.aspectj.weaver.TypeX;
/** exceptionRanges are set initially to be low priority. The various setPriority methods
* should be used accordingly. The priority is used when we pack the exception table into
* a method... the exception table should be sorted from high to low priority. Exceptions we generate
* for advice is either high priority (higher than anything coming from the original method...
* most kinds of non-execution advice) or low priority (lower than anything coming from the
* original method, for execution advice).
*
* <p> ??? This does not account for handler, or any other
* "statement-level" advice. When such statement level advice happens, we may want to go to a float level,
* so we can set the priority of advice to be lower than anything it encloses, and higher than
* anything enclosing it.
*/
/* we're actually using the fact that we're an instruction targeter, for the
* handler */
public final class ExceptionRange extends Range {
private InstructionHandle handler;
private final TypeX exceptionType;
private final int priority;
// ---- initialization
/**
* After this constructor is called, this range is not well situated unless
* {@link #associateWithTargets} is called
*
* XXX priority should be fixed
*/
public ExceptionRange(InstructionList body, TypeX exceptionType, int priority) {
super(body);
this.exceptionType = exceptionType;
this.priority = priority;
}
/**
* @param insideExisting
*/
public ExceptionRange(InstructionList body, TypeX exceptionType, boolean insideExisting) {
this(body, exceptionType, insideExisting ? Integer.MAX_VALUE : -1);
}
public void associateWithTargets(
InstructionHandle start,
InstructionHandle end,
InstructionHandle handler)
{
// assert body.contains(start) && body.contains(end) && body.contains(handler)
this.start = start;
this.end = end;
this.handler = handler;
start.addTargeter(this);
end.addTargeter(this);
handler.addTargeter(this);
}
// ----
public InstructionHandle getHandler() {
return handler;
}
public TypeX getCatchType() {
return exceptionType;
}
public int getPriority() {
return priority;
}
// ---- from object
public String toString() {
String str;
if (exceptionType == null) {
str = "finally";
} else {
str = "catch " + exceptionType;
}
// if (priority >= 0 && priority < Integer.MAX_VALUE) {
// str += " (priority " + priority + ")";
// }
return str;
}
public boolean equals(Object other) {
if (!(other instanceof ExceptionRange)) return false;
ExceptionRange o = (ExceptionRange) other;
return o.getStart() == getStart()
&& o.getEnd() == getEnd()
&& o.handler == handler
&& ((o.exceptionType == null)
? (exceptionType == null) :
o.exceptionType.equals(exceptionType))
&& o.priority == priority;
}
private volatile int hashCode = 0;
public int hashCode() {
if (hashCode == 0) {
int ret = 17;
ret = 37*ret + getStart().hashCode();
ret = 37*ret + getEnd().hashCode();
ret = 37*ret + handler.hashCode();
ret = 37*ret + ((exceptionType == null) ? 0 : exceptionType.hashCode());
ret = 37*ret + priority;
hashCode = ret;
}
return hashCode;
}
public void updateTarget(
InstructionHandle oldIh,
InstructionHandle newIh,
InstructionList newBody)
{
super.updateTarget(oldIh, newIh, newBody);
// we're guaranteed that start, end, and handler are distinct instruction handles.
if (oldIh == handler) {
handler = newIh;
}
}
public static boolean isExceptionStart(InstructionHandle ih) {
if (! isRangeHandle(ih)) return false;
Range r = getRange(ih);
if (! (r instanceof ExceptionRange)) return false;
ExceptionRange er = (ExceptionRange) r;
return er.getStart() == ih;
}
public static boolean isExceptionEnd(InstructionHandle ih) {
if (! isRangeHandle(ih)) return false;
Range r = getRange(ih);
if (! (r instanceof ExceptionRange)) return false;
ExceptionRange er = (ExceptionRange) r;
return er.getEnd() == ih;
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/LazyClassGen.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
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 org.apache.bcel.Constants;
import org.apache.bcel.classfile.Attribute;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.classfile.Unknown;
import org.apache.bcel.generic.ClassGen;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.FieldGen;
import org.apache.bcel.generic.InstructionConstants;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.PUSH;
import org.apache.bcel.generic.RETURN;
import org.apache.bcel.generic.Type;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.util.CollectionUtil;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.World;
public final class LazyClassGen {
// ---- JSR 45 info
int highestLineNumber = 0;
private SortedMap /* <String, InlinedSourceFileInfo> */ inlinedFiles = new TreeMap();
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 (Iterator iter = inlinedFiles.values().iterator(); iter.hasNext();) {
InlinedSourceFileInfo element = (InlinedSourceFileInfo) iter.next();
element.offset = i;
i = roundUpToHundreds(i + element.highestLineNumber);
}
}
private static int roundUpToHundreds(int i) {
return ((i / 100) + 1) * 100;
}
int getSourceDebugExtensionOffset(String fullpath) {
return ((InlinedSourceFileInfo) inlinedFiles.get(fullpath)).offset;
}
private Unknown getSourceDebugExtensionAttribute() {
int nameIndex = constantPoolGen.addUtf8("SourceDebugExtension");
String data = getSourceDebugExtensionString();
//System.err.println(data);
byte[] bytes = Utility.stringToUTF(data);
int length = bytes.length;
return new Unknown(nameIndex, length, bytes, constantPoolGen.getConstantPool());
}
// 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);
LazyClassGen clazz = new LazyClassGen(BcelWorld.getBcelObjectType(world.resolve(name)));
clazz.print(out);
out.println();
}
private BcelObjectType myType; // XXX is not set for types we create
private ClassGen myGen;
private ConstantPoolGen constantPoolGen;
private List /*LazyMethodGen*/
methodGens = new ArrayList();
private List /*LazyClassGen*/
classGens = new ArrayList();
private int childCounter = 0;
public int getNewGeneratedNameTag() {
return childCounter++;
}
private InstructionFactory fact;
private boolean isSerializable = false;
private boolean hasSerialVersionUIDField = false;
private boolean hasClinit = false;
// ----
public LazyClassGen(
String class_name,
String super_class_name,
String file_name,
int access_flags,
String[] interfaces)
{
myGen = new ClassGen(class_name, super_class_name, file_name, access_flags, interfaces);
constantPoolGen = myGen.getConstantPool();
fact = new InstructionFactory(myGen, constantPoolGen);
}
//Non child type, so it comes from a real type in the world.
public LazyClassGen(BcelObjectType myType) {
myGen = new ClassGen(myType.getJavaClass());
constantPoolGen = myGen.getConstantPool();
fact = new InstructionFactory(myGen, constantPoolGen);
this.myType = myType;
/* Does this class support serialization */
if (TypeX.SERIALIZABLE.isAssignableFrom(getType(),getType().getWorld())) {
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(ResolvedTypeX.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>")) {
hasClinit = true;
}
}
}
Method[] methods = myGen.getMethods();
for (int i = 0; i < methods.length; i++) {
addMethodGen(new LazyMethodGen(methods[i], this));
}
}
public static boolean hasSerialVersionUIDField (ResolvedTypeX type) {
ResolvedMember[] fields = type.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
ResolvedMember field = fields[i];
if (field.getName().equals("serialVersionUID")
&& field.isStatic() && field.getType().equals(ResolvedTypeX.LONG)) {
return true;
}
}
return false;
}
// public void addAttribute(Attribute i) {
// myGen.addAttribute(i);
// }
// ----
public String getInternalClassName() {
return getConstantPoolGen().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();
}
}
public File getPackagePath(File root) {
String str = getInternalClassName();
int index = str.lastIndexOf('/');
if (index == -1)
return root;
return new File(root, str.substring(0, index));
}
public String getClassId() {
String str = getInternalClassName();
int index = str.lastIndexOf('/');
if (index == -1)
return str;
return str.substring(index + 1);
}
public void addMethodGen(LazyMethodGen gen) {
//assert gen.getClassName() == super.getClassName();
methodGens.add(gen);
if (highestLineNumber < gen.highestLineNumber) highestLineNumber = gen.highestLineNumber;
}
public void addMethodGen(LazyMethodGen gen, ISourceLocation sourceLocation) {
addMethodGen(gen);
if (!gen.getMethod().isPrivate()) {
warnOnAddedMethod(gen.getMethod(),sourceLocation);
}
}
public void errorOnAddedField (Field field, ISourceLocation sourceLocation) {
if (isSerializable && !hasSerialVersionUIDField) {
getWorld().getLint().serialVersionUIDBroken.signal(
new String[] {
myType.getResolvedTypeX().getName().toString(),
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 myType.getResolvedTypeX().getWorld();
}
public List getMethodGens() {
return methodGens; //???Collections.unmodifiableList(methodGens);
}
private void writeBack(BcelWorld world) {
if (getConstantPoolGen().getSize() > Short.MAX_VALUE) {
// 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.getAccessFlags(), 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
);
return;
}
if (myType != null && myType.getWeaverState() != null) {
myGen.addAttribute(BcelAttributes.bcelAttribute(
new AjAttribute.WeaverState(myType.getWeaverState()),
getConstantPoolGen()));
}
addAjcInitializers();
int len = methodGens.size();
myGen.setMethods(new Method[0]);
calculateSourceDebugExtensionOffsets();
for (int i = 0; i < len; i++) {
LazyMethodGen gen = (LazyMethodGen) methodGens.get(i);
// we skip empty clinits
if (isEmptyClinit(gen)) continue;
myGen.addMethod(gen.getMethod());
}
if (inlinedFiles.size() != 0) {
if (hasSourceDebugExtensionAttribute(myGen)) {
world.showMessage(
IMessage.WARNING,
WeaverMessages.format(WeaverMessages.OVERWRITE_JSR45,getFileName()),
null,
null);
}
myGen.addAttribute(getSourceDebugExtensionAttribute());
}
}
private static boolean hasSourceDebugExtensionAttribute(ClassGen gen) {
ConstantPoolGen pool = gen.getConstantPool();
Attribute[] attrs = gen.getAttributes();
for (int i = 0; i < attrs.length; i++) {
if ("SourceDebugExtension"
.equals(((ConstantUtf8) pool.getConstant(attrs[i].getNameIndex())).getBytes())) {
return true;
}
}
return false;
}
public JavaClass getJavaClass(BcelWorld world) {
writeBack(world);
return myGen.getJavaClass();
}
public void addGeneratedInner(LazyClassGen newClass) {
classGens.add(newClass);
}
public void addInterface(TypeX typeX, ISourceLocation sourceLocation) {
myGen.addInterface(typeX.getName());
warnOnAddedInterface(typeX.getName(),sourceLocation);
}
public void setSuperClass(TypeX typeX) {
myGen.setSuperclassName(typeX.getName());
}
// non-recursive, may be a bug, ha ha.
private List getClassGens() {
List ret = new ArrayList();
ret.add(this);
ret.addAll(classGens);
return ret;
}
public List getChildClasses(BcelWorld world) {
if (classGens.isEmpty()) return Collections.EMPTY_LIST;
List ret = new ArrayList();
for (Iterator i = classGens.iterator(); i.hasNext();) {
LazyClassGen clazz = (LazyClassGen) i.next();
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;
}
public String toString() {
return toShortString();
}
public String toShortString() {
String s =
org.apache.bcel.classfile.Utility.accessToString(myGen.getAccessFlags(), true);
if (s != "")
s += " ";
s += org.apache.bcel.classfile.Utility.classOrInterface(myGen.getAccessFlags());
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 classGens = getClassGens();
for (Iterator iter = classGens.iterator(); iter.hasNext();) {
LazyClassGen element = (LazyClassGen) iter.next();
element.printOne(out);
if (iter.hasNext()) out.println();
}
}
private void printOne(PrintStream out) {
out.print(toShortString());
out.print(" extends ");
out.print(
org.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 methodGens = getMethodGens();
for (Iterator iter = methodGens.iterator(); iter.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) iter.next();
// we skip empty clinits
if (isEmptyClinit(gen)) continue;
gen.print(out);
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() instanceof RETURN)) {
start = start.getNext();
} else {
return false;
}
}
return true;
}
public ConstantPoolGen getConstantPoolGen() {
return constantPoolGen;
}
public String getName() {
return myGen.getClassName();
}
public boolean isWoven() {
return myType.getWeaverState() != null;
}
public boolean isReweavable() {
if (myType.getWeaverState()==null) return false;
return myType.getWeaverState().isReweavable();
}
public Set getAspectsAffectingType() {
if (myType.getWeaverState()==null) return null;
return myType.getWeaverState().getAspectsAffectingType();
}
public WeaverStateInfo getOrCreateWeaverStateInfo() {
WeaverStateInfo ret = myType.getWeaverState();
if (ret != null) return ret;
ret = new WeaverStateInfo();
myType.setWeaverState(ret);
return ret;
}
public InstructionFactory getFactory() {
return fact;
}
public LazyMethodGen getStaticInitializer() {
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) i.next();
if (gen.getName().equals("<clinit>")) return gen;
}
LazyMethodGen clinit = new LazyMethodGen(
Modifier.STATIC,
Type.VOID,
"<clinit>",
new Type[0],
CollectionUtil.NO_STRINGS,
this);
clinit.getBody().insert(InstructionConstants.RETURN);
methodGens.add(clinit);
return clinit;
}
public LazyMethodGen getAjcPreClinit() {
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) i.next();
if (gen.getName().equals(NameMangler.AJC_PRE_CLINIT_NAME)) return gen;
}
LazyMethodGen ajcClinit = new LazyMethodGen(
Modifier.STATIC,
Type.VOID,
NameMangler.AJC_PRE_CLINIT_NAME,
new Type[0],
CollectionUtil.NO_STRINGS,
this);
ajcClinit.getBody().insert(InstructionConstants.RETURN);
methodGens.add(ajcClinit);
getStaticInitializer().getBody().insert(Utility.createInvoke(getFactory(), ajcClinit));
return ajcClinit;
}
// reflective thisJoinPoint support
Map/*BcelShadow, Field*/ tjpFields = new HashMap();
public static final ObjectType tjpType =
new ObjectType("org.aspectj.lang.JoinPoint");
public static final ObjectType staticTjpType =
new ObjectType("org.aspectj.lang.JoinPoint$StaticPart");
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) {
Field ret = (Field)tjpFields.get(shadow);
if (ret != null) return ret;
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;
}
ret = new FieldGen(modifiers,
staticTjpType,
"ajc$tjp_" + tjpFields.size(),
getConstantPoolGen()).getField();
addField(ret);
tjpFields.put(shadow, ret);
return ret;
}
private void addAjcInitializers() {
if (tjpFields.size() == 0) return;
InstructionList il = initializeAllTjps();
getStaticInitializer().getBody().insert(il);
}
private InstructionList initializeAllTjps() {
InstructionList list = new InstructionList();
InstructionFactory fact = getFactory();
// make a new factory
list.append(fact.createNew(factoryType));
list.append(InstructionFactory.createDup(1));
list.append(new PUSH(getConstantPoolGen(), getFileName()));
// load the current Class object
//XXX check that this works correctly for inners/anonymous
list.append(new PUSH(getConstantPoolGen(), getClassName()));
//XXX do we need to worry about the fact the theorectically this could throw
//a ClassNotFoundException
list.append(fact.createInvoke("java.lang.Class", "forName", classType,
new Type[] {Type.STRING}, Constants.INVOKESTATIC));
list.append(fact.createInvoke(factoryType.getClassName(), "<init>",
Type.VOID, new Type[] {Type.STRING, classType},
Constants.INVOKESPECIAL));
list.append(InstructionFactory.createStore(factoryType, 0));
List entries = new ArrayList(tjpFields.entrySet());
Collections.sort(entries, new Comparator() {
public int compare(Object a, Object b) {
Map.Entry ae = (Map.Entry) a;
Map.Entry be = (Map.Entry) b;
return ((Field) ae.getValue())
.getName()
.compareTo(((Field)be.getValue()).getName());
}
});
for (Iterator i = entries.iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry)i.next();
initializeTjp(fact, list, (Field)entry.getValue(), (BcelShadow)entry.getKey());
}
return list;
}
private void initializeTjp(InstructionFactory fact, InstructionList list,
Field field, BcelShadow shadow)
{
Member sig = shadow.getSignature();
//ResolvedMember mem = shadow.getSignature().resolve(shadow.getWorld());
// load the factory
list.append(InstructionFactory.createLoad(factoryType, 0));
// load the kind
list.append(new PUSH(getConstantPoolGen(), shadow.getKind().getName()));
// create the signature
list.append(InstructionFactory.createLoad(factoryType, 0));
list.append(new PUSH(getConstantPoolGen(), sig.getSignatureString(shadow.getWorld())));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING },
Constants.INVOKEVIRTUAL));
//XXX should load source location from shadow
list.append(Utility.createConstant(fact, shadow.getSourceLine()));
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));
}
public ResolvedTypeX getType() {
if (myType == null) return null;
return myType.getResolvedTypeX();
}
public BcelObjectType getBcelObjectType() {
return myType;
}
public String getFileName() {
return myGen.getFileName();
}
private void addField(Field field) {
myGen.addField(field);
}
public void addField(Field 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 LazyMethodGen getLazyMethodGen(Member m) {
return getLazyMethodGen(m.getName(), m.getSignature());
}
public LazyMethodGen getLazyMethodGen(String name, String signature) {
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) i.next();
if (gen.getName().equals(name) && gen.getSignature().equals(signature))
return gen;
}
throw new BCException("Class " + this.getName() + " does not have a method "
+ name + " with signature " + signature);
}
public void forcePublic() {
myGen.setAccessFlags(Utility.makePublic(myGen.getAccessFlags()));
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/LazyMethodGen.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.Attribute;
import org.apache.bcel.classfile.ConstantPool;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.classfile.Synthetic;
import org.apache.bcel.generic.BranchHandle;
import org.apache.bcel.generic.BranchInstruction;
import org.apache.bcel.generic.CPInstruction;
import org.apache.bcel.generic.ClassGenException;
import org.apache.bcel.generic.CodeExceptionGen;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.InstructionTargeter;
import org.apache.bcel.generic.LineNumberGen;
import org.apache.bcel.generic.LocalVariableGen;
import org.apache.bcel.generic.LocalVariableInstruction;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.Select;
import org.apache.bcel.generic.Type;
import org.aspectj.bridge.IMessage;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.WeaverMessages;
/**
* A LazyMethodGen should be treated as a MethodGen. It's our way of abstracting over the
* low-level Method objects. It converts through {@link MethodGen} to create
* and to serialize, but that's it.
*
* <p> At any rate, there are two ways to create LazyMethodGens.
* One is from a method, which
* does work through MethodGen to do the correct thing.
* The other is the creation of a completely empty
* LazyMethodGen, and it is used when we're constructing code from scratch.
*
* <p> We stay away from targeters for rangey things like Shadows and Exceptions.
*/
public final class LazyMethodGen {
private int accessFlags;
private Type returnType;
private final String name;
private Type[] argumentTypes;
//private final String[] argumentNames;
private String[] declaredExceptions;
private InstructionList body; // leaving null for abstracts
private Attribute[] attributes;
/* private */ final LazyClassGen enclosingClass;
private final BcelMethod memberView;
int highestLineNumber = 0;
/** This is nonnull if this method is the result of an "inlining". We currently
* copy methods into other classes for around advice. We add this field so
* we can get JSR45 information correct. If/when we do _actual_ inlining,
* we'll need to subtype LineNumberTag to have external line numbers.
*/
String fromFilename = null;
private int maxLocals;
private boolean canInline = true;
private boolean hasExceptionHandlers;
private boolean isSynthetic = false;
/**
* only used by {@link BcelClassWeaver}
*/
List /*ShadowMungers*/ matchedShadows;
// Used for interface introduction
// this is the type of the interface the method is technically on
public ResolvedTypeX definingType = null;
public LazyMethodGen(
int accessFlags,
Type returnType,
String name,
Type[] paramTypes,
String[] declaredExceptions,
LazyClassGen enclosingClass)
{
//System.err.println("raw create of: " + name + ", " + enclosingClass.getName() + ", " + returnType);
this.memberView = null; // ??? should be okay, since constructed ones aren't woven into
this.accessFlags = accessFlags;
this.returnType = returnType;
this.name = name;
this.argumentTypes = paramTypes;
//this.argumentNames = Utility.makeArgNames(paramTypes.length);
this.declaredExceptions = declaredExceptions;
if (!Modifier.isAbstract(accessFlags)) {
body = new InstructionList();
setMaxLocals(calculateMaxLocals());
} else {
body = null;
}
this.attributes = new Attribute[0];
this.enclosingClass = enclosingClass;
assertGoodBody();
}
private int calculateMaxLocals() {
int ret = 0;
if (!Modifier.isStatic(accessFlags)) ret++;
for (int i = 0, len = argumentTypes.length; i < len; i++) {
ret += argumentTypes[i].getSize();
}
return ret;
}
private Method savedMethod = null;
// build from an existing method, lazy build saves most work for initialization
public LazyMethodGen(Method m, LazyClassGen enclosingClass) {
savedMethod = m;
this.enclosingClass = enclosingClass;
if (!(m.isAbstract() || m.isNative()) && m.getCode() == null) {
throw new RuntimeException("bad non-abstract method with no code: " + m + " on " + enclosingClass);
}
if ((m.isAbstract() || m.isNative()) && m.getCode() != null) {
throw new RuntimeException("bad abstract method with code: " + m + " on " + enclosingClass);
}
this.memberView = new BcelMethod(enclosingClass.getBcelObjectType(), m);
this.accessFlags = m.getAccessFlags();
this.name = m.getName();
}
private void initialize() {
if (returnType != null) return;
//System.err.println("initializing: " + getName() + ", " + enclosingClass.getName() + ", " + returnType + ", " + savedMethod);
MethodGen gen = new MethodGen(savedMethod, enclosingClass.getName(), enclosingClass.getConstantPoolGen());
this.returnType = gen.getReturnType();
this.argumentTypes = gen.getArgumentTypes();
this.declaredExceptions = gen.getExceptions();
this.attributes = gen.getAttributes();
this.maxLocals = gen.getMaxLocals();
// this.returnType = BcelWorld.makeBcelType(memberView.getReturnType());
// this.argumentTypes = BcelWorld.makeBcelTypes(memberView.getParameterTypes());
//
// this.declaredExceptions = TypeX.getNames(memberView.getExceptions()); //gen.getExceptions();
// this.attributes = new Attribute[0]; //gen.getAttributes();
// this.maxLocals = savedMethod.getCode().getMaxLocals();
if (gen.isAbstract() || gen.isNative()) {
body = null;
} else {
//body = new InstructionList(savedMethod.getCode().getCode());
body = gen.getInstructionList();
unpackHandlers(gen);
unpackLineNumbers(gen);
unpackLocals(gen);
}
assertGoodBody();
//System.err.println("initialized: " + this.getClassName() + "." + this.getName());
}
// XXX we're relying on the javac promise I've just made up that we won't have an early exception
// in the list mask a later exception: That is, for two exceptions E and F,
// if E preceeds F, then either E \cup F = {}, or E \nonstrictsubset F. So when we add F,
// we add it on the _OUTSIDE_ of any handlers that share starts or ends with it.
// with that in mind, we merrily go adding ranges for exceptions.
private void unpackHandlers(MethodGen gen) {
CodeExceptionGen[] exns = gen.getExceptionHandlers();
if (exns != null) {
int len = exns.length;
if (len > 0) hasExceptionHandlers = true;
int priority = len - 1;
for (int i = 0; i < len; i++, priority--) {
CodeExceptionGen exn = exns[i];
InstructionHandle start =
Range.genStart(
body,
getOutermostExceptionStart(exn.getStartPC()));
InstructionHandle end = Range.genEnd(body, getOutermostExceptionEnd(exn.getEndPC()));
// this doesn't necessarily handle overlapping correctly!!!
ExceptionRange er =
new ExceptionRange(
body,
exn.getCatchType() == null
? null
: BcelWorld.fromBcel(exn.getCatchType()),
priority);
er.associateWithTargets(start, end, exn.getHandlerPC());
exn.setStartPC(null); // also removes from target
exn.setEndPC(null); // also removes from target
exn.setHandlerPC(null); // also removes from target
}
gen.removeExceptionHandlers();
}
}
private InstructionHandle getOutermostExceptionStart(InstructionHandle ih) {
while (true) {
if (ExceptionRange.isExceptionStart(ih.getPrev())) {
ih = ih.getPrev();
} else {
return ih;
}
}
}
private InstructionHandle getOutermostExceptionEnd(InstructionHandle ih) {
while (true) {
if (ExceptionRange.isExceptionEnd(ih.getNext())) {
ih = ih.getNext();
} else {
return ih;
}
}
}
private void unpackLineNumbers(MethodGen gen) {
LineNumberTag lr = null;
for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) {
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters != null) {
for (int i = targeters.length - 1; i >= 0; i--) {
InstructionTargeter targeter = targeters[i];
if (targeter instanceof LineNumberGen) {
LineNumberGen lng = (LineNumberGen) targeter;
lng.updateTarget(ih, null);
int lineNumber = lng.getSourceLine();
if (highestLineNumber < lineNumber) highestLineNumber = lineNumber;
lr = new LineNumberTag(lineNumber);
}
}
}
if (lr != null) {
ih.addTargeter(lr);
}
}
gen.removeLineNumbers();
}
private void unpackLocals(MethodGen gen) {
Set locals = new HashSet();
for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) {
InstructionTargeter[] targeters = ih.getTargeters();
List ends = new ArrayList(0);
if (targeters != null) {
for (int i = targeters.length - 1; i >= 0; i--) {
InstructionTargeter targeter = targeters[i];
if (targeter instanceof LocalVariableGen) {
LocalVariableGen lng = (LocalVariableGen) targeter;
LocalVariableTag lr = new LocalVariableTag(BcelWorld.fromBcel(lng.getType()), lng.getName(), lng.getIndex());
if (lng.getStart() == ih) {
locals.add(lr);
} else {
ends.add(lr);
}
}
}
}
for (Iterator i = locals.iterator(); i.hasNext(); ) {
ih.addTargeter((LocalVariableTag) i.next());
}
locals.removeAll(ends);
}
gen.removeLocalVariables();
}
// ===============
public int allocateLocal(Type type) {
return allocateLocal(type.getSize());
}
public int allocateLocal(int slots) {
int max = getMaxLocals();
setMaxLocals(max + slots);
return max;
}
public Method getMethod() {
if (savedMethod != null) return savedMethod; //??? this relies on gentle treatment of constant pool
try {
MethodGen gen = pack();
return gen.getMethod();
} catch (ClassGenException e) {
enclosingClass.getBcelObjectType().getResolvedTypeX().getWorld().showMessage(
IMessage.ERROR,
WeaverMessages.format(WeaverMessages.PROBLEM_GENERATING_METHOD,
this.getClassName(),
this.getName(),
e.getMessage()),
this.getMemberView() == null ? null : this.getMemberView().getSourceLocation(), null);
// throw e; PR 70201.... let the normal problem reporting infrastructure deal with this rather than crashing.
body = null;
MethodGen gen = pack();
return gen.getMethod();
}
}
public void markAsChanged() {
initialize();
savedMethod = null;
}
// =============================
public String toString() {
return toLongString();
}
public String toShortString() {
String access = org.apache.bcel.classfile.Utility.accessToString(getAccessFlags());
StringBuffer buf = new StringBuffer();
if (!access.equals("")) {
buf.append(access);
buf.append(" ");
}
buf.append(
org.apache.bcel.classfile.Utility.signatureToString(
getReturnType().getSignature(),
true));
buf.append(" ");
buf.append(getName());
buf.append("(");
{
int len = argumentTypes.length;
if (len > 0) {
buf.append(
org.apache.bcel.classfile.Utility.signatureToString(
argumentTypes[0].getSignature(),
true));
for (int i = 1; i < argumentTypes.length; i++) {
buf.append(", ");
buf.append(
org.apache.bcel.classfile.Utility.signatureToString(
argumentTypes[i].getSignature(),
true));
}
}
}
buf.append(")");
{
int len = declaredExceptions != null ? declaredExceptions.length : 0;
if (len > 0) {
buf.append(" throws ");
buf.append(declaredExceptions[0]);
for (int i = 1; i < declaredExceptions.length; i++) {
buf.append(", ");
buf.append(declaredExceptions[i]);
}
}
}
return buf.toString();
}
public String toLongString() {
ByteArrayOutputStream s = new ByteArrayOutputStream();
print(new PrintStream(s));
return new String(s.toByteArray());
}
public void print() {
print(System.out);
}
public void print(PrintStream out) {
out.print(" " + toShortString());
printAspectAttributes(out);
InstructionList body = getBody();
if (body == null) {
out.println(";");
return;
}
out.println(":");
new BodyPrinter(out).run();
out.println(" end " + toShortString());
}
private void printAspectAttributes(PrintStream out) {
ISourceContext context = null;
if (enclosingClass != null && enclosingClass.getType() != null) {
context = enclosingClass.getType().getSourceContext();
}
List as = BcelAttributes.readAjAttributes(attributes, context);
if (! as.isEmpty()) {
out.println(" " + as.get(0)); // XXX assuming exactly one attribute, munger...
}
}
private class BodyPrinter {
Map prefixMap = new HashMap();
Map suffixMap = new HashMap();
Map labelMap = new HashMap();
InstructionList body;
PrintStream out;
ConstantPool pool;
List ranges;
BodyPrinter(PrintStream out) {
this.pool = enclosingClass.getConstantPoolGen().getConstantPool();
this.body = getBody();
this.out = out;
}
void run() {
//killNops();
assignLabels();
print();
}
// label assignment
void assignLabels() {
LinkedList exnTable = new LinkedList();
String pendingLabel = null;
// boolean hasPendingTargeters = false;
int lcounter = 0;
for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) {
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters != null) {
for (int i = targeters.length - 1; i >= 0; i--) {
InstructionTargeter t = targeters[i];
if (t instanceof ExceptionRange) {
// assert isRangeHandle(h);
ExceptionRange r = (ExceptionRange) t;
if (r.getStart() == ih) {
insertHandler(r, exnTable);
}
} else if (t instanceof BranchInstruction) {
if (pendingLabel == null) {
pendingLabel = "L" + lcounter++;
}
} else {
// assert isRangeHandle(h)
}
}
}
if (pendingLabel != null) {
labelMap.put(ih, pendingLabel);
if (! Range.isRangeHandle(ih)) {
pendingLabel = null;
}
}
}
int ecounter = 0;
for (Iterator i = exnTable.iterator(); i.hasNext();) {
ExceptionRange er = (ExceptionRange) i.next();
String exceptionLabel = "E" + ecounter++;
labelMap.put(Range.getRealStart(er.getHandler()), exceptionLabel);
labelMap.put(er.getHandler(), exceptionLabel);
}
}
// printing
void print() {
int depth = 0;
int currLine = -1;
bodyPrint:
for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) {
if (Range.isRangeHandle(ih)) {
Range r = Range.getRange(ih);
// don't print empty ranges, that is, ranges who contain no actual instructions
for (InstructionHandle xx = r.getStart(); Range.isRangeHandle(xx); xx = xx.getNext()) {
if (xx == r.getEnd()) continue bodyPrint;
}
// doesn't handle nested: if (r.getStart().getNext() == r.getEnd()) continue;
if (r.getStart() == ih) {
printRangeString(r, depth++);
} else {
if (r.getEnd() != ih) throw new RuntimeException("bad");
printRangeString(r, --depth);
}
} else {
printInstruction(ih, depth);
int line = getLineNumber(ih, currLine);
if (line != currLine) {
currLine = line;
out.println(" (line " + line + ")");
} else {
out.println();
}
}
}
}
void printRangeString(Range r, int depth) {
printDepth(depth);
out.println(getRangeString(r, labelMap));
}
String getRangeString(Range r, Map labelMap) {
if (r instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) r;
return er.toString() + " -> " + labelMap.get(er.getHandler());
//
// + " PRI " + er.getPriority();
} else {
return r.toString();
}
}
void printDepth(int depth) {
pad(BODY_INDENT);
while (depth > 0) {
out.print("| ");
depth--;
}
}
void printLabel(String s, int depth) {
int space = Math.max(CODE_INDENT - depth * 2, 0);
if (s == null) {
pad(space);
} else {
space = Math.max(space - (s.length() + 2), 0);
pad(space);
out.print(s);
out.print(": ");
}
}
void printInstruction(InstructionHandle h, int depth) {
printDepth(depth);
printLabel((String) labelMap.get(h), depth);
Instruction inst = h.getInstruction();
if (inst instanceof CPInstruction) {
CPInstruction cpinst = (CPInstruction) inst;
out.print(Constants.OPCODE_NAMES[cpinst.getOpcode()].toUpperCase());
out.print(" ");
out.print(pool.constantToString(pool.getConstant(cpinst.getIndex())));
} else if (inst instanceof Select) {
Select sinst = (Select) inst;
out.println(Constants.OPCODE_NAMES[sinst.getOpcode()].toUpperCase());
int[] matches = sinst.getMatchs();
InstructionHandle[] targets = sinst.getTargets();
InstructionHandle defaultTarget = sinst.getTarget();
for (int i = 0, len = matches.length; i < len; i++) {
printDepth(depth);
printLabel(null, depth);
out.print(" ");
out.print(matches[i]);
out.print(": \t");
out.println(labelMap.get(targets[i]));
}
printDepth(depth);
printLabel(null, depth);
out.print(" ");
out.print("default: \t");
out.print(labelMap.get(defaultTarget));
} else if (inst instanceof BranchInstruction) {
BranchInstruction brinst = (BranchInstruction) inst;
out.print(Constants.OPCODE_NAMES[brinst.getOpcode()].toUpperCase());
out.print(" ");
out.print(labelMap.get(brinst.getTarget()));
} else if (inst instanceof LocalVariableInstruction) {
LocalVariableInstruction lvinst = (LocalVariableInstruction) inst;
out.print(inst.toString(false).toUpperCase());
int index = lvinst.getIndex();
LocalVariableTag tag = getLocalVariableTag(h, index);
if (tag != null) {
out.print(" // ");
out.print(tag.getType());
out.print(" ");
out.print(tag.getName());
}
} else {
out.print(inst.toString(false).toUpperCase());
}
}
static final int BODY_INDENT = 4;
static final int CODE_INDENT = 16;
void pad(int size) {
for (int i = 0; i < size; i++) {
out.print(" ");
}
}
}
static LocalVariableTag getLocalVariableTag(
InstructionHandle ih,
int index)
{
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters == null) return null;
for (int i = targeters.length - 1; i >= 0; i--) {
InstructionTargeter t = targeters[i];
if (t instanceof LocalVariableTag) {
LocalVariableTag lvt = (LocalVariableTag) t;
if (lvt.getSlot() == index) return lvt;
}
}
return null;
}
static int getLineNumber(
InstructionHandle ih,
int prevLine)
{
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters == null) return prevLine;
for (int i = targeters.length - 1; i >= 0; i--) {
InstructionTargeter t = targeters[i];
if (t instanceof LineNumberTag) {
return ((LineNumberTag)t).getLineNumber();
}
}
return prevLine;
}
public boolean isStatic() {
return Modifier.isStatic(getAccessFlags());
}
public boolean isAbstract() {
return Modifier.isAbstract(getAccessFlags());
}
public void addExceptionHandler(
InstructionHandle start,
InstructionHandle end,
InstructionHandle handlerStart,
ObjectType catchType,
boolean highPriority) {
InstructionHandle start1 = Range.genStart(body, start);
InstructionHandle end1 = Range.genEnd(body, end);
ExceptionRange er =
new ExceptionRange(body, BcelWorld.fromBcel(catchType), highPriority);
er.associateWithTargets(start1, end1, handlerStart);
}
public int getAccessFlags() {
return accessFlags;
}
public Type[] getArgumentTypes() {
initialize();
return argumentTypes;
}
public LazyClassGen getEnclosingClass() {
return enclosingClass;
}
public int getMaxLocals() {
return maxLocals;
}
public String getName() {
return name;
}
public Type getReturnType() {
initialize();
return returnType;
}
public void setMaxLocals(int maxLocals) {
this.maxLocals = maxLocals;
}
public InstructionList getBody() {
markAsChanged();
return body;
}
public boolean hasBody() {
if (savedMethod != null) return savedMethod.getCode() != null;
return body != null;
}
public Attribute[] getAttributes() {
return attributes;
}
public String[] getDeclaredExceptions() {
return declaredExceptions;
}
public String getClassName() {
return enclosingClass.getName();
}
// ---- packing!
public MethodGen pack() {
//killNops();
MethodGen gen =
new MethodGen(
getAccessFlags(),
getReturnType(),
getArgumentTypes(),
null, //getArgumentNames(),
getName(),
getEnclosingClass().getName(),
new InstructionList(),
getEnclosingClass().getConstantPoolGen());
for (int i = 0, len = declaredExceptions.length; i < len; i++) {
gen.addException(declaredExceptions[i]);
}
for (int i = 0, len = attributes.length; i < len; i++) {
gen.addAttribute(attributes[i]);
}
if (isSynthetic) {
ConstantPoolGen cpg = gen.getConstantPool();
int index = cpg.addUtf8("Synthetic");
gen.addAttribute(new Synthetic(index, 0, new byte[0], cpg.getConstantPool()));
}
if (hasBody()) {
packBody(gen);
gen.setMaxLocals();
gen.setMaxStack();
} else {
gen.setInstructionList(null);
}
return gen;
}
public void makeSynthetic() {
isSynthetic = true;
}
/** fill the newly created method gen with our body,
* inspired by InstructionList.copy()
*/
public void packBody(MethodGen gen) {
HashMap map = new HashMap();
InstructionList fresh = gen.getInstructionList();
/* Make copies of all instructions, append them to the new list
* and associate old instruction references with the new ones, i.e.,
* a 1:1 mapping.
*/
for (InstructionHandle ih = getBody().getStart(); ih != null; ih = ih.getNext()) {
if (Range.isRangeHandle(ih)) {
continue;
}
Instruction i = ih.getInstruction();
Instruction c = Utility.copyInstruction(i);
if (c instanceof BranchInstruction)
map.put(ih, fresh.append((BranchInstruction) c));
else
map.put(ih, fresh.append(c));
}
// at this point, no rangeHandles are in fresh. Let's use that...
/* Update branch targets and insert various attributes.
* Insert our exceptionHandlers
* into a sorted list, so they can be added in order later.
*/
InstructionHandle ih = getBody().getStart();
InstructionHandle jh = fresh.getStart();
LinkedList exnList = new LinkedList();
// map from localvariabletag to instruction handle
Map localVariableStarts = new HashMap();
Map localVariableEnds = new HashMap();
int currLine = -1;
while (ih != null) {
if (map.get(ih) == null) {
// we're a range instruction
Range r = Range.getRange(ih);
if (r instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) r;
if (er.getStart() == ih) {
//System.err.println("er " + er);
if (!er.isEmpty()){
// order is important, insert handlers in order of start
insertHandler(er, exnList);
}
}
} else {
// we must be a shadow range or something equally useless,
// so forget about doing anything
}
// just increment ih.
ih = ih.getNext();
} else {
// assert map.get(ih) == jh
Instruction i = ih.getInstruction();
Instruction j = jh.getInstruction();
if (i instanceof BranchInstruction) {
BranchInstruction bi = (BranchInstruction) i;
BranchInstruction bj = (BranchInstruction) j;
InstructionHandle itarget = bi.getTarget(); // old target
// try {
// New target is in hash map
bj.setTarget(remap(itarget, map));
// } catch (NullPointerException e) {
// print();
// System.out.println("Was trying to remap " + bi);
// System.out.println("who's target was supposedly " + itarget);
// throw e;
// }
if (bi instanceof Select) {
// Either LOOKUPSWITCH or TABLESWITCH
InstructionHandle[] itargets = ((Select) bi).getTargets();
InstructionHandle[] jtargets = ((Select) bj).getTargets();
for (int k = itargets.length - 1; k >= 0; k--) {
// Update all targets
jtargets[k] = remap(itargets[k], map);
jtargets[k].addTargeter(bj);
}
}
}
// now deal with line numbers
// and store up info for local variables
InstructionTargeter[] targeters = ih.getTargeters();
int lineNumberOffset =
(fromFilename == null)
? 0
: getEnclosingClass().getSourceDebugExtensionOffset(fromFilename);
if (targeters != null) {
for (int k = targeters.length - 1; k >= 0; k--) {
InstructionTargeter targeter = targeters[k];
if (targeter instanceof LineNumberTag) {
int line = ((LineNumberTag)targeter).getLineNumber();
if (line != currLine) {
gen.addLineNumber(jh, line + lineNumberOffset);
currLine = line;
}
} else if (targeter instanceof LocalVariableTag) {
LocalVariableTag lvt = (LocalVariableTag) targeter;
if (localVariableStarts.get(lvt) == null) {
localVariableStarts.put(lvt, jh);
}
localVariableEnds.put(lvt, jh);
}
}
}
// now continue
ih = ih.getNext();
jh = jh.getNext();
}
}
// now add exception handlers
for (Iterator iter = exnList.iterator(); iter.hasNext();) {
ExceptionRange r = (ExceptionRange) iter.next();
if (r.isEmpty()) continue;
gen.addExceptionHandler(
remap(r.getRealStart(), map),
remap(r.getRealEnd(), map),
remap(r.getHandler(), map),
(r.getCatchType() == null)
? null
: (ObjectType) BcelWorld.makeBcelType(r.getCatchType()));
}
// now add local variables
gen.removeLocalVariables();
// this next iteration _might_ be overkill, but we had problems with
// bcel before with duplicate local variables. Now that we're patching
// bcel we should be able to do without it if we're paranoid enough
// through the rest of the compiler.
Map duplicatedLocalMap = new HashMap();
List keys = new ArrayList();
keys.addAll(localVariableStarts.keySet());
for (Iterator iter = keys.iterator(); iter.hasNext(); ) {
LocalVariableTag tag = (LocalVariableTag) iter.next();
// have we already added one with the same slot number and start location?
// if so, just continue.
InstructionHandle start = (InstructionHandle) localVariableStarts.get(tag);
Set slots = (Set) duplicatedLocalMap.get(start);
if (slots == null) {
slots = new HashSet();
duplicatedLocalMap.put(start, slots);
}
if (slots.contains(new Integer(tag.getSlot()))) {
// we already have a var starting at this tag with this slot
continue;
}
slots.add(new Integer(tag.getSlot()));
gen.addLocalVariable(
tag.getName(),
BcelWorld.makeBcelType(tag.getType()),
tag.getSlot(),
(InstructionHandle) localVariableStarts.get(tag),
(InstructionHandle) localVariableEnds.get(tag));
}
}
/** This proedure should not currently be used.
*/
// public void killNops() {
// InstructionHandle curr = body.getStart();
// while (true) {
// if (curr == null) break;
// InstructionHandle next = curr.getNext();
// if (curr.getInstruction() instanceof NOP) {
// InstructionTargeter[] targeters = curr.getTargeters();
// if (targeters != null) {
// for (int i = 0, len = targeters.length; i < len; i++) {
// InstructionTargeter targeter = targeters[i];
// targeter.updateTarget(curr, next);
// }
// }
// try {
// body.delete(curr);
// } catch (TargetLostException e) {
// }
// }
// curr = next;
// }
// }
private static InstructionHandle remap(InstructionHandle ih, Map map) {
while (true) {
Object ret = map.get(ih);
if (ret == null) {
ih = ih.getNext();
} else {
return (InstructionHandle) ret;
}
}
}
// exception ordering.
// What we should be doing is dealing with priority inversions way earlier than we are
// and counting on the tree structure. In which case, the below code is in fact right.
// XXX THIS COMMENT BELOW IS CURRENTLY WRONG.
// An exception A preceeds an exception B in the exception table iff:
// * A and B were in the original method, and A preceeded B in the original exception table
// * If A has a higher priority than B, than it preceeds B.
// * If A and B have the same priority, then the one whose START happens EARLIEST has LEAST priority.
// in short, the outermost exception has least priority.
// we implement this with a LinkedList. We could possibly implement this with a java.util.SortedSet,
// but I don't trust the only implementation, TreeSet, to do the right thing.
/* private */ static void insertHandler(ExceptionRange fresh, LinkedList l) {
// for (ListIterator iter = l.listIterator(); iter.hasNext();) {
// ExceptionRange r = (ExceptionRange) iter.next();
// if (fresh.getPriority() >= r.getPriority()) {
// iter.previous();
// iter.add(fresh);
// return;
// }
// }
l.add(0, fresh);
}
public boolean isPrivate() {
return Modifier.isPrivate(getAccessFlags());
}
// ----
/** A good body is a body with the following properties:
*
* <ul>
* <li> For each branch instruction S in body, target T of S is in body.
* <li> For each branch instruction S in body, target T of S has S as a targeter.
* <li> For each instruction T in body, for each branch instruction S that is a
* targeter of T, S is in body.
* <li> For each non-range-handle instruction T in body, for each instruction S
* that is a targeter of T, S is
* either a branch instruction, an exception range or a tag
* <li> For each range-handle instruction T in body, there is exactly one targeter S
* that is a range.
* <li> For each range-handle instruction T in body, the range R targeting T is in body.
* <li> For each instruction T in body, for each exception range R targeting T, R is
* in body.
* <li> For each exception range R in body, let T := R.handler. T is in body, and R is one
* of T's targeters
* <li> All ranges are properly nested: For all ranges Q and R, if Q.start preceeds
* R.start, then R.end preceeds Q.end.
* </ul>
*
* Where the shorthand "R is in body" means "R.start is in body, R.end is in body, and
* any InstructionHandle stored in a field of R (such as an exception handle) is in body".
*/
public void assertGoodBody() {
if (true) return; // only enable for debugging, consider using cheaper toString()
assertGoodBody(getBody(), toString()); //definingType.getNameAsIdentifier() + "." + getName()); //toString());
}
public static void assertGoodBody(InstructionList il, String from) {
if (true) return; // only to be enabled for debugging
if (il == null) return;
Set body = new HashSet();
Stack ranges = new Stack();
for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) {
body.add(ih);
if (ih.getInstruction() instanceof BranchInstruction) {
body.add(ih.getInstruction());
}
}
for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) {
assertGoodHandle(ih, body, ranges, from);
InstructionTargeter[] ts = ih.getTargeters();
if (ts != null) {
for (int i = ts.length - 1; i >= 0; i--) {
assertGoodTargeter(ts[i], ih, body, from);
}
}
}
}
private static void assertGoodHandle(InstructionHandle ih, Set body, Stack ranges, String from) {
Instruction inst = ih.getInstruction();
if ((inst instanceof BranchInstruction) ^ (ih instanceof BranchHandle)) {
throw new BCException("bad instruction/handle pair in " + from);
}
if (Range.isRangeHandle(ih)) {
assertGoodRangeHandle(ih, body, ranges, from);
} else if (inst instanceof BranchInstruction) {
assertGoodBranchInstruction((BranchHandle) ih, (BranchInstruction) inst, body, ranges, from);
}
}
private static void assertGoodBranchInstruction(
BranchHandle ih,
BranchInstruction inst,
Set body,
Stack ranges,
String from)
{
if (ih.getTarget() != inst.getTarget()) {
throw new BCException("bad branch instruction/handle pair in " + from);
}
InstructionHandle target = ih.getTarget();
assertInBody(target, body, from);
assertTargetedBy(target, inst, from);
if (inst instanceof Select) {
Select sel = (Select) inst;
InstructionHandle[] itargets = sel.getTargets();
for (int k = itargets.length - 1; k >= 0; k--) {
assertInBody(itargets[k], body, from);
assertTargetedBy(itargets[k], inst, from);
}
}
}
/** ih is an InstructionHandle or a BranchInstruction */
private static void assertInBody(Object ih, Set body, String from) {
if (! body.contains(ih)) throw new BCException("thing not in body in " + from);
}
private static void assertGoodRangeHandle(InstructionHandle ih, Set body, Stack ranges, String from) {
Range r = getRangeAndAssertExactlyOne(ih, from);
assertGoodRange(r, body, from);
if (r.getStart() == ih) {
ranges.push(r);
} else if (r.getEnd() == ih) {
if (ranges.peek() != r) throw new BCException("bad range inclusion in " + from);
ranges.pop();
}
}
private static void assertGoodRange(Range r, Set body, String from) {
assertInBody(r.getStart(), body, from);
assertRangeHandle(r.getStart(), from);
assertTargetedBy(r.getStart(), r, from);
assertInBody(r.getEnd(), body, from);
assertRangeHandle(r.getEnd(), from);
assertTargetedBy(r.getEnd(), r, from);
if (r instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) r;
assertInBody(er.getHandler(), body, from);
assertTargetedBy(er.getHandler(), r, from);
}
}
private static void assertRangeHandle(InstructionHandle ih, String from) {
if (! Range.isRangeHandle(ih)) throw new BCException("bad range handle " + ih + " in " + from);
}
private static void assertTargetedBy(
InstructionHandle target,
InstructionTargeter targeter,
String from)
{
InstructionTargeter[] ts = target.getTargeters();
if (ts == null) throw new BCException("bad targeting relationship in " + from);
for (int i = ts.length - 1; i >= 0; i--) {
if (ts[i] == targeter) return;
}
throw new RuntimeException("bad targeting relationship in " + from);
}
private static void assertTargets(InstructionTargeter targeter, InstructionHandle target, String from) {
if (targeter instanceof Range) {
Range r = (Range) targeter;
if (r.getStart() == target || r.getEnd() == target) return;
if (r instanceof ExceptionRange) {
if (((ExceptionRange)r).getHandler() == target) return;
}
} else if (targeter instanceof BranchInstruction) {
BranchInstruction bi = (BranchInstruction) targeter;
if (bi.getTarget() == target) return;
if (targeter instanceof Select) {
Select sel = (Select) targeter;
InstructionHandle[] itargets = sel.getTargets();
for (int k = itargets.length - 1; k >= 0; k--) {
if (itargets[k] == target) return;
}
}
} else if (targeter instanceof Tag) {
return;
}
throw new BCException(targeter + " doesn't target " + target + " in " + from );
}
private static Range getRangeAndAssertExactlyOne(InstructionHandle ih, String from) {
Range ret = null;
InstructionTargeter[] ts = ih.getTargeters();
if (ts == null) throw new BCException("range handle with no range in " + from);
for (int i = ts.length - 1; i >= 0; i--) {
if (ts[i] instanceof Range) {
if (ret != null) throw new BCException("range handle with multiple ranges in " + from);
ret = (Range) ts[i];
}
}
if (ret == null) throw new BCException("range handle with no range in " + from);
return ret;
}
private static void assertGoodTargeter(
InstructionTargeter t,
InstructionHandle ih,
Set body,
String from)
{
assertTargets(t, ih, from);
if (t instanceof Range) {
assertGoodRange((Range) t, body, from);
} else if (t instanceof BranchInstruction) {
assertInBody(t, body, from);
}
}
// ----
boolean isAdviceMethod() {
return memberView.getAssociatedShadowMunger() != null;
}
boolean isAjSynthetic() {
if (memberView == null) return true;
return memberView.isAjSynthetic();
}
public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() {
//if (memberView == null) return null;
return memberView.getEffectiveSignature();
}
public String getSignature() {
if (memberView!=null) return memberView.getSignature();
return Member.typesToSignature(BcelWorld.fromBcel(getReturnType()),
BcelWorld.fromBcel(getArgumentTypes()));
}
public BcelMethod getMemberView() {
return memberView;
}
public void forcePublic() {
markAsChanged();
accessFlags = Utility.makePublic(accessFlags);
}
public boolean getCanInline() {
return canInline;
}
public void setCanInline(boolean canInline) {
this.canInline = canInline;
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/Range.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.util.Map;
import org.apache.bcel.generic.IMPDEP1;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.InstructionTargeter;
import org.aspectj.weaver.BCException;
abstract class Range implements InstructionTargeter {
protected InstructionList body;
protected InstructionHandle start;
protected InstructionHandle end;
// ---- initialization
protected Range(InstructionList il) {
this.body = il;
}
// ----
final InstructionList getBody() {
return body;
}
final InstructionHandle getStart() {
return start;
}
final InstructionHandle getEnd() {
return end;
}
// ----
boolean isEmpty() {
InstructionHandle ih = start;
//System.err.println(" looking for " + end);
while (ih != end) {
//System.err.println(" ih " + ih);
if (! Range.isRangeHandle(ih)) return false;
ih = ih.getNext();
}
return true;
}
static InstructionHandle getRealStart(InstructionHandle ih) {
while (Range.isRangeHandle(ih)) {
ih = ih.getNext();
}
return ih;
}
InstructionHandle getRealStart() {
return getRealStart(start);
}
static InstructionHandle getRealEnd(InstructionHandle ih) {
while (Range.isRangeHandle(ih)) {
ih = ih.getPrev();
}
return ih;
}
InstructionHandle getRealEnd() {
return getRealEnd(end);
}
InstructionHandle getRealNext() {
return getRealStart(end);
}
static InstructionHandle getRealPrev(InstructionHandle ih) {
InstructionHandle ret = ih.getPrev();
while (isRangeHandle(ret)) {
ret = ret.getPrev();
}
return ret;
}
// ----
InstructionHandle insert(Instruction i, Where where) {
InstructionList il = new InstructionList();
InstructionHandle ret = il.insert(i);
insert(il, where);
return ret;
}
void insert(InstructionList freshIl, Where where) {
InstructionHandle h;
if (where == InsideBefore || where == OutsideBefore) {
h = getStart();
} else {
h = getEnd();
}
if (where == InsideBefore || where == OutsideAfter) {
body.append(h, freshIl);
} else {
InstructionHandle newStart = body.insert(h, freshIl);
if (where == OutsideBefore) {
// XXX this is slow. There's a better design than this. We should
// never have to retarget branches apart from the creation of ranges.
// basically, we should never weave OutsideBefore.
BcelShadow.retargetAllBranches(h, newStart);
}
}
}
InstructionHandle append(Instruction i) {
return insert(i, InsideAfter);
}
void append(InstructionList i) {
insert(i, InsideAfter);
}
static InstructionHandle remap(InstructionHandle h, Map m) {
return (InstructionHandle) m.get(h);
}
private static void setLineNumberFromNext(InstructionHandle ih) {
int lineNumber = Utility.getSourceLine(ih.getNext());
if (lineNumber != -1) {
Utility.setSourceLine(ih, lineNumber);
}
}
static InstructionHandle genStart(InstructionList body) {
InstructionHandle ih = body.insert(Range.RANGEINSTRUCTION);
setLineNumberFromNext(ih);
return ih;
}
static InstructionHandle genEnd(InstructionList body) {
return body.append(Range.RANGEINSTRUCTION);
}
static InstructionHandle genStart(InstructionList body, InstructionHandle ih) {
if (ih == null) return genStart(body);
InstructionHandle freshIh = body.insert(ih, Range.RANGEINSTRUCTION);
setLineNumberFromNext(freshIh);
return freshIh;
}
static InstructionHandle genEnd(InstructionList body, InstructionHandle ih) {
if (ih == null) return genEnd(body);
return body.append(ih, Range.RANGEINSTRUCTION);
}
// -----
public boolean containsTarget(InstructionHandle ih) {
return false;
}
public final void updateTarget(InstructionHandle old_ih, InstructionHandle new_ih) {
throw new RuntimeException("Ranges must be updated with an enclosing instructionList");
}
protected void updateTarget(
InstructionHandle old_ih,
InstructionHandle new_ih,
InstructionList new_il)
{
old_ih.removeTargeter(this);
if (new_ih != null)
new_ih.addTargeter(this);
body = new_il;
if (old_ih == start) {
start = new_ih;
}
if (old_ih == end) {
end = new_ih;
}
}
public static final boolean isRangeHandle(InstructionHandle ih) {
if (ih == null) return false;
return ih.getInstruction() == Range.RANGEINSTRUCTION;
}
protected static final Range getRange(InstructionHandle ih) {
// assert isRangeHandle(ih)
Range ret = null;
InstructionTargeter[] targeters = ih.getTargeters();
for (int i = targeters.length - 1; i >= 0; i--) {
if (targeters[i] instanceof Range) {
Range r = (Range) targeters[i];
if (r.getStart() != ih && r.getEnd() != ih) continue;
if (ret != null) throw new BCException("multiple ranges on same range handle: " + ret + ", " + targeters[i]);
ret = (Range) targeters[i];
}
}
if (ret == null) throw new BCException("shouldn't happen");
return ret;
}
// ----
static final Where InsideBefore = new Where("insideBefore");
static final Where InsideAfter = new Where("insideAfter");
static final Where OutsideBefore = new Where("outsideBefore");
static final Where OutsideAfter = new Where("outsideAfter");
// ---- constants
// note that this is STUPIDLY copied by Instruction.copy(), so don't do that.
public static final Instruction RANGEINSTRUCTION = new IMPDEP1();
// ----
static class Where {
private String name;
public Where(String name) { this.name = name; }
public String toString() { return name; }
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/ShadowRange.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import org.apache.bcel.generic.BranchInstruction;
import org.apache.bcel.generic.IndexedInstruction;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.InstructionTargeter;
import org.apache.bcel.generic.LocalVariableInstruction;
import org.apache.bcel.generic.RET;
import org.apache.bcel.generic.Select;
import org.apache.bcel.generic.TargetLostException;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Shadow;
final class ShadowRange extends Range {
private BcelShadow shadow;
// ---- initialization
/**
* After this constructor is called, this range is not well situated unless both
* {@link #associateWithTargets} and {@link #associateWithShadow} are called.
*/
public ShadowRange(InstructionList body) {
super(body);
}
protected void associateWithTargets(InstructionHandle start, InstructionHandle end) {
// assert body.contains(start) && body.contains(end);
this.start = start;
this.end = end;
start.addTargeter(this);
end.addTargeter(this);
}
public void associateWithShadow(BcelShadow shadow) {
this.shadow = shadow;
shadow.setRange(this);
}
// ----
public Shadow.Kind getKind() {
return shadow.getKind();
}
public String toString() {
return shadow.toString();
}
void extractInstructionsInto(LazyMethodGen freshMethod, IntMap remap, boolean addReturn) {
LazyMethodGen.assertGoodBody(getBody(), toString());
freshMethod.assertGoodBody();
InstructionList freshBody = freshMethod.getBody();
for (InstructionHandle oldIh = start.getNext(); oldIh != end; oldIh = oldIh.getNext()) {
// first we copy the instruction itself.
Instruction oldI = oldIh.getInstruction();
Instruction freshI = (oldI == RANGEINSTRUCTION) ? oldI : Utility.copyInstruction(oldI);
// Now we add it to the new instruction list.
InstructionHandle freshIh;
if (freshI instanceof BranchInstruction) {
//If it's a targeting instruction,
// update the target(s) to point to the new copy instead of the old copy.
BranchInstruction oldBranch = (BranchInstruction) oldI;
BranchInstruction freshBranch = (BranchInstruction) freshI;
InstructionHandle oldTarget = oldBranch.getTarget();
oldTarget.removeTargeter(oldBranch);
oldTarget.addTargeter(freshBranch);
if (freshBranch instanceof Select) {
Select oldSelect = (Select) oldI;
Select freshSelect = (Select) freshI;
InstructionHandle[] oldTargets = freshSelect.getTargets();
for (int k = oldTargets.length - 1; k >= 0; k--) {
oldTargets[k].removeTargeter(oldSelect);
oldTargets[k].addTargeter(freshSelect);
}
}
freshIh = freshBody.append(freshBranch);
} else {
freshIh = freshBody.append(freshI);
}
// if source comes before target:
// source <--> target
// --> [process: target.removeTargeter(source); target.addTargeter(sourcecopy)]
// source ---------\
// v
// sourcecopy <--> target
// --> [ process: sourcecopy.updateTarget(target, targetcopy) ]
// source ----> target
// sourcecopy <--> targetcopy
// if target comes before source
// target <--> source
// --> [process: source.updateTarget(target, targetcopy) ]
// target
// targetcopy <--> source
// --> [process: targetcopy.removeTargeter(source); targetcopy.addTargeter(sourcecopy)]
// target source
// v
// targetcopy <--> sourcecopy
// now deal with the old instruction's targeters. Update them all to point to us
// instead of the old instruction. We use updateTarget to do this. One goal is
// to make sure we remove all targeters from the old guy, so we can successfully
// delete it.
InstructionTargeter[] sources = oldIh.getTargeters();
if (sources != null) {
for (int j = sources.length - 1; j >= 0; j--) {
InstructionTargeter source = sources[j];
if (source instanceof LocalVariableTag) {
// XXX destroying local variable info
source.updateTarget(oldIh, null);
} else if (source instanceof Range) {
// exceptions and shadows are just moved
((Range)source).updateTarget(oldIh, freshIh, freshBody);
} else {
// line numbers can be shared,
// branches will be copied along with us.
source.updateTarget(oldIh, freshIh);
}
}
}
// we're now done with the old instruction entirely, and will ignore them through
// the rest of this loop. The only time we'll see them again is a second pass to
// delete them.
// now deal with local variable instructions. If this points to a remapped
// frame location, update the instruction's index. If this doesn't,
// do compaction/expansion: allocate a new local variable, and modify the remap
// to handle it. XXX We're doing the safe thing and allocating ALL these local variables
// as double-wides, in case the location is found to hold a double-wide later.
if (freshI instanceof LocalVariableInstruction || freshI instanceof RET) {
IndexedInstruction indexedI = (IndexedInstruction) freshI;
int oldIndex = indexedI.getIndex();
int freshIndex;
if (! remap.hasKey(oldIndex)) {
freshIndex = freshMethod.allocateLocal(2);
remap.put(oldIndex, freshIndex);
} else {
freshIndex = remap.get(oldIndex);
}
indexedI.setIndex(freshIndex);
}
// System.err.println("JUST COPIED: " + oldIh.getInstruction().toString(freshMethod.getEnclosingClass().getConstantPoolGen().getConstantPool())
// + " INTO " + freshIh.getInstruction().toString(freshMethod.getEnclosingClass().getConstantPoolGen().getConstantPool()));
}
// we've now copied out all the instructions.
// now delete the instructions... we've already taken care of the damn
// targets, but since TargetLostException is checked, we have to do this stuff.
try {
for (InstructionHandle oldIh = start.getNext(); oldIh != end; ) {
InstructionHandle next = oldIh.getNext();
body.delete(oldIh);
oldIh = next;
}
} catch (TargetLostException e) {
throw new BCException("shouldn't have gotten a target lost");
}
// now add the return, if one is warranted.
InstructionHandle ret = null;
if (addReturn) {
// we really should pull this out somewhere...
ret = freshBody.append(
InstructionFactory.createReturn(freshMethod.getReturnType()));
}
// and remap all the old targeters of the end handle of the range to the return.
InstructionTargeter[] ts = end.getTargeters();
if (ts != null) { // shouldn't be the case, but let's test for paranoia
for (int j = ts.length - 1; j >= 0; j--) {
InstructionTargeter t = ts[j];
if (t == this) continue;
if (! addReturn) {
throw new BCException("range has target, but we aren't adding a return");
} else {
t.updateTarget(end, ret);
}
}
}
LazyMethodGen.assertGoodBody(getBody(), toString());
freshMethod.assertGoodBody();
}
public BcelShadow getShadow() {
return shadow;
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/Tag.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionTargeter;
/** A tag is an instruction-targeter that doesn't bother remembering its target(s) */
abstract class Tag implements InstructionTargeter, Cloneable {
public Tag() {
}
// ---- from InstructionTargeter
public boolean containsTarget(InstructionHandle ih) {
return false;
}
public void updateTarget(InstructionHandle old_ih, InstructionHandle new_ih) {
old_ih.removeTargeter(this);
if (new_ih != null)
new_ih.addTargeter(this);
}
public Tag copy() {
try {
return (Tag)clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException("Sanity check, can't clone me");
}
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/UnwovenClassFile.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.bcel.classfile.JavaClass;
import org.aspectj.util.FileUtil;
public class UnwovenClassFile {
protected String filename;
protected byte[] bytes;
// protected JavaClass javaClass = null;
//protected byte[] writtenBytes = null;
protected List /* ChildClass */ writtenChildClasses = new ArrayList(0);
protected String className = null;
public UnwovenClassFile(String filename, byte[] bytes) {
this.filename = filename;
this.bytes = bytes;
}
public String getFilename() {
return filename;
}
public String makeInnerFileName(String innerName) {
String prefix = filename.substring(0, filename.length()-6); // strip the .class
return prefix + "$" + innerName + ".class";
}
public byte[] getBytes() {
// if (bytes == null) bytes = javaClass.getBytes();
return bytes;
}
public JavaClass getJavaClass() {
//XXX need to know when to make a new class and when not to
//XXX this is an important optimization
if (getBytes() == null) {
System.out.println("no bytes for: " + getFilename());
//Thread.currentThread().dumpStack();
Thread.dumpStack();
}
return Utility.makeJavaClass(filename, getBytes());
// if (javaClass == null) javaClass = Utility.makeJavaClass(filename, getBytes());
// return javaClass;
}
public boolean exists() {
return getBytes() != null;
}
public void writeUnchangedBytes() throws IOException {
writeWovenBytes(getBytes(), Collections.EMPTY_LIST);
}
public void writeWovenBytes(byte[] bytes, List childClasses) throws IOException {
writeChildClasses(childClasses);
//System.err.println("should write: " + getClassName());
//System.err.println("about to write: " + this + ", " + writtenBytes + ", ");
// + writtenBytes != null + " && " + unchanged(bytes, writtenBytes) );
//if (writtenBytes != null && unchanged(bytes, writtenBytes)) return;
//System.err.println(" actually wrote it");
BufferedOutputStream os = FileUtil.makeOutputStream(new File(filename));
os.write(bytes);
os.close();
//writtenBytes = bytes;
}
private void writeChildClasses(List childClasses) throws IOException {
//??? we only really need to delete writtenChildClasses whose
//??? names aren't in childClasses; however, it's unclear
//??? how much that will affect performance
deleteAllChildClasses();
childClasses.removeAll(writtenChildClasses); //XXX is this right
for (Iterator iter = childClasses.iterator(); iter.hasNext();) {
ChildClass childClass = (ChildClass) iter.next();
writeChildClassFile(childClass.name, childClass.bytes);
}
writtenChildClasses = childClasses;
}
private void writeChildClassFile(String innerName, byte[] bytes) throws IOException {
BufferedOutputStream os =
FileUtil.makeOutputStream(new File(makeInnerFileName(innerName)));
os.write(bytes);
os.close();
}
protected void deleteAllChildClasses() {
for (Iterator iter = writtenChildClasses.iterator(); iter.hasNext();) {
ChildClass childClass = (ChildClass) iter.next();
deleteChildClassFile(childClass.name);
}
}
protected void deleteChildClassFile(String innerName) {
File childClassFile = new File(makeInnerFileName(innerName));
childClassFile.delete();
}
/* private */ static boolean unchanged(byte[] b1, byte[] b2) {
int len = b1.length;
if (b2.length != len) return false;
for (int i=0; i < len; i++) {
if (b1[i] != b2[i]) return false;
}
return true;
}
public String getClassName() {
if (className == null) className = getJavaClass().getClassName();
return className;
}
public String toString() {
return "UnwovenClassFile(" + filename + ", " + getClassName() + ")";
}
/**
* delete not just this file, but any files in the same directory that
* were generated as a result of weaving it (e.g. for an around closure).
*/
public void deleteRealFile() throws IOException {
File victim = new File(filename);
String namePrefix = victim.getName();
namePrefix = namePrefix.substring(0,namePrefix.lastIndexOf('.'));
final String targetPrefix = namePrefix + "$Ajc";
File dir = victim.getParentFile();
if (dir != null) {
File[] weaverGenerated = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(targetPrefix);
}});
for (int i = 0; i < weaverGenerated.length; i++) {
weaverGenerated[i].delete();
}
}
victim.delete();
}
// record
public static class ChildClass {
public final String name;
public final byte[] bytes;
ChildClass(String name, byte[] bytes) {
this.name = name;
this.bytes = bytes;
}
public boolean equals(Object other) {
if (! (other instanceof ChildClass)) return false;
ChildClass o = (ChildClass) other;
return o.name.equals(name) && unchanged(o.bytes, bytes);
}
public int hashCode() {
return name.hashCode();
}
public String toString() {
return "(ChildClass " + name + ")";
}
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40: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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Modifier;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ArrayType;
import org.apache.bcel.generic.BIPUSH;
import org.apache.bcel.generic.BasicType;
import org.apache.bcel.generic.BranchInstruction;
import org.apache.bcel.generic.ConstantPushInstruction;
import org.apache.bcel.generic.INSTANCEOF;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionConstants;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.InstructionTargeter;
import org.apache.bcel.generic.LDC;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.ReferenceType;
import org.apache.bcel.generic.SIPUSH;
import org.apache.bcel.generic.SWITCH;
import org.apache.bcel.generic.Select;
import org.apache.bcel.generic.TargetLostException;
import org.apache.bcel.generic.Type;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.TypeX;
public class Utility {
private Utility() {
super();
}
public static Instruction createSuperInvoke(
InstructionFactory fact,
BcelWorld world,
Member signature) {
short kind;
if (signature.isInterface()) {
throw new RuntimeException("bad");
} else if (signature.isPrivate() || signature.getName().equals("<init>")) {
throw new RuntimeException("unimplemented, possibly bad");
} else if (signature.isStatic()) {
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;
if (signature.isInterface()) {
kind = Constants.INVOKEINTERFACE;
} else if (signature.isStatic()) {
kind = Constants.INVOKESTATIC;
} else if (signature.isPrivate() || signature.getName().equals("<init>")) {
kind = Constants.INVOKESPECIAL;
} else {
kind = Constants.INVOKEVIRTUAL;
}
return fact.createInvoke(
signature.getDeclaringType().getName(),
signature.getName(),
BcelWorld.makeBcelType(signature.getReturnType()),
BcelWorld.makeBcelTypes(signature.getParameterTypes()),
kind);
}
public static Instruction createGet(InstructionFactory fact, Member signature) {
short kind;
if (signature.isStatic()) {
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 (signature.isStatic()) {
kind = Constants.PUTSTATIC;
} else {
kind = Constants.PUTFIELD;
}
return fact.createFieldAccess(
signature.getDeclaringType().getName(),
signature.getName(),
BcelWorld.makeBcelType(signature.getReturnType()),
kind);
}
public static Instruction createInvoke(
InstructionFactory fact,
JavaClass declaringClass,
Method newMethod) {
short kind;
if (newMethod.isInterface()) {
kind = Constants.INVOKEINTERFACE;
} else if (newMethod.isStatic()) {
kind = Constants.INVOKESTATIC;
} else if (newMethod.isPrivate() || newMethod.getName().equals("<init>")) {
kind = Constants.INVOKESPECIAL;
} else {
kind = Constants.INVOKEVIRTUAL;
}
return fact.createInvoke(
declaringClass.getClassName(),
newMethod.getName(),
Type.getReturnType(newMethod.getSignature()),
Type.getArgumentTypes(newMethod.getSignature()),
kind);
}
public static byte[] stringToUTF(String s) {
try {
ByteArrayOutputStream out0 = new ByteArrayOutputStream();
DataOutputStream out1 = new DataOutputStream(out0);
out1.writeUTF(s);
return out0.toByteArray();
} catch (IOException e) {
throw new RuntimeException("sanity check");
}
}
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 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);
}
// ??? 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++) {
ret[i] = "arg" + i;
}
return ret;
}
public static void appendConversion(
InstructionList il,
InstructionFactory fact,
ResolvedTypeX fromType,
ResolvedTypeX toType)
{
if (! toType.isConvertableFrom(fromType)) {
throw new BCException("can't convert from " + fromType + " to " + toType);
}
if (toType.needsNoConversionFrom(fromType)) return;
if (toType.equals(ResolvedTypeX.VOID)) {
// assert fromType.equals(TypeX.OBJECT)
il.append(InstructionFactory.createPop(fromType.getSize()));
} else if (fromType.equals(ResolvedTypeX.VOID)) {
// assert toType.equals(TypeX.OBJECT)
il.append(InstructionFactory.createNull(Type.OBJECT));
return;
} else if (fromType.equals(TypeX.OBJECT)) {
Type to = BcelWorld.makeBcelType(toType);
if (toType.isPrimitive()) {
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(TypeX.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 (fromType.isPrimitive()) {
// assert toType.isPrimitive()
Type from = BcelWorld.makeBcelType(fromType);
Type to = BcelWorld.makeBcelType(toType);
try {
il.append(fact.createCast(from, 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 fact,
Type fromType,
Type toType) {
//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;
}
il.append(fact.createCast(fromType, toType));
return il;
}
public static Instruction createConstant(
InstructionFactory fact,
int i) {
Instruction inst;
switch(i) {
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;
}
if (i <= Byte.MAX_VALUE && i >= Byte.MIN_VALUE) {
inst = new BIPUSH((byte)i);
} else if (i <= Short.MAX_VALUE && i >= Short.MIN_VALUE) {
inst = new SIPUSH((short)i);
} else {
inst = new LDC(fact.getClassGen().getConstantPool().addInteger(i));
}
return inst;
}
public static JavaClass makeJavaClass(String filename, byte[] bytes) {
try {
ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes), filename);
return parser.parse();
} catch (IOException e) {
throw new BCException("malformed class file");
}
}
public static String arrayToString(int[] a) {
int len = a.length;
if (len == 0) return "[]";
StringBuffer buf = new StringBuffer("[");
buf.append(a[0]);
for (int i = 1; i < len; i++) {
buf.append(", ");
buf.append(a[i]);
}
buf.append("]");
return buf.toString();
}
/**
* 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,
BranchInstruction branchInstruction,
LazyMethodGen enclosingMethod)
{
InstructionList il = enclosingMethod.getBody();
InstructionHandle fresh = il.append(ih, branchInstruction);
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();
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters != null) {
for (int i = targeters.length - 1; i >= 0; i--) {
InstructionTargeter targeter = targeters[i];
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()) && within(org.aspectj.weaver)
* && !withincode(* Utility.copyInstruction(Instruction)):
* "use Utility.copyInstruction to work-around bug in Select.copy()";
* </pre>
*/
public static Instruction copyInstruction(Instruction i) {
if (i instanceof Select) {
Select freshSelect = (Select)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
SWITCH switchStatement =
new SWITCH(freshSelect.getMatchs(), targets, freshSelect.getTarget());
return (Select)switchStatement.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) {
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;
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();
}
}
}
ih = ih.getNext();
}
//System.err.println("no line information available for: " + ih);
return -1;
}
// 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) {
ih.addTargeter(new LineNumberTag(lineNumber));
}
public static int makePublic(int i) {
return i & ~(Modifier.PROTECTED | Modifier.PRIVATE) | Modifier.PUBLIC;
}
public static int makePrivate(int i) {
return i & ~(Modifier.PROTECTED | Modifier.PUBLIC) | Modifier.PRIVATE;
}
public static BcelVar[] pushAndReturnArrayOfVars(
ResolvedTypeX[] proceedParamTypes,
InstructionList il,
InstructionFactory fact,
LazyMethodGen enclosingMethod)
{
int len = proceedParamTypes.length;
BcelVar[] ret = new BcelVar[len];
for (int i = len - 1; i >= 0; i--) {
ResolvedTypeX 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) {
return (i instanceof ConstantPushInstruction) || (i instanceof LDC);
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/testsrc/org/aspectj/weaver/bcel/ArgsWeaveTestCase.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.bcel.Constants;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.Type;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
/**.
*/
public class ArgsWeaveTestCase extends WeaveTestCase {
{
regenerate = false;
}
public ArgsWeaveTestCase(String name) {
super(name);
}
public void testAfterReturningArgs() throws IOException {
weaveTest("HelloWorld", "ArgsAfterReturningHelloWorld", makeArgsMunger("afterReturning"));
}
public void testFancyAfterReturningArgs() throws IOException {
weaveTest("FancyHelloWorld", "ArgsAfterReturningFancyHelloWorld", makeArgsMunger("afterReturning"));
}
public void testThrowing() throws IOException {
weaveTest("HelloWorld", "ArgsAfterThrowingHelloWorld", makeArgsMunger("afterThrowing"));
}
public void testLots() throws IOException {
List l = new ArrayList();
BcelAdvice p1 =
makeArgsMunger("before");
BcelAdvice p2 =
makeArgsMunger("afterThrowing");
BcelAdvice p3 =
makeArgsMunger("afterReturning");
l.add(p1);
l.add(p2);
l.add(p3);
weaveTest("HelloWorld", "ArgsBeforeAfterHelloWorld", addLexicalOrder(l));
}
/* private */ InstructionList getArgsAdviceTag(BcelShadow shadow, String where) {
String methodName =
"ajc_" + where + "_" + shadow.getKind().toLegalJavaIdentifier();
InstructionFactory fact = shadow.getFactory();
InstructionList il = new InstructionList();
il.append(
BcelRenderer.renderExpr(
fact,
new BcelWorld(),
shadow.getArgVar(0),
Type.OBJECT));
il.append(
fact.createInvoke(
"Aspect",
methodName,
Type.VOID,
new Type[] { Type.OBJECT },
Constants.INVOKESTATIC));
return il;
}
private BcelAdvice makeArgsMunger(final String kindx) {
ResolvedTypeX rtx = world.resolve(TypeX.forName("Aspect"),true);
assertTrue("Cant find required type Aspect",rtx!=ResolvedTypeX.MISSING);
return new BcelAdvice(AdviceKind.stringToKind(kindx), makePointcutNoZeroArg(),
Member.method(TypeX.forName("Aspect"), 0, "foo", "()V"), 0, -1, -1, null,
rtx) {
public void specializeOn(Shadow shadow) {
super.specializeOn(shadow);
shadow.getArgVar(0);
}
public InstructionList getAdviceInstructions(BcelShadow shadow, BcelVar extraVar, InstructionHandle fk) {
return getArgsAdviceTag(shadow, kindx);
}
};
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/testsrc/org/aspectj/weaver/bcel/MoveInstructionsWeaveTestCase.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.*;
import org.apache.bcel.generic.InstructionFactory;
import org.aspectj.weaver.*;
public class MoveInstructionsWeaveTestCase extends WeaveTestCase {
{
regenerate = false;
}
public MoveInstructionsWeaveTestCase(String name) {
super(name);
}
public void testHello() throws IOException {
BcelAdvice p = new BcelAdvice(null, makePointcutAll(), null, 0, -1, -1, null, null) {
public void specializeOn(Shadow s) {
super.specializeOn(s);
((BcelShadow) s).initializeForAroundClosure();
}
public void implementOn(Shadow s) {
BcelShadow shadow = (BcelShadow) s;
LazyMethodGen newMethod =
shadow.extractMethod(
shadow.getSignature().getExtractableName() + "_extracted",
0,
this);
shadow.getRange().append(shadow.makeCallToCallback(newMethod));
if (!shadow.isFallsThrough()) {
shadow.getRange().append(
InstructionFactory.createReturn(newMethod.getReturnType()));
}
}
};
weaveTest("HelloWorld", "ExtractedHelloWorld", p);
}
static int counter = 0;
public void testFancyHello() throws IOException {
BcelAdvice p = new BcelAdvice(null, makePointcutAll(), null, 0, -1, -1, null, null) {
public void specializeOn(Shadow s) {
super.specializeOn(s);
((BcelShadow) s).initializeForAroundClosure();
}
public void implementOn(Shadow s) {
BcelShadow shadow = (BcelShadow) s;
LazyMethodGen newMethod = shadow.extractMethod(shadow.getSignature().getExtractableName() + "_extracted" + counter++, 0, this);
shadow.getRange().append(shadow.makeCallToCallback(newMethod));
if (! shadow.isFallsThrough()) {
shadow.getRange().append(InstructionFactory.createReturn(newMethod.getReturnType()));
}
}
};
weaveTest("FancyHelloWorld", "ExtractedFancyHelloWorld", p);
}
}
|
61,374
|
Bug 61374 Version the BCEL libraries to allow graceful failure when the wrong version is found.
| null |
resolved fixed
|
228fc8d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-12T07:57:44Z
| 2004-05-07T11:40:00Z
|
weaver/testsrc/org/aspectj/weaver/bcel/WeaveTestCase.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.*;
import java.util.*;
import junit.framework.*;
import org.apache.bcel.Constants;
import org.apache.bcel.generic.*;
import org.aspectj.weaver.*;
import org.aspectj.weaver.patterns.*;
import org.aspectj.testing.util.TestUtil;
import org.aspectj.util.FileUtil;
public abstract class WeaveTestCase extends TestCase {
public boolean regenerate = false;
public boolean runTests = true;
File outDir;
String outDirPath;
public BcelWorld world = new BcelWorld();
public WeaveTestCase(String name) {
super(name);
}
public void setUp() {
outDir = BcweaverTests.getOutdir();
outDirPath = outDir.getAbsolutePath();
}
public void tearDown() {
BcweaverTests.removeOutDir();
outDir = null;
outDirPath = null;
}
public static InstructionList getAdviceTag(BcelShadow shadow, String where) {
String methodName =
"ajc_" + where + "_" + shadow.getKind().toLegalJavaIdentifier();
InstructionFactory fact = shadow.getFactory();
InvokeInstruction il =
fact.createInvoke("Aspect", methodName, Type.VOID, new Type[] {
}, Constants.INVOKESTATIC);
return new InstructionList(il);
}
public void weaveTest(String name, String outName, ShadowMunger planner) throws IOException {
List l = new ArrayList(1);
l.add(planner);
weaveTest(name, outName, l);
}
//static String classDir = "../weaver/bin";
static String classDir = BcweaverTests.TESTDATA_PATH + File.separator + "bin";
public void weaveTest(String name, String outName, List planners) throws IOException {
BcelWeaver weaver = new BcelWeaver(world);
UnwovenClassFile classFile = makeUnwovenClassFile(classDir, name, outDirPath);
weaver.addClassFile(classFile);
weaver.setShadowMungers(planners);
weaveTestInner(weaver, classFile, name, outName);
}
protected void weaveTestInner(
BcelWeaver weaver,
UnwovenClassFile classFile,
String name,
String outName)
throws IOException
{
//int preErrors = currentResult.errorCount();
BcelObjectType classType =
BcelWorld.getBcelObjectType(world.resolve(classFile.getClassName()));
LazyClassGen gen = weaver.weave(classFile, classType);
if (gen == null) {
// we didn't do any weaving, but let's make a gen anyway
gen = classType.getLazyClassGen(); //new LazyClassGen(classType);
}
try {
checkClass(gen, outDirPath, outName + ".txt");
if (runTests) {
System.out.println(
"*******RUNNING: " + outName + " " + name + " *******");
TestUtil.runMain(makeClassPath(outDirPath), name);
}
} catch (Error e) {
gen.print(System.err);
throw e;
} catch (RuntimeException e) {
gen.print(System.err);
throw e;
}
}
public String makeClassPath(String outDir) {
return outDir
+ File.pathSeparator
+ getTraceJar()
+ File.pathSeparator
+ System.getProperty("java.class.path");
}
/** '/' in the name indicates the location of the class
*/
public static UnwovenClassFile makeUnwovenClassFile(
String classDir,
String name,
String outDir) throws IOException {
File outFile = new File(outDir, name+".class");
if (classDir.endsWith(".jar")) {
String fname = name+".class";
UnwovenClassFile ret =
new UnwovenClassFile(outFile.getAbsolutePath(),
FileUtil.readAsByteArray(FileUtil.getStreamFromZip(classDir, fname)));
return ret;
} else {
File inFile = new File(classDir, name+".class");
return new UnwovenClassFile(outFile.getAbsolutePath(), FileUtil.readAsByteArray(inFile));
}
}
public void checkClass(LazyClassGen gen, String outDir, String expectedFile) throws IOException {
if (regenerate) genClass(gen, outDir, expectedFile);
else realCheckClass(gen, outDir, expectedFile);
}
static final File TESTDATA_DIR = new File(BcweaverTests.TESTDATA_PATH);
void genClass(LazyClassGen gen, String outDir, String expectedFile) throws IOException {
//ClassGen b = getJavaClass(outDir, className);
FileOutputStream out = new FileOutputStream(new File(TESTDATA_DIR, expectedFile));
PrintStream ps = new PrintStream(out);
gen.print(ps);
ps.flush();
}
void realCheckClass(LazyClassGen gen, String outDir, String expectedFile) throws IOException {
TestUtil.assertMultiLineStringEquals(expectedFile/*"classes"*/,
FileUtil.readAsString(new File(TESTDATA_DIR, expectedFile)),
gen.toLongString());
}
// ----
public ShadowMunger makeConcreteAdvice(String mungerString) {
return makeConcreteAdvice(mungerString, 0, null);
}
public ShadowMunger makeConcreteAdvice(String mungerString, int extraArgFlag) {
return makeConcreteAdvice(mungerString, extraArgFlag, null);
}
protected ShadowMunger makeConcreteAdvice(String mungerString, int extraArgFlag, PerClause perClause) {
Advice myMunger =
world.shadowMunger(mungerString, extraArgFlag);
// PerSingleton s = new PerSingleton();
// s.concretize(world.resolve("Aspect"));
//System.err.println(((KindedPointcut)myMunger.getPointcut().getPointcut()).getKind());
Advice cm = (Advice) myMunger.concretize(myMunger.getDeclaringAspect().resolve(world),
world, perClause);
return cm;
}
public ShadowMunger makeAdviceField(String kind, String extraArgType) {
return makeConcreteAdvice(
kind
+ "(): get(* *.*) -> static void Aspect.ajc_"
+ kind
+ "_field_get("
+ extraArgType
+ ")",
1);
}
public List makeAdviceAll(String kind, boolean matchOnlyPrintln) {
List ret = new ArrayList();
if (matchOnlyPrintln) {
ret.add(
makeConcreteAdvice(
kind
+ "(): call(* *.println(..)) -> static void Aspect.ajc_"
+ kind
+ "_method_execution()"));
} else {
ret.add(
makeConcreteAdvice(
kind
+ "(): call(* *.*(..)) -> static void Aspect.ajc_"
+ kind
+ "_method_call()"));
ret.add(
makeConcreteAdvice(
kind
+ "(): call(*.new(..)) -> static void Aspect.ajc_"
+ kind
+ "_constructor_call()"));
ret.add(
makeConcreteAdvice(
kind
+ "(): execution(* *.*(..)) -> static void Aspect.ajc_"
+ kind
+ "_method_execution()"));
ret.add(
makeConcreteAdvice(
kind
+ "(): execution(*.new(..)) -> static void Aspect.ajc_"
+ kind
+ "_constructor_execution()"));
// ret.add(
// makeConcreteMunger(
// kind
// + "(): staticinitialization(*) -> static void Aspect.ajc_"
// + kind
// + "_staticinitialization()"));
ret.add(
makeConcreteAdvice(
kind + "(): get(* *.*) -> static void Aspect.ajc_" + kind + "_field_get()"));
// ret.add(
// makeConcreteMunger(
// kind + "(): set(* *.*) -> static void Aspect.ajc_" + kind + "_field_set()"));
// XXX no test for advice execution, staticInitialization or (god help us) preInitialization
}
return ret;
}
public List makeAdviceAll(final String kind) {
return makeAdviceAll(kind, false);
}
public Pointcut makePointcutAll() {
return makeConcretePointcut("get(* *.*) || call(* *.*(..)) || execution(* *.*(..)) || call(*.new(..)) || execution(*.new(..))");
}
public Pointcut makePointcutNoZeroArg() {
return makeConcretePointcut("call(* *.*(*, ..)) || execution(* *.*(*, ..)) || call(*.new(*, ..)) || execution(*.new(*, ..))");
}
public Pointcut makePointcutPrintln() {
return makeConcretePointcut("call(* *.println(..))");
}
public Pointcut makeConcretePointcut(String s) {
return makeResolvedPointcut(s).concretize(null, 0);
}
public Pointcut makeResolvedPointcut(String s) {
Pointcut pointcut0 = Pointcut.fromString(s);
return pointcut0.resolve(new SimpleScope(world, FormalBinding.NONE));
}
// ----
public String[] getStandardTargets() {
return new String[] {"HelloWorld", "FancyHelloWorld"};
}
public String getTraceJar() {
return BcweaverTests.TESTDATA_PATH + "/tracing.jar";
}
// ----
protected void weaveTest(
String[] inClassNames,
String outKind,
ShadowMunger patternMunger) throws IOException {
for (int i = 0; i < inClassNames.length; i++) {
String inFileName = inClassNames[i];
weaveTest(inFileName, outKind + inFileName, patternMunger);
}
}
protected void weaveTest(
String[] inClassNames,
String outKind,
List patternMungers) throws IOException {
for (int i = 0; i < inClassNames.length; i++) {
String inFileName = inClassNames[i];
weaveTest(inFileName, outKind + inFileName, patternMungers);
}
}
protected List addLexicalOrder(List l) {
int i = 10;
for (Iterator iter = l.iterator(); iter.hasNext();) {
Advice element = (Advice) iter.next();
element.setLexicalPosition(i+=10);
}
return l;
}
//XXX cut-and-paster from IdWeaveTestCase
public void checkShadowSet(List l, String[] ss) {
outer:
for (int i = 0, len = ss.length; i < len; i++) {
inner:
for (Iterator j = l.iterator(); j.hasNext(); ) {
BcelShadow shadow = (BcelShadow) j.next();
String shadowString = shadow.toString();
if (shadowString.equals(ss[i])) {
j.remove();
continue outer;
}
}
assertTrue("didn't find " + ss[i] + " in " + l, false);
}
assertTrue("too many things in " + l, l.size() == 0);
}
}
|
71,878
|
Bug 71878 Bad injar aspect name on Linux
|
If you checkout the "JarUsingProject" project from "org.eclipse.ajdt.test/manual testing" in the AJDT 1.1.12 tree, and look at the advised-by entries in the outline view and the context menu of the gutter annotation, on Windows you get "injar aspect: AbstractAspect.aj", but on Linux you get "injar aspect: C:\eclipse30AJDTPluginTest\eclipse\workspace\JarGeneratingProject\src\p1\AbstractAspect.aj". The Windows-style path indicates the location of the original class files in the JAR file, which was clearly built on Windows.
|
resolved fixed
|
2dfc738
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-13T14:49:39Z
| 2004-08-12T17:00:00Z
|
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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Mik Kersten initial implementation
* Andy Clement Extensions for better IDE representation
* ******************************************************************/
package org.aspectj.asm.internal;
import java.io.*;
import java.util.*;
import org.aspectj.asm.*;
import org.aspectj.bridge.*;
/**
* @author Mik Kersten
*/
public class AspectJElementHierarchy implements IHierarchy {
protected IProgramElement root = null;
protected String configFile = null;
private Map fileMap = null;
private Map handleMap = null;
private Map typeMap = null;
public IProgramElement getElement(String handle) {
IProgramElement cachedEntry = (IProgramElement)handleMap.get(handle);
if (cachedEntry!=null) return cachedEntry;
StringTokenizer st = new StringTokenizer(handle, ProgramElement.ID_DELIM);
String file = st.nextToken();
int line = new Integer(st.nextToken()).intValue();
// int col = new Integer(st.nextToken()).intValue(); TODO: use column number when available
String canonicalSFP = AsmManager.getDefault().getCanonicalFilePath(new File(file));
IProgramElement ret = findNodeForSourceLineHelper(root,canonicalSFP, line);
if (ret!=null) {
handleMap.put(handle,ret);
}
return ret;
}
public IProgramElement getRoot() {
return root;
}
public void setRoot(IProgramElement root) {
this.root = root;
handleMap = new HashMap();
typeMap = new HashMap();
}
public void addToFileMap( Object key, Object value ){
fileMap.put( key, value );
}
public boolean removeFromFileMap(Object key) {
return (fileMap.remove(key)!=null);
}
public void setFileMap(HashMap fileMap) {
this.fileMap = fileMap;
}
public Object findInFileMap( Object key ) {
return fileMap.get(key);
}
public Set getFileMapEntrySet() {
return fileMap.entrySet();
}
public boolean isValid() {
return root != null && fileMap != null;
}
/**
* Returns the first match
*
* @param parent
* @param kind not null
* @return null if not found
*/
public IProgramElement findElementForSignature(IProgramElement parent, IProgramElement.Kind kind, String signature) {
for (Iterator it = parent.getChildren().iterator(); it.hasNext(); ) {
IProgramElement node = (IProgramElement)it.next();
if (node.getKind() == kind && signature.equals(node.toSignatureString())) {
return node;
} else {
IProgramElement childSearch = findElementForSignature(node, kind, signature);
if (childSearch != null) return childSearch;
}
}
return null;
}
public IProgramElement findElementForLabel(
IProgramElement parent,
IProgramElement.Kind kind,
String label) {
for (Iterator it = parent.getChildren().iterator(); it.hasNext(); ) {
IProgramElement node = (IProgramElement)it.next();
if (node.getKind() == kind && label.equals(node.toLabelString())) {
return node;
} else {
IProgramElement childSearch = findElementForSignature(node, kind, label);
if (childSearch != null) return childSearch;
}
}
return null;
}
/**
* @param packageName if null default package is searched
* @param className can't be null
*/
public IProgramElement findElementForType(String packageName, String typeName) {
StringBuffer keyb = (packageName == null) ? new StringBuffer() :
new StringBuffer(packageName);
keyb.append(".");
keyb.append(typeName);
String key = keyb.toString();
IProgramElement ret = (IProgramElement) typeMap.get(key);
if (ret == null) {
IProgramElement packageNode = null;
if (packageName == null) {
packageNode = root;
} else {
for (Iterator it = root.getChildren().iterator(); it.hasNext(); ) {
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);
if (cNode != null) {
ret = cNode;
typeMap.put(key,ret);
}
}
}
return ret;
}
private IProgramElement findClassInNodes(Collection nodes, String name) {
String baseName;
String innerName;
int dollar = name.indexOf('$');
if (dollar == -1) {
baseName = name;
innerName = null;
} else {
baseName = name.substring(0, dollar);
innerName = name.substring(dollar+1);
}
for (Iterator j = nodes.iterator(); j.hasNext(); ) {
IProgramElement classNode = (IProgramElement)j.next();
if (baseName.equals(classNode.getName())) {
if (innerName == null) return classNode;
else return findClassInNodes(classNode.getChildren(), innerName);
} else if (name.equals(classNode.getName())) {
return classNode;
}
}
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 =
AsmManager.getDefault().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(
AsmManager.getDefault().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 = AsmManager.getDefault().getCanonicalFilePath(
new File(sourceFilePath));
IProgramElement node = findNodeForSourceLineHelper(root, canonicalSFP, lineNumber);
if (node != null) {
return node;
} else {
return createFileStructureNode(sourceFilePath);
}
}
private IProgramElement createFileStructureNode(String sourceFilePath) {
String fileName = new File(sourceFilePath).getName();
IProgramElement fileNode = new ProgramElement(fileName, IProgramElement.Kind.FILE_JAVA, null);
fileNode.setSourceLocation(new SourceLocation(new File(sourceFilePath), 1, 1));
fileNode.addChild(NO_STRUCTURE);
return fileNode;
}
private IProgramElement findNodeForSourceLineHelper(IProgramElement node, String sourceFilePath, int lineNumber) {
if (matches(node, sourceFilePath, lineNumber)
&& !hasMoreSpecificChild(node, sourceFilePath, lineNumber)) {
return node;
}
if (node != null && node.getChildren() != null) {
for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) {
IProgramElement foundNode = findNodeForSourceLineHelper(
(IProgramElement)it.next(),
sourceFilePath,
lineNumber);
if (foundNode != null) return foundNode;
}
}
return null;
}
private boolean matches(IProgramElement node, String sourceFilePath, int lineNumber) {
// try {
// if (node != null && node.getSourceLocation() != null)
// System.err.println("====\n1: " +
// sourceFilePath + "\n2: " +
// node.getSourceLocation().getSourceFile().getCanonicalPath().equals(sourceFilePath)
// );
return node != null
&& node.getSourceLocation() != null
&& node.getSourceLocation().getSourceFile().getAbsolutePath().equals(sourceFilePath)
&& ((node.getSourceLocation().getLine() <= lineNumber
&& node.getSourceLocation().getEndLine() >= lineNumber)
||
(lineNumber <= 1
&& node.getKind().isSourceFile())
);
// } catch (IOException ioe) {
// return false;
// }
}
private boolean hasMoreSpecificChild(IProgramElement node, String sourceFilePath, int lineNumber) {
for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) {
IProgramElement child = (IProgramElement)it.next();
if (matches(child, sourceFilePath, lineNumber)) return true;
}
return false;
}
public String getConfigFile() {
return configFile;
}
public void setConfigFile(String configFile) {
this.configFile = configFile;
}
// TODO: optimize this lookup
public IProgramElement findElementForHandle(String handle) {
// try the cache first...
IProgramElement ret = (IProgramElement) handleMap.get(handle);
if (ret != null) return ret;
StringTokenizer st = new StringTokenizer(handle, ProgramElement.ID_DELIM);
String file = st.nextToken();
int line = new Integer(st.nextToken()).intValue();
// int col = new Integer(st.nextToken()).intValue();
// TODO: use column number when available
ret = findElementForSourceLine(file, line);
if (ret != null) {
cache(handle,(ProgramElement)ret);
}
return ret;
// IProgramElement parent = findElementForType(packageName, typeName);
// if (parent == null) return null;
// if (kind == IProgramElement.Kind.CLASS ||
// kind == IProgramElement.Kind.ASPECT) {
// return parent;
// } else {
// return findElementForSignature(parent, kind, name);
// }
}
//
// 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, ProgramElement pe) {
handleMap.put(handle,pe);
}
public void flushTypeMap() {
typeMap.clear();
}
public void flushHandleMap() {
handleMap.clear();
}
}
|
67,578
|
Bug 67578 Privileged Aspect Access Problem Across Packages
|
From Irum Godil's aspectj-users posting: package a; public class ITD { private void returnNothing(Object a) { } } package b; import a.*; privileged aspect B { public void ITD.newFun() { returnNothing("a"); } } returns: C:\devel\test\priv\b\B.aj:8 error The method returnNothing(Object) from the type ITD is not visible returnNothing("a"); ^^^^^^ 1 error Which it should not (and AspectJ 1.0.6 does not give an error) Work around: use this.returnNothing("a");
|
resolved fixed
|
6b1ef0f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-16T16:16:20Z
| 2004-06-17T05:26:40Z
|
tests/src/org/aspectj/systemtest/ajc121/Ajc121Tests.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.systemtest.ajc121;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc121Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc121Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc121/ajc121.xml");
}
public void test001(){
runTest("false ambiguous binding error (introduced in 1.2rc2)");
}
public void test002(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test003(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test004(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test005(){
runTest("compiler aborts with 'conflicting dominates orders' with circular declare precedences");
}
public void test006(){
runTest("'can't bind type' message has $ for . in type name for declare soft");
}
public void test007(){
runTest("Hiding of Instance Methods by static methods");
}
public void test008(){
runTest("if(false) optimisation");
}
public void test009(){
runTest("if(true) optimisation");
}
public void test010(){
runTest("java.lang.NullPointerException in WeaverMessageHandler class");
}
public void test011(){
runTest("ClassCastException at BcelRenderer.java:169");
}
public void test012(){
runTest("Front-end bug, shouldn't allow patterns of the form foo.., should be foo..*");
}
public void test013() {
runTest("Nullpointer-Exception when defining a withincode() pointcut");
}
public void test014() {
runTest("NPE, Incorrect XLint:unmatchedSuperTypeInCall warning");
}
public void test015_invalidXlint() { // keywords: "laurie hendren"
runTest("invalid warning indicating no match when a match really occurs");
}
public void test016_ByteConversionInstructions() {
runTest("RuntimeException thrown: Could not find instruction: org.apache.bcel.generic.B2I");
String output = getLastRunResult().getStdErr();
assertTrue("Expected to find [b2] in this output but didn't:"+output,output.indexOf("[b2]")!=-1);
assertTrue("Expected to find [b127] in this output but didn't:"+output,output.indexOf("[b127]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
assertTrue("Expected to find [c65] in this output but didn't:"+output,output.indexOf("[c65]")!=-1);
assertTrue("Expected to find [c66] in this output but didn't:"+output,output.indexOf("[c66]")!=-1);
assertTrue("Expected to find [c67] in this output but didn't:"+output,output.indexOf("[c67]")!=-1);
assertTrue("Expected to find [s1] in this output but didn't:"+output,output.indexOf("[s1]")!=-1);
assertTrue("Expected to find [s32767] in this output but didn't:"+output,output.indexOf("[s32767]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
}
public void test017_PrivateMethodCallsInAroundAdvice() {
runTest("Cannot advise private method call in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test018_PrivateFieldSetsInAroundAdvice() {
runTest("Cannot advise private field sets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test019_PrivateFieldGetsInAroundAdvice() {
runTest("Cannot advise private field gets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
// test takes over 5 minutes to run, so not included in normal suite run
// public void test020_branchTargetOffsetTooLargeForShort() {
// runTest("Branch target offset too large for short");
// }
// public void test021_BcelFailureWithVeryLargeClasses() {
// runTest("Weaver fails in BCEL for large classes");
// }
//
// public void test022_BcelFailureWithVeryLargeClasses_Binary() {
// runTest("Weaver fails in BCEL for large classes (binary)");
// }
public void test023_proceedInAround1() {
runTest("proceed used as method name in around advice (1)");
}
public void test024_proceedInAround2() {
runTest("proceed used as method name in around advice (2)");
}
public void test025_proceedInAround3() {
runTest("proceed used as method name in around advice (3)");
}
public void test026_bindingThisAndTargetToTheSameFormal() {
runTest("ajc crashes when compiling the following program (binding this() and target())");
}
public void test027_itdsOnInnerClassesAsStatic() {
runTest("ITDs on inner classes should be static context");
}
public void test028_itdsAndInitializers() {
runTest("resolution of IT field inits");
}
public void test029_falseInvalidAbsoluteTypeName() {
runTest("Valid but inaccessible type names should not be flagged by XLint:invalidAbsoluteTypeName");
}
public void test030_privateITDinitialisersBeingMatched() {
runTest("intertype initialisers should match field set pointcuts");
}
public void test031_privateITDinitialisersBeingMatched_OxfordTest() {
runTest("intertype initialisers should match field set pointcuts (oxford testcase)");
//System.err.println(">"+getLastRunResult().getStdErr());
String exp = ":set field set(int C.n):set field set(int C.m):get field get(int C.n):set field set(int C.n)";
assertTrue("Expected output '"+exp+"' but got "+getLastRunResult().getStdErr(),
getLastRunResult().getStdErr().equals(exp));
}
public void test032_stringConcatForDEOW() {
runTest("Compile time declarations (warning and error) do not accept string concatenation (with +)");
}
public void test033_stringConcatForDEOWErrorCase() {
runTest("Compile time declarations (warning and error) do not accept string concatenation (with +) (2)");
}
public void test034_scopeForITDS_pr61768() {
runTest("scope for inter-type methods");
}
public void test035_innerAspectCallsPrivateMethod_pr71372() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test036_innerAspectCallsPrivateMethod_pr71372_2() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (2)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test037_innerAspectCallsPrivateMethod_pr71372_3() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (3)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test038_innerAspectCallsPrivateMethod_pr71372_4() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (4)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
}
|
70,241
|
Bug 70241 outline view shows anonymous inner classes in different way than jdt outline
|
See screenshots.
|
resolved fixed
|
a2469c7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-17T09:37:46Z
| 2004-07-16T15:00:00Z
|
ajde/testdata/extensions/InnerClasses.java
| |
70,241
|
Bug 70241 outline view shows anonymous inner classes in different way than jdt outline
|
See screenshots.
|
resolved fixed
|
a2469c7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-17T09:37:46Z
| 2004-07-16T15:00:00Z
|
ajde/testsrc/org/aspectj/ajde/ExtensionTests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Matthew Webster - initial implementation
*******************************************************************************/
package org.aspectj.ajde;
import java.util.List;
import java.io.File;
import org.aspectj.bridge.IMessage;
import org.aspectj.tools.ajc.AjcTestCase;
import org.aspectj.tools.ajc.CompilationResult;
import org.eclipse.jdt.core.compiler.IProblem;
/**
* Tests the 'extensions' to AJDE:
* 1) ID is now available on messages to allow you to see what 'kind' of
* message it is - this activates quick fixes/etc in Eclipse.
*/
public class ExtensionTests extends AjcTestCase {
public static final String PROJECT_DIR = "extensions";
private File baseDir;
protected void setUp() throws Exception {
super.setUp();
baseDir = new File("../ajde/testdata",PROJECT_DIR);
}
/**
* Aim: Check that the ID of certain message kinds are correct
*
* ajc -warn:unusedImport UnusedImport.java
*
* Expected result = id
*/
public void testOutjarInInjars () {
String[] args = new String[] {"UnusedImport.java","-warn:unusedImport"};
CompilationResult result = ajc(baseDir,args);
List l = result.getWarningMessages();
IMessage m = ((IMessage)l.get(0));
assertTrue("Expected ID of message to be "+IProblem.UnusedImport+" (UnusedImport) but found an ID of "+m.getID(),
m.getID()==IProblem.UnusedImport);
}
}
|
70,241
|
Bug 70241 outline view shows anonymous inner classes in different way than jdt outline
|
See screenshots.
|
resolved fixed
|
a2469c7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-17T09:37:46Z
| 2004-07-16T15:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmHierarchyBuilder.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Stack;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeDeclaration;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedMember;
import org.eclipse.jdt.internal.compiler.ASTVisitor;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.AbstractVariableDeclaration;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration;
import org.eclipse.jdt.internal.compiler.ast.ExtendedStringLiteral;
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
import org.eclipse.jdt.internal.compiler.ast.ImportReference;
import org.eclipse.jdt.internal.compiler.ast.Initializer;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.QualifiedAllocationExpression;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope;
import org.eclipse.jdt.internal.compiler.lookup.MethodScope;
import org.eclipse.jdt.internal.compiler.problem.ProblemHandler;
/**
* At each iteration of <CODE>processCompilationUnit</CODE> the declarations for a
* particular compilation unit are added to the hierarchy passed as a a parameter.
*
* Clients who extend this class need to ensure that they do not override any of the existing
* behavior. If they do, the structure model will not be built properly and tools such as IDE
* structure views and ajdoc will fail.
*
* @author Mik Kersten
*/
public class AsmHierarchyBuilder extends ASTVisitor {
// public static void build(
// CompilationUnitDeclaration unit,
// IHierarchy structureModel, AjBuildConfig buildConfig) {
// LangUtil.throwIaxIfNull(unit, "unit");
// new AsmHierarchyBuilder(unit., ).;
// }
protected AsmElementFormatter formatter = new AsmElementFormatter();
/**
* Reset for every compilation unit.
*/
protected AjBuildConfig buildConfig;
/**
* Reset for every compilation unit.
*/
protected Stack stack;
/**
* Reset for every compilation unit.
*/
private CompilationResult currCompilationResult;
/**
*
* @param cuDeclaration
* @param buildConfig
* @param structureModel hiearchy to add this unit's declarations to
*/
public void buildStructureForCompilationUnit(CompilationUnitDeclaration cuDeclaration, IHierarchy structureModel, AjBuildConfig buildConfig) {
currCompilationResult = cuDeclaration.compilationResult();
LangUtil.throwIaxIfNull(currCompilationResult, "result");
stack = new Stack();
this.buildConfig = buildConfig;
internalBuild(cuDeclaration, structureModel);
// throw new RuntimeException("not implemented");
}
private void internalBuild(CompilationUnitDeclaration unit, IHierarchy structureModel) {
LangUtil.throwIaxIfNull(structureModel, "structureModel");
if (!currCompilationResult.equals(unit.compilationResult())) {
throw new IllegalArgumentException("invalid unit: " + unit);
}
// ---- summary
// add unit to package (or root if no package),
// first removing any duplicate (XXX? removes children if 3 classes in same file?)
// push the node on the stack
// and traverse
// -- create node to add
final File file = new File(new String(unit.getFileName()));
final IProgramElement cuNode;
{
// AMC - use the source start and end from the compilation unit decl
int startLine = getStartLine(unit);
int endLine = getEndLine(unit);
ISourceLocation sourceLocation
= new SourceLocation(file, startLine, endLine);
cuNode = new ProgramElement(
new String(file.getName()),
IProgramElement.Kind.FILE_JAVA,
sourceLocation,
0,
"",
new ArrayList());
}
cuNode.addChild(new ProgramElement(
"import declarations",
IProgramElement.Kind.IMPORT_REFERENCE,
null,
0,
"",
new ArrayList()));
final IProgramElement addToNode = genAddToNode(unit, structureModel);
// -- remove duplicates before adding (XXX use them instead?)
if (addToNode!=null && addToNode.getChildren()!=null) {
for (ListIterator itt = addToNode.getChildren().listIterator(); itt.hasNext(); ) {
IProgramElement child = (IProgramElement)itt.next();
ISourceLocation childLoc = child.getSourceLocation();
if (null == childLoc) {
// XXX ok, packages have null source locations
// signal others?
} else if (childLoc.getSourceFile().equals(file)) {
itt.remove();
}
}
}
// -- add and traverse
addToNode.addChild(cuNode);
stack.push(cuNode);
unit.traverse(this, unit.scope);
// -- update file map (XXX do this before traversal?)
try {
structureModel.addToFileMap(file.getCanonicalPath(), cuNode);
} catch (IOException e) {
System.err.println("IOException " + e.getMessage()
+ " creating path for " + file );
// XXX signal IOException when canonicalizing file path
}
}
/**
* Get/create the node (package or root) to add to.
*/
private IProgramElement genAddToNode(
CompilationUnitDeclaration unit,
IHierarchy structureModel) {
final IProgramElement addToNode;
{
ImportReference currentPackage = unit.currentPackage;
if (null == currentPackage) {
addToNode = structureModel.getRoot();
} else {
String pkgName;
{
StringBuffer nameBuffer = new StringBuffer();
final char[][] importName = currentPackage.getImportName();
final int last = importName.length-1;
for (int i = 0; i < importName.length; i++) {
nameBuffer.append(new String(importName[i]));
if (i < last) {
nameBuffer.append('.');
}
}
pkgName = nameBuffer.toString();
}
IProgramElement pkgNode = null;
if (structureModel!=null && structureModel.getRoot()!=null && structureModel.getRoot().getChildren()!=null) {
for (Iterator it = structureModel.getRoot().getChildren().iterator();
it.hasNext(); ) {
IProgramElement currNode = (IProgramElement)it.next();
if (pkgName.equals(currNode.getName())) {
pkgNode = currNode;
break;
}
}
}
if (pkgNode == null) {
// note packages themselves have no source location
pkgNode = new ProgramElement(
pkgName,
IProgramElement.Kind.PACKAGE,
new ArrayList()
);
structureModel.getRoot().addChild(pkgNode);
}
addToNode = pkgNode;
}
}
return addToNode;
}
public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
String name = new String(typeDeclaration.name);
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (typeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT;
else if (typeDeclaration.isInterface()) kind = IProgramElement.Kind.INTERFACE;
IProgramElement peNode = new ProgramElement(
name,
kind,
makeLocation(typeDeclaration),
typeDeclaration.modifiers,
"",
new ArrayList());
peNode.setSourceSignature(genSourceSignature(typeDeclaration));
peNode.setFormalComment(generateJavadocComment(typeDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
stack.pop();
}
// ??? share impl with visit(TypeDeclaration, ..) ?
public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
String name = new String(memberTypeDeclaration.name);
//System.err.println("member type with name: " + name);
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (memberTypeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT;
else if (memberTypeDeclaration.isInterface()) kind = IProgramElement.Kind.INTERFACE;
IProgramElement peNode = new ProgramElement(
name,
kind,
makeLocation(memberTypeDeclaration),
memberTypeDeclaration.modifiers,
"",
new ArrayList());
peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration));
peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
stack.pop();
}
public boolean visit(TypeDeclaration memberTypeDeclaration, BlockScope scope) {
// String name = new String(memberTypeDeclaration.name);
String fullName = "<undefined>";
if (memberTypeDeclaration.binding != null
&& memberTypeDeclaration.binding.constantPoolName() != null) {
fullName = new String(memberTypeDeclaration.binding.constantPoolName());
}
int dollar = fullName.indexOf('$');
fullName = fullName.substring(dollar+1);
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (memberTypeDeclaration.isInterface()) kind = IProgramElement.Kind.INTERFACE;
IProgramElement peNode = new ProgramElement(
fullName,
kind,
makeLocation(memberTypeDeclaration),
memberTypeDeclaration.modifiers,
"",
new ArrayList());
peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration));
peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration));
//??? we add this to the compilation unit
findEnclosingClass(stack).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration memberTypeDeclaration, BlockScope scope) {
stack.pop();
}
private String genSourceSignature(TypeDeclaration typeDeclaration) {
StringBuffer output = new StringBuffer();
typeDeclaration.printHeader(0, output);
return output.toString();
}
private IProgramElement findEnclosingClass(Stack stack) {
for (int i = stack.size()-1; i >= 0; i--) {
IProgramElement pe = (IProgramElement)stack.get(i);
if (pe.getKind() == IProgramElement.Kind.CLASS) {
return pe;
}
}
return (IProgramElement)stack.peek();
}
public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) {
IProgramElement peNode = null;
// For intertype decls, use the modifiers from the original signature, not the generated method
if (methodDeclaration instanceof InterTypeDeclaration) {
InterTypeDeclaration itd = (InterTypeDeclaration) methodDeclaration;
ResolvedMember sig = itd.getSignature();
peNode = new ProgramElement(
"",
IProgramElement.Kind.ERROR,
makeLocation(methodDeclaration),
(sig!=null?sig.getModifiers():0),
"",
new ArrayList());
} else {
peNode = new ProgramElement(
"",
IProgramElement.Kind.ERROR,
makeLocation(methodDeclaration),
methodDeclaration.modifiers,
"",
new ArrayList());
}
formatter.genLabelAndKind(methodDeclaration, peNode);
genBytecodeInfo(methodDeclaration, peNode);
if (methodDeclaration.returnType!=null) {
peNode.setCorrespondingType(methodDeclaration.returnType.toString());
} else {
peNode.setCorrespondingType(null);
}
peNode.setSourceSignature(genSourceSignature(methodDeclaration));
peNode.setFormalComment(generateJavadocComment(methodDeclaration));
// TODO: add return type test
if (peNode.getKind().equals(IProgramElement.Kind.METHOD)) {
if (peNode.toLabelString().equals("main(String[])")
&& peNode.getModifiers().contains(IProgramElement.Modifiers.STATIC)
&& peNode.getAccessibility().equals(IProgramElement.Accessibility.PUBLIC)) {
((IProgramElement)stack.peek()).setRunnable(true);
}
}
stack.push(peNode);
return true;
}
private String genSourceSignature(MethodDeclaration methodDeclaration) {
StringBuffer output = new StringBuffer();
ASTNode.printModifiers(methodDeclaration.modifiers, output);
methodDeclaration.printReturnType(0, output).append(methodDeclaration.selector).append('(');
if (methodDeclaration.arguments != null) {
for (int i = 0; i < methodDeclaration.arguments.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
methodDeclaration.arguments[i].print(0, output);
}
}
output.append(')');
if (methodDeclaration.thrownExceptions != null) {
output.append(" throws "); //$NON-NLS-1$
for (int i = 0; i < methodDeclaration.thrownExceptions.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
methodDeclaration.thrownExceptions[i].print(0, output);
}
}
return output.toString();
}
private void genBytecodeInfo(MethodDeclaration methodDeclaration, IProgramElement peNode) {
if (methodDeclaration.binding != null) {
String memberName = "";
String memberBytecodeSignature = "";
try {
Member member = EclipseFactory.makeResolvedMember(methodDeclaration.binding);
memberName = member.getName();
memberBytecodeSignature = member.getSignature();
} catch (NullPointerException npe) {
memberName = "<undefined>";
}
peNode.setBytecodeName(memberName);
peNode.setBytecodeSignature(memberBytecodeSignature);
}
((IProgramElement)stack.peek()).addChild(peNode);
}
public void endVisit(MethodDeclaration methodDeclaration, ClassScope scope) {
stack.pop();
}
public boolean visit(ImportReference importRef, CompilationUnitScope scope) {
int dotIndex = importRef.toString().lastIndexOf('.');
String currPackageImport = "";
if (dotIndex != -1) {
currPackageImport = importRef.toString().substring(0, dotIndex);
}
if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) {
IProgramElement peNode = new ProgramElement(
new String(importRef.toString()),
IProgramElement.Kind.IMPORT_REFERENCE,
makeLocation(importRef),
0,
"",
new ArrayList());
ProgramElement imports = (ProgramElement)((ProgramElement)stack.peek()).getChildren().get(0);
imports.addChild(0, peNode);
stack.push(peNode);
}
return true;
}
public void endVisit(ImportReference importRef, CompilationUnitScope scope) {
int dotIndex = importRef.toString().lastIndexOf('.');
String currPackageImport = "";
if (dotIndex != -1) {
currPackageImport = importRef.toString().substring(0, dotIndex);
}
if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) {
stack.pop();
}
}
public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) {
IProgramElement peNode = new ProgramElement(
new String(fieldDeclaration.name),
IProgramElement.Kind.FIELD,
makeLocation(fieldDeclaration),
fieldDeclaration.modifiers,
"",
new ArrayList());
peNode.setCorrespondingType(fieldDeclaration.type.toString());
peNode.setSourceSignature(genSourceSignature(fieldDeclaration));
peNode.setFormalComment(generateJavadocComment(fieldDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(FieldDeclaration fieldDeclaration, MethodScope scope) {
stack.pop();
}
/**
* Checks if comments should be added to the model before generating.
*/
private String generateJavadocComment(ASTNode astNode) {
if (buildConfig != null && !buildConfig.isGenerateJavadocsInModelMode()) return null;
StringBuffer sb = new StringBuffer(); // !!! specify length?
boolean completed = false;
int startIndex = -1;
if (astNode instanceof MethodDeclaration) {
startIndex = ((MethodDeclaration)astNode).declarationSourceStart;
} else if (astNode instanceof FieldDeclaration) {
startIndex = ((FieldDeclaration)astNode).declarationSourceStart;
} else if (astNode instanceof TypeDeclaration) {
startIndex = ((TypeDeclaration)astNode).declarationSourceStart;
}
if (startIndex == -1) {
return null;
} else if (currCompilationResult.compilationUnit.getContents()[startIndex] == '/' // look for /**
&& currCompilationResult.compilationUnit.getContents()[startIndex+1] == '*'
&& currCompilationResult.compilationUnit.getContents()[startIndex+2] == '*') {
for (int i = startIndex; i < astNode.sourceStart && !completed; i++) {
char curr = currCompilationResult.compilationUnit.getContents()[i];
if (curr == '/' && sb.length() > 2 && sb.charAt(sb.length()-1) == '*') completed = true; // found */
sb.append(currCompilationResult.compilationUnit.getContents()[i]);
}
// System.err.println(">> " + sb.toString());
return sb.toString();
} else {
return null;
}
}
/**
* Doesn't print qualified allocation expressions.
*/
private String genSourceSignature(FieldDeclaration fieldDeclaration) {
StringBuffer output = new StringBuffer();
FieldDeclaration.printModifiers(fieldDeclaration.modifiers, output);
fieldDeclaration.type.print(0, output).append(' ').append(fieldDeclaration.name);
if (fieldDeclaration.initialization != null
&& !(fieldDeclaration.initialization instanceof QualifiedAllocationExpression)) {
output.append(" = "); //$NON-NLS-1$
if (fieldDeclaration.initialization instanceof ExtendedStringLiteral) {
output.append("\"<extended string literal>\"");
} else {
fieldDeclaration.initialization.printExpression(0, output);
}
}
output.append(';');
return output.toString();
}
// public boolean visit(ImportReference importRef, CompilationUnitScope scope) {
// ProgramElementNode peNode = new ProgramElementNode(
// new String(importRef.toString()),
// ProgramElementNode.Kind.,
// makeLocation(importRef),
// 0,
// "",
// new ArrayList());
// ((IProgramElement)stack.peek()).addChild(0, peNode);
// stack.push(peNode);
// return true;
// }
// public void endVisit(ImportReference importRef,CompilationUnitScope scope) {
// stack.pop();
// }
public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
if (constructorDeclaration.isDefaultConstructor) {
stack.push(null); // a little wierd but does the job
return true;
}
StringBuffer argumentsSignature = new StringBuffer();
argumentsSignature.append("(");
if (constructorDeclaration.arguments!=null) {
for (int i = 0;i<constructorDeclaration.arguments.length;i++) {
argumentsSignature.append(constructorDeclaration.arguments[i]);
if (i+1<constructorDeclaration.arguments.length) argumentsSignature.append(",");
}
}
argumentsSignature.append(")");
IProgramElement peNode = new ProgramElement(
new String(constructorDeclaration.selector)+argumentsSignature,
IProgramElement.Kind.CONSTRUCTOR,
makeLocation(constructorDeclaration),
constructorDeclaration.modifiers,
"",
new ArrayList());
peNode.setModifiers(constructorDeclaration.modifiers);
peNode.setSourceSignature(genSourceSignature(constructorDeclaration));
// Fix to enable us to anchor things from ctor nodes
if (constructorDeclaration.binding != null) {
String memberName = "";
String memberBytecodeSignature = "";
try {
Member member = EclipseFactory.makeResolvedMember(constructorDeclaration.binding);
memberName = member.getName();
memberBytecodeSignature = member.getSignature();
} catch (NullPointerException npe) {
memberName = "<undefined>";
}
peNode.setBytecodeName(memberName);
peNode.setBytecodeSignature(memberBytecodeSignature);
}
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
stack.pop();
}
private String genSourceSignature(ConstructorDeclaration constructorDeclaration) {
StringBuffer output = new StringBuffer();
ASTNode.printModifiers(constructorDeclaration.modifiers, output);
output.append(constructorDeclaration.selector).append('(');
if (constructorDeclaration.arguments != null) {
for (int i = 0; i < constructorDeclaration.arguments.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
constructorDeclaration.arguments[i].print(0, output);
}
}
output.append(')');
if (constructorDeclaration.thrownExceptions != null) {
output.append(" throws "); //$NON-NLS-1$
for (int i = 0; i < constructorDeclaration.thrownExceptions.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
constructorDeclaration.thrownExceptions[i].print(0, output);
}
}
return output.toString();
}
// public boolean visit(Clinit clinit, ClassScope scope) {
// ProgramElementNode peNode = new ProgramElementNode(
// "<clinit>",
// ProgramElementNode.Kind.INITIALIZER,
// makeLocation(clinit),
// clinit.modifiers,
// "",
// new ArrayList());
// ((IProgramElement)stack.peek()).addChild(peNode);
// stack.push(peNode);
// return false;
// }
// public void endVisit(Clinit clinit, ClassScope scope) {
// stack.pop();
// }
/** This method works-around an odd traverse implementation on Initializer
*/
private Initializer inInitializer = null;
public boolean visit(Initializer initializer, MethodScope scope) {
if (initializer == inInitializer) return false;
inInitializer = initializer;
IProgramElement peNode = new ProgramElement(
"...",
IProgramElement.Kind.INITIALIZER,
makeLocation(initializer),
initializer.modifiers,
"",
new ArrayList());
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
initializer.block.traverse(this, scope);
stack.pop();
return false;
}
// ??? handle non-existant files
private ISourceLocation makeLocation(ASTNode node) {
String fileName = "";
if (currCompilationResult.getFileName() != null) {
fileName = new String(currCompilationResult.getFileName());
}
// AMC - different strategies based on node kind
int startLine = getStartLine(node);
int endLine = getEndLine(node);
ISourceLocation loc = null;
if ( startLine <= endLine ) {
// found a valid end line for this node...
loc = new SourceLocation(new File(fileName), startLine, endLine);
} else {
loc = new SourceLocation(new File(fileName), startLine);
}
return loc;
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getStartLine( ASTNode n){
// if ( n instanceof AbstractVariableDeclaration ) return getStartLine( (AbstractVariableDeclaration)n);
// if ( n instanceof AbstractMethodDeclaration ) return getStartLine( (AbstractMethodDeclaration)n);
// if ( n instanceof TypeDeclaration ) return getStartLine( (TypeDeclaration)n);
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
n.sourceStart);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( ASTNode n){
if ( n instanceof AbstractVariableDeclaration ) return getEndLine( (AbstractVariableDeclaration)n);
if ( n instanceof AbstractMethodDeclaration ) return getEndLine( (AbstractMethodDeclaration)n);
if ( n instanceof TypeDeclaration ) return getEndLine( (TypeDeclaration)n);
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
n.sourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( AbstractVariableDeclaration avd ) {
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// avd.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( AbstractVariableDeclaration avd ){
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
avd.declarationSourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( AbstractMethodDeclaration amd ){
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// amd.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( AbstractMethodDeclaration amd) {
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
amd.declarationSourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( TypeDeclaration td ){
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// td.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( TypeDeclaration td){
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
td.declarationSourceEnd);
}
}
|
62,642
|
Bug 62642 proper handling of ExceptionInIntializer inside <clinit> in presence of after throwing advice
|
When a <clinit> of a class contains after throwing advice that may catch ExceptionInInitializer errors due to an embedded advice aspectOf() that fails, the ExceptionInIntializer error does not get properly reported. For the example below: public class Main { static int x = 13; int y; public Main() { y= 14; } public static void main(String args[]) { Main m = new Main(); m.y = 3; System.out.println("hi"); } } aspect Aspect { before () : within(*) { System.out.println("BEFORE " + thisJoinPointStaticPart.getKind() + " at " + thisJoinPointStaticPart.getSourceLocation()); } after () : within(*) { System.out.println("AFTER " + thisJoinPointStaticPart.getKind() + " at " + thisJoinPointStaticPart.getSourceLocation()); } } .... when compiled with ajc, and then run, the following exception is given, Exception in thread "main" java.lang.NoClassDefFoundError at Main.<clinit>(Main.java:1) when really one wants the following: Exception in thread "main" java.lang.ExceptionInInitializerError at Main. ... Caused by: org.aspectj.lang.NoAspectBoundException: Aspect at Aspect.aspectOf .. ------------- Here is a fix ... I give the decompiled <clinit> for Main.java and indicate with comments, look for ***LJH ****, what can be woven to fix it. Basically, the catch block for after throwing, when in <clinit>, should first check if the caught exception if a ExceptionInInitializerError, and if so just throw it. ----------- static { org.aspectj.runtime.reflect.Factory r1; java.lang.Throwable r2, r31; int $i0; r1 = new Factory("Main.java", Class.forName("Main")); ajc$tjp_0 = r1.makeSJP("field-set", r1.makeFieldSig("8-x-Main-int-"), 2); ajc$tjp_1 = r1.makeSJP("staticinitialization", r1.makeInitializerSig("8--Main-"), 2); ajc$tjp_10 = r1.makeSJP("preinitialization", r1.makeConstructorSig("1--Main----"), 5); ajc$tjp_2 = r1.makeSJP("field-set", r1.makeFieldSig("0-y-Main-int-"), 6); ajc$tjp_3 = r1.makeSJP("constructor-execution", r1.makeConstructorSig("1--Main----"), 6); ajc$tjp_4 = r1.makeSJP("constructor-call", r1.makeConstructorSig("1--Main----"), 10); ajc$tjp_5 = r1.makeSJP("field-set", r1.makeFieldSig("0-y-Main-int-"), 11); ajc$tjp_6 = r1.makeSJP("field-get", r1.makeFieldSig("19-out-java.lang.System-java.io.PrintStream-"), 12); ajc$tjp_7 = r1.makeSJP("method-call", r1.makeMethodSig("1-println-java.io.PrintStream-java.lang.String:-arg0:--void-"), 12); ajc$tjp_8 = r1.makeSJP("method-execution", r1.makeMethodSig("9-main-Main-[Ljava.lang.String;:-args:--void-"), 10); ajc$tjp_9 = r1.makeSJP("initialization", r1.makeConstructorSig("1--Main----"), 6); try { Aspect.aspectOf().ajc$before$Aspect$1$36f01b1c(ajc$tjp_1); $i0 = 13; try { Aspect.aspectOf().ajc$before$Aspect$1$36f01b1c(ajc$tjp_0); x = $i0; } catch (Throwable $r30) { /*** LJH insert here *****/ if ($r30 instanceof ExceptionInIntializerError) //*** throw($r30); //*** /***********/ r31 = $r30; Aspect.aspectOf().ajc$after$Aspect$2$36f01b1c(ajc$tjp_0); throw r31; } Aspect.aspectOf().ajc$after$Aspect$2$36f01b1c(ajc$tjp_0); } catch (Throwable $r36) { /*** LJH insert here *****/ if ($r36 instanceof ExceptionInIntializerError) //*** throw($r36); //*** /***********/ r2 = $r36; Aspect.aspectOf().ajc$after$Aspect$2$36f01b1c(ajc$tjp_1); throw r2; } Aspect.aspectOf().ajc$after$Aspect$2$36f01b1c(ajc$tjp_1); }
|
resolved fixed
|
84e4e53
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-17T14:04:29Z
| 2004-05-18T14:20:00Z
|
tests/bugs/pr62642.java
| |
62,642
|
Bug 62642 proper handling of ExceptionInIntializer inside <clinit> in presence of after throwing advice
|
When a <clinit> of a class contains after throwing advice that may catch ExceptionInInitializer errors due to an embedded advice aspectOf() that fails, the ExceptionInIntializer error does not get properly reported. For the example below: public class Main { static int x = 13; int y; public Main() { y= 14; } public static void main(String args[]) { Main m = new Main(); m.y = 3; System.out.println("hi"); } } aspect Aspect { before () : within(*) { System.out.println("BEFORE " + thisJoinPointStaticPart.getKind() + " at " + thisJoinPointStaticPart.getSourceLocation()); } after () : within(*) { System.out.println("AFTER " + thisJoinPointStaticPart.getKind() + " at " + thisJoinPointStaticPart.getSourceLocation()); } } .... when compiled with ajc, and then run, the following exception is given, Exception in thread "main" java.lang.NoClassDefFoundError at Main.<clinit>(Main.java:1) when really one wants the following: Exception in thread "main" java.lang.ExceptionInInitializerError at Main. ... Caused by: org.aspectj.lang.NoAspectBoundException: Aspect at Aspect.aspectOf .. ------------- Here is a fix ... I give the decompiled <clinit> for Main.java and indicate with comments, look for ***LJH ****, what can be woven to fix it. Basically, the catch block for after throwing, when in <clinit>, should first check if the caught exception if a ExceptionInInitializerError, and if so just throw it. ----------- static { org.aspectj.runtime.reflect.Factory r1; java.lang.Throwable r2, r31; int $i0; r1 = new Factory("Main.java", Class.forName("Main")); ajc$tjp_0 = r1.makeSJP("field-set", r1.makeFieldSig("8-x-Main-int-"), 2); ajc$tjp_1 = r1.makeSJP("staticinitialization", r1.makeInitializerSig("8--Main-"), 2); ajc$tjp_10 = r1.makeSJP("preinitialization", r1.makeConstructorSig("1--Main----"), 5); ajc$tjp_2 = r1.makeSJP("field-set", r1.makeFieldSig("0-y-Main-int-"), 6); ajc$tjp_3 = r1.makeSJP("constructor-execution", r1.makeConstructorSig("1--Main----"), 6); ajc$tjp_4 = r1.makeSJP("constructor-call", r1.makeConstructorSig("1--Main----"), 10); ajc$tjp_5 = r1.makeSJP("field-set", r1.makeFieldSig("0-y-Main-int-"), 11); ajc$tjp_6 = r1.makeSJP("field-get", r1.makeFieldSig("19-out-java.lang.System-java.io.PrintStream-"), 12); ajc$tjp_7 = r1.makeSJP("method-call", r1.makeMethodSig("1-println-java.io.PrintStream-java.lang.String:-arg0:--void-"), 12); ajc$tjp_8 = r1.makeSJP("method-execution", r1.makeMethodSig("9-main-Main-[Ljava.lang.String;:-args:--void-"), 10); ajc$tjp_9 = r1.makeSJP("initialization", r1.makeConstructorSig("1--Main----"), 6); try { Aspect.aspectOf().ajc$before$Aspect$1$36f01b1c(ajc$tjp_1); $i0 = 13; try { Aspect.aspectOf().ajc$before$Aspect$1$36f01b1c(ajc$tjp_0); x = $i0; } catch (Throwable $r30) { /*** LJH insert here *****/ if ($r30 instanceof ExceptionInIntializerError) //*** throw($r30); //*** /***********/ r31 = $r30; Aspect.aspectOf().ajc$after$Aspect$2$36f01b1c(ajc$tjp_0); throw r31; } Aspect.aspectOf().ajc$after$Aspect$2$36f01b1c(ajc$tjp_0); } catch (Throwable $r36) { /*** LJH insert here *****/ if ($r36 instanceof ExceptionInIntializerError) //*** throw($r36); //*** /***********/ r2 = $r36; Aspect.aspectOf().ajc$after$Aspect$2$36f01b1c(ajc$tjp_1); throw r2; } Aspect.aspectOf().ajc$after$Aspect$2$36f01b1c(ajc$tjp_1); }
|
resolved fixed
|
84e4e53
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-17T14:04:29Z
| 2004-05-18T14:20:00Z
|
tests/src/org/aspectj/systemtest/ajc121/Ajc121Tests.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.systemtest.ajc121;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc121Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc121Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc121/ajc121.xml");
}
public void test001(){
runTest("false ambiguous binding error (introduced in 1.2rc2)");
}
public void test002(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test003(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test004(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test005(){
runTest("compiler aborts with 'conflicting dominates orders' with circular declare precedences");
}
public void test006(){
runTest("'can't bind type' message has $ for . in type name for declare soft");
}
public void test007(){
runTest("Hiding of Instance Methods by static methods");
}
public void test008(){
runTest("if(false) optimisation");
}
public void test009(){
runTest("if(true) optimisation");
}
public void test010(){
runTest("java.lang.NullPointerException in WeaverMessageHandler class");
}
public void test011(){
runTest("ClassCastException at BcelRenderer.java:169");
}
public void test012(){
runTest("Front-end bug, shouldn't allow patterns of the form foo.., should be foo..*");
}
public void test013() {
runTest("Nullpointer-Exception when defining a withincode() pointcut");
}
public void test014() {
runTest("NPE, Incorrect XLint:unmatchedSuperTypeInCall warning");
}
public void test015_invalidXlint() { // keywords: "laurie hendren"
runTest("invalid warning indicating no match when a match really occurs");
}
public void test016_ByteConversionInstructions() {
runTest("RuntimeException thrown: Could not find instruction: org.apache.bcel.generic.B2I");
String output = getLastRunResult().getStdErr();
assertTrue("Expected to find [b2] in this output but didn't:"+output,output.indexOf("[b2]")!=-1);
assertTrue("Expected to find [b127] in this output but didn't:"+output,output.indexOf("[b127]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
assertTrue("Expected to find [c65] in this output but didn't:"+output,output.indexOf("[c65]")!=-1);
assertTrue("Expected to find [c66] in this output but didn't:"+output,output.indexOf("[c66]")!=-1);
assertTrue("Expected to find [c67] in this output but didn't:"+output,output.indexOf("[c67]")!=-1);
assertTrue("Expected to find [s1] in this output but didn't:"+output,output.indexOf("[s1]")!=-1);
assertTrue("Expected to find [s32767] in this output but didn't:"+output,output.indexOf("[s32767]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
}
public void test017_PrivateMethodCallsInAroundAdvice() {
runTest("Cannot advise private method call in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test018_PrivateFieldSetsInAroundAdvice() {
runTest("Cannot advise private field sets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test019_PrivateFieldGetsInAroundAdvice() {
runTest("Cannot advise private field gets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
// test takes over 5 minutes to run, so not included in normal suite run
// public void test020_branchTargetOffsetTooLargeForShort() {
// runTest("Branch target offset too large for short");
// }
// public void test021_BcelFailureWithVeryLargeClasses() {
// runTest("Weaver fails in BCEL for large classes");
// }
//
// public void test022_BcelFailureWithVeryLargeClasses_Binary() {
// runTest("Weaver fails in BCEL for large classes (binary)");
// }
public void test023_proceedInAround1() {
runTest("proceed used as method name in around advice (1)");
}
public void test024_proceedInAround2() {
runTest("proceed used as method name in around advice (2)");
}
public void test025_proceedInAround3() {
runTest("proceed used as method name in around advice (3)");
}
public void test026_bindingThisAndTargetToTheSameFormal() {
runTest("ajc crashes when compiling the following program (binding this() and target())");
}
public void test027_itdsOnInnerClassesAsStatic() {
runTest("ITDs on inner classes should be static context");
}
public void test028_itdsAndInitializers() {
runTest("resolution of IT field inits");
}
public void test029_falseInvalidAbsoluteTypeName() {
runTest("Valid but inaccessible type names should not be flagged by XLint:invalidAbsoluteTypeName");
}
public void test030_privateITDinitialisersBeingMatched() {
runTest("intertype initialisers should match field set pointcuts");
}
public void test031_privateITDinitialisersBeingMatched_OxfordTest() {
runTest("intertype initialisers should match field set pointcuts (oxford testcase)");
//System.err.println(">"+getLastRunResult().getStdErr());
String exp = ":set field set(int C.n):set field set(int C.m):get field get(int C.n):set field set(int C.n)";
assertTrue("Expected output '"+exp+"' but got "+getLastRunResult().getStdErr(),
getLastRunResult().getStdErr().equals(exp));
}
public void test032_stringConcatForDEOW() {
runTest("Compile time declarations (warning and error) do not accept string concatenation (with +)");
}
public void test033_stringConcatForDEOWErrorCase() {
runTest("Compile time declarations (warning and error) do not accept string concatenation (with +) (2)");
}
public void test034_scopeForITDS_pr61768() {
runTest("scope for inter-type methods");
}
public void test035_innerAspectCallsPrivateMethod_pr71372() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test036_innerAspectCallsPrivateMethod_pr71372_2() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (2)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test037_innerAspectCallsPrivateMethod_pr71372_3() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (3)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test038_innerAspectCallsPrivateMethod_pr71372_4() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (4)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test039_privilegedAspectAccessingPrivateMethods_pr67579() {
runTest("NPE on privileged aspect error");
}
public void test040_privilegedAspectAccessingPrivateMethods_pr67579_2() {
runTest("NPE on privileged aspect error (2)");
}
public void test041_ITDaccessingPrivateMethod_pr67578() {
runTest("Privileged Aspect Access Problem Across Packages");
}
public void test042_ITDaccessingPrivateMethod_pr67578_2() {
runTest("Privileged Aspect Access Problem Across Packages (2)");
}
}
|
62,642
|
Bug 62642 proper handling of ExceptionInIntializer inside <clinit> in presence of after throwing advice
|
When a <clinit> of a class contains after throwing advice that may catch ExceptionInInitializer errors due to an embedded advice aspectOf() that fails, the ExceptionInIntializer error does not get properly reported. For the example below: public class Main { static int x = 13; int y; public Main() { y= 14; } public static void main(String args[]) { Main m = new Main(); m.y = 3; System.out.println("hi"); } } aspect Aspect { before () : within(*) { System.out.println("BEFORE " + thisJoinPointStaticPart.getKind() + " at " + thisJoinPointStaticPart.getSourceLocation()); } after () : within(*) { System.out.println("AFTER " + thisJoinPointStaticPart.getKind() + " at " + thisJoinPointStaticPart.getSourceLocation()); } } .... when compiled with ajc, and then run, the following exception is given, Exception in thread "main" java.lang.NoClassDefFoundError at Main.<clinit>(Main.java:1) when really one wants the following: Exception in thread "main" java.lang.ExceptionInInitializerError at Main. ... Caused by: org.aspectj.lang.NoAspectBoundException: Aspect at Aspect.aspectOf .. ------------- Here is a fix ... I give the decompiled <clinit> for Main.java and indicate with comments, look for ***LJH ****, what can be woven to fix it. Basically, the catch block for after throwing, when in <clinit>, should first check if the caught exception if a ExceptionInInitializerError, and if so just throw it. ----------- static { org.aspectj.runtime.reflect.Factory r1; java.lang.Throwable r2, r31; int $i0; r1 = new Factory("Main.java", Class.forName("Main")); ajc$tjp_0 = r1.makeSJP("field-set", r1.makeFieldSig("8-x-Main-int-"), 2); ajc$tjp_1 = r1.makeSJP("staticinitialization", r1.makeInitializerSig("8--Main-"), 2); ajc$tjp_10 = r1.makeSJP("preinitialization", r1.makeConstructorSig("1--Main----"), 5); ajc$tjp_2 = r1.makeSJP("field-set", r1.makeFieldSig("0-y-Main-int-"), 6); ajc$tjp_3 = r1.makeSJP("constructor-execution", r1.makeConstructorSig("1--Main----"), 6); ajc$tjp_4 = r1.makeSJP("constructor-call", r1.makeConstructorSig("1--Main----"), 10); ajc$tjp_5 = r1.makeSJP("field-set", r1.makeFieldSig("0-y-Main-int-"), 11); ajc$tjp_6 = r1.makeSJP("field-get", r1.makeFieldSig("19-out-java.lang.System-java.io.PrintStream-"), 12); ajc$tjp_7 = r1.makeSJP("method-call", r1.makeMethodSig("1-println-java.io.PrintStream-java.lang.String:-arg0:--void-"), 12); ajc$tjp_8 = r1.makeSJP("method-execution", r1.makeMethodSig("9-main-Main-[Ljava.lang.String;:-args:--void-"), 10); ajc$tjp_9 = r1.makeSJP("initialization", r1.makeConstructorSig("1--Main----"), 6); try { Aspect.aspectOf().ajc$before$Aspect$1$36f01b1c(ajc$tjp_1); $i0 = 13; try { Aspect.aspectOf().ajc$before$Aspect$1$36f01b1c(ajc$tjp_0); x = $i0; } catch (Throwable $r30) { /*** LJH insert here *****/ if ($r30 instanceof ExceptionInIntializerError) //*** throw($r30); //*** /***********/ r31 = $r30; Aspect.aspectOf().ajc$after$Aspect$2$36f01b1c(ajc$tjp_0); throw r31; } Aspect.aspectOf().ajc$after$Aspect$2$36f01b1c(ajc$tjp_0); } catch (Throwable $r36) { /*** LJH insert here *****/ if ($r36 instanceof ExceptionInIntializerError) //*** throw($r36); //*** /***********/ r2 = $r36; Aspect.aspectOf().ajc$after$Aspect$2$36f01b1c(ajc$tjp_1); throw r2; } Aspect.aspectOf().ajc$after$Aspect$2$36f01b1c(ajc$tjp_1); }
|
resolved fixed
|
84e4e53
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-17T14:04:29Z
| 2004-05-18T14:20:00Z
|
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.generic.ACONST_NULL;
import org.aspectj.apache.bcel.generic.ArrayType;
import org.aspectj.apache.bcel.generic.BranchInstruction;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.DUP;
import org.aspectj.apache.bcel.generic.DUP_X1;
import org.aspectj.apache.bcel.generic.FieldInstruction;
import org.aspectj.apache.bcel.generic.INVOKESPECIAL;
import org.aspectj.apache.bcel.generic.INVOKESTATIC;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionTargeter;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.NEW;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.ReturnInstruction;
import org.aspectj.apache.bcel.generic.SWAP;
import org.aspectj.apache.bcel.generic.StoreInstruction;
import org.aspectj.apache.bcel.generic.TargetLostException;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Var;
/*
* Some fun implementation stuff:
*
* * expressionKind advice is non-execution advice
* * may have a target.
* * if the body is extracted, it will be extracted into
* a static method. The first argument to the static
* method is the target
* * advice may expose a this object, but that's the advice's
* consideration, not ours. This object will NOT be cached in another
* local, but will always come from frame zero.
*
* * non-expressionKind advice is execution advice
* * may have a this.
* * target is same as this, and is exposed that way to advice
* (i.e., target will not be cached, will always come from frame zero)
* * if the body is extracted, it will be extracted into a method
* with same static/dynamic modifier as enclosing method. If non-static,
* target of callback call will be this.
*
* * because of these two facts, the setup of the actual arguments (including
* possible target) callback method is the same for both kinds of advice:
* push the targetVar, if it exists (it will not exist for advice on static
* things), then push all the argVars.
*
* Protected things:
*
* * the above is sufficient for non-expressionKind advice for protected things,
* since the target will always be this.
*
* * For expressionKind things, we have to modify the signature of the callback
* method slightly. For non-static expressionKind things, we modify
* the first argument of the callback method NOT to be the type specified
* by the method/field signature (the owner), but rather we type it to
* the currentlyEnclosing type. We are guaranteed this will be fine,
* since the verifier verifies that the target is a subtype of the currently
* enclosingType.
*
* Worries:
*
* * ConstructorCalls will be weirder than all of these, since they
* supposedly don't have a target (according to AspectJ), but they clearly
* do have a target of sorts, just one that needs to be pushed on the stack,
* dupped, and not touched otherwise until the constructor runs.
*
* @author Jim Hugunin
* @author Erik Hilsdale
*
*/
public class BcelShadow extends Shadow {
private ShadowRange range;
private final BcelWorld world;
private final LazyMethodGen enclosingMethod;
private boolean fallsThrough; //XXX not used anymore
// ---- initialization
/**
* 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;
fallsThrough = kind.argsOnStack();
}
// ---- copies all state, including Shadow's mungers...
public BcelShadow copyInto(LazyMethodGen recipient, BcelShadow enclosing) {
BcelShadow s = new BcelShadow(world, getKind(), getSignature(), recipient, enclosing);
List src = mungers;
List dest = s.mungers;
for (Iterator i = src.iterator(); i.hasNext(); ) {
dest.add(i.next());
}
return s;
}
// ---- overridden behaviour
public World getIWorld() {
return world;
}
private void deleteNewAndDup() {
final ConstantPoolGen cpg = getEnclosingClass().getConstantPoolGen();
int depth = 1;
InstructionHandle ih = range.getStart();
while (true) {
Instruction inst = ih.getInstruction();
if (inst instanceof INVOKESPECIAL
&& ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) {
depth++;
} else if (inst instanceof NEW) {
depth--;
if (depth == 0) break;
}
ih = ih.getPrev();
}
// now IH points to the NEW. We're followed by the DUP, and that is followed
// by the actual instruciton we care about.
InstructionHandle newHandle = ih;
InstructionHandle endHandle = newHandle.getNext();
InstructionHandle nextHandle;
if (endHandle.getInstruction() instanceof DUP) {
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else if (endHandle.getInstruction() instanceof DUP_X1) {
InstructionHandle dupHandle = endHandle;
endHandle = endHandle.getNext();
nextHandle = endHandle.getNext();
if (endHandle.getInstruction() instanceof SWAP) {}
else {
// XXX see next XXX comment
throw new RuntimeException("Unhandled kind of new " + endHandle);
}
retargetFrom(newHandle, nextHandle);
retargetFrom(dupHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else {
endHandle = newHandle;
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
// add a POP here... we found a NEW w/o a dup or anything else, so
// we must be in statement context.
getRange().insert(InstructionConstants.POP, Range.OutsideAfter);
}
// assert (dupHandle.getInstruction() instanceof DUP);
try {
range.getBody().delete(newHandle, endHandle);
} catch (TargetLostException e) {
throw new BCException("shouldn't happen");
}
}
private void retargetFrom(InstructionHandle old, InstructionHandle fresh) {
InstructionTargeter[] sources = old.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
sources[i].updateTarget(old, fresh);
}
}
}
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) {
deleteNewAndDup();
initializeArgVars();
} else if (getKind() == ExceptionHandler) {
ShadowRange range = getRange();
InstructionList body = range.getBody();
InstructionHandle start = range.getStart();
InstructionHandle freshIh = body.insert(start, InstructionConstants.NOP);
InstructionTargeter[] targeters = start.getTargeters();
for (int i = 0; i < targeters.length; i++) {
InstructionTargeter t = targeters[i];
if (t instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) t;
er.updateTarget(start, freshIh, body);
}
}
}
// now we ask each munger to request our state
isThisJoinPointLazy = world.isXlazyTjp();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
munger.specializeOn(this);
}
initializeThisJoinPoint();
// 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) {
range.insert(
BcelRenderer.renderExprs(fact, world, argVars),
Range.InsideBefore);
if (targetVar != null) {
range.insert(
BcelRenderer.renderExpr(fact, world, targetVar),
Range.InsideBefore);
}
if (getKind() == ConstructorCall) {
range.insert((Instruction) 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;
}
public int getSourceLine() {
if (range == null) {
if (getEnclosingMethod().hasBody()) {
return Utility.getSourceLine(getEnclosingMethod().getBody().getStart());
} else {
return 0;
}
}
int ret = Utility.getSourceLine(range.getStart());
if (ret < 0) return 0;
return ret;
}
// overrides
public TypeX 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.makeMethodSignature(enclosingMethod),
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().getConstantPoolGen())
.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().getConstantPoolGen()).equals(NameMangler.AJC_POST_CLINIT_NAME)) {
// clinitEnd = clinitEnd.getPrev();
// }
// }
BcelShadow s =
new BcelShadow(
world,
StaticInitialization,
world.makeMethodSignature(enclosingMethod),
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();
TypeX catchType = exceptionRange.getCatchType();
TypeX inType = enclosingMethod.getEnclosingClass().getType();
ResolvedMember sig = Member.makeExceptionHandlerSignature(inType, catchType);
sig.parameterNames = 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() instanceof StoreInstruction &&
startOfHandler.getNext() != null)
{
int slot = ((StoreInstruction)startOfHandler.getInstruction()).getIndex();
//System.out.println("got store: " + startOfHandler.getInstruction() + ", " + index);
InstructionTargeter[] targeters = startOfHandler.getNext().getTargeters();
if (targeters!=null) {
for (int i=targeters.length-1; i >= 0; i--) {
if (targeters[i] instanceof LocalVariableTag) {
LocalVariableTag t = (LocalVariableTag)targeters[i];
if (t.getSlot() == slot) {
return t.getName();
}
//System.out.println("tag: " + targeters[i]);
}
}
}
}
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)
{
InstructionList body = constructor.getBody();
// TypeX 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();
// // TypeX 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)
{
return new BcelShadow(
world,
Initialization,
world.makeMethodSignature(constructor),
constructor,
null);
}
public static BcelShadow makeUnfinishedPreinitialization(
BcelWorld world,
LazyMethodGen constructor)
{
BcelShadow ret = new BcelShadow(
world,
PreInitialization,
world.makeMethodSignature(constructor),
constructor,
null);
ret.fallsThrough = true;
return ret;
}
public static BcelShadow makeMethodExecution(
BcelWorld world,
LazyMethodGen enclosingMethod,
boolean lazyInit)
{
if (!lazyInit) return makeMethodExecution(world, enclosingMethod);
BcelShadow s =
new BcelShadow(
world,
MethodExecution,
enclosingMethod.getMemberView(),
enclosingMethod,
null);
return s;
}
public void init() {
if (range != null) return;
final InstructionList body = enclosingMethod.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(this);
r.associateWithTargets(
Range.genStart(body),
Range.genEnd(body));
}
public static BcelShadow makeMethodExecution(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
return makeShadowForMethod(world, enclosingMethod, MethodExecution,
enclosingMethod.getMemberView()); //world.makeMethodSignature(enclosingMethod));
}
public static BcelShadow makeShadowForMethod(BcelWorld world,
LazyMethodGen enclosingMethod, Shadow.Kind kind, Member sig)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
kind,
sig,
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
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.makeMethodSignature(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 = BcelWorld.makeMethodSignature(
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 makeMethodCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
MethodCall,
BcelWorld.makeMethodSignature(
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,
LazyMethodGen enclosingMethod,
InstructionHandle getHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldGet,
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,
LazyMethodGen enclosingMethod,
InstructionHandle setHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldSet,
BcelWorld.makeFieldSignature(
enclosingMethod.getEnclosingClass(),
(FieldInstruction) setHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, setHandle),
Range.genEnd(body, setHandle));
retargetAllBranches(setHandle, r.getStart());
return s;
}
public static void retargetAllBranches(InstructionHandle from, InstructionHandle to) {
InstructionTargeter[] sources = from.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
InstructionTargeter source = sources[i];
if (source instanceof BranchInstruction) {
source.updateTarget(from, to);
}
}
}
}
// // ---- type access methods
// private ObjectType getTargetBcelType() {
// return (ObjectType) BcelWorld.makeBcelType(getTargetType());
// }
// private Type getArgBcelType(int arg) {
// return BcelWorld.makeBcelType(getArgType(arg));
// }
// ---- kinding
/**
* If the end of my range has no real instructions following then
* my context needs a return at the end.
*/
public boolean terminatesWithReturn() {
return getRange().getRealNext() == null;
}
/**
* Is arg0 occupied with the value of this
*/
public boolean arg0HoldsThis() {
if (getKind().isEnclosingKind()) {
return !getSignature().isStatic();
} else if (enclosingShadow == null) {
//XXX this is mostly right
// this doesn't do the right thing for calls in the pre part of introduced constructors.
return !enclosingMethod.isStatic();
} else {
return ((BcelShadow)enclosingShadow).arg0HoldsThis();
}
}
// ---- argument getting methods
private BcelVar thisVar = null;
private BcelVar targetVar = null;
private BcelVar[] argVars = null;
public Var getThisVar() {
if (!hasThis()) {
throw new IllegalStateException("no this");
}
initializeThisVar();
return thisVar;
}
public Var getTargetVar() {
if (!hasTarget()) {
throw new IllegalStateException("no target");
}
initializeTargetVar();
return targetVar;
}
public Var getArgVar(int i) {
initializeArgVars();
return argVars[i];
}
// reflective thisJoinPoint support
private BcelVar thisJoinPointVar = null;
private boolean isThisJoinPointLazy;
private int lazyTjpConsumers = 0;
private BcelVar thisJoinPointStaticPartVar = null;
// private BcelVar thisEnclosingJoinPointStaticPartVar = null;
public final Var getThisJoinPointStaticPartVar() {
return getThisJoinPointStaticPartBcelVar();
}
public final Var getThisEnclosingJoinPointStaticPartVar() {
return getThisEnclosingJoinPointStaticPartBcelVar();
}
public void requireThisJoinPoint(boolean hasGuardTest) {
if (!hasGuardTest) {
isThisJoinPointLazy = false;
} else {
lazyTjpConsumers++;
}
if (thisJoinPointVar == null) {
thisJoinPointVar = genTempVar(TypeX.forName("org.aspectj.lang.JoinPoint"));
}
}
public Var getThisJoinPointVar() {
requireThisJoinPoint(false);
return thisJoinPointVar;
}
void initializeThisJoinPoint() {
if (thisJoinPointVar == null) return;
if (isThisJoinPointLazy) {
isThisJoinPointLazy = checkLazyTjp();
}
if (isThisJoinPointLazy) {
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 {
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) {
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) {
il.append(createThisJoinPoint());
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 {
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(new ACONST_NULL());
}
if (hasTarget()) {
((BcelVar)getTargetVar()).appendLoad(il, fact);
} else {
il.append(new 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(ResolvedTypeX.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(ResolvedTypeX.OBJECT));
((BcelVar)getArgVar(1)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedTypeX.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;
}
public BcelVar getThisJoinPointStaticPartBcelVar() {
if (thisJoinPointStaticPartVar == null) {
Field field = getEnclosingClass().getTjpField(this);
thisJoinPointStaticPartVar =
new BcelFieldRef(
world.getCoreType(TypeX.forName("org.aspectj.lang.JoinPoint$StaticPart")),
getEnclosingClass().getClassName(),
field.getName());
// getEnclosingClass().warnOnAddedStaticInitializer(this,munger.getSourceLocation());
}
return thisJoinPointStaticPartVar;
}
public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() {
if (enclosingShadow == null) {
// the enclosing of an execution is itself
return getThisJoinPointStaticPartBcelVar();
} else {
return ((BcelShadow)enclosingShadow).getThisJoinPointStaticPartBcelVar();
}
}
//??? need to better understand all the enclosing variants
public Member getEnclosingCodeSignature() {
if (getKind().isEnclosingKind()) {
return getSignature();
} else if (getKind() == Shadow.PreInitialization) {
// PreInit doesn't enclose code but its signature
// is correctly the signature of the ctor.
return getSignature();
} else if (enclosingShadow == null) {
return getEnclosingMethod().getMemberView();
} else {
return enclosingShadow.getSignature();
}
}
private InstructionList makeArgsObjectArray() {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY);
final InstructionList il = new InstructionList();
int alen = getArgCount() ;
il.append(Utility.createConstant(fact, alen));
il.append((Instruction)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
TypeX type = getTargetType();
targetVar = genTempVar(type, "ajc$target");
range.insert(targetVar.createStore(fact), Range.OutsideBefore);
targetVar.setPositionInAroundState(hasThis() ? 1 : 0);
}
}
public void initializeArgVars() {
if (argVars != null) return;
InstructionFactory fact = getFactory();
int len = getArgCount();
argVars = new BcelVar[len];
int positionOffset = (hasTarget() ? 1 : 0) +
((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
if (getKind().argsOnStack()) {
// we move backwards because we're popping off the stack
for (int i = len - 1; i >= 0; i--) {
TypeX 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++) {
TypeX type = getArgType(i);
BcelVar tmp = genTempVar(type, "ajc$arg" + i);
range.insert(tmp.createCopyFrom(fact, index), Range.OutsideBefore);
argVars[i] = tmp;
int position = i;
position += positionOffset;
// System.out.println("set position: " + tmp + ", " + position + " in " + this);
// System.out.println(" hasThis: " + hasThis() + ", hasTarget: " + hasTarget());
tmp.setPositionInAroundState(position);
index += type.getSize();
}
}
}
public void initializeForAroundClosure() {
initializeArgVars();
if (hasTarget()) initializeTargetVar();
if (hasThis()) initializeThisVar();
// System.out.println("initialized: " + this + " thisVar = " + thisVar);
}
// ---- weave methods
void weaveBefore(BcelAdvice munger) {
range.insert(
munger.getAdviceInstructions(this, null, range.getRealStart()),
Range.InsideBefore);
}
public void weaveAfter(BcelAdvice munger) {
weaveAfterThrowing(munger, TypeX.THROWABLE);
weaveAfterReturning(munger);
}
/**
* We guarantee that the return value is on the top of the stack when
* munger.getAdviceInstructions() will be run
* (Unless we have a void return type in which case there's nothing)
*/
public void weaveAfterReturning(BcelAdvice munger) {
// InstructionFactory fact = getFactory();
List returns = new ArrayList();
Instruction ret = null;
for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
if (ih.getInstruction() instanceof ReturnInstruction) {
returns.add(ih);
ret = Utility.copyInstruction(ih.getInstruction());
}
}
InstructionList retList;
InstructionHandle afterAdvice;
if (ret != null) {
retList = new InstructionList(ret);
afterAdvice = retList.getStart();
} else /* if (munger.hasDynamicTests()) */ {
retList = new InstructionList(InstructionConstants.NOP);
afterAdvice = retList.getStart();
// } else {
// retList = new InstructionList();
// afterAdvice = null;
}
InstructionList advice = new InstructionList();
BcelVar tempVar = null;
if (munger.hasExtraParameter()) {
TypeX tempVarType = getReturnType();
if (tempVarType.equals(ResolvedTypeX.VOID)) {
tempVar = genTempVar(TypeX.OBJECT);
advice.append(InstructionConstants.ACONST_NULL);
tempVar.appendStore(advice, getFactory());
} else {
tempVar = genTempVar(tempVarType);
advice.append(InstructionFactory.createDup(tempVarType.getSize()));
tempVar.appendStore(advice, getFactory());
}
}
advice.append(munger.getAdviceInstructions(this, tempVar, afterAdvice));
if (ret != null) {
InstructionHandle gotoTarget = advice.getStart();
for (Iterator i = returns.iterator(); i.hasNext();) {
InstructionHandle ih = (InstructionHandle) i.next();
Utility.replaceInstruction(
ih,
InstructionFactory.createBranchInstruction(
Constants.GOTO,
gotoTarget),
enclosingMethod);
}
range.append(advice);
range.append(retList);
} else {
range.append(advice);
range.append(retList);
}
}
public void weaveAfterThrowing(BcelAdvice munger, TypeX 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);
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, TypeX 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);
// ENH 42743 suggests that we don't soften runtime exceptions.
// To implement that, would need to add instructions into the handler
// stream here to test if exceptionVar is an instanceof RuntimeException,
// and if it is, just re-throw it without softening.
// (Not yet implemented obviously).
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);
InstructionHandle handlerStart = handler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = range.getEnd();//handler.append(fact.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),
// 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);
}
public void weaveCflowEntry(final BcelAdvice munger, final Member cflowStackField) {
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(ResolvedTypeX.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();
BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY);
int alen = cflowStateVars.length;
entrySuccessInstructions.append(Utility.createConstant(fact, alen));
entrySuccessInstructions.append(
(Instruction) 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, cflowStackField));
arrayVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID,
new Type[] { objectArrayType },
Constants.INVOKEVIRTUAL));
}
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
}
// this is the same for both per and non-per
weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) {
public InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice) {
InstructionList exitInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
testResult.appendLoad(exitInstructions, fact);
exitInstructions.append(
InstructionFactory.createBranchInstruction(
Constants.IFEQ,
ifNoAdvice));
}
exitInstructions.append(Utility.createGet(fact, cflowStackField));
exitInstructions
.append(
fact
.createInvoke(
NameMangler.CFLOW_STACK_TYPE,
"pop",
Type.VOID,
new Type[] {
}, Constants.INVOKEVIRTUAL));
return exitInstructions;
}
});
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveAroundInline(
BcelAdvice munger,
boolean hasDynamicTest)
{
/* 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.
*/
// !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...);
Member mungerSig = munger.getSignature();
ResolvedTypeX declaringType = world.resolve(mungerSig.getDeclaringType());
//??? might want some checks here to give better errors
BcelObjectType ot = BcelWorld.getBcelObjectType(declaringType);
LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig);
if (!adviceMethod.getCanInline())
{
weaveAroundClosure(munger, hasDynamicTest);
return;
}
// We can't inline around methods if they have around advice on them, this
// is because the weaving will extract the body and hence the proceed call.
//??? should consider optimizations to recognize simple cases that don't require body extraction
enclosingMethod.setCanInline(false);
// start by exposing various useful things into the frame
final InstructionFactory fact = getFactory();
// now generate the aroundBody method
LazyMethodGen extractedMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
Modifier.PRIVATE,
munger);
// now extract the advice into its own method
String adviceMethodName =
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()) + "$advice";
List argVarList = new ArrayList();
List proceedVarList = new ArrayList();
int extraParamOffset = 0;
// Create the extra parameters that are needed for passing to proceed
// This code is very similar to that found in makeCallToCallback and should
// be rationalized in the future
if (thisVar != null) {
argVarList.add(thisVar);
proceedVarList.add(new BcelVar(thisVar.getType(), extraParamOffset));
extraParamOffset += thisVar.getType().getSize();
}
if (targetVar != null && targetVar != thisVar) {
argVarList.add(targetVar);
proceedVarList.add(new BcelVar(targetVar.getType(), extraParamOffset));
extraParamOffset += targetVar.getType().getSize();
}
for (int i = 0, len = getArgCount(); i < len; i++) {
argVarList.add(argVars[i]);
proceedVarList.add(new BcelVar(argVars[i].getType(), extraParamOffset));
extraParamOffset += argVars[i].getType().getSize();
}
if (thisJoinPointVar != null) {
argVarList.add(thisJoinPointVar);
proceedVarList.add(new BcelVar(thisJoinPointVar.getType(), extraParamOffset));
extraParamOffset += thisJoinPointVar.getType().getSize();
}
Type[] adviceParameterTypes = adviceMethod.getArgumentTypes();
Type[] extractedMethodParameterTypes = extractedMethod.getArgumentTypes();
Type[] parameterTypes =
new Type[extractedMethodParameterTypes.length
+ adviceParameterTypes.length
+ 1];
int parameterIndex = 0;
System.arraycopy(
extractedMethodParameterTypes,
0,
parameterTypes,
parameterIndex,
extractedMethodParameterTypes.length);
parameterIndex += extractedMethodParameterTypes.length;
parameterTypes[parameterIndex++] =
BcelWorld.makeBcelType(adviceMethod.getEnclosingClass().getType());
System.arraycopy(
adviceParameterTypes,
0,
parameterTypes,
parameterIndex,
adviceParameterTypes.length);
LazyMethodGen localAdviceMethod =
new LazyMethodGen(
Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC,
adviceMethod.getReturnType(),
adviceMethodName,
parameterTypes,
new String[0],
getEnclosingClass());
String donorFileName = adviceMethod.getEnclosingClass().getInternalFileName();
String recipientFileName = getEnclosingClass().getInternalFileName();
// System.err.println("donor " + donorFileName);
// System.err.println("recip " + recipientFileName);
if (! donorFileName.equals(recipientFileName)) {
localAdviceMethod.fromFilename = donorFileName;
getEnclosingClass().addInlinedSourceFileInfo(
donorFileName,
adviceMethod.highestLineNumber);
}
getEnclosingClass().addMethodGen(localAdviceMethod);
// create a map that will move all slots in advice method forward by extraParamOffset
// in order to make room for the new proceed-required arguments that are added at
// the beginning of the parameter list
int nVars = adviceMethod.getMaxLocals() + extraParamOffset;
IntMap varMap = IntMap.idMap(nVars);
for (int i=extraParamOffset; i < nVars; i++) {
varMap.put(i-extraParamOffset, i);
}
localAdviceMethod.getBody().insert(
BcelClassWeaver.genInlineInstructions(adviceMethod,
localAdviceMethod, varMap, fact, true));
localAdviceMethod.setMaxLocals(nVars);
//System.err.println(localAdviceMethod);
// the shadow is now empty. First, create a correct call
// to the around advice. This includes both the call (which may involve
// value conversion of the advice arguments) and the return
// (which may involve value conversion of the return value). Right now
// we push a null for the unused closure. It's sad, but there it is.
InstructionList advice = new InstructionList();
// InstructionHandle adviceMethodInvocation;
{
for (Iterator i = argVarList.iterator(); i.hasNext(); ) {
BcelVar var = (BcelVar)i.next();
var.appendLoad(advice, fact);
}
// ??? we don't actually need to push NULL for the closure if we take care
advice.append(
munger.getAdviceArgSetup(
this,
null,
new InstructionList(InstructionConstants.ACONST_NULL)));
// adviceMethodInvocation =
advice.append(
Utility.createInvoke(fact, localAdviceMethod)); //(fact, getWorld(), munger.getSignature()));
advice.append(
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType()),
extractedMethod.getReturnType()));
if (! isFallsThrough()) {
advice.append(InstructionFactory.createReturn(extractedMethod.getReturnType()));
}
}
// now, situate the call inside the possible dynamic tests,
// and actually add the whole mess to the shadow
if (! hasDynamicTest) {
range.append(advice);
} else {
InstructionList afterThingie = new InstructionList(InstructionConstants.NOP);
InstructionList callback = makeCallToCallback(extractedMethod);
if (terminatesWithReturn()) {
callback.append(
InstructionFactory.createReturn(extractedMethod.getReturnType()));
} else {
//InstructionHandle endNop = range.insert(fact.NOP, Range.InsideAfter);
advice.append(
InstructionFactory.createBranchInstruction(
Constants.GOTO,
afterThingie.getStart()));
}
range.append(
munger.getTestInstructions(
this,
advice.getStart(),
callback.getStart(),
advice.getStart()));
range.append(advice);
range.append(callback);
range.append(afterThingie);
}
// now search through the advice, looking for a call to PROCEED.
// Then we replace the call to proceed with some argument setup, and a
// call to the extracted method.
String proceedName =
NameMangler.proceedMethodName(munger.getSignature().getName());
InstructionHandle curr = localAdviceMethod.getBody().getStart();
InstructionHandle end = localAdviceMethod.getBody().getEnd();
ConstantPoolGen cpg = localAdviceMethod.getEnclosingClass().getConstantPoolGen();
while (curr != end) {
InstructionHandle next = curr.getNext();
Instruction inst = curr.getInstruction();
if ((inst instanceof INVOKESTATIC)
&& proceedName.equals(((INVOKESTATIC) inst).getMethodName(cpg))) {
localAdviceMethod.getBody().append(
curr,
getRedoneProceedCall(
fact,
extractedMethod,
munger,
localAdviceMethod,
proceedVarList));
Utility.deleteInstruction(curr, localAdviceMethod);
}
curr = next;
}
// and that's it.
}
private InstructionList getRedoneProceedCall(
InstructionFactory fact,
LazyMethodGen callbackMethod,
BcelAdvice munger,
LazyMethodGen localAdviceMethod,
List argVarList)
{
InstructionList ret = new InstructionList();
// we have on stack all the arguments for the ADVICE call.
// we have in frame somewhere all the arguments for the non-advice call.
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars();
IntMap proceedMap = makeProceedArgumentMap(adviceVars);
// System.out.println(proceedMap + " for " + this);
// System.out.println(argVarList);
ResolvedTypeX[] proceedParamTypes =
world.resolve(munger.getSignature().getParameterTypes());
// remove this*JoinPoint* as arguments to proceed
if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) {
int len = munger.getBaseParameterCount()+1;
ResolvedTypeX[] newTypes = new ResolvedTypeX[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];
ResolvedTypeX 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;
}
public void weaveAroundClosure(
BcelAdvice munger,
boolean hasDynamicTest)
{
InstructionFactory fact = getFactory();
enclosingMethod.setCanInline(false);
// MOVE OUT ALL THE INSTRUCTIONS IN MY SHADOW INTO ANOTHER METHOD!
LazyMethodGen callbackMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
0,
munger);
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars();
String closureClassName =
NameMangler.makeClosureClassName(
getEnclosingClass().getType(),
getEnclosingClass().getNewGeneratedNameTag());
Member constructorSig = new Member(Member.CONSTRUCTOR,
TypeX.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(TypeX.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++) {
stateTempVar.appendConvertableArrayLoad(
returnConversionCode,
fact,
i,
world.resolve(BcelWorld.fromBcel(stateTypes[i])));
}
} else {
returnConversionCode =
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType()),
callbackMethod.getReturnType());
if (!isFallsThrough()) {
returnConversionCode.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
}
}
InstructionList advice = new InstructionList();
advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation));
// advice.append(closureInstantiation);
advice.append(munger.getNonTestAdviceInstructions(this));
advice.append(returnConversionCode);
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(TypeX.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((Instruction)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(new 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 = (BcelVar) 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[] {});
InstructionFactory fact = new InstructionFactory(closureClass.getConstantPoolGen());
// 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(TypeX.OBJECTARRAY.resolve(world), 1);
// int proceedVarIndex = 1;
BcelVar stateVar =
new BcelVar(TypeX.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];
ResolvedTypeX stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
if (proceedMap.hasKey(i)) {
mbody.append(
proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i),
stateTypeX));
} else {
mbody.append(
stateVar.createConvertableArrayLoad(fact, i,
stateTypeX));
}
}
mbody.append(Utility.createInvoke(fact, callbackMethod));
if (getKind() == PreInitialization) {
mbody.append(Utility.createSet(
fact,
AjcMemberMaker.aroundClosurePreInitializationField()));
mbody.append(InstructionConstants.ACONST_NULL);
} else {
mbody.append(
Utility.createConversion(
fact,
callbackMethod.getReturnType(),
Type.OBJECT));
}
mbody.append(InstructionFactory.createReturn(Type.OBJECT));
closureClass.addMethodGen(runMethod);
// class
getEnclosingClass().addGeneratedInner(closureClass);
return constructor;
}
// ---- extraction methods
public LazyMethodGen extractMethod(String newMethodName, int visibilityModifier, ShadowMunger munger) {
LazyMethodGen.assertGoodBody(range.getBody(), newMethodName);
if (!getKind().allowsExtraction()) throw new BCException();
LazyMethodGen freshMethod = createMethodGen(newMethodName,visibilityModifier);
// System.err.println("******");
// System.err.println("ABOUT TO EXTRACT METHOD for" + this);
// enclosingMethod.print(System.err);
// System.err.println("INTO");
// freshMethod.print(System.err);
// System.err.println("WITH REMAP");
// System.err.println(makeRemap());
range.extractInstructionsInto(freshMethod, makeRemap(),
(getKind() != PreInitialization) &&
isFallsThrough());
if (getKind() == PreInitialization) {
addPreInitializationReturnCode(
freshMethod,
getSuperConstructorParameterTypes());
}
getEnclosingClass().addMethodGen(freshMethod,munger.getSourceLocation());
return freshMethod;
}
private void addPreInitializationReturnCode(
LazyMethodGen extractedMethod,
Type[] superConstructorTypes)
{
InstructionList body = extractedMethod.getBody();
final InstructionFactory fact = getFactory();
BcelVar arrayVar = new BcelVar(
world.getCoreType(TypeX.OBJECTARRAY),
extractedMethod.allocateLocal(1));
int len = superConstructorTypes.length;
body.append(Utility.createConstant(fact, len));
body.append((Instruction)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().getConstantPoolGen());
}
/** 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++) {
TypeX type = getArgType(i);
ret.put(oldi, newi);
oldi += type.getSize();
newi += type.getSize();
}
}
// System.err.println("making remap for : " + this);
// if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot());
// if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot());
// System.err.println(ret);
return ret;
}
/**
* The new method always static.
* It may take some extra arguments: this, target.
* If it's argsOnStack, then it must take both this/target
* If it's argsOnFrame, it shares this and target.
* ??? rewrite this to do less array munging, please
*/
private LazyMethodGen createMethodGen(String newMethodName, int visibilityModifier) {
Type[] parameterTypes = BcelWorld.makeBcelTypes(getArgTypes());
int modifiers = Modifier.FINAL | visibilityModifier;
// XXX some bug
// if (! isExpressionKind() && getSignature().isStrict(world)) {
// modifiers |= Modifier.STRICT;
// }
modifiers |= Modifier.STATIC;
if (targetVar != null && targetVar != thisVar) {
TypeX targetType = getTargetType();
ResolvedMember resolvedMember = getSignature().resolve(world);
if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) &&
!samePackage(targetType.getPackageName(), getEnclosingType().getPackageName()))
{
if (!targetType.isAssignableFrom(getThisType(), world)) {
throw new BCException("bad bytecode");
}
targetType = getThisType();
}
parameterTypes = addType(BcelWorld.makeBcelType(targetType), parameterTypes);
}
if (thisVar != null) {
TypeX thisType = getThisType();
parameterTypes = addType(BcelWorld.makeBcelType(thisType), parameterTypes);
}
// We always want to pass down thisJoinPoint in case we have already woven
// some advice in here. If we only have a single piece of around advice on a
// join point, it is unnecessary to accept (and pass) tjp.
if (thisJoinPointVar != null) {
parameterTypes = addTypeToEnd(LazyClassGen.tjpType, parameterTypes);
}
TypeX returnType;
if (getKind() == PreInitialization) {
returnType = TypeX.OBJECTARRAY;
} else {
returnType = getReturnType();
}
return
new LazyMethodGen(
modifiers,
BcelWorld.makeBcelType(returnType),
newMethodName,
parameterTypes,
new String[0],
// XXX again, we need to look up methods!
// TypeX.getNames(getSignature().getExceptions(world)),
getEnclosingClass());
}
private boolean samePackage(String p1, String p2) {
if (p1 == null) return p2 == null;
if (p2 == null) return false;
return p1.equals(p2);
}
private Type[] addType(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[0] = type;
System.arraycopy(types, 0, ret, 1, len);
return ret;
}
private Type[] addTypeToEnd(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[len] = type;
System.arraycopy(types, 0, ret, 0, len);
return ret;
}
public BcelVar genTempVar(TypeX typeX) {
return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize()));
}
// public static final boolean CREATE_TEMP_NAMES = true;
public BcelVar genTempVar(TypeX typeX, String localName) {
BcelVar tv = genTempVar(typeX);
// if (CREATE_TEMP_NAMES) {
// for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
// if (Range.isRangeHandle(ih)) continue;
// ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot()));
// }
// }
return tv;
}
// eh doesn't think we need to garbage collect these (64K is a big number...)
private int genTempVarIndex(int size) {
return enclosingMethod.allocateLocal(size);
}
public InstructionFactory getFactory() {
return getEnclosingClass().getFactory();
}
public ISourceLocation getSourceLocation() {
int sourceLine = getSourceLine();
if (sourceLine == 0 || sourceLine == -1) {
// Thread.currentThread().dumpStack();
// System.err.println(this + ": " + range);
return getEnclosingClass().getType().getSourceLocation();
} else {
return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine);
}
}
public Shadow getEnclosingShadow() {
return enclosingShadow;
}
public LazyMethodGen getEnclosingMethod() {
return enclosingMethod;
}
public boolean isFallsThrough() {
return !terminatesWithReturn(); //fallsThrough;
}
}
|
71,076
|
Bug 71076 Missing Javadoc comments that aren't missing
|
Reported in the AJDT newsgroup: Go to Preferences > Java > Compiler > Javadoc and set "Missing javadoc comments" to "Warning". You then get warnings against things you wouldn't expect, such as after advice. /** * A comment */ public aspect World { pointcut greeting() : execution(* Hello.sayHello(..)); /** * A comment */ after() returning : greeting() { System.out.println("world"); } } This gives two warnings, one for the aspect itself, and one for the after returning advice. The warnings occur both with and without the existence of Javadoc comments!
|
resolved fixed
|
5b90224
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-18T10:33:07Z
| 2004-07-29T14:06:40Z
|
org.aspectj.ajdt.core/testdata/javadoc/World.java
| |
71,076
|
Bug 71076 Missing Javadoc comments that aren't missing
|
Reported in the AJDT newsgroup: Go to Preferences > Java > Compiler > Javadoc and set "Missing javadoc comments" to "Warning". You then get warnings against things you wouldn't expect, such as after advice. /** * A comment */ public aspect World { pointcut greeting() : execution(* Hello.sayHello(..)); /** * A comment */ after() returning : greeting() { System.out.println("world"); } } This gives two warnings, one for the aspect itself, and one for the after returning advice. The warnings occur both with and without the existence of Javadoc comments!
|
resolved fixed
|
5b90224
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-18T10:33:07Z
| 2004-07-29T14:06:40Z
|
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/AjdtBatchTests.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.batch;
import junit.framework.*;
public class AjdtBatchTests extends TestCase {
public static Test suite() {
TestSuite suite = new TestSuite(AjdtBatchTests.class.getName());
// Abstract superclass
//suite.addTestSuite(CommandTestCase.class);
//$JUnit-BEGIN$
suite.addTestSuite(BasicCommandTestCase.class);
suite.addTestSuite(BinaryFormsTestCase.class);
suite.addTestSuite(CompileAndRunTestCase.class);
suite.addTestSuite(PerformanceTestCase.class);
suite.addTestSuite(ImageTestCase.class);
suite.addTestSuite(MultipleCompileTestCase.class);
// XXX suite.addTestSuite(VerifyWeaveTestCase.class);
//suite.addTestSuite(WorkingCommandTestCase.class);
//$JUnit-END$
return suite;
}
public AjdtBatchTests(String name) { super(name); }
}
|
71,076
|
Bug 71076 Missing Javadoc comments that aren't missing
|
Reported in the AJDT newsgroup: Go to Preferences > Java > Compiler > Javadoc and set "Missing javadoc comments" to "Warning". You then get warnings against things you wouldn't expect, such as after advice. /** * A comment */ public aspect World { pointcut greeting() : execution(* Hello.sayHello(..)); /** * A comment */ after() returning : greeting() { System.out.println("world"); } } This gives two warnings, one for the aspect itself, and one for the after returning advice. The warnings occur both with and without the existence of Javadoc comments!
|
resolved fixed
|
5b90224
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-18T10:33:07Z
| 2004-07-29T14:06:40Z
|
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/JavadocTest.java
| |
71,723
|
Bug 71723 Inconsistency in scoping of protected members in ITDs
|
When introducing new member functions to existing classes via inter-type declarations, the scoping rules that apply to the ITD bodies are the same as for the aspect - for example, private members of the target class cannot be accessed unless the aspect is privileged. Similarly, protected members of classes in different packages should not be visible in ITDs unless the aspect is privileged. This rule is only enforced for protected members declared in the target class - protected members that are inherited are visible from ITDs in aspects in different packages. The following is an example of this: ---------------------- package foo; public class Foo extends AncientFoo { protected int i() { return 42; } public static void main(String[] args) { new Foo().doStuff(); } public void doStuff() { } protected int ancientI() { return 42; } } class AncientFoo { protected int ancientI() { return -42; } protected int ancientJ() { return 0; } } ---------- package bar; import foo.Foo; aspect Bar { public void Foo.doing() { try { System.out.println(i()); // fails in ajc System.out.println(ancientI()); // fails in ajc System.out.println(ancientJ()); // succeeds System.out.println(clone()); // succeeds } catch(Throwable t) { } } before(Foo f) : call(* doStuff(..)) && target(f) { f.doing(); } } ------------------- All four calls in Foo.doing() should fail, as they refer to protected members of foo.Foo from package bar. However, only the first 2 - the ones directly declared/overridden in foo.Foo - are detected as errors, and removing them makes the rest compile and execute. Best wishes, Pavel
|
resolved fixed
|
dfb15c1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-18T12:39:40Z
| 2004-08-10T17:46:40Z
|
tests/bugs/pr71723/foo/Foo.java
| |
71,723
|
Bug 71723 Inconsistency in scoping of protected members in ITDs
|
When introducing new member functions to existing classes via inter-type declarations, the scoping rules that apply to the ITD bodies are the same as for the aspect - for example, private members of the target class cannot be accessed unless the aspect is privileged. Similarly, protected members of classes in different packages should not be visible in ITDs unless the aspect is privileged. This rule is only enforced for protected members declared in the target class - protected members that are inherited are visible from ITDs in aspects in different packages. The following is an example of this: ---------------------- package foo; public class Foo extends AncientFoo { protected int i() { return 42; } public static void main(String[] args) { new Foo().doStuff(); } public void doStuff() { } protected int ancientI() { return 42; } } class AncientFoo { protected int ancientI() { return -42; } protected int ancientJ() { return 0; } } ---------- package bar; import foo.Foo; aspect Bar { public void Foo.doing() { try { System.out.println(i()); // fails in ajc System.out.println(ancientI()); // fails in ajc System.out.println(ancientJ()); // succeeds System.out.println(clone()); // succeeds } catch(Throwable t) { } } before(Foo f) : call(* doStuff(..)) && target(f) { f.doing(); } } ------------------- All four calls in Foo.doing() should fail, as they refer to protected members of foo.Foo from package bar. However, only the first 2 - the ones directly declared/overridden in foo.Foo - are detected as errors, and removing them makes the rest compile and execute. Best wishes, Pavel
|
resolved fixed
|
dfb15c1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-18T12:39:40Z
| 2004-08-10T17:46:40Z
|
tests/src/org/aspectj/systemtest/ajc121/Ajc121Tests.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.systemtest.ajc121;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc121Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc121Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc121/ajc121.xml");
}
public void test001(){
runTest("false ambiguous binding error (introduced in 1.2rc2)");
}
public void test002(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test003(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test004(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test005(){
runTest("compiler aborts with 'conflicting dominates orders' with circular declare precedences");
}
public void test006(){
runTest("'can't bind type' message has $ for . in type name for declare soft");
}
public void test007(){
runTest("Hiding of Instance Methods by static methods");
}
public void test008(){
runTest("if(false) optimisation");
}
public void test009(){
runTest("if(true) optimisation");
}
public void test010(){
runTest("java.lang.NullPointerException in WeaverMessageHandler class");
}
public void test011(){
runTest("ClassCastException at BcelRenderer.java:169");
}
public void test012(){
runTest("Front-end bug, shouldn't allow patterns of the form foo.., should be foo..*");
}
public void test013() {
runTest("Nullpointer-Exception when defining a withincode() pointcut");
}
public void test014() {
runTest("NPE, Incorrect XLint:unmatchedSuperTypeInCall warning");
}
public void test015_invalidXlint() { // keywords: "laurie hendren"
runTest("invalid warning indicating no match when a match really occurs");
}
public void test016_ByteConversionInstructions() {
runTest("RuntimeException thrown: Could not find instruction: org.apache.bcel.generic.B2I");
String output = getLastRunResult().getStdErr();
assertTrue("Expected to find [b2] in this output but didn't:"+output,output.indexOf("[b2]")!=-1);
assertTrue("Expected to find [b127] in this output but didn't:"+output,output.indexOf("[b127]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
assertTrue("Expected to find [c65] in this output but didn't:"+output,output.indexOf("[c65]")!=-1);
assertTrue("Expected to find [c66] in this output but didn't:"+output,output.indexOf("[c66]")!=-1);
assertTrue("Expected to find [c67] in this output but didn't:"+output,output.indexOf("[c67]")!=-1);
assertTrue("Expected to find [s1] in this output but didn't:"+output,output.indexOf("[s1]")!=-1);
assertTrue("Expected to find [s32767] in this output but didn't:"+output,output.indexOf("[s32767]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
}
public void test017_PrivateMethodCallsInAroundAdvice() {
runTest("Cannot advise private method call in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test018_PrivateFieldSetsInAroundAdvice() {
runTest("Cannot advise private field sets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test019_PrivateFieldGetsInAroundAdvice() {
runTest("Cannot advise private field gets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
// test takes over 5 minutes to run, so not included in normal suite run
// public void test020_branchTargetOffsetTooLargeForShort() {
// runTest("Branch target offset too large for short");
// }
// public void test021_BcelFailureWithVeryLargeClasses() {
// runTest("Weaver fails in BCEL for large classes");
// }
//
// public void test022_BcelFailureWithVeryLargeClasses_Binary() {
// runTest("Weaver fails in BCEL for large classes (binary)");
// }
public void test023_proceedInAround1() {
runTest("proceed used as method name in around advice (1)");
}
public void test024_proceedInAround2() {
runTest("proceed used as method name in around advice (2)");
}
public void test025_proceedInAround3() {
runTest("proceed used as method name in around advice (3)");
}
public void test026_bindingThisAndTargetToTheSameFormal() {
runTest("ajc crashes when compiling the following program (binding this() and target())");
}
public void test027_itdsOnInnerClassesAsStatic() {
runTest("ITDs on inner classes should be static context");
}
public void test028_itdsAndInitializers() {
runTest("resolution of IT field inits");
}
public void test029_falseInvalidAbsoluteTypeName() {
runTest("Valid but inaccessible type names should not be flagged by XLint:invalidAbsoluteTypeName");
}
public void test030_privateITDinitialisersBeingMatched() {
runTest("intertype initialisers should match field set pointcuts");
}
public void test031_privateITDinitialisersBeingMatched_OxfordTest() {
runTest("intertype initialisers should match field set pointcuts (oxford testcase)");
//System.err.println(">"+getLastRunResult().getStdErr());
String exp = ":set field set(int C.n):set field set(int C.m):get field get(int C.n):set field set(int C.n)";
assertTrue("Expected output '"+exp+"' but got "+getLastRunResult().getStdErr(),
getLastRunResult().getStdErr().equals(exp));
}
public void test032_stringConcatForDEOW() {
runTest("Compile time declarations (warning and error) do not accept string concatenation (with +)");
}
public void test033_stringConcatForDEOWErrorCase() {
runTest("Compile time declarations (warning and error) do not accept string concatenation (with +) (2)");
}
public void test034_scopeForITDS_pr61768() {
runTest("scope for inter-type methods");
}
public void test035_innerAspectCallsPrivateMethod_pr71372() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test036_innerAspectCallsPrivateMethod_pr71372_2() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (2)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test037_innerAspectCallsPrivateMethod_pr71372_3() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (3)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test038_innerAspectCallsPrivateMethod_pr71372_4() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (4)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test039_privilegedAspectAccessingPrivateMethods_pr67579() {
runTest("NPE on privileged aspect error");
}
public void test040_privilegedAspectAccessingPrivateMethods_pr67579_2() {
runTest("NPE on privileged aspect error (2)");
}
public void test041_ITDaccessingPrivateMethod_pr67578() {
runTest("Privileged Aspect Access Problem Across Packages");
}
public void test042_ITDaccessingPrivateMethod_pr67578_2() {
runTest("Privileged Aspect Access Problem Across Packages (2)");
}
public void test043_pr62642_ExceptionInInitializerError() {
runTest("proper handling of ExceptionInIntializer inside clinit in presence of after throwing advice");
String s = getLastRunResult().getStdErr();
assertTrue("Output should contain java.lang.ExceptionInInitializerError but is '"+s+"'",
s.indexOf("java.lang.ExceptionInInitializerError")!=-1);
// No getCause on 1.3 JVMs
// assertTrue("Output should contain 'CAUSE=org.aspectj.lang.NoAspectBoundException' but is '"+s+"'",
// s.indexOf("CAUSE=org.aspectj.lang.NoAspectBoundException")!=-1);
}
public void test044_ITDnameClashes() {
runTest("ITD name clashes with private members");
}
}
|
49,657
|
Bug 49657 Weaver results in rt error if affected base class not exposed
|
I was weaving a 3rd party library and wrote an aspect that should affect both a base class and a derived class, but inadvertently wove only the derived class. This resulted in the following error. I would like the weaver to catch this kind of error at weave (link) time, rather than creating code that results in a rt error... I get this error in 1.1.1 final and in a fairly recent version from CVS HEAD: java.lang.AbstractMethodError at ajee.logging.LogManager.ajc$interMethodDispatch1 $ajee_logging_LogManager$ajee_logging_Loggable$getLogger(LogManager.java) at ajee.tracing.ExecutionTracer.ajc$before$ajee_tracing_ExecutionTracer$926 (ExecutionTracer.java:62) at library.Derived.<init>(Derived.java:46) This line is a call to super(); I've attached a small example that reproduces another error that I think is related: C:\devel\test\ctors\twoPass>build C:\devel\test\ctors\twoPass>call ajc -outjar fullBase.jar sample\Base.java sampl e\Derived.java Exception in thread "main" java.lang.ExceptionInInitializerError at sample.Derived.<init>(Derived.java:6) at sample.Derived.main(Derived.java:13) Caused by: org.aspectj.lang.NoAspectBoundException at sample.Trace.aspectOf(Trace.aj) at sample.Trace.<init>(Trace.aj:5) at sample.Trace.ajc$postClinit(Trace.aj) at sample.Trace.<clinit>(Trace.aj:5) ... 2 more
|
resolved fixed
|
dbe1024
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-19T16:38:16Z
| 2004-01-07T21:13:20Z
|
org.aspectj.ajdt.core/testdata/partialHierarchy/sample/Base.java
| |
49,657
|
Bug 49657 Weaver results in rt error if affected base class not exposed
|
I was weaving a 3rd party library and wrote an aspect that should affect both a base class and a derived class, but inadvertently wove only the derived class. This resulted in the following error. I would like the weaver to catch this kind of error at weave (link) time, rather than creating code that results in a rt error... I get this error in 1.1.1 final and in a fairly recent version from CVS HEAD: java.lang.AbstractMethodError at ajee.logging.LogManager.ajc$interMethodDispatch1 $ajee_logging_LogManager$ajee_logging_Loggable$getLogger(LogManager.java) at ajee.tracing.ExecutionTracer.ajc$before$ajee_tracing_ExecutionTracer$926 (ExecutionTracer.java:62) at library.Derived.<init>(Derived.java:46) This line is a call to super(); I've attached a small example that reproduces another error that I think is related: C:\devel\test\ctors\twoPass>build C:\devel\test\ctors\twoPass>call ajc -outjar fullBase.jar sample\Base.java sampl e\Derived.java Exception in thread "main" java.lang.ExceptionInInitializerError at sample.Derived.<init>(Derived.java:6) at sample.Derived.main(Derived.java:13) Caused by: org.aspectj.lang.NoAspectBoundException at sample.Trace.aspectOf(Trace.aj) at sample.Trace.<init>(Trace.aj:5) at sample.Trace.ajc$postClinit(Trace.aj) at sample.Trace.<clinit>(Trace.aj:5) ... 2 more
|
resolved fixed
|
dbe1024
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-19T16:38:16Z
| 2004-01-07T21:13:20Z
|
org.aspectj.ajdt.core/testdata/partialHierarchy/sample/Derived.java
| |
49,657
|
Bug 49657 Weaver results in rt error if affected base class not exposed
|
I was weaving a 3rd party library and wrote an aspect that should affect both a base class and a derived class, but inadvertently wove only the derived class. This resulted in the following error. I would like the weaver to catch this kind of error at weave (link) time, rather than creating code that results in a rt error... I get this error in 1.1.1 final and in a fairly recent version from CVS HEAD: java.lang.AbstractMethodError at ajee.logging.LogManager.ajc$interMethodDispatch1 $ajee_logging_LogManager$ajee_logging_Loggable$getLogger(LogManager.java) at ajee.tracing.ExecutionTracer.ajc$before$ajee_tracing_ExecutionTracer$926 (ExecutionTracer.java:62) at library.Derived.<init>(Derived.java:46) This line is a call to super(); I've attached a small example that reproduces another error that I think is related: C:\devel\test\ctors\twoPass>build C:\devel\test\ctors\twoPass>call ajc -outjar fullBase.jar sample\Base.java sampl e\Derived.java Exception in thread "main" java.lang.ExceptionInInitializerError at sample.Derived.<init>(Derived.java:6) at sample.Derived.main(Derived.java:13) Caused by: org.aspectj.lang.NoAspectBoundException at sample.Trace.aspectOf(Trace.aj) at sample.Trace.<init>(Trace.aj:5) at sample.Trace.ajc$postClinit(Trace.aj) at sample.Trace.<clinit>(Trace.aj:5) ... 2 more
|
resolved fixed
|
dbe1024
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-19T16:38:16Z
| 2004-01-07T21:13:20Z
|
org.aspectj.ajdt.core/testdata/partialHierarchy/sample/Iface.java
| |
49,657
|
Bug 49657 Weaver results in rt error if affected base class not exposed
|
I was weaving a 3rd party library and wrote an aspect that should affect both a base class and a derived class, but inadvertently wove only the derived class. This resulted in the following error. I would like the weaver to catch this kind of error at weave (link) time, rather than creating code that results in a rt error... I get this error in 1.1.1 final and in a fairly recent version from CVS HEAD: java.lang.AbstractMethodError at ajee.logging.LogManager.ajc$interMethodDispatch1 $ajee_logging_LogManager$ajee_logging_Loggable$getLogger(LogManager.java) at ajee.tracing.ExecutionTracer.ajc$before$ajee_tracing_ExecutionTracer$926 (ExecutionTracer.java:62) at library.Derived.<init>(Derived.java:46) This line is a call to super(); I've attached a small example that reproduces another error that I think is related: C:\devel\test\ctors\twoPass>build C:\devel\test\ctors\twoPass>call ajc -outjar fullBase.jar sample\Base.java sampl e\Derived.java Exception in thread "main" java.lang.ExceptionInInitializerError at sample.Derived.<init>(Derived.java:6) at sample.Derived.main(Derived.java:13) Caused by: org.aspectj.lang.NoAspectBoundException at sample.Trace.aspectOf(Trace.aj) at sample.Trace.<init>(Trace.aj:5) at sample.Trace.ajc$postClinit(Trace.aj) at sample.Trace.<clinit>(Trace.aj:5) ... 2 more
|
resolved fixed
|
dbe1024
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-19T16:38:16Z
| 2004-01-07T21:13:20Z
|
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/AjdtBatchTests.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.batch;
import junit.framework.*;
public class AjdtBatchTests extends TestCase {
public static Test suite() {
TestSuite suite = new TestSuite(AjdtBatchTests.class.getName());
// Abstract superclass
//suite.addTestSuite(CommandTestCase.class);
//$JUnit-BEGIN$
suite.addTestSuite(BasicCommandTestCase.class);
suite.addTestSuite(BinaryFormsTestCase.class);
suite.addTestSuite(CompileAndRunTestCase.class);
suite.addTestSuite(PerformanceTestCase.class);
suite.addTestSuite(ImageTestCase.class);
suite.addTestSuite(MultipleCompileTestCase.class);
suite.addTestSuite(JavadocTest.class);
// XXX suite.addTestSuite(VerifyWeaveTestCase.class);
//suite.addTestSuite(WorkingCommandTestCase.class);
//$JUnit-END$
return suite;
}
public AjdtBatchTests(String name) { super(name); }
}
|
49,657
|
Bug 49657 Weaver results in rt error if affected base class not exposed
|
I was weaving a 3rd party library and wrote an aspect that should affect both a base class and a derived class, but inadvertently wove only the derived class. This resulted in the following error. I would like the weaver to catch this kind of error at weave (link) time, rather than creating code that results in a rt error... I get this error in 1.1.1 final and in a fairly recent version from CVS HEAD: java.lang.AbstractMethodError at ajee.logging.LogManager.ajc$interMethodDispatch1 $ajee_logging_LogManager$ajee_logging_Loggable$getLogger(LogManager.java) at ajee.tracing.ExecutionTracer.ajc$before$ajee_tracing_ExecutionTracer$926 (ExecutionTracer.java:62) at library.Derived.<init>(Derived.java:46) This line is a call to super(); I've attached a small example that reproduces another error that I think is related: C:\devel\test\ctors\twoPass>build C:\devel\test\ctors\twoPass>call ajc -outjar fullBase.jar sample\Base.java sampl e\Derived.java Exception in thread "main" java.lang.ExceptionInInitializerError at sample.Derived.<init>(Derived.java:6) at sample.Derived.main(Derived.java:13) Caused by: org.aspectj.lang.NoAspectBoundException at sample.Trace.aspectOf(Trace.aj) at sample.Trace.<init>(Trace.aj:5) at sample.Trace.ajc$postClinit(Trace.aj) at sample.Trace.<clinit>(Trace.aj:5) ... 2 more
|
resolved fixed
|
dbe1024
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-19T16:38:16Z
| 2004-01-07T21:13:20Z
|
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/PartiallyExposedHierarchyTestCase.java
| |
49,657
|
Bug 49657 Weaver results in rt error if affected base class not exposed
|
I was weaving a 3rd party library and wrote an aspect that should affect both a base class and a derived class, but inadvertently wove only the derived class. This resulted in the following error. I would like the weaver to catch this kind of error at weave (link) time, rather than creating code that results in a rt error... I get this error in 1.1.1 final and in a fairly recent version from CVS HEAD: java.lang.AbstractMethodError at ajee.logging.LogManager.ajc$interMethodDispatch1 $ajee_logging_LogManager$ajee_logging_Loggable$getLogger(LogManager.java) at ajee.tracing.ExecutionTracer.ajc$before$ajee_tracing_ExecutionTracer$926 (ExecutionTracer.java:62) at library.Derived.<init>(Derived.java:46) This line is a call to super(); I've attached a small example that reproduces another error that I think is related: C:\devel\test\ctors\twoPass>build C:\devel\test\ctors\twoPass>call ajc -outjar fullBase.jar sample\Base.java sampl e\Derived.java Exception in thread "main" java.lang.ExceptionInInitializerError at sample.Derived.<init>(Derived.java:6) at sample.Derived.main(Derived.java:13) Caused by: org.aspectj.lang.NoAspectBoundException at sample.Trace.aspectOf(Trace.aj) at sample.Trace.<init>(Trace.aj:5) at sample.Trace.ajc$postClinit(Trace.aj) at sample.Trace.<clinit>(Trace.aj:5) ... 2 more
|
resolved fixed
|
dbe1024
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-19T16:38:16Z
| 2004-01-07T21:13:20Z
|
weaver/src/org/aspectj/weaver/ResolvedTypeX.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
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.Iterator;
import java.util.List;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.weaver.patterns.Declare;
import org.aspectj.weaver.patterns.PerClause;
public abstract class ResolvedTypeX extends TypeX {
protected World world;
ResolvedTypeX(String signature, World world) {
super(signature);
this.world = world;
}
// ---- things that don't require a world
/** returns Iterator<ResolvedTypeX>
*/
public final Iterator getDirectSupertypes() {
Iterator ifacesIterator = Iterators.array(getDeclaredInterfaces());
ResolvedTypeX superclass = getSuperclass();
if (superclass == null) {
return ifacesIterator;
} else {
return Iterators.snoc(ifacesIterator, superclass);
}
}
public abstract ResolvedMember[] getDeclaredFields();
public abstract ResolvedMember[] getDeclaredMethods();
public abstract ResolvedTypeX[] getDeclaredInterfaces();
public abstract ResolvedMember[] getDeclaredPointcuts();
public abstract ResolvedTypeX getSuperclass();
public abstract int getModifiers();
public abstract boolean needsNoConversionFrom(TypeX other);
public abstract boolean isCoerceableFrom(TypeX other);
public abstract boolean isAssignableFrom(TypeX other);
// ---- things that would require a world if I weren't resolved
public final Iterator getDirectSupertypes(World world) {
return getDirectSupertypes();
}
public final ResolvedMember[] getDeclaredFields(World world) {
return getDeclaredFields();
}
public final ResolvedMember[] getDeclaredMethods(World world) {
return getDeclaredMethods();
}
public final TypeX[] getDeclaredInterfaces(World world) {
return getDeclaredInterfaces();
}
public final ResolvedMember[] getDeclaredPointcuts(World world) {
return getDeclaredPointcuts();
}
public final int getModifiers(World world) {
return getModifiers();
}
public final TypeX getSuperclass(World world) {
return getSuperclass();
}
// conversions
public final boolean isAssignableFrom(TypeX other, World world) {
return isAssignableFrom(other);
}
public final boolean isCoerceableFrom(TypeX other, World world) {
return isCoerceableFrom(other);
}
public boolean needsNoConversionFrom(TypeX other, World world) {
return needsNoConversionFrom(other);
}
public final boolean isConvertableFrom(TypeX other) {
if (this.equals(OBJECT) || other.equals(OBJECT)) return true;
return this.isCoerceableFrom(other);
}
// utilities
public ResolvedTypeX getResolvedComponentType() {
return null;
}
public ResolvedTypeX resolve(World world) {
return this;
}
public World getWorld() {
return world;
}
// ---- things from object
public final boolean equals(Object other) {
if (other instanceof ResolvedTypeX) {
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
*
* <ul><li> fields from current class </li>
* <li> recur into direct superinterfaces </li>
* <li> recur into superclass </li>
* </ul>
*
* We keep a hashSet of interfaces that we've visited so we don't spiral
* out into 2^n land.
*/
public Iterator getFields() {
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedTypeX)o).getDirectSupertypes());
}
};
Iterators.Getter fieldGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return Iterators.array(((ResolvedTypeX)o).getDeclaredFields());
}
};
return
Iterators.mapOver(
Iterators.recur(this, typeGetter),
fieldGetter);
}
/**
* 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
*
* <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 </li>
* </ul>
*
* We keep a hashSet of interfaces that we've visited so we don't spiral
* out into 2^n land.
*/
public Iterator getMethods() {
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter ifaceGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
Iterators.array(((ResolvedTypeX)o).getDeclaredInterfaces())
);
}
};
Iterators.Getter methodGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return Iterators.array(((ResolvedTypeX)o).getDeclaredMethods());
}
};
return
Iterators.mapOver(
Iterators.append(
new Iterator() {
ResolvedTypeX curr = ResolvedTypeX.this;
public boolean hasNext() {
return curr != null;
}
public Object next() {
ResolvedTypeX ret = curr;
curr = curr.getSuperclass();
return ret;
}
public void remove() {
throw new UnsupportedOperationException();
}
},
Iterators.recur(this, ifaceGetter)),
methodGetter);
}
/**
* described in JVM spec 2ed 5.4.3.2
*/
public ResolvedMember lookupField(Member m) {
return lookupMember(m, getFields());
}
/**
* described in JVM spec 2ed 5.4.3.3
*/
public ResolvedMember lookupMethod(Member m) {
return lookupMember(m, getMethods());
}
/** return null if not found */
private ResolvedMember lookupMember(Member m, Iterator i) {
while (i.hasNext()) {
ResolvedMember f = (ResolvedMember) i.next();
if (matches(f, m)) return f;
}
return null; //ResolvedMember.Missing;
//throw new BCException("can't find " + m);
}
/** 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;
}
public static boolean matches(Member m1, Member m2) {
if (m1 == null) return m2 == null;
if (m2 == null) return false;
return m1.getName().equals(m2.getName()) && m1.getSignature().equals(m2.getSignature());
}
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;
}
TypeX[] p1 = m1.getParameterTypes();
TypeX[] 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
*
* <ul><li> pointcuts from current class </li>
* <li> recur into direct superinterfaces </li>
* <li> recur into superclass </li>
* </ul>
*
* We keep a hashSet of interfaces that we've visited so we don't spiral
* out into 2^n land.
*/
public Iterator getPointcuts() {
final Iterators.Filter dupFilter = Iterators.dupFilter();
// same order as fields
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedTypeX)o).getDirectSupertypes());
}
};
Iterators.Getter pointcutGetter = new Iterators.Getter() {
public Iterator get(Object o) {
//System.err.println("getting for " + o);
return Iterators.array(((ResolvedTypeX)o).getDeclaredPointcuts());
}
};
return
Iterators.mapOver(
Iterators.recur(this, typeGetter),
pointcutGetter);
}
public ResolvedPointcutDefinition findPointcut(String name) {
//System.err.println("looking for pointcuts " + this);
for (Iterator i = getPointcuts(); i.hasNext(); ) {
ResolvedPointcutDefinition f = (ResolvedPointcutDefinition) i.next();
//System.err.println(f);
if (name.equals(f.getName())) {
return f;
}
}
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() {
crosscuttingMembers = new CrosscuttingMembers(this);
crosscuttingMembers.setPerClause(getPerClause());
crosscuttingMembers.addShadowMungers(collectShadowMungers());
crosscuttingMembers.addTypeMungers(getTypeMungers());
crosscuttingMembers.addDeclares(collectDeclares(!this.doesNotExposeShadowMungers()));
crosscuttingMembers.addPrivilegedAccesses(getPrivilegedAccesses());
//System.err.println("collected cc members: " + this + ", " + collectDeclares());
return crosscuttingMembers;
}
public final Collection collectDeclares(boolean includeAdviceLike) {
if (! this.isAspect() ) return Collections.EMPTY_LIST;
ArrayList ret = new ArrayList();
//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 dupFilter = Iterators.dupFilter();
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedTypeX)o).getDirectSupertypes());
}
};
Iterator typeIterator = Iterators.recur(this, typeGetter);
while (typeIterator.hasNext()) {
ResolvedTypeX ty = (ResolvedTypeX) typeIterator.next();
//System.out.println("super: " + ty + ", " + );
for (Iterator i = ty.getDeclares().iterator(); i.hasNext();) {
Declare dec = (Declare) i.next();
if (dec.isAdviceLike()) ret.add(dec);
}
}
}
return ret;
}
private final Collection collectShadowMungers() {
if (! this.isAspect() || this.isAbstract() || this.doesNotExposeShadowMungers()) return Collections.EMPTY_LIST;
ArrayList acc = new ArrayList();
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedTypeX)o).getDirectSupertypes());
}
};
Iterator typeIterator = Iterators.recur(this, typeGetter);
while (typeIterator.hasNext()) {
ResolvedTypeX ty = (ResolvedTypeX) typeIterator.next();
acc.addAll(ty.getDeclaredShadowMungers());
}
return acc;
}
protected boolean doesNotExposeShadowMungers() {
return false;
}
public PerClause getPerClause() { return null; }
protected Collection getDeclares() {
return Collections.EMPTY_LIST;
}
protected Collection getTypeMungers() { return Collections.EMPTY_LIST; }
protected Collection getPrivilegedAccesses() { return Collections.EMPTY_LIST; }
// ---- 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 isSynthetic() {
return signature.indexOf("$ajc") != -1;
}
public final boolean isFinal() {
return Modifier.isFinal(getModifiers());
}
public Collection getDeclaredAdvice() {
List l = new ArrayList();
ResolvedMember[] methods = getDeclaredMethods();
for (int i=0, len = methods.length; i < len; i++) {
ShadowMunger munger = methods[i].getAssociatedShadowMunger();
if (munger != null) l.add(munger);
}
return l;
}
private List shadowMungers = new ArrayList(0);
public Collection getDeclaredShadowMungers() {
Collection c = getDeclaredAdvice();
c.addAll(shadowMungers);
return c;
}
public void addShadowMunger(ShadowMunger munger) {
shadowMungers.add(munger);
}
// ---- only for testing!
public ResolvedMember[] getDeclaredJavaFields() {
return filterInJavaVisible(getDeclaredFields());
}
public ResolvedMember[] getDeclaredJavaMethods() {
return filterInJavaVisible(getDeclaredMethods());
}
public ShadowMunger[] getDeclaredShadowMungersArray() {
List l = (List) getDeclaredShadowMungers();
return (ShadowMunger[]) l.toArray(new ShadowMunger[l.size()]);
}
private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) {
List l = new ArrayList();
for (int i=0, len = ms.length; i < len; i++) {
if (! ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) {
l.add(ms[i]);
}
}
return (ResolvedMember[]) l.toArray(new ResolvedMember[l.size()]);
}
public abstract ISourceContext getSourceContext();
// ---- fields
public static final ResolvedTypeX[] NONE = new ResolvedTypeX[0];
public static final Primitive BYTE = new Primitive("B", 1, 0);
public static final Primitive CHAR = new Primitive("C", 1, 1);
public static final Primitive DOUBLE = new Primitive("D", 2, 2);
public static final Primitive FLOAT = new Primitive("F", 1, 3);
public static final Primitive INT = new Primitive("I", 1, 4);
public static final Primitive LONG = new Primitive("J", 2, 5);
public static final Primitive SHORT = new Primitive("S", 1, 6);
public static final Primitive VOID = new Primitive("V", 0, 8);
public static final Primitive BOOLEAN = new Primitive("Z", 1, 7);
public static final Missing MISSING = new Missing();
// ---- types
public static class Name extends ResolvedTypeX {
private ConcreteName delegate = null;
private ISourceContext sourceContext = null;
private int startPos = 0;
private int endPos = 0;
//??? should set delegate before any use
public Name(String signature, World world) {
super(signature, world);
}
public final boolean isClass() {
return delegate.isClass();
}
public boolean isAspect() {
return delegate.isAspect();
}
public final boolean needsNoConversionFrom(TypeX o) {
return isAssignableFrom(o);
}
public final boolean isAssignableFrom(TypeX o) {
if (o.isPrimitive()) return false;
ResolvedTypeX other = o.resolve(world);
return isAssignableFrom(other);
}
public final boolean isCoerceableFrom(TypeX o) {
ResolvedTypeX other = o.resolve(world);
if (this.isAssignableFrom(other) || other.isAssignableFrom(this)) {
return true;
}
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 = ((Name)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 boolean isAssignableFrom(ResolvedTypeX other) {
if (this == other) return true;
for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) {
if (this.isAssignableFrom((ResolvedTypeX) i.next())) return true;
}
return false;
}
public ISourceContext getSourceContext() {
return sourceContext;
}
public ISourceLocation getSourceLocation() {
if (sourceContext == null) return null;
return sourceContext.makeSourceLocation(new Position(startPos, endPos));
}
public boolean isExposedToWeaver() {
return (delegate == null) || delegate.isExposedToWeaver(); //??? where does this belong
}
public WeaverStateInfo getWeaverState() {
return delegate.getWeaverState();
}
public ResolvedMember[] getDeclaredFields() {
return delegate.getDeclaredFields();
}
public ResolvedTypeX[] getDeclaredInterfaces() {
return delegate.getDeclaredInterfaces();
}
public ResolvedMember[] getDeclaredMethods() {
return delegate.getDeclaredMethods();
}
public ResolvedMember[] getDeclaredPointcuts() {
return delegate.getDeclaredPointcuts();
}
public PerClause getPerClause() { return delegate.getPerClause(); }
protected Collection getDeclares() { return delegate.getDeclares(); }
protected Collection getTypeMungers() { return delegate.getTypeMungers(); }
protected Collection getPrivilegedAccesses() { return delegate.getPrivilegedAccesses(); }
public int getModifiers() {
return delegate.getModifiers();
}
public ResolvedTypeX getSuperclass() {
return delegate.getSuperclass();
}
public ConcreteName getDelegate() {
return delegate;
}
public void setDelegate(ConcreteName delegate) {
this.delegate = delegate;
}
public int getEndPos() {
return endPos;
}
public int getStartPos() {
return startPos;
}
public void setEndPos(int endPos) {
this.endPos = endPos;
}
public void setSourceContext(ISourceContext sourceContext) {
this.sourceContext = sourceContext;
}
public void setStartPos(int startPos) {
this.startPos = startPos;
}
public boolean doesNotExposeShadowMungers() {
return delegate.doesNotExposeShadowMungers();
}
}
public static abstract class ConcreteName {
//protected ISourceContext sourceContext;
protected boolean exposedToWeaver;
protected ResolvedTypeX.Name resolvedTypeX;
public ConcreteName(ResolvedTypeX.Name resolvedTypeX, boolean exposedToWeaver) {
//???super(signature, world);
this.resolvedTypeX = resolvedTypeX;
this.exposedToWeaver = exposedToWeaver;
}
public final boolean isClass() {
return !isAspect() && !isInterface();
}
public abstract boolean isAspect();
public abstract boolean isInterface();
public abstract ResolvedMember[] getDeclaredFields();
public abstract ResolvedTypeX[] getDeclaredInterfaces();
public abstract ResolvedMember[] getDeclaredMethods();
public abstract ResolvedMember[] getDeclaredPointcuts();
public abstract PerClause getPerClause();
protected abstract Collection getDeclares() ;
protected abstract Collection getTypeMungers();
protected abstract Collection getPrivilegedAccesses();
public abstract int getModifiers();
public abstract ResolvedTypeX getSuperclass();
// public abstract ISourceLocation getSourceLocation();
public abstract WeaverStateInfo getWeaverState();
// public ISourceContext getSourceContext() {
// return sourceContext;
// }
/**
* Designed to be overriden by EclipseType to disable collection of shadow mungers
* during pre-weave compilation phase
*/
public boolean doesNotExposeShadowMungers() {
return false;
}
public boolean isExposedToWeaver() {
return exposedToWeaver;
}
public ResolvedTypeX.Name getResolvedTypeX() {
return resolvedTypeX;
}
}
static class Array extends ResolvedTypeX {
ResolvedTypeX componentType;
Array(String s, World world, ResolvedTypeX componentType) {
super(s, world);
this.componentType = componentType;
}
public final ResolvedMember[] getDeclaredFields() {
return ResolvedMember.NONE;
}
public final ResolvedMember[] getDeclaredMethods() {
// ??? should this return clone? Probably not...
return ResolvedMember.NONE;
}
public final ResolvedTypeX[] getDeclaredInterfaces() {
return
new ResolvedTypeX[] {
world.getCoreType(CLONEABLE),
world.getCoreType(SERIALIZABLE)
};
}
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
public final ResolvedTypeX getSuperclass() {
return world.getCoreType(OBJECT);
}
public final boolean isAssignableFrom(TypeX o) {
if (! o.isArray()) return false;
if (o.getComponentType().isPrimitive()) {
return o.equals(this);
} else {
return getComponentType().isAssignableFrom(o.getComponentType(), world);
}
}
public final boolean isCoerceableFrom(TypeX o) {
if (o.equals(TypeX.OBJECT) ||
o.equals(TypeX.SERIALIZABLE) ||
o.equals(TypeX.CLONEABLE)) {
return true;
}
if (! o.isArray()) return false;
if (o.getComponentType().isPrimitive()) {
return o.equals(this);
} else {
return getComponentType().isCoerceableFrom(o.getComponentType(), world);
}
}
public final boolean needsNoConversionFrom(TypeX o) {
return isAssignableFrom(o);
}
public final int getModifiers() {
int mask = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED;
return (componentType.getModifiers() & mask) | Modifier.FINAL;
}
public TypeX getComponentType() {
return componentType;
}
public ResolvedTypeX getResolvedComponentType() {
return componentType;
}
public ISourceContext getSourceContext() {
return getResolvedComponentType().getSourceContext();
}
}
static class Primitive extends ResolvedTypeX {
private int size;
private int index;
Primitive(String signature, int size, int index) {
super(signature, null);
this.size = size;
this.index = index;
}
public final int getSize() {
return size;
}
public final int getModifiers() {
return Modifier.PUBLIC | Modifier.FINAL;
}
public final boolean isPrimitive() {
return true;
}
public final boolean isAssignableFrom(TypeX other) {
if (! other.isPrimitive()) return false;
return assignTable[((Primitive)other).index][index];
}
public final boolean isCoerceableFrom(TypeX other) {
if (this == other) return true;
if (! other.isPrimitive()) return false;
if (index > 6 || ((Primitive)other).index > 6) return false;
return true;
}
public final boolean needsNoConversionFrom(TypeX other) {
if (! other.isPrimitive()) 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
};
// ----
public final ResolvedMember[] getDeclaredFields() {
return ResolvedMember.NONE;
}
public final ResolvedMember[] getDeclaredMethods() {
return ResolvedMember.NONE;
}
public final ResolvedTypeX[] getDeclaredInterfaces() {
return ResolvedTypeX.NONE;
}
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
public final ResolvedTypeX getSuperclass() {
return null;
}
public ISourceContext getSourceContext() {
return null;
}
}
static class Missing extends ResolvedTypeX {
Missing() {
super(MISSING_NAME, null);
}
// public final String toString() {
// return "<missing>";
// }
public final String getName() {
return MISSING_NAME;
}
public final ResolvedMember[] getDeclaredFields() {
return ResolvedMember.NONE;
}
public final ResolvedMember[] getDeclaredMethods() {
return ResolvedMember.NONE;
}
public final ResolvedTypeX[] getDeclaredInterfaces() {
return ResolvedTypeX.NONE;
}
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
public final ResolvedTypeX getSuperclass() {
return null;
}
public final int getModifiers() {
return 0;
}
public final boolean isAssignableFrom(TypeX other) {
return false;
}
public final boolean isCoerceableFrom(TypeX other) {
return false;
}
public boolean needsNoConversionFrom(TypeX other) {
return false;
}
public ISourceContext getSourceContext() {
return null;
}
}
/** return null if not found */
public ResolvedMember lookupMemberNoSupers(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());
}
if (ret == null && interTypeMungers != null) {
for (Iterator i = interTypeMungers.iterator(); i.hasNext();) {
ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next();
if (matches(tm.getSignature(), member)) {
return tm.getSignature();
}
}
}
return ret;
}
protected List interTypeMungers = new ArrayList(0);
public List getInterTypeMungers() {
return interTypeMungers;
}
/**
* ??? This method is O(N*M) where N = number of methods and M is number of
* inter-type declarations in my super
*/
public List getInterTypeMungersIncludingSupers() {
ArrayList ret = new ArrayList();
collectInterTypeMungers(ret);
return ret;
}
private void collectInterTypeMungers(List collector) {
for (Iterator iter = getDirectSupertypes(); iter.hasNext();) {
ResolvedTypeX superType = (ResolvedTypeX) iter.next();
superType.collectInterTypeMungers(collector);
}
outer: for (Iterator iter1 = collector.iterator(); iter1.hasNext(); ) {
ConcreteTypeMunger superMunger = (ConcreteTypeMunger) iter1.next();
if ( superMunger.getSignature() == null) continue;
if ( !superMunger.getSignature().isAbstract()) continue;
for (Iterator iter = getInterTypeMungers().iterator(); iter.hasNext();) {
ConcreteTypeMunger myMunger = (ConcreteTypeMunger) iter.next();
if (conflictingSignature(myMunger.getSignature(), superMunger.getSignature())) {
iter1.remove();
continue outer;
}
}
if (!superMunger.getSignature().isPublic()) continue;
for (Iterator iter = getMethods(); iter.hasNext(); ) {
ResolvedMember method = (ResolvedMember)iter.next();
if (conflictingSignature(method, superMunger.getSignature())) {
iter1.remove();
continue outer;
}
}
}
collector.addAll(getInterTypeMungers());
}
/**
* Check that we don't have any abstract type mungers unless this
* type is abstract.
*/
public void checkInterTypeMungers() {
if (isAbstract()) return;
for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) {
ConcreteTypeMunger element = (ConcreteTypeMunger) iter.next();
if (element.getSignature() != null && element.getSignature().isAbstract()) {
ISourceLocation xtraLocation = element.getSourceLocation();
if (xtraLocation == null) {
// Until intertype mungers remember where they came from, the source location
// for the element is null when binary weaving. In these cases uses the
// source location for the aspect containing the ITD
xtraLocation = element.getAspectType().getSourceLocation();
}
world.getMessageHandler().handleMessage(
new Message("must implement abstract inter-type declaration: " + element.getSignature(),
"", IMessage.ERROR, getSourceLocation(), null,
new ISourceLocation[] { xtraLocation }));
}
}
}
/**
* Returns a ResolvedTypeX object representing the declaring type of this type, or
* null if this type does not represent a non-package-level-type.
*
* <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 TypeX object, or null.
*/
public ResolvedTypeX getDeclaringType() {
if (isArray()) return null;
String name = getName();
int lastDollar = name.lastIndexOf('$');
while (lastDollar != -1) {
ResolvedTypeX ret = world.resolve(TypeX.forName(name.substring(0, lastDollar)), true);
if (ret != ResolvedTypeX.MISSING) return ret;
lastDollar = name.lastIndexOf('$', lastDollar-1);
}
return null;
}
public static boolean isVisible(int modifiers, ResolvedTypeX targetType, ResolvedTypeX 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(
ResolvedTypeX targetType,
ResolvedTypeX fromType)
{
String p1 = targetType.getPackageName();
String p2 = fromType.getPackageName();
if (p1 == null) return p2 == null;
if (p2 == null) return false;
return p1.equals(p2);
}
public void addInterTypeMunger(ConcreteTypeMunger munger) {
ResolvedMember sig = munger.getSignature();
if (sig == null || munger.getMunger() == null ||
munger.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess)
{
interTypeMungers.add(munger);
return;
}
//System.err.println("add: " + munger + " to " + this.getClassName() + " with " + interTypeMungers);
if (sig.getKind() == Member.METHOD) {
if (!compareToExistingMembers(munger, getMethods())) return;
if (this.isInterface()) {
if (!compareToExistingMembers(munger,
Arrays.asList(world.getCoreType(OBJECT).getDeclaredMethods()).iterator())) return;
}
} else if (sig.getKind() == Member.FIELD) {
if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredFields()).iterator())) return;
} else {
if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredMethods()).iterator())) return;
}
// now compare to existingMungers
for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger existingMunger = (ConcreteTypeMunger)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().comparePrecedence(munger.getAspectType(), existingMunger.getAspectType());
}
//System.err.println(" compare: " + c);
if (c < 0) {
// the existing munger dominates the new munger
checkLegalOverride(munger.getSignature(), existingMunger.getSignature());
return;
} else if (c > 0) {
// the new munger dominates the existing one
checkLegalOverride(existingMunger.getSignature(), munger.getSignature());
i.remove();
break;
} else {
interTypeConflictError(munger, existingMunger);
interTypeConflictError(existingMunger, munger);
return;
}
}
}
}
//System.err.println("adding: " + munger + " to " + this);
interTypeMungers.add(munger);
}
//??? returning too soon
private boolean compareToExistingMembers(ConcreteTypeMunger munger, Iterator existingMembers) {
ResolvedMember sig = munger.getSignature();
while (existingMembers.hasNext()) {
ResolvedMember existingMember = (ResolvedMember)existingMembers.next();
//System.err.println("Comparing munger: "+sig+" with member "+existingMember);
if (conflictingSignature(existingMember, munger.getSignature())) {
//System.err.println("conflict: existingMember=" + existingMember + " typeMunger=" + munger);
//System.err.println(munger.getSourceLocation() + ", " + munger.getSignature() + ", " + munger.getSignature().getSourceLocation());
if (isVisible(existingMember.getModifiers(), this, munger.getAspectType())) {
int c = compareMemberPrecedence(sig, existingMember);
//System.err.println(" c: " + c);
if (c < 0) {
// existingMember dominates munger
checkLegalOverride(munger.getSignature(), existingMember);
return false;
} else if (c > 0) {
// munger dominates existingMember
checkLegalOverride(existingMember, munger.getSignature());
//interTypeMungers.add(munger);
//??? might need list of these overridden abstracts
continue;
} else {
//XXX dual errors possible if (this instanceof BcelObjectType) return false; //XXX ignores separate comp
getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(),
existingMember),
munger.getSourceLocation())
);
}
} else if (isDuplicateMemberWithinTargetType(existingMember,this,sig)) {
getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(),
existingMember),
munger.getSourceLocation())
);;
}
//return;
}
}
return true;
}
// 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, ResolvedTypeX targetType,ResolvedMember itdMember) {
if ( (existingMember.isAbstract() || itdMember.isAbstract())) return false;
TypeX declaringType = existingMember.getDeclaringType();
if (!targetType.equals(declaringType)) return false;
// now have to test that itdMember is visible from targetType
if (itdMember.isPrivate()) 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;
}
public boolean checkLegalOverride(ResolvedMember parent, ResolvedMember child) {
//System.err.println("check: " + child.getDeclaringType() + " overrides " + parent.getDeclaringType());
if (!parent.getReturnType().equals(child.getReturnType())) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_RETURN_TYPE_MISMATCH,parent,child),
child.getSourceLocation(), parent.getSourceLocation());
return false;
}
if (parent.getKind() == Member.POINTCUT) {
TypeX[] pTypes = parent.getParameterTypes();
TypeX[] 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
ResolvedTypeX[] childExceptions = world.resolve(child.getExceptions());
ResolvedTypeX[] parentExceptions = world.resolve(parent.getExceptions());
ResolvedTypeX runtimeException = world.resolve("java.lang.RuntimeException");
ResolvedTypeX 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;
}
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_DOESNT_THROW,childExceptions[i].getName()),
child.getSourceLocation(), null);
return false;
}
if (parent.isStatic() && !child.isStatic()) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_OVERRIDDEN_STATIC,child,parent),
child.getSourceLocation(),null);
} else if (child.isStatic() && !parent.isStatic()) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_OVERIDDING_STATIC,child,parent),
child.getSourceLocation(),null);
}
return true;
}
private int compareMemberPrecedence(ResolvedMember m1, ResolvedMember m2) {
//if (!m1.getReturnType().equals(m2.getReturnType())) return 0;
if (Modifier.isAbstract(m1.getModifiers())) return -1;
if (Modifier.isAbstract(m2.getModifiers())) return +1;
if (m1.getDeclaringType().equals(m2.getDeclaringType())) return 0;
ResolvedTypeX t1 = m1.getDeclaringType().resolve(world);
ResolvedTypeX 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;
//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());
}
public ResolvedMember lookupSyntheticMember(Member member) {
//??? horribly inefficient
//for (Iterator i =
//System.err.println("lookup " + member + " in " + interTypeMungers);
for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger m = (ConcreteTypeMunger)i.next();
ResolvedMember ret = m.getMatchingSyntheticMember(member);
if (ret != null) {
//System.err.println(" found: " + ret);
return ret;
}
}
return null;
}
public void clearInterTypeMungers() {
interTypeMungers = new ArrayList();
}
public boolean isTopmostImplementor(ResolvedTypeX interfaceType) {
if (isInterface()) return false;
if (!interfaceType.isAssignableFrom(this)) return false;
// check that I'm truly the topmost implementor
if (interfaceType.isAssignableFrom(this.getSuperclass())) {
return false;
}
return true;
}
public List getExposedPointcuts() {
List ret = new ArrayList();
if (getSuperclass() != null) ret.addAll(getSuperclass().getExposedPointcuts());
for (Iterator i = Arrays.asList(getDeclaredInterfaces()).iterator(); i.hasNext(); ) {
ResolvedTypeX t = (ResolvedTypeX)i.next();
addPointcutsResolvingConflicts(ret, Arrays.asList(t.getDeclaredPointcuts()), false);
}
addPointcutsResolvingConflicts(ret, Arrays.asList(getDeclaredPointcuts()), true);
for (Iterator i = ret.iterator(); i.hasNext(); ) {
ResolvedPointcutDefinition inherited = (ResolvedPointcutDefinition)i.next();
// System.err.println("looking at: " + inherited + " in " + this);
// System.err.println(" " + inherited.isAbstract() + " in " + this.isAbstract());
if (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 acc, List added, boolean isOverriding) {
for (Iterator i = added.iterator(); i.hasNext();) {
ResolvedPointcutDefinition toAdd =
(ResolvedPointcutDefinition) i.next();
//System.err.println("adding: " + toAdd);
for (Iterator j = acc.iterator(); j.hasNext();) {
ResolvedPointcutDefinition existing =
(ResolvedPointcutDefinition) j.next();
if (existing == toAdd) continue;
if (!isVisible(existing.getModifiers(),
existing.getDeclaringType().resolve(getWorld()),
this)) {
continue;
}
if (conflictingSignature(existing, toAdd)) {
if (isOverriding) {
checkLegalOverride(existing, toAdd);
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;
}
}
|
49,657
|
Bug 49657 Weaver results in rt error if affected base class not exposed
|
I was weaving a 3rd party library and wrote an aspect that should affect both a base class and a derived class, but inadvertently wove only the derived class. This resulted in the following error. I would like the weaver to catch this kind of error at weave (link) time, rather than creating code that results in a rt error... I get this error in 1.1.1 final and in a fairly recent version from CVS HEAD: java.lang.AbstractMethodError at ajee.logging.LogManager.ajc$interMethodDispatch1 $ajee_logging_LogManager$ajee_logging_Loggable$getLogger(LogManager.java) at ajee.tracing.ExecutionTracer.ajc$before$ajee_tracing_ExecutionTracer$926 (ExecutionTracer.java:62) at library.Derived.<init>(Derived.java:46) This line is a call to super(); I've attached a small example that reproduces another error that I think is related: C:\devel\test\ctors\twoPass>build C:\devel\test\ctors\twoPass>call ajc -outjar fullBase.jar sample\Base.java sampl e\Derived.java Exception in thread "main" java.lang.ExceptionInInitializerError at sample.Derived.<init>(Derived.java:6) at sample.Derived.main(Derived.java:13) Caused by: org.aspectj.lang.NoAspectBoundException at sample.Trace.aspectOf(Trace.aj) at sample.Trace.<init>(Trace.aj:5) at sample.Trace.ajc$postClinit(Trace.aj) at sample.Trace.<clinit>(Trace.aj:5) ... 2 more
|
resolved fixed
|
dbe1024
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-19T16:38:16Z
| 2004-01-07T21:13:20Z
|
weaver/src/org/aspectj/weaver/WeaverMessages.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.aspectj.weaver;
import java.text.MessageFormat;
import java.util.ResourceBundle;
public class WeaverMessages {
private static ResourceBundle bundle = ResourceBundle.getBundle("org.aspectj.weaver.weaver-messages");
public static final String ARGS_IN_DECLARE = "argsInDeclare";
public static final String CFLOW_IN_DECLARE = "cflowInDeclare";
public static final String IF_IN_DECLARE = "ifInDeclare";
public static final String THIS_OR_TARGET_IN_DECLARE = "thisOrTargetInDeclare";
public static final String ABSTRACT_POINTCUT = "abstractPointcut";
public static final String POINCUT_NOT_CONCRETE = "abstractPointcutNotMadeConcrete";
public static final String CONFLICTING_INHERITED_POINTCUTS = "conflictingInheritedPointcuts";
public static final String CIRCULAR_POINTCUT = "circularPointcutDeclaration";
public static final String CANT_FIND_POINTCUT = "cantFindPointcut";
public static final String EXACT_TYPE_PATTERN_REQD = "exactTypePatternRequired";
public static final String CANT_BIND_TYPE = "cantBindType";
public static final String WILDCARD_NOT_ALLOWED = "wildcardTypePatternNotAllowed";
public static final String DECP_OBJECT = "decpObject";
public static final String CANT_EXTEND_SELF="cantExtendSelf";
public static final String INTERFACE_CANT_EXTEND_CLASS="interfaceExtendClass";
public static final String DECP_HIERARCHY_ERROR = "decpHierarchy";
public static final String MULTIPLE_MATCHES_IN_PRECEDENCE = "multipleMatchesInPrecedence";
public static final String TWO_STARS_IN_PRECEDENCE = "circularityInPrecedenceStar";
public static final String CLASSES_IN_PRECEDENCE = "nonAspectTypesInPrecedence";
public static final String TWO_PATTERN_MATCHES_IN_PRECEDENCE = "circularityInPrecedenceTwo";
public static final String NOT_THROWABLE = "notThrowable";
public static final String ITD_CONS_ON_ASPECT = "itdConsOnAspect";
public static final String ITD_RETURN_TYPE_MISMATCH = "returnTypeMismatch";
public static final String ITD_PARAM_TYPE_MISMATCH = "paramTypeMismatch";
public static final String ITD_VISIBILITY_REDUCTION = "visibilityReduction";
public static final String ITD_DOESNT_THROW = "doesntThrow";
public static final String ITD_OVERRIDDEN_STATIC = "overriddenStatic";
public static final String ITD_OVERIDDING_STATIC = "overridingStatic";
public static final String ITD_CONFLICT = "itdConflict";
public static final String ITD_MEMBER_CONFLICT = "itdMemberConflict";
public static final String NON_VOID_RETURN = "nonVoidReturn";
public static final String INCOMPATIBLE_RETURN_TYPE="incompatibleReturnType";
public static final String CANT_THROW_CHECKED = "cantThrowChecked";
public static final String CIRCULAR_DEPENDENCY = "circularDependency";
public static final String MISSING_PER_CLAUSE = "missingPerClause";
public static final String WRONG_PER_CLAUSE = "wrongPerClause";
public static final String ALREADY_WOVEN = "alreadyWoven";
public static final String REWEAVABLE_MODE = "reweavableMode";
public static final String PROCESSING_REWEAVABLE = "processingReweavable";
public static final String MISSING_REWEAVABLE_TYPE = "missingReweavableType";
public static final String VERIFIED_REWEAVABLE_TYPE = "verifiedReweavableType";
public static final String ASPECT_NEEDED = "aspectNeeded";
public static final String CANT_FIND_TYPE = "cantFindType";
public static final String CANT_FIND_CORE_TYPE = "cantFindCoreType";
public static final String CANT_FIND_TYPE_WITHINPCD = "cantFindTypeWithinpcd";
public static final String DECP_BINARY_LIMITATION = "decpBinaryLimitation";
public static final String OVERWRITE_JSR45 = "overwriteJSR45";
public static final String IF_IN_PERCLAUSE = "ifInPerClause";
public static final String IF_LEXICALLY_IN_CFLOW = "ifLexicallyInCflow";
public static final String ONLY_BEFORE_ON_HANDLER = "onlyBeforeOnHandler";
public static final String AROUND_ON_PREINIT = "aroundOnPreInit";
public static final String AROUND_ON_INIT = "aroundOnInit";
public static final String AROUND_ON_INTERFACE_STATICINIT = "aroundOnInterfaceStaticInit";
public static final String PROBLEM_GENERATING_METHOD = "problemGeneratingMethod";
public static final String CLASS_TOO_BIG = "classTooBig";
public static final String ZIPFILE_ENTRY_MISSING = "zipfileEntryMissing";
public static final String ZIPFILE_ENTRY_INVALID = "zipfileEntryInvalid";
public static final String DIRECTORY_ENTRY_MISSING = "directoryEntryMissing";
public static final String OUTJAR_IN_INPUT_PATH = "outjarInInputPath";
public static final String XLINT_LOAD_ERROR = "problemLoadingXLint";
public static final String XLINTDEFAULT_LOAD_ERROR = "unableToLoadXLintDefault";
public static final String XLINTDEFAULT_LOAD_PROBLEM = "errorLoadingXLintDefault";
public static final String XLINT_KEY_ERROR = "invalidXLintKey";
public static final String XLINT_VALUE_ERROR = "invalidXLintMessageKind";
public static String format(String key) {
return bundle.getString(key);
}
public static String format(String key, Object insert) {
return MessageFormat.format(bundle.getString(key),new Object[] {insert});
}
public static String format(String key, Object insert1, Object insert2) {
return MessageFormat.format(bundle.getString(key),new Object[] {insert1,insert2});
}
public static String format(String key, Object insert1, Object insert2, Object insert3) {
return MessageFormat.format(bundle.getString(key),new Object[] {insert1, insert2, insert3});
}
}
|
49,657
|
Bug 49657 Weaver results in rt error if affected base class not exposed
|
I was weaving a 3rd party library and wrote an aspect that should affect both a base class and a derived class, but inadvertently wove only the derived class. This resulted in the following error. I would like the weaver to catch this kind of error at weave (link) time, rather than creating code that results in a rt error... I get this error in 1.1.1 final and in a fairly recent version from CVS HEAD: java.lang.AbstractMethodError at ajee.logging.LogManager.ajc$interMethodDispatch1 $ajee_logging_LogManager$ajee_logging_Loggable$getLogger(LogManager.java) at ajee.tracing.ExecutionTracer.ajc$before$ajee_tracing_ExecutionTracer$926 (ExecutionTracer.java:62) at library.Derived.<init>(Derived.java:46) This line is a call to super(); I've attached a small example that reproduces another error that I think is related: C:\devel\test\ctors\twoPass>build C:\devel\test\ctors\twoPass>call ajc -outjar fullBase.jar sample\Base.java sampl e\Derived.java Exception in thread "main" java.lang.ExceptionInInitializerError at sample.Derived.<init>(Derived.java:6) at sample.Derived.main(Derived.java:13) Caused by: org.aspectj.lang.NoAspectBoundException at sample.Trace.aspectOf(Trace.aj) at sample.Trace.<init>(Trace.aj:5) at sample.Trace.ajc$postClinit(Trace.aj) at sample.Trace.<clinit>(Trace.aj:5) ... 2 more
|
resolved fixed
|
dbe1024
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-19T16:38:16Z
| 2004-01-07T21:13: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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.Iterator;
import java.util.Set;
import org.aspectj.apache.bcel.Constants;
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.InstructionList;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.WeaveMessage;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.AsmRelationshipProvider;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewConstructorTypeMunger;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.NewParentTypeMunger;
import org.aspectj.weaver.PerObjectInterfaceTypeMunger;
import org.aspectj.weaver.PrivilegedAccessMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.patterns.Pointcut;
//XXX addLazyMethodGen is probably bad everywhere
public class BcelTypeMunger extends ConcreteTypeMunger {
public BcelTypeMunger(ResolvedTypeMunger munger, ResolvedTypeX aspectType) {
super(munger, aspectType);
}
public String toString() {
return "(BcelTypeMunger " + getMunger() + ")";
}
public boolean munge(BcelClassWeaver weaver) {
boolean changed = false;
boolean worthReporting = true;
if (munger.getKind() == ResolvedTypeMunger.Field) {
changed = mungeNewField(weaver, (NewFieldTypeMunger)munger);
} else if (munger.getKind() == ResolvedTypeMunger.Method) {
changed = mungeNewMethod(weaver, (NewMethodTypeMunger)munger);
} else if (munger.getKind() == ResolvedTypeMunger.PerObjectInterface) {
changed = mungePerObjectInterface(weaver, (PerObjectInterfaceTypeMunger)munger);
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 {
throw new RuntimeException("unimplemented");
}
if (changed && munger.changesPublicSignature()) {
WeaverStateInfo info =
weaver.getLazyClassGen().getOrCreateWeaverStateInfo();
info.addConcreteMunger(this);
}
// Whilst type mungers aren't persisting their source locations, we add this relationship during
// compilation time (see other reference to ResolvedTypeMunger.persist)
if (ResolvedTypeMunger.persistSourceLocation) {
if (changed) {
if (munger.getKind().equals(ResolvedTypeMunger.Parent)) {
AsmRelationshipProvider.getDefault().addRelationship(weaver.getLazyClassGen().getType(), munger,getAspectType());
} else {
AsmRelationshipProvider.getDefault().addRelationship(weaver.getLazyClassGen().getType(), munger,getAspectType());
}
}
}
// TAG: WeavingMessage
if (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 will come out of AjLookupEnvironment.addParent if doing a source
// compilation.
NewParentTypeMunger parentTM = (NewParentTypeMunger)munger;
if (parentTM.getNewParent().isInterface()) {
weaver.getWorld().getMessageHandler().handleMessage(WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS,
new String[]{weaver.getLazyClassGen().getType().getName(),
tName,parentTM.getNewParent().getName(),fName}));
} else {
System.err.println("BANG, you need to fix this. BcelTypeMunger");
}
} else {
weaver.getWorld().getMessageHandler().handleMessage(WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ITD,
new String[]{weaver.getLazyClassGen().getType().getName(),
tName,munger.getKind().toString().toLowerCase(),
getAspectType().getName(),
fName+":'"+munger.getSignature()+"'"}));
// ??? If only type mungers knew their originating line numbers ...
}
}
return changed;
}
private String getShortname(String path) {
int takefrom = path.lastIndexOf('/');
if (takefrom == -1) {
takefrom = path.lastIndexOf('\\');
}
return path.substring(takefrom+1);
}
private boolean mungeNewParent(BcelClassWeaver weaver, NewParentTypeMunger munger) {
LazyClassGen gen = weaver.getLazyClassGen();
ResolvedTypeX newParent = munger.getNewParent();
if (newParent.isClass()) {
//gen.setSuperClass(newParent);
} else {
gen.addInterface(newParent,getSourceLocation());
}
return true;
}
private boolean mungePrivilegedAccess(
BcelClassWeaver weaver,
PrivilegedAccessMunger munger)
{
LazyClassGen gen = weaver.getLazyClassGen();
ResolvedMember member = munger.getMember();
ResolvedTypeX onType = weaver.getWorld().resolve(member.getDeclaringType());
//System.out.println("munging: " + gen + " with " + member);
if (onType.equals(gen.getType())) {
if (member.getKind() == Member.FIELD) {
//System.out.println("matched: " + gen);
addFieldGetter(gen, member,
AjcMemberMaker.privilegedAccessMethodForFieldGet(aspectType, member));
addFieldSetter(gen, member,
AjcMemberMaker.privilegedAccessMethodForFieldSet(aspectType, member));
return true;
} else if (member.getKind() == Member.METHOD) {
addMethodDispatch(gen, member,
AjcMemberMaker.privilegedAccessMethodForMethod(aspectType, member));
return true;
} else if (member.getKind() == Member.CONSTRUCTOR) {
for (Iterator i = gen.getMethodGens().iterator(); i.hasNext(); ) {
LazyMethodGen m = (LazyMethodGen)i.next();
if (m.getMemberView() != null
&& m.getMemberView().getKind() == Member.CONSTRUCTOR) {
// m.getMemberView().equals(member)) {
m.forcePublic();
//return true;
}
}
return true;
//throw new BCException("no match for " + member + " in " + gen);
} else if (member.getKind() == Member.STATIC_INITIALIZATION) {
gen.forcePublic();
return true;
} else {
throw new RuntimeException("unimplemented");
}
}
return false;
}
private void addFieldGetter(
LazyClassGen gen,
ResolvedMember field,
ResolvedMember accessMethod)
{
LazyMethodGen mg = makeMethodGen(gen, accessMethod);
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
if (field.isStatic()) {
il.append(fact.createFieldAccess(
gen.getClassName(),
field.getName(),
BcelWorld.makeBcelType(field.getType()), Constants.GETSTATIC));
} else {
il.append(InstructionConstants.ALOAD_0);
il.append(fact.createFieldAccess(
gen.getClassName(),
field.getName(),
BcelWorld.makeBcelType(field.getType()), Constants.GETFIELD));
}
il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(field.getType())));
mg.getBody().insert(il);
gen.addMethodGen(mg,getSignature().getSourceLocation());
}
private void addFieldSetter(
LazyClassGen gen,
ResolvedMember field,
ResolvedMember accessMethod)
{
LazyMethodGen mg = makeMethodGen(gen, accessMethod);
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
Type fieldType = BcelWorld.makeBcelType(field.getType());
if (field.isStatic()) {
il.append(InstructionFactory.createLoad(fieldType, 0));
il.append(fact.createFieldAccess(
gen.getClassName(),
field.getName(),
fieldType, Constants.PUTSTATIC));
} else {
il.append(InstructionConstants.ALOAD_0);
il.append(InstructionFactory.createLoad(fieldType, 1));
il.append(fact.createFieldAccess(
gen.getClassName(),
field.getName(),
fieldType, Constants.PUTFIELD));
}
il.append(InstructionFactory.createReturn(Type.VOID));
mg.getBody().insert(il);
gen.addMethodGen(mg,getSignature().getSourceLocation());
}
private void addMethodDispatch(
LazyClassGen gen,
ResolvedMember method,
ResolvedMember accessMethod)
{
LazyMethodGen mg = makeMethodGen(gen, accessMethod);
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
//Type fieldType = BcelWorld.makeBcelType(field.getType());
Type[] paramTypes = BcelWorld.makeBcelTypes(method.getParameterTypes());
int pos = 0;
if (!method.isStatic()) {
il.append(InstructionConstants.ALOAD_0);
pos++;
}
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
il.append(InstructionFactory.createLoad(paramType, pos));
pos+=paramType.getSize();
}
il.append(Utility.createInvoke(fact, (BcelWorld)aspectType.getWorld(),
method));
il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(method.getReturnType())));
mg.getBody().insert(il);
gen.addMethodGen(mg);
}
private LazyMethodGen makeMethodGen(LazyClassGen gen, ResolvedMember member) {
LazyMethodGen ret = new LazyMethodGen(
member.getModifiers(),
BcelWorld.makeBcelType(member.getReturnType()),
member.getName(),
BcelWorld.makeBcelTypes(member.getParameterTypes()),
TypeX.getNames(member.getExceptions()),
gen);
// 43972 : Static crosscutting makes interfaces unusable for javac
// ret.makeSynthetic();
return ret;
}
private FieldGen makeFieldGen(LazyClassGen gen, ResolvedMember member) {
return new FieldGen(
member.getModifiers(),
BcelWorld.makeBcelType(member.getReturnType()),
member.getName(),
gen.getConstantPoolGen());
}
private boolean mungePerObjectInterface(
BcelClassWeaver weaver,
PerObjectInterfaceTypeMunger munger)
{
LazyClassGen gen = weaver.getLazyClassGen();
if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) {
FieldGen fg = makeFieldGen(gen,
AjcMemberMaker.perObjectField(gen.getType(), aspectType));
gen.addField(fg.getField(),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(),getSourceLocation());
return true;
} else {
return false;
}
}
private boolean couldMatch(
BcelObjectType bcelObjectType,
Pointcut pointcut) {
return !bcelObjectType.isInterface();
}
private boolean mungeNewMethod(BcelClassWeaver weaver, NewMethodTypeMunger munger) {
ResolvedMember signature = munger.getSignature();
ResolvedMember dispatchMethod = munger.getDispatchMethod(aspectType);
LazyClassGen gen = weaver.getLazyClassGen();
ResolvedTypeX onType = weaver.getWorld().resolve(signature.getDeclaringType());
boolean onInterface = onType.isInterface();
if (onType.equals(gen.getType())) {
ResolvedMember introMethod =
AjcMemberMaker.interMethod(signature, aspectType, onInterface);
LazyMethodGen mg = makeMethodGen(gen, introMethod);
if (!onInterface && !Modifier.isAbstract(introMethod.getModifiers())) {
InstructionList body = mg.getBody();
InstructionFactory fact = gen.getFactory();
int pos = 0;
if (!signature.isStatic()) {
body.append(InstructionFactory.createThis());
pos++;
}
Type[] paramTypes = BcelWorld.makeBcelTypes(introMethod.getParameterTypes());
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
body.append(InstructionFactory.createLoad(paramType, pos));
pos+=paramType.getSize();
}
body.append(Utility.createInvoke(fact, weaver.getWorld(), dispatchMethod));
body.append(
InstructionFactory.createReturn(
BcelWorld.makeBcelType(introMethod.getReturnType())));
} else {
//??? this is okay
//if (!(mg.getBody() == null)) throw new RuntimeException("bas");
}
// XXX make sure to check that we set exceptions properly on this guy.
weaver.addLazyMethodGen(mg);
weaver.getLazyClassGen().warnOnAddedMethod(mg.getMethod(),getSignature().getSourceLocation());
addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled());
return true;
} else if (onInterface && gen.getType().isTopmostImplementor(onType) &&
!Modifier.isAbstract(signature.getModifiers()))
{
ResolvedMember introMethod =
AjcMemberMaker.interMethod(signature, aspectType, false);
LazyMethodGen mg = makeMethodGen(gen, introMethod);
Type[] paramTypes = BcelWorld.makeBcelTypes(introMethod.getParameterTypes());
Type returnType = BcelWorld.makeBcelType(introMethod.getReturnType());
InstructionList body = mg.getBody();
InstructionFactory fact = gen.getFactory();
int pos = 0;
if (!introMethod.isStatic()) {
body.append(InstructionFactory.createThis());
pos++;
}
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
body.append(InstructionFactory.createLoad(paramType, pos));
pos+=paramType.getSize();
}
body.append(Utility.createInvoke(fact, weaver.getWorld(), dispatchMethod));
body.append(InstructionFactory.createReturn(returnType));
mg.definingType = onType;
weaver.addOrReplaceLazyMethodGen(mg);
addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled());
return true;
} else {
return false;
}
}
private void addNeededSuperCallMethods(
BcelClassWeaver weaver,
ResolvedTypeX onType,
Set neededSuperCalls)
{
LazyClassGen gen = weaver.getLazyClassGen();
for (Iterator iter = neededSuperCalls.iterator(); iter.hasNext();) {
ResolvedMember superMethod = (ResolvedMember) iter.next();
if (weaver.addDispatchTarget(superMethod)) {
//System.err.println("super type: " + superMethod.getDeclaringType() + ", " + gen.getType());
boolean isSuper = !superMethod.getDeclaringType().equals(gen.getType());
String dispatchName;
if (isSuper)
dispatchName =
NameMangler.superDispatchMethod(onType, superMethod.getName());
else
dispatchName =
NameMangler.protectedDispatchMethod(
onType,
superMethod.getName());
LazyMethodGen dispatcher =
makeDispatcher(
gen,
dispatchName,
superMethod,
weaver.getWorld(),
isSuper);
weaver.addLazyMethodGen(dispatcher);
}
}
}
private boolean mungeNewConstructor(
BcelClassWeaver weaver,
NewConstructorTypeMunger newConstructorTypeMunger)
{
final LazyClassGen currentClass = weaver.getLazyClassGen();
final InstructionFactory fact = currentClass.getFactory();
ResolvedMember newConstructorMember = newConstructorTypeMunger.getSyntheticConstructor();
TypeX onType = newConstructorMember.getDeclaringType();
if (! onType.equals(currentClass.getType())) return false;
ResolvedMember explicitConstructor = newConstructorTypeMunger.getExplicitConstructor();
//int declaredParameterCount = newConstructorTypeMunger.getDeclaredParameterCount();
LazyMethodGen freshConstructor =
makeMethodGen(currentClass, newConstructorMember);
currentClass.addMethodGen(freshConstructor);
//weaver.addLazyMethodGen(freshConstructor);
InstructionList body = freshConstructor.getBody();
// add to body: push arts for call to pre, from actual args starting at 1 (skipping this), going to
// declared argcount + 1
TypeX[] declaredParams = newConstructorTypeMunger.getSignature().getParameterTypes();
Type[] paramTypes = freshConstructor.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 = freshConstructor.allocateLocal(1);
body.append(InstructionFactory.createStore(Type.OBJECT, arraySlot));
// put this on the stack
body.append(InstructionConstants.ALOAD_0);
// unpack pre args onto stack
TypeX[] 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);
TypeX[] 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,
TypeX.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();
ResolvedTypeX onType = weaver.getWorld().resolve(field.getDeclaringType());
boolean onInterface = onType.isInterface();
if (onType.equals(gen.getType())) {
if (onInterface) {
LazyMethodGen mg = makeMethodGen(gen,
AjcMemberMaker.interFieldInterfaceGetter(field, onType, aspectType));
gen.addMethodGen(mg);
LazyMethodGen mg1 = makeMethodGen(gen,
AjcMemberMaker.interFieldInterfaceSetter(field, onType, aspectType));
gen.addMethodGen(mg1);
} else {
weaver.addInitializer(this);
FieldGen fg = makeFieldGen(gen,
AjcMemberMaker.interFieldClassField(field, aspectType));
gen.addField(fg.getField(),getSourceLocation());
}
return true;
} else if (onInterface && gen.getType().isTopmostImplementor(onType)) {
// wew know that we can't be static since we don't allow statics on interfaces
if (field.isStatic()) throw new RuntimeException("unimplemented");
weaver.addInitializer(this);
//System.err.println("impl body on " + gen.getType() + " for " + munger);
Type fieldType = BcelWorld.makeBcelType(field.getType());
FieldGen fg = makeFieldGen(gen,
AjcMemberMaker.interFieldInterfaceField(field, onType, aspectType));
gen.addField(fg.getField(),getSourceLocation());
//this uses a shadow munger to add init method to constructors
//weaver.getShadowMungers().add(makeInitCallShadowMunger(initMethod));
LazyMethodGen mg = makeMethodGen(gen,
AjcMemberMaker.interFieldInterfaceGetter(field, gen.getType(), aspectType));
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
if (field.isStatic()) {
il.append(fact.createFieldAccess(
gen.getClassName(),
fg.getName(),
fieldType, Constants.GETSTATIC));
} else {
il.append(InstructionConstants.ALOAD_0);
il.append(fact.createFieldAccess(
gen.getClassName(),
fg.getName(),
fieldType, Constants.GETFIELD));
}
il.append(InstructionFactory.createReturn(fieldType));
mg.getBody().insert(il);
gen.addMethodGen(mg);
LazyMethodGen mg1 = makeMethodGen(gen,
AjcMemberMaker.interFieldInterfaceSetter(field, gen.getType(), aspectType));
InstructionList il1 = new InstructionList();
if (field.isStatic()) {
il1.append(InstructionFactory.createLoad(fieldType, 0));
il1.append(fact.createFieldAccess(
gen.getClassName(),
fg.getName(),
fieldType, Constants.PUTSTATIC));
} else {
il1.append(InstructionConstants.ALOAD_0);
il1.append(InstructionFactory.createLoad(fieldType, 1));
il1.append(fact.createFieldAccess(
gen.getClassName(),
fg.getName(),
fieldType, Constants.PUTFIELD));
}
il1.append(InstructionFactory.createReturn(Type.VOID));
mg1.getBody().insert(il1);
gen.addMethodGen(mg1);
return true;
} else {
return false;
}
}
}
|
71,811
|
Bug 71811 AJDoc: should be able to set encoding like javadoc
|
ajdoc doesn't support the -encoding -docencoding and -charset options of javadoc. Especially, it doesn't pass on the -encoding to ajc. If your project uses a source file encoding (e.g. UTF-8) differing form the platform standard, and some java identifiers use characters byond the standard ASCII range, you won't be able to use ajdoc at all.
|
resolved fixed
|
5f80c8c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-20T01:01:45Z
| 2004-08-11T18:46:40Z
|
ajdoc/src/org/aspectj/tools/ajdoc/Main.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* Mik Kersten port to AspectJ 1.1+ code base
* ******************************************************************/
package org.aspectj.tools.ajdoc;
import java.io.*;
import java.util.*;
import java.io.FileFilter;
import org.aspectj.bridge.Version;
import org.aspectj.util.FileUtil;
/**
* This is an old implementation of ajdoc that does not use an OO style. However, it
* does the job, and should serve to evolve a lightweight ajdoc implementation until
* we can make a properly extended javadoc implementation.
*
* @author Mik Kersten
*/
public class Main implements Config {
private static final String FAIL_MESSAGE = "> compile failed, exiting ajdoc";
static SymbolManager symbolManager = null;
/** Command line options. */
static Vector options;
/** Options to pass to ajc. */
static Vector ajcOptions;
/** All of the files to be processed by ajdoc. */
static Vector filenames;
/** List of files to pass to javadoc. */
static Vector fileList;
/** List of packages to pass to javadoc. */
static Vector packageList;
/** Default to package visiblity. */
static String docModifier = "package";
static Vector sourcepath;
static boolean verboseMode = false;
static boolean packageMode = false;
static boolean authorStandardDocletSwitch = false;
static boolean versionStandardDocletSwitch = false;
static File rootDir = null;
static Hashtable declIDTable = new Hashtable();
static String docDir = ".";
private static boolean deleteTempFilesOnExit = true;
private static boolean aborted = false;
public static void clearState() {
symbolManager = null;
options = new Vector();
ajcOptions = new Vector();
filenames = new Vector();
fileList= new Vector();
packageList = new Vector();
docModifier = "package";
sourcepath = new Vector();
verboseMode = false;
packageMode = false;
rootDir = null;
declIDTable = new Hashtable();
docDir = ".";
aborted = false;
deleteTempFilesOnExit = true;
}
public static void main(String[] args) {
clearState();
// if (!JavadocRunner.has14ToolsAvailable()) {
// System.err.println("ajdoc requires a JDK 1.4 or later tools jar - exiting");
// aborted = true;
// return;
// }
// STEP 1: parse the command line and do other global setup
sourcepath.addElement("."); // add the current directory to the classapth
parseCommandLine(args);
rootDir = getRootDir();
symbolManager = SymbolManager.getDefault();
File[] inputFiles = new File[filenames.size()];
File[] signatureFiles = new File[filenames.size()];
try {
// create the workingdir if it doesn't exist
if ( !(new File( Config.WORKING_DIR ).isDirectory()) ) {
File dir = new File( Config.WORKING_DIR );
dir.mkdir();
if (deleteTempFilesOnExit) dir.deleteOnExit();
}
for (int i = 0; i < filenames.size(); i++) {
inputFiles[i] = new File((String)filenames.elementAt(i));
//signatureFiles[i] = createSignatureFile(inputFiles[i]);
}
// PHASE 0: call ajc
ajcOptions.addElement("-noExit");
ajcOptions.addElement("-XjavadocsInModel"); // TODO: wrong option to force model gen
ajcOptions.addElement("-d");
ajcOptions.addElement(rootDir.getAbsolutePath());
String[] argsToCompiler = new String[ajcOptions.size() + inputFiles.length];
int i = 0;
for ( ; i < ajcOptions.size(); i++ ) {
argsToCompiler[i] = (String)ajcOptions.elementAt(i);
}
for ( int j = 0; j < inputFiles.length; j++) {
argsToCompiler[i] = inputFiles[j].getAbsolutePath();
//System.out.println(">> file to ajc: " + inputFiles[j].getAbsolutePath());
i++;
}
// System.out.println(Arrays.asList(argsToCompiler));
System.out.println( "> Calling ajc..." );
CompilerWrapper.main(argsToCompiler);
if (CompilerWrapper.hasErrors()) {
System.out.println(FAIL_MESSAGE);
aborted = true;
return;
}
/*
for (int ii = 0; ii < inputFiles.length; ii++) {
String tempFP = inputFiles[ii].getAbsolutePath();
tempFP = tempFP.substring(0, tempFP.length()-4);
tempFP += "ajsym";
System.out.println( ">> checking: " + tempFP);
File tempF = new File(tempFP);
if ( !tempF.exists() ) System.out.println( ">>> doesn't exist!" );
}
*/
for (int ii = 0; ii < filenames.size(); ii++) {
signatureFiles[ii] = createSignatureFile(inputFiles[ii]);
}
// PHASE 1: generate Signature files (Java with DeclIDs and no bodies).
System.out.println( "> Building signature files..." );
StubFileGenerator.doFiles(declIDTable, symbolManager, inputFiles, signatureFiles);
// PHASE 2: let Javadoc generate HTML (with DeclIDs)
System.out.println( "> Calling javadoc..." );
String[] javadocargs = null;
if ( packageMode ) {
int numExtraArgs = 2;
if (authorStandardDocletSwitch) numExtraArgs++;
if (versionStandardDocletSwitch) numExtraArgs++;
javadocargs = new String[numExtraArgs + options.size() + packageList.size() +
fileList.size() ];
javadocargs[0] = "-sourcepath";
javadocargs[1] = Config.WORKING_DIR;
int argIndex = 2;
if (authorStandardDocletSwitch) {
javadocargs[argIndex] = "-author";
argIndex++;
}
if (versionStandardDocletSwitch) {
javadocargs[argIndex] = "-version";
}
//javadocargs[1] = getSourcepathAsString();
for (int k = 0; k < options.size(); k++) {
javadocargs[numExtraArgs+k] = (String)options.elementAt(k);
}
for (int k = 0; k < packageList.size(); k++) {
javadocargs[numExtraArgs+options.size() + k] = (String)packageList.elementAt(k);
}
for (int k = 0; k < fileList.size(); k++) {
javadocargs[numExtraArgs+options.size() + packageList.size() + k] = (String)fileList.elementAt(k);
}
}
else {
javadocargs = new String[options.size() + signatureFiles.length];
for (int k = 0; k < options.size(); k++) {
javadocargs[k] = (String)options.elementAt(k);
}
for (int k = 0; k < signatureFiles.length; k++) {
javadocargs[options.size() + k] = StructureUtil.translateAjPathName(signatureFiles[k].getCanonicalPath());
}
}
JavadocRunner.callJavadoc(javadocargs);
//for ( int o = 0; o < inputFiles.length; o++ ) {
// System.out.println( "file: " + inputFiles[o] );
//}
// PHASE 3: add AspectDoc specific stuff to the HTML (and remove the DeclIDS).
/** We start with the known HTML files (the ones that correspond directly to the
* input files.) As we go along, we may learn that Javadoc split one .java file
* into multiple .html files to handle inner classes or local classes. The html
* file decorator picks that up.
*/
System.out.println( "> Decorating html files..." );
HtmlDecorator.decorateHTMLFromInputFiles(declIDTable,
rootDir,
symbolManager,
inputFiles,
docModifier);
System.out.println( "> Removing generated tags (this may take a while)..." );
removeDeclIDsFromFile("index-all.html", true);
removeDeclIDsFromFile("serialized-form.html", true);
if (packageList.size() > 0) {
for (int p = 0; p < packageList.size(); p++) {
removeDeclIDsFromFile(((String)packageList.elementAt(p)).replace('.','/') +
Config.DIR_SEP_CHAR +
"package-summary.html", true);
}
} else {
File[] files = FileUtil.listFiles(rootDir, new FileFilter() {
public boolean accept(File f) {
return f.getName().equals("package-summary.html");
}
});
for (int j = 0; j < files.length; j++) {
removeDeclIDsFromFile(files[j].getAbsolutePath(), false);
}
}
System.out.println( "> Finished." );
} catch (Throwable e) {
handleInternalError(e);
exit(-2);
}
}
private static void removeDeclIDsFromFile(String filename, boolean relativePath) {
// Remove the decl ids from "index-all.html"
File indexFile;
if (relativePath) {
indexFile = new File(docDir + Config.DIR_SEP_CHAR + filename);
} else {
indexFile = new File(filename);
}
try {
if ( indexFile.exists() ) {
BufferedReader indexFileReader = new BufferedReader( new FileReader( indexFile ) );
String indexFileBuffer = "";
String line = indexFileReader.readLine();
while ( line != null ) {
int indexStart = line.indexOf( Config.DECL_ID_STRING );
int indexEnd = line.indexOf( Config.DECL_ID_TERMINATOR );
if ( indexStart != -1 && indexEnd != -1 ) {
line = line.substring( 0, indexStart ) +
line.substring( indexEnd+Config.DECL_ID_TERMINATOR.length() );
}
indexFileBuffer += line;
line = indexFileReader.readLine();
}
FileOutputStream fos = new FileOutputStream( indexFile );
fos.write( indexFileBuffer.getBytes() );
}
}
catch (IOException ioe) {
// be siltent
}
}
static Vector getSourcePath() {
Vector sourcePath = new Vector();
boolean found = false;
for ( int i = 0; i < options.size(); i++ ) {
String currOption = (String)options.elementAt(i);
if (found && !currOption.startsWith("-")) {
sourcePath.add(currOption);
}
if (currOption.equals("-sourcepath")) {
found = true;
}
}
return sourcePath;
}
static File getRootDir() {
File rootDir = new File( "." );
for ( int i = 0; i < options.size(); i++ ) {
if ( ((String)options.elementAt(i)).equals( "-d" ) ) {
rootDir = new File((String)options.elementAt(i+1));
if ( !rootDir.exists() ) {
rootDir.mkdir();
// System.out.println( "Destination directory not found: " +
// (String)options.elementAt(i+1) );
// System.exit( -1 );
}
}
}
return rootDir;
}
static File createSignatureFile(File inputFile) throws IOException {
String packageName = StructureUtil.getPackageDeclarationFromFile(inputFile);
String filename = "";
if ( packageName != null ) {
String pathName = Config.WORKING_DIR + '/' + packageName.replace('.', '/');
File packageDir = new File(pathName);
if ( !packageDir.exists() ) {
packageDir.mkdirs();
if (deleteTempFilesOnExit) packageDir.deleteOnExit();
}
//verifyPackageDirExists(packageName, null);
packageName = packageName.replace( '.','/' ); // !!!
filename = Config.WORKING_DIR + Config.DIR_SEP_CHAR + packageName +
Config.DIR_SEP_CHAR + inputFile.getName();
}
else {
filename = Config.WORKING_DIR + Config.DIR_SEP_CHAR + inputFile.getName();
}
File signatureFile = new File( filename );
if (deleteTempFilesOnExit) signatureFile.deleteOnExit();
return signatureFile;
}
// static void verifyPackageDirExists( String packageName, String offset ) {
// System.err.println(">>> name: " + packageName + ", offset: " + offset);
// if ( packageName.indexOf( "." ) != -1 ) {
// File tempFile = new File("c:/aspectj-test/d1/d2/d3");
// tempFile.mkdirs();
// String currPkgDir = packageName.substring( 0, packageName.indexOf( "." ) );
// String remainingPkg = packageName.substring( packageName.indexOf( "." )+1 );
// String filePath = null;
// if ( offset != null ) {
// filePath = Config.WORKING_DIR + Config.DIR_SEP_CHAR +
// offset + Config.DIR_SEP_CHAR + currPkgDir ;
// }
// else {
// filePath = Config.WORKING_DIR + Config.DIR_SEP_CHAR + currPkgDir;
// }
// File packageDir = new File( filePath );
// if ( !packageDir.exists() ) {
// packageDir.mkdir();
// if (deleteTempFilesOnExit) packageDir.deleteOnExit();
// }
// if ( remainingPkg != "" ) {
// verifyPackageDirExists( remainingPkg, currPkgDir );
// }
// }
// else {
// String filePath = null;
// if ( offset != null ) {
// filePath = Config.WORKING_DIR + Config.DIR_SEP_CHAR + offset + Config.DIR_SEP_CHAR + packageName;
// }
// else {
// filePath = Config.WORKING_DIR + Config.DIR_SEP_CHAR + packageName;
// }
// File packageDir = new File( filePath );
// if ( !packageDir.exists() ) {
// packageDir.mkdir();
// if (deleteTempFilesOnExit) packageDir.deleteOnExit();
// }
// }
// }
/**
* Can read Eclipse-generated single-line arg
*/
static void parseCommandLine(String[] args) {
if (args.length == 0) {
displayHelpAndExit( null );
} else if (args.length == 1 && args[0].startsWith("@")) {
String argFile = args[0].substring(1);
System.out.println("> Using arg file: " + argFile);
BufferedReader br;
try {
br = new BufferedReader(new FileReader(argFile));
String line = "";
line = br.readLine();
StringTokenizer st = new StringTokenizer(line, " ");
List argList = new ArrayList();
while(st.hasMoreElements()) {
argList.add((String)st.nextElement());
}
//System.err.println(argList);
args = new String[argList.size()];
int counter = 0;
for (Iterator it = argList.iterator(); it.hasNext(); ) {
args[counter] = (String)it.next();
counter++;
}
} catch (FileNotFoundException e) {
System.err.println("> could not read arg file: " + argFile);
e.printStackTrace();
} catch (IOException ioe) {
System.err.println("> could not read arg file: " + argFile);
ioe.printStackTrace();
}
}
List vargs = new LinkedList(Arrays.asList(args));
parseArgs(vargs, new File( "." )); // !!!
if (filenames.size() == 0) {
displayHelpAndExit( "ajdoc: No packages or classes specified" );
}
}
static void setSourcepath(String arg) {
sourcepath.clear();
arg = arg + File.pathSeparator; // makes things easier for ourselves
StringTokenizer tokenizer = new StringTokenizer(arg, File.pathSeparator);
while (tokenizer.hasMoreElements()) {
sourcepath.addElement(tokenizer.nextElement());
}
}
static String getSourcepathAsString() {
String cPath = "";
for (int i = 0; i < sourcepath.size(); i++) {
cPath += (String)sourcepath.elementAt(i) + Config.DIR_SEP_CHAR + Config.WORKING_DIR;
if (i != sourcepath.size()-1) {
cPath += File.pathSeparator;
}
}
return cPath;
}
static void parseArgs(List vargs, File currentWorkingDir) {
boolean addNextAsOption = false;
boolean addNextAsArgFile = false;
boolean addNextToAJCOptions = false;
boolean addNextAsDocDir = false;
boolean addNextAsClasspath = false;
boolean ignoreArg = false; // used for discrepancy betwen class/sourcepath in ajc/javadoc
boolean addNextAsSourcePath = false;
if ( vargs.size() == 0 ) {
displayHelpAndExit( null );
}
for (int i = 0; i < vargs.size() ; i++) {
String arg = (String)vargs.get(i);
ignoreArg = false;
if ( addNextToAJCOptions ) {
ajcOptions.addElement( arg );
addNextToAJCOptions = false;
}
if ( addNextAsDocDir ) {
docDir = arg;
addNextAsDocDir = false;
}
if ( addNextAsClasspath ) {
addNextAsClasspath = false;
}
if ( addNextAsSourcePath ) {
setSourcepath( arg );
addNextAsSourcePath = false;
ignoreArg = true;
}
if ( arg.startsWith("@") ) {
expandAtSignFile(arg.substring(1), currentWorkingDir);
}
else if ( arg.equals( "-argfile" ) ) {
addNextAsArgFile = true;
}
else if ( addNextAsArgFile ) {
expandAtSignFile(arg, currentWorkingDir);
addNextAsArgFile = false;
}
else if (arg.equals("-d") ) {
addNextAsOption = true;
options.addElement(arg);
addNextAsDocDir = true;
}
else if ( arg.equals( "-bootclasspath" ) ) {
addNextAsOption = true;
addNextToAJCOptions = true;
options.addElement( arg );
ajcOptions.addElement( arg );
}
else if ( arg.equals( "-source" ) ) {
addNextAsOption = true;
addNextToAJCOptions = true;
addNextAsClasspath = true;
options.addElement(arg);
ajcOptions.addElement(arg);
}
else if ( arg.equals( "-classpath" ) ) {
addNextAsOption = true;
addNextToAJCOptions = true;
addNextAsClasspath = true;
options.addElement( arg );
ajcOptions.addElement( arg );
}
else if ( arg.equals( "-sourcepath" ) ) {
addNextAsSourcePath = true;
//options.addElement( arg );
//ajcOptions.addElement( arg );
}
else if (arg.equals("-XajdocDebug")) {
deleteTempFilesOnExit = false;
}
else if (arg.equals("-use")) {
System.out.println("> Ignoring unsupported option: -use");
}
else if (arg.equals("-splitindex")) {
// passed to javadoc
}
else if (arg.startsWith("-") || addNextAsOption) {
if ( arg.equals( "-private" ) ) {
docModifier = "private";
}else if ( arg.equals( "-package" ) ) {
docModifier = "package";
} else if ( arg.equals( "-protected" ) ) {
docModifier = "protected";
} else if ( arg.equals( "-public" ) ) {
docModifier = "public";
} else if ( arg.equals( "-verbose" ) ) {
verboseMode = true;
} else if ( arg.equals( "-author" ) ) {
authorStandardDocletSwitch = true;
} else if ( arg.equals( "-version" ) ) {
versionStandardDocletSwitch = true;
} else if ( arg.equals( "-v" ) ) {
System.out.println(getVersion());
exit(0);
} else if ( arg.equals( "-help" ) ) {
displayHelpAndExit( null );
} else if ( arg.equals( "-doclet" ) || arg.equals( "-docletpath" ) ) {
System.out.println( "The doclet and docletpath options are not currently supported \n" +
"since ajdoc makes assumptions about the behavior of the standard \n" +
"doclet. If you would find this option useful please email us at: \n" +
" \n" +
" aspectj-dev@eclipse.org \n" +
" \n" );
exit(0);
} else if (arg.equals("-nonavbar")
|| arg.equals("-noindex")) {
// pass through
//System.err.println("> ignoring unsupported option: " + arg);
} else if ( addNextAsOption ) {
// pass through
} else {
System.err.println("> unrecognized argument: " + arg);
displayHelpAndExit( null );
}
options.addElement(arg);
addNextAsOption = false;
}
else {
// check if this is a file or a package
// System.err.println(">>>>>>>> " + );
String entryName = arg.substring(arg.lastIndexOf(File.separator)+1);
if (FileUtil.hasSourceSuffix(arg)
|| arg.endsWith(".lst")
&& arg != null ) {
File f = new File(arg);
if (f.isAbsolute()) {
filenames.addElement(arg);
}
else {
filenames.addElement( currentWorkingDir + Config.DIR_SEP_CHAR + arg );
}
fileList.addElement( arg );
}
// PACKAGE MODE STUFF
else if (!ignoreArg) {
packageMode = true;
packageList.addElement( arg );
arg = arg.replace( '.', '/' ); // !!!
// do this for every item in the classpath
for ( int c = 0; c < sourcepath.size(); c++ ) {
String path = (String)sourcepath.elementAt(c) + Config.DIR_SEP_CHAR + arg;
File pkg = new File(path);
if ( pkg.isDirectory() ) {
String[] files = pkg.list( new FilenameFilter() {
public boolean accept( File dir, String name ) {
int index1 = name.lastIndexOf( "." );
int index2 = name.length();
if ( (index1 >= 0 && index2 >= 0 ) &&
(name.substring(index1, index2).equals( ".java" )
|| name.substring(index1, index2).equals( ".aj" ))) {
return true;
}
else {
return false;
}
}
} );
for ( int j = 0; j < files.length; j++ ) {
filenames.addElement( (String)sourcepath.elementAt(c) +
Config.DIR_SEP_CHAR +
arg + Config.DIR_SEP_CHAR + files[j] );
}
}
else if (c == sourcepath.size() ) { // last element on classpath
System.out.println( "ajdoc: No package, class, or source file " +
"found named " + arg + "." );
}
else {
// didn't find it on that element of the classpath but that's ok
}
}
}
}
}
// set the default visibility as an option to javadoc option
if ( !options.contains( "-private" ) &&
!options.contains( "-package" ) &&
!options.contains( "-protected" ) &&
!options.contains( "-public" ) ) {
options.addElement( "-package" );
}
}
static void expandAtSignFile(String filename, File currentWorkingDir) {
List result = new LinkedList();
File atFile = qualifiedFile(filename, currentWorkingDir);
String atFileParent = atFile.getParent();
File myWorkingDir = null;
if (atFileParent != null) myWorkingDir = new File(atFileParent);
try {
BufferedReader stream = new BufferedReader(new FileReader(atFile));
String line = null;
while ( (line = stream.readLine()) != null) {
// strip out any comments of the form # to end of line
int commentStart = line.indexOf("//");
if (commentStart != -1) {
line = line.substring(0, commentStart);
}
// remove extra whitespace that might have crept in
line = line.trim();
// ignore blank lines
if (line.length() == 0) continue;
result.add(line);
}
} catch (IOException e) {
System.err.println("Error while reading the @ file " + atFile.getPath() + ".\n"
+ e);
System.exit( -1 );
}
parseArgs(result, myWorkingDir);
}
static File qualifiedFile(String name, File currentWorkingDir) {
name = name.replace('/', File.separatorChar);
File file = new File(name);
if (!file.isAbsolute() && currentWorkingDir != null) {
file = new File(currentWorkingDir, name);
}
return file;
}
static void displayHelpAndExit(String message) {
if (message != null) System.err.println(message);
System.err.println();
System.err.println(Config.USAGE);
exit(0);
}
static protected void exit(int value) {
System.out.flush();
System.err.flush();
System.exit(value);
}
/* This section of code handles errors that occur during compilation */
static final String internalErrorMessage =
"Please copy the following text into an email message and send it,\n" +
"along with any additional information you can add to: \n" +
" \n" +
" aspectj-dev@eclipse.org \n" +
" \n";
static public void handleInternalError(Throwable uncaughtThrowable) {
System.err.println("An internal error occured in ajdoc");
System.err.println(internalErrorMessage);
System.err.println(uncaughtThrowable.toString());
uncaughtThrowable.printStackTrace();
System.err.println();
}
static String getVersion() {
return "ajdoc version " + Version.text;
}
public static boolean hasAborted() {
return aborted;
}
}
|
71,811
|
Bug 71811 AJDoc: should be able to set encoding like javadoc
|
ajdoc doesn't support the -encoding -docencoding and -charset options of javadoc. Especially, it doesn't pass on the -encoding to ajc. If your project uses a source file encoding (e.g. UTF-8) differing form the platform standard, and some java identifiers use characters byond the standard ASCII range, you won't be able to use ajdoc at all.
|
resolved fixed
|
5f80c8c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-20T01:01:45Z
| 2004-08-11T18:46:40Z
|
ajdoc/testsrc/org/aspectj/tools/ajdoc/CoverageTestCase.java
|
/* *******************************************************************
* Copyright (c) 2003 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Mik Kersten initial implementation
* ******************************************************************/
package org.aspectj.tools.ajdoc;
import java.io.File;
import junit.framework.TestCase;
/**
* A long way to go until full coverage, but this is the place to add more.
*
* @author Mik Kersten
*/
public class CoverageTestCase extends TestCase {
File file0 = new File("testdata/coverage/InDefaultPackage.java");
File file1 = new File("testdata/coverage/foo/ClassA.java");
File aspect1 = new File("testdata/coverage/foo/UseThisAspectForLinkCheck.aj");
File file2 = new File("testdata/coverage/foo/InterfaceI.java");
File file3 = new File("testdata/coverage/foo/PlainJava.java");
File file4 = new File("testdata/coverage/foo/ModelCoverage.java");
File file5 = new File("testdata/coverage/fluffy/Fluffy.java");
File file6 = new File("testdata/coverage/fluffy/bunny/Bunny.java");
File file7 = new File("testdata/coverage/fluffy/bunny/rocks/Rocks.java");
File file8 = new File("testdata/coverage/fluffy/bunny/rocks/UseThisAspectForLinkCheckToo.java");
File file9 = new File("testdata/coverage/foo/PkgVisibleClass.java");
File outdir = new File("testdata/coverage/doc");
public void testCoverage() {
outdir.delete();
String[] args = {
// "-XajdocDebug",
"-source",
"1.4",
"-private",
"-d",
outdir.getAbsolutePath(),
aspect1.getAbsolutePath(),
file0.getAbsolutePath(),
file1.getAbsolutePath(),
file2.getAbsolutePath(),
file3.getAbsolutePath(),
file4.getAbsolutePath(),
file5.getAbsolutePath(),
file6.getAbsolutePath(),
file7.getAbsolutePath(),
file8.getAbsolutePath(),
file9.getAbsolutePath()
};
org.aspectj.tools.ajdoc.Main.main(args);
}
public void testCoveragePublicMode() {
outdir.delete();
String[] args = {
"-public",
"-source",
"1.4",
"-d",
outdir.getAbsolutePath(),
file3.getAbsolutePath(),
file9.getAbsolutePath()
};
org.aspectj.tools.ajdoc.Main.main(args);
}
// public void testPlainJava() {
// outdir.delete();
// String[] args = { "-d",
// outdir.getAbsolutePath(),
// file3.getAbsolutePath() };
// org.aspectj.tools.ajdoc.Main.main(args);
// }
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
}
|
72,154
|
Bug 72154 Support for simple dump file
|
When the compiler terminates abnormally (exception) or behaves unexpectedly (warning/error/abort) a simple dump of the compiler state should be produced to aid problem diagnosis. The content and conditions under which the dump is produced should be configurable by the user but the facility should be enabled by default for exceptions. Consequently its inclusion should have negligible impact on compiler performance and footprint. The file should be attached to bug reports to give a complete and objective description of the users environment and support problem resolution where a testcase cannot be provided. One approach is to write a uniquely name file (using date & time) in the current directory e.g ajcore.20040818.105200.txt which should be human readable (it can be zipped if large) to allow the user to potentially diagnose their own problems or remove potentially sensitive data before submission. It should contain basic information such as AspectJ version, system properties and command line as well as failure information such as _full_ exception stack trace, compiler messages and internal compiler state.
|
resolved fixed
|
f503523
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-23T13:40:31Z
| 2004-08-18T09:06:40Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/AjdtCommand.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.ajc;
import org.aspectj.ajdt.internal.core.builder.*;
import org.aspectj.bridge.*;
import org.eclipse.jdt.internal.core.builder.MissingSourceFileException;
/**
* ICommand adapter for the AspectJ compiler.
* Not thread-safe.
*/
public class AjdtCommand implements ICommand {
/** Message String for any AbortException thrown from ICommand API's */
public static final String ABORT_MESSAGE = "ABORT";
// private boolean canRepeatCommand = true;
AjBuildManager buildManager = null;
String[] savedArgs = null;
/**
* Run AspectJ compiler, wrapping any exceptions thrown as
* ABORT messages (containing ABORT_MESSAGE String).
* @param args the String[] for the compiler
* @param handler the IMessageHandler for any messages
* @see org.aspectj.bridge.ICommand#runCommand(String[], IMessageHandler)
* @return false if handler has errors or the command failed
*/
public boolean runCommand(String[] args, IMessageHandler handler) {
buildManager = new AjBuildManager(handler);
savedArgs = new String[args.length];
System.arraycopy(args, 0, savedArgs, 0, savedArgs.length);
for (int i = 0; i < args.length; i++) {
// AMC - PR58681. No need to abort on -help as the Eclipse compiler does the right thing.
// if ("-help".equals(args[i])) {
// // should be info, but handler usually suppresses
// MessageUtil.abort(handler, BuildArgParser.getUsage());
// return true;
// } else
if ("-X".equals(args[i])) {
// should be info, but handler usually suppresses
MessageUtil.abort(handler, BuildArgParser.getXOptionUsage());
return true;
}
}
return doCommand(handler, false);
}
/**
* Run AspectJ compiler, wrapping any exceptions thrown as
* ABORT messages (containing ABORT_MESSAGE String).
* @param handler the IMessageHandler for any messages
* @see org.aspectj.bridge.ICommand#repeatCommand(IMessageHandler)
* @return false if handler has errors or the command failed
*/
public boolean repeatCommand(IMessageHandler handler) {
if (null == buildManager) {
MessageUtil.abort(handler, "repeatCommand called before runCommand");
return false;
}
return doCommand(handler, true);
}
/**
* Delegate of both runCommand and repeatCommand.
* This invokes the argument parser each time
* (even when repeating).
* If the parser detects errors, this signals an
* abort with the usage message and returns false.
* @param handler the IMessageHandler sink for any messages
* @param repeat if true, do incremental build, else do batch build
* @return false if handler has any errors or command failed
*/
protected boolean doCommand(IMessageHandler handler, boolean repeat) {
try {
//buildManager.setMessageHandler(handler);
CountingMessageHandler counter = new CountingMessageHandler(handler);
if (counter.hasErrors()) {
return false;
}
// regenerate configuration b/c world might have changed (?)
AjBuildConfig config = genBuildConfig(savedArgs, counter);
if (!config.shouldProceed()) {
return true;
}
if (!config.hasSources()) {
MessageUtil.error(counter, "no sources specified");
}
if (counter.hasErrors()) { // print usage for config errors
String usage = BuildArgParser.getUsage();
MessageUtil.abort(handler, usage);
return false;
}
//System.err.println("errs: " + counter.hasErrors());
return ((repeat
? buildManager.incrementalBuild(config, handler)
: buildManager.batchBuild(config, handler))
&& !counter.hasErrors());
} catch (AbortException ae) {
if (ae.isSilent()) {
throw ae;
} else {
MessageUtil.abort(handler, ABORT_MESSAGE, ae);
}
} catch (MissingSourceFileException t) {
MessageUtil.error(handler, t.getMessage());
} catch (Throwable t) {
MessageUtil.abort(handler, ABORT_MESSAGE, t);
}
return false;
}
/**
* This creates a build configuration for the arguments.
* Errors reported to the handler:
* <ol>
* <li>The parser detects some directly</li>
* <li>The parser grabs some from the error stream
* emitted by its superclass</li>
* <li>The configuration has a self-test</li>
* </ol>
* In the latter two cases, the errors do not have
* a source location context for locating the error.
*/
public static AjBuildConfig genBuildConfig(String[] args, CountingMessageHandler handler) {
BuildArgParser parser = new BuildArgParser(handler);
AjBuildConfig config = parser.genBuildConfig(args);
ISourceLocation location = null;
if (config.getConfigFile() != null) {
location = new SourceLocation(config.getConfigFile(), 0);
}
String message = parser.getOtherMessages(true);
if (null != message) {
IMessage.Kind kind = inferKind(message);
IMessage m = new Message(message, kind, null, location);
handler.handleMessage(m);
}
// message = config.configErrors();
// if (null != message) {
// IMessage.Kind kind = inferKind(message);
// IMessage m = new Message(message, kind, null, location);
// handler.handleMessage(m);
// }
return config;
}
/** @return IMessage.WARNING unless message contains error or info */
protected static IMessage.Kind inferKind(String message) { // XXX dubious
if (-1 != message.indexOf("error")) {
return IMessage.ERROR;
} else if (-1 != message.indexOf("info")) {
return IMessage.INFO;
} else {
return IMessage.WARNING;
}
}
}
|
72,154
|
Bug 72154 Support for simple dump file
|
When the compiler terminates abnormally (exception) or behaves unexpectedly (warning/error/abort) a simple dump of the compiler state should be produced to aid problem diagnosis. The content and conditions under which the dump is produced should be configurable by the user but the facility should be enabled by default for exceptions. Consequently its inclusion should have negligible impact on compiler performance and footprint. The file should be attached to bug reports to give a complete and objective description of the users environment and support problem resolution where a testcase cannot be provided. One approach is to write a uniquely name file (using date & time) in the current directory e.g ajcore.20040818.105200.txt which should be human readable (it can be zipped if large) to allow the user to potentially diagnose their own problems or remove potentially sensitive data before submission. It should contain basic information such as AspectJ version, system properties and command line as well as failure information such as _full_ exception stack trace, compiler messages and internal compiler state.
|
resolved fixed
|
f503523
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-23T13:40:31Z
| 2004-08-18T09:06:40Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/BuildArgParser.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.ajc;
import java.io.*;
import java.util.*;
import org.aspectj.ajdt.internal.core.builder.*;
import org.aspectj.bridge.*;
import org.aspectj.util.*;
import org.aspectj.weaver.WeaverMessages;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.internal.compiler.batch.Main;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
public class BuildArgParser extends Main {
private static final String BUNDLE_NAME = "org.aspectj.ajdt.ajc.messages";
private static boolean LOADED_BUNDLE = false;
static {
bundle = ResourceBundle.getBundle(BUNDLE_NAME);
if (!LOADED_BUNDLE) {
LOADED_BUNDLE = true;
}
}
/** to initialize super's PrintWriter but refer to underlying StringWriter */
private static class StringPrintWriter extends PrintWriter {
public final StringWriter stringWriter;
StringPrintWriter(StringWriter sw) {
super(sw);
this.stringWriter = sw;
}
}
/** @return multi-line String usage for the compiler */
public static String getUsage() {
return Main.bind("misc.usage");
}
public static String getXOptionUsage() {
return Main.bind("xoption.usage");
}
/**
* StringWriter sink for some errors.
* This only captures errors not handled by any IMessageHandler parameter
* and only when no PrintWriter is set in the constructor.
* XXX This relies on (Sun's) implementation of StringWriter,
* which returns the actual (not copy) internal StringBuffer.
*/
private final StringBuffer errorSink;
private IMessageHandler handler;
/**
* Overrides super's bundle.
*/
public BuildArgParser(PrintWriter writer, IMessageHandler handler) {
super(writer, writer, false);
if (writer instanceof StringPrintWriter) {
errorSink = ((StringPrintWriter) writer).stringWriter.getBuffer();
} else {
errorSink = null;
}
this.handler = handler;
}
/** Set up to capture messages using getOtherMessages(boolean) */
public BuildArgParser(IMessageHandler handler) {
this(new StringPrintWriter(new StringWriter()),handler);
}
/**
* Generate build configuration for the input args,
* passing to handler any error messages.
* @param args the String[] arguments for the build configuration
* @return AjBuildConfig per args,
* which will be invalid unless there are no handler errors.
*/
public AjBuildConfig genBuildConfig(String[] args) {
AjBuildConfig config = new AjBuildConfig();
populateBuildConfig(config, args, true, null);
return config;
}
/**
* Generate build configuration for the input args,
* passing to handler any error messages.
* @param args the String[] arguments for the build configuration
* @param setClasspath determines if the classpath should be parsed and set on the build configuration
* @param configFile can be null
* @return AjBuildConfig per args,
* which will be invalid unless there are no handler errors.
*/
public AjBuildConfig populateBuildConfig(AjBuildConfig buildConfig, String[] args, boolean setClasspath, File configFile) {
buildConfig.setConfigFile(configFile);
try {
// sets filenames to be non-null in order to make sure that file paramters are ignored
super.filenames = new String[] { "" };
AjcConfigParser parser = new AjcConfigParser(buildConfig, handler);
parser.parseCommandLine(args);
boolean swi = buildConfig.getShowWeavingInformation();
// Now jump through firey hoops to turn them on/off
if (handler instanceof CountingMessageHandler) {
IMessageHandler delegate = ((CountingMessageHandler)handler).delegate;
// Without dontIgnore() on the IMessageHandler interface, we have to do this *blurgh*
if (delegate instanceof MessageHandler) {
if (swi)
((MessageHandler)delegate).dontIgnore(IMessage.WEAVEINFO);
else
((MessageHandler)delegate).ignore(IMessage.WEAVEINFO);
}
}
boolean incrementalMode = buildConfig.isIncrementalMode()
|| buildConfig.isIncrementalFileMode();
List fileList = new ArrayList();
List files = parser.getFiles();
if (!LangUtil.isEmpty(files)) {
if (incrementalMode) {
MessageUtil.error(handler, "incremental mode only handles source files using -sourceroots");
} else {
fileList.addAll(files);
}
}
List javaArgList = new ArrayList();
// disable all special eclipse warnings by default - why???
//??? might want to instead override getDefaultOptions()
javaArgList.add("-warn:none");
// these next four lines are some nonsense to fool the eclipse batch compiler
// without these it will go searching for reasonable values from properties
//TODO fix org.eclipse.jdt.internal.compiler.batch.Main so this hack isn't needed
javaArgList.add("-classpath");
javaArgList.add(System.getProperty("user.dir"));
javaArgList.add("-bootclasspath");
javaArgList.add(System.getProperty("user.dir"));
javaArgList.addAll(parser.getUnparsedArgs());
super.configure((String[])javaArgList.toArray(new String[javaArgList.size()]));
if (!proceed) {
buildConfig.doNotProceed();
return buildConfig;
}
if (buildConfig.getSourceRoots() != null) {
for (Iterator i = buildConfig.getSourceRoots().iterator(); i.hasNext(); ) {
fileList.addAll(collectSourceRootFiles((File)i.next()));
}
}
buildConfig.setFiles(fileList);
if (destinationPath != null) { // XXX ?? unparsed but set?
buildConfig.setOutputDir(new File(destinationPath));
}
if (setClasspath) {
buildConfig.setClasspath(getClasspath(parser));
}
if (incrementalMode
&& (0 == buildConfig.getSourceRoots().size())) {
MessageUtil.error(handler, "specify a source root when in incremental mode");
}
/*
* Ensure we don't overwrite injars, inpath or aspectpath with outjar
* bug-71339
*/
File outjar = buildConfig.getOutputJar();
if (outjar != null) {
/* Search injars */
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File injar = (File)i.next();
if (injar.equals(outjar)) {
String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH);
MessageUtil.error(handler,message);
}
}
/* Search inpath */
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (!inPathElement.isDirectory() && inPathElement.equals(outjar)) {
String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH);
MessageUtil.error(handler,message);
}
}
/* Search aspectpath */
for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext(); ) {
File pathElement = (File)i.next();
if (!pathElement.isDirectory() && pathElement.equals(outjar)) {
String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH);
MessageUtil.error(handler,message);
}
}
}
setDebugOptions();
buildConfig.getOptions().set(options);
} catch (InvalidInputException iie) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
location = new SourceLocation(buildConfig.getConfigFile(), 0);
}
IMessage m = new Message(iie.getMessage(), IMessage.ERROR, null, location);
handler.handleMessage(m);
}
return buildConfig;
}
// from super...
public void printVersion() {
System.err.println("AspectJ Compiler " + Version.text + " built on " + Version.time_text); //$NON-NLS-1$
System.err.flush();
}
public void printUsage() {
System.out.println(bind("misc.usage")); //$NON-NLS-1$
System.out.flush();
}
/**
* Get messages not dumped to handler or any PrintWriter.
* @param flush if true, empty errors
* @return null if none, String otherwise
* @see BuildArgParser()
*/
public String getOtherMessages(boolean flush) {
if (null == errorSink) {
return null;
}
String result = errorSink.toString().trim();
if (0 == result.length()) {
result = null;
}
if (flush) {
errorSink.setLength(0);
}
return result;
}
private void setDebugOptions() {
options.put(
CompilerOptions.OPTION_LocalVariableAttribute,
CompilerOptions.GENERATE);
options.put(
CompilerOptions.OPTION_LineNumberAttribute,
CompilerOptions.GENERATE);
options.put(
CompilerOptions.OPTION_SourceFileAttribute,
CompilerOptions.GENERATE);
}
private Collection collectSourceRootFiles(File dir) {
return Arrays.asList(FileUtil.listFiles(dir, FileUtil.aspectjSourceFileFilter));
}
/**
* If the classpath is not set, we use the environment's java.class.path, but remove
* the aspectjtools.jar entry from that list in order to prevent wierd bootstrap issues
* (refer to bug#39959).
*/
public List getClasspath(AjcConfigParser parser) {
List ret = new ArrayList();
if (parser.bootclasspath == null) {
addClasspath(System.getProperty("sun.boot.class.path", ""), ret);
} else {
addClasspath(parser.bootclasspath, ret);
}
String extdirs = parser.extdirs;
if (extdirs == null) {
extdirs = System.getProperty("java.ext.dirs", "");
}
addExtDirs(extdirs, ret);
if (parser.classpath == null) {
addClasspath(System.getProperty("java.class.path", ""), ret);
List fixedList = new ArrayList();
for (Iterator it = ret.iterator(); it.hasNext(); ) {
String entry = (String)it.next();
if (!entry.endsWith("aspectjtools.jar")) {
fixedList.add(entry);
}
}
ret = fixedList;
} else {
addClasspath(parser.classpath, ret);
}
//??? eclipse seems to put outdir on the classpath
//??? we're brave and believe we don't need it
return ret;
}
private void addExtDirs(String extdirs, List classpathCollector) {
StringTokenizer tokenizer = new StringTokenizer(extdirs, File.pathSeparator);
while (tokenizer.hasMoreTokens()) {
// classpathCollector.add(tokenizer.nextToken());
File dirFile = new File((String)tokenizer.nextToken());
if (dirFile.canRead() && dirFile.isDirectory()) {
File[] files = dirFile.listFiles(FileUtil.ZIP_FILTER);
for (int i = 0; i < files.length; i++) {
classpathCollector.add(files[i].getAbsolutePath());
}
} else {
// XXX alert on invalid -extdirs entries
}
}
}
private void addClasspath(String classpath, List classpathCollector) {
StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator);
while (tokenizer.hasMoreTokens()) {
classpathCollector.add(tokenizer.nextToken());
}
}
private class AjcConfigParser extends ConfigParser {
private String bootclasspath = null;
private String classpath = null;
private String extdirs = null;
private List unparsedArgs = new ArrayList();
private AjBuildConfig buildConfig;
private IMessageHandler handler;
public AjcConfigParser(AjBuildConfig buildConfig, IMessageHandler handler) {
this.buildConfig = buildConfig;
this.handler = handler;
}
public List getUnparsedArgs() {
return unparsedArgs;
}
/**
* Extract AspectJ-specific options (except for argfiles).
* Caller should warn when sourceroots is empty but in
* incremental mode.
* Signals warnings or errors through handler set in constructor.
*/
public void parseOption(String arg, LinkedList args) { // XXX use ListIterator.remove()
int nextArgIndex = args.indexOf(arg)+1; // XXX assumes unique
// trim arg?
if (LangUtil.isEmpty(arg)) {
showWarning("empty arg found");
} else if (arg.equals("-inpath")) {;
if (args.size() > nextArgIndex) {
// buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_Inpath, CompilerOptions.PRESERVE);
List inPath = buildConfig.getInpath();
StringTokenizer st = new StringTokenizer(
((ConfigParser.Arg)args.get(nextArgIndex)).getValue(),
File.pathSeparator);
while (st.hasMoreTokens()) {
String filename = st.nextToken();
File file = makeFile(filename);
if (file.exists() && FileUtil.hasZipSuffix(filename)) {
inPath.add(file);
} else {
if (file.isDirectory()) {
inPath.add(file);
} else
showError("bad inpath component: " + filename);
}
}
buildConfig.setInPath(inPath);
args.remove(args.get(nextArgIndex));
}
} else if (arg.equals("-injars")) {;
if (args.size() > nextArgIndex) {
// buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_InJARs, CompilerOptions.PRESERVE);
StringTokenizer st = new StringTokenizer(
((ConfigParser.Arg)args.get(nextArgIndex)).getValue(),
File.pathSeparator);
while (st.hasMoreTokens()) {
String filename = st.nextToken();
File jarFile = makeFile(filename);
if (jarFile.exists() && FileUtil.hasZipSuffix(filename)) {
buildConfig.getInJars().add(jarFile);
} else {
File dirFile = makeFile(filename);
if (dirFile.isDirectory()) {
buildConfig.getInJars().add(dirFile);
} else
showError("bad injar: " + filename);
}
}
args.remove(args.get(nextArgIndex));
}
} else if (arg.equals("-aspectpath")) {;
if (args.size() > nextArgIndex) {
StringTokenizer st = new StringTokenizer(
((ConfigParser.Arg)args.get(nextArgIndex)).getValue(),
File.pathSeparator);
while (st.hasMoreTokens()) {
String filename = st.nextToken();
File jarFile = makeFile(filename);
if (jarFile.exists() && FileUtil.hasZipSuffix(filename)) {
buildConfig.getAspectpath().add(jarFile);
} else {
showError("bad aspectpath: " + filename);
}
}
args.remove(args.get(nextArgIndex));
}
} else if (arg.equals("-sourceroots")) {
if (args.size() > nextArgIndex) {
List sourceRoots = new ArrayList();
StringTokenizer st = new StringTokenizer(
((ConfigParser.Arg)args.get(nextArgIndex)).getValue(),
File.pathSeparator);
while (st.hasMoreTokens()) {
File f = makeFile(st.nextToken());
if (f.isDirectory() && f.canRead()) {
sourceRoots.add(f);
} else {
showError("bad sourceroot: " + f);
}
}
if (0 < sourceRoots.size()) {
buildConfig.setSourceRoots(sourceRoots);
}
args.remove(args.get(nextArgIndex));
} else {
showError("-sourceroots requires list of directories");
}
} else if (arg.equals("-outjar")) {
if (args.size() > nextArgIndex) {
// buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_OutJAR, CompilerOptions.GENERATE);
File jarFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue());
if (FileUtil.hasZipSuffix(jarFile)) {
try {
if (!jarFile.exists()) {
jarFile.createNewFile();
}
buildConfig.setOutputJar(jarFile);
} catch (IOException ioe) {
showError("unable to create outjar file: " + jarFile);
}
} else {
showError("invalid -outjar file: " + jarFile);
}
args.remove(args.get(nextArgIndex));
} else {
showError("-outjar requires jar path argument");
}
} else if (arg.equals("-incremental")) {
buildConfig.setIncrementalMode(true);
} else if (arg.equals("-XincrementalFile")) {
if (args.size() > nextArgIndex) {
File file = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue());
buildConfig.setIncrementalFile(file);
if (!file.canRead()) {
showError("bad -XincrementalFile : " + file);
// if not created before recompile test, stop after first compile
}
args.remove(args.get(nextArgIndex));
} else {
showError("-XincrementalFile requires file argument");
}
} else if (arg.equals("-emacssym")) {
buildConfig.setEmacsSymMode(true);
buildConfig.setGenerateModelMode(true);
} else if (arg.equals("-XjavadocsInModel")) {
buildConfig.setGenerateModelMode(true);
buildConfig.setGenerateJavadocsInModelMode(true);
} else if (arg.equals("-noweave") || arg.equals( "-XnoWeave")) {
buildConfig.setNoWeave(true);
} else if (arg.equals("-XserializableAspects")) {
buildConfig.setXserializableAspects(true);
} else if (arg.equals("-XlazyTjp")) {
buildConfig.setXlazyTjp(true);
} else if (arg.startsWith("-Xreweavable")) {
buildConfig.setXreweavable(true);
if (arg.endsWith(":compress")) {
buildConfig.setXreweavableCompressClasses(true);
}
} else if (arg.equals("-XnoInline")) {
buildConfig.setXnoInline(true);
} else if (arg.startsWith("-showWeaveInfo")) {
buildConfig.setShowWeavingInformation(true);
} else if (arg.equals("-Xlintfile")) {
if (args.size() > nextArgIndex) {
File lintSpecFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue());
// XXX relax restriction on props file suffix?
if (lintSpecFile.canRead() && lintSpecFile.getName().endsWith(".properties")) {
buildConfig.setLintSpecFile(lintSpecFile);
} else {
showError("bad -Xlintfile file: " + lintSpecFile);
buildConfig.setLintSpecFile(null);
}
args.remove(args.get(nextArgIndex));
} else {
showError("-Xlintfile requires .properties file argument");
}
} else if (arg.equals("-Xlint")) {
// buildConfig.getAjOptions().put(
// AjCompilerOptions.OPTION_Xlint,
// CompilerOptions.GENERATE);
buildConfig.setLintMode(AjBuildConfig.AJLINT_DEFAULT);
} else if (arg.startsWith("-Xlint:")) {
if (7 < arg.length()) {
buildConfig.setLintMode(arg.substring(7));
} else {
showError("invalid lint option " + arg);
}
} else if (arg.equals("-bootclasspath")) {
if (args.size() > nextArgIndex) {
String bcpArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
StringBuffer bcp = new StringBuffer();
StringTokenizer strTok = new StringTokenizer(bcpArg,File.pathSeparator);
while (strTok.hasMoreTokens()) {
bcp.append(makeFile(strTok.nextToken()));
if (strTok.hasMoreTokens()) {
bcp.append(File.pathSeparator);
}
}
bootclasspath = bcp.toString();
args.remove(args.get(nextArgIndex));
} else {
showError("-bootclasspath requires classpath entries");
}
} else if (arg.equals("-classpath")) {
if (args.size() > nextArgIndex) {
String cpArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
StringBuffer cp = new StringBuffer();
StringTokenizer strTok = new StringTokenizer(cpArg,File.pathSeparator);
while (strTok.hasMoreTokens()) {
cp.append(makeFile(strTok.nextToken()));
if (strTok.hasMoreTokens()) {
cp.append(File.pathSeparator);
}
}
classpath = cp.toString();
args.remove(args.get(nextArgIndex));
} else {
showError("-classpath requires classpath entries");
}
} else if (arg.equals("-extdirs")) {
if (args.size() > nextArgIndex) {
String extdirsArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
StringBuffer ed = new StringBuffer();
StringTokenizer strTok = new StringTokenizer(extdirsArg,File.pathSeparator);
while (strTok.hasMoreTokens()) {
ed.append(makeFile(strTok.nextToken()));
if (strTok.hasMoreTokens()) {
ed.append(File.pathSeparator);
}
}
extdirs = ed.toString();
args.remove(args.get(nextArgIndex));
} else {
showError("-extdirs requires list of external directories");
}
// error on directory unless -d, -{boot}classpath, or -extdirs
} else if (arg.equals("-d")) {
dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-classpath")) {
// dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-bootclasspath")) {
// dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-extdirs")) {
// dirLookahead(arg, args, nextArgIndex);
} else if (new File(arg).isDirectory()) {
showError("dir arg not permitted: " + arg);
} else {
// argfile, @file parsed by superclass
// no eclipse options parsed:
// -d args, -help (handled),
// -classpath, -target, -1.3, -1.4, -source [1.3|1.4]
// -nowarn, -warn:[...], -deprecation, -noImportError,
// -proceedOnError, -g:[...], -preserveAllLocals,
// -referenceInfo, -encoding, -verbose, -log, -time
// -noExit, -repeat
unparsedArgs.add(arg);
}
}
protected void dirLookahead(String arg, LinkedList argList, int nextArgIndex) {
unparsedArgs.add(arg);
ConfigParser.Arg next = (ConfigParser.Arg) argList.get(nextArgIndex);
String value = next.getValue();
if (!LangUtil.isEmpty(value)) {
if (new File(value).isDirectory()) {
unparsedArgs.add(value);
argList.remove(next);
return;
}
}
}
public void showError(String message) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
location = new SourceLocation(buildConfig.getConfigFile(), 0);
}
IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.ERROR, null, location);
handler.handleMessage(errorMessage);
// MessageUtil.error(handler, CONFIG_MSG + message);
}
protected void showWarning(String message) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
location = new SourceLocation(buildConfig.getConfigFile(), 0);
}
IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.WARNING, null, location);
handler.handleMessage(errorMessage);
// MessageUtil.warn(handler, message);
}
protected File makeFile(File dir, String name) {
name = name.replace('/', File.separatorChar);
File ret = new File(name);
if (dir == null || ret.isAbsolute()) return ret;
try {
dir = dir.getCanonicalFile();
} catch (IOException ioe) { }
return new File(dir, name);
}
}
}
|
72,154
|
Bug 72154 Support for simple dump file
|
When the compiler terminates abnormally (exception) or behaves unexpectedly (warning/error/abort) a simple dump of the compiler state should be produced to aid problem diagnosis. The content and conditions under which the dump is produced should be configurable by the user but the facility should be enabled by default for exceptions. Consequently its inclusion should have negligible impact on compiler performance and footprint. The file should be attached to bug reports to give a complete and objective description of the users environment and support problem resolution where a testcase cannot be provided. One approach is to write a uniquely name file (using date & time) in the current directory e.g ajcore.20040818.105200.txt which should be human readable (it can be zipped if large) to allow the user to potentially diagnose their own problems or remove potentially sensitive data before submission. It should contain basic information such as AspectJ version, system properties and command line as well as failure information such as _full_ exception stack trace, compiler messages and internal compiler state.
|
resolved fixed
|
f503523
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-23T13:40:31Z
| 2004-08-18T09: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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.*;
import java.util.*;
import java.util.jar.*;
import java.util.zip.ZipEntry;
import org.aspectj.ajdt.internal.compiler.AjCompilerAdapter;
import org.aspectj.ajdt.internal.compiler.IBinarySourceProvider;
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.*;
import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter;
import org.aspectj.asm.*;
//import org.aspectj.asm.internal.*;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.*;
import org.aspectj.util.FileUtil;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.*;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jdt.core.compiler.*;
import org.eclipse.jdt.internal.compiler.*;
import org.eclipse.jdt.internal.compiler.batch.*;
import org.eclipse.jdt.internal.compiler.batch.FileSystem;
import org.eclipse.jdt.internal.compiler.env.*;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.parser.Parser;
import org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
//import org.eclipse.jdt.internal.compiler.util.HashtableOfObject;
public class AjBuildManager implements IOutputClassFileNameProvider,IBinarySourceProvider,ICompilerAdapterFactory {
private static final String CANT_WRITE_RESULT = "unable to write compilation result";
private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF";
static final boolean COPY_INPATH_DIR_RESOURCES = false;
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.
*/
private static AsmHierarchyBuilder asmHierarchyBuilder = new AsmHierarchyBuilder();
private IProgressListener progressListener = null;
private int compiledCount;
private int sourceFileCount;
private JarOutputStream zos;
private boolean batchCompile = true;
private INameEnvironment environment;
private Map /* String -> List<UCF>*/ binarySourcesForTheNextCompile = new HashMap();
private IHierarchy structureModel;
public AjBuildConfig buildConfig;
AjState state = new AjState(this);
BcelWeaver bcelWeaver;
public BcelWorld bcelWorld;
public CountingMessageHandler handler;
public AjBuildManager(IMessageHandler holder) {
super();
this.handler = CountingMessageHandler.makeCountingMessageHandler(holder);
}
/** @return true if we should generate a model as a side-effect */
public boolean doGenerateModel() {
return buildConfig.isGenerateModelMode();
}
public boolean batchBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler)
throws IOException, AbortException {
return doBuild(buildConfig, baseHandler, true);
}
public boolean incrementalBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler)
throws IOException, AbortException {
return doBuild(buildConfig, baseHandler, false);
}
/** @throws AbortException if check for runtime fails */
protected boolean doBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler,
boolean batch) throws IOException, AbortException {
boolean ret = true;
batchCompile = batch;
try {
if (batch) {
this.state = new AjState(this);
}
boolean canIncremental = state.prepareForNextBuild(buildConfig);
if (!canIncremental && !batch) { // retry as batch?
return doBuild(buildConfig, baseHandler, true);
}
this.handler =
CountingMessageHandler.makeCountingMessageHandler(baseHandler);
// XXX duplicate, no? remove?
String check = checkRtJar(buildConfig);
if (check != null) {
if (FAIL_IF_RUNTIME_NOT_FOUND) {
MessageUtil.error(handler, check);
return false;
} else {
MessageUtil.warn(handler, check);
}
}
// if (batch) {
setBuildConfig(buildConfig);
//}
if (batch || !AsmManager.attemptIncrementalModelRepairs) {
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
setupModel(buildConfig);
// }
}
if (batch) {
initBcelWorld(handler);
}
if (handler.hasErrors()) {
return false;
}
if (buildConfig.getOutputJar() != null) {
if (!openOutputStream(buildConfig.getOutputJar())) return false;
}
if (batch) {
// System.err.println("XXXX batch: " + buildConfig.getFiles());
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
bcelWorld.setModel(AsmManager.getDefault().getHierarchy());
// in incremental build, only get updated model?
}
binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true);
performCompilation(buildConfig.getFiles());
if (handler.hasErrors()) {
return false;
}
if (AsmManager.isReporting())
AsmManager.getDefault().reportModelInfo("After a batch build");
} else {
// done already?
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
// bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel());
// }
// System.err.println("XXXX start inc ");
binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true);
List files = state.getFilesToCompile(true);
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode())
if (AsmManager.attemptIncrementalModelRepairs)
AsmManager.getDefault().processDelta(files,state.addedFiles,state.deletedFiles);
boolean hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty());
for (int i = 0; (i < 5) && hereWeGoAgain; i++) {
// System.err.println("XXXX inc: " + files);
performCompilation(files);
if (handler.hasErrors() || (progressListener!=null && progressListener.isCancelledRequested())) {
return false;
}
binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(false);
files = state.getFilesToCompile(false);
hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty());
// TODO Andy - Needs some thought here...
// I think here we might want to pass empty addedFiles/deletedFiles as they were
// dealt with on the first call to processDelta - we are going through this loop
// again because in compiling something we found something else we needed to
// rebuild. But what case causes this?
if (hereWeGoAgain)
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode())
if (AsmManager.attemptIncrementalModelRepairs)
AsmManager.getDefault().processDelta(files,state.addedFiles,state.deletedFiles);
}
if (!files.isEmpty()) {
return batchBuild(buildConfig, baseHandler);
} else {
if (AsmManager.isReporting())
AsmManager.getDefault().reportModelInfo("After an incremental build");
}
}
// XXX not in Mik's incremental
if (buildConfig.isEmacsSymMode()) {
new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel();
}
// have to tell state we succeeded or next is not incremental
state.successfulCompile(buildConfig);
copyResourcesToDestination();
/*boolean weaved = *///weaveAndGenerateClassFiles();
// if not weaved, then no-op build, no model changes
// but always returns true
// XXX weaved not in Mik's incremental
if (buildConfig.isGenerateModelMode()) {
AsmManager.getDefault().fireModelUpdated();
}
} finally {
if (zos != null) {
closeOutputStream(buildConfig.getOutputJar());
}
ret = !handler.hasErrors();
// bug 59895, don't release reference to handler as may be needed by a nested call
//handler = null;
}
return ret;
}
private boolean openOutputStream(File outJar) {
try {
OutputStream os = FileUtil.makeOutputStream(buildConfig.getOutputJar());
zos = new JarOutputStream(os,bcelWeaver.getManifest(true));
} catch (IOException ex) {
IMessage message =
new Message("Unable to open outjar "
+ outJar.getPath()
+ "(" + ex.getMessage()
+ ")",
new SourceLocation(outJar,0),
true);
handler.handleMessage(message);
return false;
}
return true;
}
private void closeOutputStream(File outJar) {
try {
if (zos != null) zos.close();
zos = null;
/* Ensure we don't write an incomplete JAR bug-71339 */
if (handler.hasErrors()) {
outJar.delete();
}
} catch (IOException ex) {
IMessage message =
new Message("Unable to write outjar "
+ outJar.getPath()
+ "(" + ex.getMessage()
+ ")",
new SourceLocation(outJar,0),
true);
handler.handleMessage(message);
}
}
private void copyResourcesToDestination() throws IOException {
// resources that we need to copy are contained in the injars and inpath only
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File inJar = (File)i.next();
copyResourcesFromJarFile(inJar);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (inPathElement.isDirectory()) {
copyResourcesFromDirectory(inPathElement);
} else {
copyResourcesFromJarFile(inPathElement);
}
}
if (buildConfig.getSourcePathResources() != null) {
for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) {
String resource = (String)i.next();
File from = (File)buildConfig.getSourcePathResources().get(resource);
copyResourcesFromFile(from,resource,from);
}
}
writeManifest();
}
private void copyResourcesFromJarFile(File jarFile) throws IOException {
JarInputStream inStream = null;
try {
inStream = new JarInputStream(new FileInputStream(jarFile));
while (true) {
ZipEntry entry = inStream.getNextEntry();
if (entry == null) break;
String filename = entry.getName();
// System.out.println("? copyResourcesFromJarFile() filename='" + filename +"'");
if (!entry.isDirectory() && acceptResource(filename)) {
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)) 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();
}
}
private void writeResource(String filename, byte[] content, File srcLocation) throws IOException {
if (state.resources.contains(filename)) {
IMessage msg = new Message("duplicate resource: '" + filename + "'",
IMessage.WARNING,
null,
new SourceLocation(srcLocation,0));
handler.handleMessage(msg);
return;
}
if (zos != null) {
ZipEntry newEntry = new ZipEntry(filename); //??? get compression scheme right
zos.putNextEntry(newEntry);
zos.write(content);
zos.closeEntry();
} else {
OutputStream fos =
FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),filename));
fos.write(content);
fos.close();
}
state.resources.add(filename);
}
/*
* If we are writing to an output directory copy the manifest but only
* if we already have one
*/
private void writeManifest () throws IOException {
Manifest manifest = bcelWeaver.getManifest(false);
if (manifest != null && zos == null) {
OutputStream fos =
FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),MANIFEST_NAME));
manifest.write(fos);
fos.close();
}
}
private boolean acceptResource(String resourceName) {
if (
(resourceName.startsWith("CVS/")) ||
(resourceName.indexOf("/CVS/") != -1) ||
(resourceName.endsWith("/CVS")) ||
(resourceName.endsWith(".class")) ||
(resourceName.toUpperCase().equals(MANIFEST_NAME))
)
{
return false;
} else {
return true;
}
}
// 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.
*
* TODO: implement incremental policy.
*/
private void setupModel(AjBuildConfig config) {
IHierarchy model = AsmManager.getDefault().getHierarchy();
String rootLabel = "<root>";
AsmManager.getDefault().getRelationshipMap().clear();
IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA;
if (buildConfig.getConfigFile() != null) {
rootLabel = buildConfig.getConfigFile().getName();
model.setConfigFile(
buildConfig.getConfigFile().getAbsolutePath()
);
kind = IProgramElement.Kind.FILE_LST;
}
model.setRoot(new ProgramElement(rootLabel, kind, new ArrayList()));
model.setFileMap(new HashMap());
setStructureModel(model);
}
//
// 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);
// }
// }
/** init only on initial batch compile? no file-specific options */
private void initBcelWorld(IMessageHandler handler) throws IOException {
bcelWorld = new BcelWorld(buildConfig.getClasspath(), handler, null);
bcelWorld.setXnoInline(buildConfig.isXnoInline());
bcelWorld.setXlazyTjp(buildConfig.isXlazyTjp());
bcelWeaver = new BcelWeaver(bcelWorld);
state.binarySourceFiles = new HashMap();
for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext();) {
File f = (File) i.next();
bcelWeaver.addLibraryJarFile(f);
}
// String lintMode = buildConfig.getLintMode();
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());
}
//??? incremental issues
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File inJar = (File)i.next();
List unwovenClasses = bcelWeaver.addJarFile(inJar, buildConfig.getOutputDir(),false);
state.binarySourceFiles.put(inJar.getPath(), unwovenClasses);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (!inPathElement.isDirectory()) {
// its a jar file on the inpath
// the weaver method can actually handle dirs, but we don't call it, see next block
List unwovenClasses = bcelWeaver.addJarFile(inPathElement,buildConfig.getOutputDir(),true);
state.binarySourceFiles.put(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, buildConfig.getOutputDir());
List ucfl = new ArrayList();
ucfl.add(ucf);
state.binarySourceFiles.put(binSrcs[j].getPath(),ucfl);
}
}
}
bcelWeaver.setReweavableMode(buildConfig.isXreweavable(),buildConfig.getXreweavableCompressClasses());
//check for org.aspectj.runtime.JoinPoint
bcelWorld.resolve("org.aspectj.lang.JoinPoint");
}
public World getWorld() {
return bcelWorld;
}
void addAspectClassFilesToWeaver(List addedClassFiles) throws IOException {
for (Iterator i = addedClassFiles.iterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile) i.next();
bcelWeaver.addClassFile(classFile);
}
}
// public boolean weaveAndGenerateClassFiles() throws IOException {
// handler.handleMessage(MessageUtil.info("weaving"));
// if (progressListener != null) progressListener.setText("weaving aspects");
// bcelWeaver.setProgressListener(progressListener, 0.5, 0.5/state.addedClassFiles.size());
// //!!! doesn't provide intermediate progress during weaving
// // XXX add all aspects even during incremental builds?
// addAspectClassFilesToWeaver(state.addedClassFiles);
// if (buildConfig.isNoWeave()) {
// if (buildConfig.getOutputJar() != null) {
// bcelWeaver.dumpUnwoven(buildConfig.getOutputJar());
// } else {
// bcelWeaver.dumpUnwoven();
// bcelWeaver.dumpResourcesToOutPath();
// }
// } else {
// if (buildConfig.getOutputJar() != null) {
// bcelWeaver.weave(buildConfig.getOutputJar());
// } else {
// bcelWeaver.weave();
// bcelWeaver.dumpResourcesToOutPath();
// }
// }
// if (progressListener != null) progressListener.setProgress(1.0);
// return true;
// //return messageAdapter.getErrorCount() == 0; //!javaBuilder.notifier.anyErrors();
// }
public FileSystem getLibraryAccess(String[] classpaths, String[] filenames) {
String defaultEncoding = buildConfig.getOptions().defaultEncoding;
if ("".equals(defaultEncoding)) //$NON-NLS-1$
defaultEncoding = null; //$NON-NLS-1$
// Bug 46671: We need an array as long as the number of elements in the classpath - *even though* not every
// element of the classpath is likely to be a directory. If we ensure every element of the array is set to
// only look for BINARY, then we make sure that for any classpath element that is a directory, we won't build
// a classpathDirectory object that will attempt to look for source when it can't find binary.
int[] classpathModes = new int[classpaths.length];
for (int i =0 ;i<classpaths.length;i++) classpathModes[i]=ClasspathDirectory.BINARY;
return new FileSystem(classpaths, filenames, defaultEncoding,classpathModes);
}
public IProblemFactory getProblemFactory() {
return new DefaultProblemFactory(Locale.getDefault());
}
/*
* Build the set of compilation source units
*/
public CompilationUnit[] getCompilationUnits(String[] filenames, String[] encodings) {
int fileCount = filenames.length;
CompilationUnit[] units = new CompilationUnit[fileCount];
// HashtableOfObject knownFileNames = new HashtableOfObject(fileCount);
String defaultEncoding = buildConfig.getOptions().defaultEncoding;
if ("".equals(defaultEncoding)) //$NON-NLS-1$
defaultEncoding = null; //$NON-NLS-1$
for (int i = 0; i < fileCount; i++) {
String encoding = encodings[i];
if (encoding == null)
encoding = defaultEncoding;
units[i] = new CompilationUnit(null, filenames[i], encoding);
}
return units;
}
public String extractDestinationPathFromSourceFile(CompilationResult result) {
ICompilationUnit compilationUnit = result.compilationUnit;
if (compilationUnit != null) {
char[] fileName = compilationUnit.getFileName();
int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName);
if (lastIndex == -1) {
return System.getProperty("user.dir"); //$NON-NLS-1$
}
return new String(CharOperation.subarray(fileName, 0, lastIndex));
}
return System.getProperty("user.dir"); //$NON-NLS-1$
}
public void performCompilation(List files) {
if (progressListener != null) {
compiledCount = 0;
sourceFileCount = files.size();
progressListener.setText("compiling source files");
}
//System.err.println("got files: " + files);
String[] filenames = new String[files.size()];
String[] encodings = new String[files.size()];
//System.err.println("filename: " + this.filenames);
for (int i=0; i < files.size(); i++) {
filenames[i] = ((File)files.get(i)).getPath();
}
List cps = buildConfig.getFullClasspath();
String[] classpaths = new String[cps.size()];
for (int i=0; i < cps.size(); i++) {
classpaths[i] = (String)cps.get(i);
}
//System.out.println("compiling");
environment = getLibraryAccess(classpaths, filenames);
if (!state.classesFromName.isEmpty()) {
environment = new StatefulNameEnvironment(environment, state.classesFromName);
}
org.eclipse.jdt.internal.compiler.Compiler.setCompilerAdapterFactory(this);
org.eclipse.jdt.internal.compiler.Compiler compiler =
new org.eclipse.jdt.internal.compiler.Compiler(environment,
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
buildConfig.getOptions().getMap(),
getBatchRequestor(),
getProblemFactory());
CompilerOptions options = compiler.options;
options.produceReferenceInfo = true; //TODO turn off when not needed
try {
compiler.compile(getCompilationUnits(filenames, encodings));
} catch (OperationCanceledException oce) {
handler.handleMessage(new Message("build cancelled:"+oce.getMessage(),IMessage.WARNING,null,null));
}
// cleanup
environment.cleanup();
environment = null;
}
/*
* Answer the component to which will be handed back compilation results from the compiler
*/
public IIntermediateResultsRequestor getInterimResultRequestor() {
return new IIntermediateResultsRequestor() {
int lineDelta = 0;
public void acceptResult(InterimCompilationResult result) {
if (progressListener != null) {
compiledCount++;
progressListener.setProgress((compiledCount/2.0)/sourceFileCount);
progressListener.setText("compiled: " + result.fileName());
}
state.noteResult(result);
if (progressListener!=null && progressListener.isCancelledRequested()) {
throw new AbortCompilation(true,
new OperationCanceledException("Compilation cancelled as requested"));
}
}
};
}
public ICompilerRequestor getBatchRequestor() {
return new ICompilerRequestor() {
public void acceptResult(CompilationResult unitResult) {
// end of compile, must now write the results to the output destination
// this is either a jar file or a file in a directory
if (!(unitResult.hasErrors() && !proceedOnError())) {
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";
try {
if (buildConfig.getOutputJar() == null) {
writeDirectoryEntry(unitResult, classFile,filename);
} else {
writeZipEntry(classFile,filename);
}
} catch (IOException ex) {
IMessage message = EclipseAdapterUtils.makeErrorMessage(
new String(unitResult.fileName),
CANT_WRITE_RESULT,
ex);
handler.handleMessage(message);
}
}
}
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]);
handler.handleMessage(message);
}
}
}
private void writeDirectoryEntry(
CompilationResult unitResult,
ClassFile classFile,
String filename)
throws IOException {
File destinationPath = buildConfig.getOutputDir();
String outFile;
if (destinationPath == null) {
outFile = new File(filename).getName();
outFile = new File(extractDestinationPathFromSourceFile(unitResult), outFile).getPath();
} else {
outFile = new File(destinationPath, filename).getPath();
}
BufferedOutputStream os =
FileUtil.makeOutputStream(new File(outFile));
os.write(classFile.getBytes());
os.close();
}
private void writeZipEntry(ClassFile classFile, String name)
throws IOException {
name = name.replace(File.separatorChar,'/');
ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right
zos.putNextEntry(newEntry);
zos.write(classFile.getBytes());
zos.closeEntry();
}
};
}
protected boolean proceedOnError() {
return true; //???
}
// 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;
handler.reset();
}
String makeClasspathString() {
if (buildConfig == null || buildConfig.getClasspath() == null) return "";
StringBuffer buf = new StringBuffer();
boolean first = true;
for (Iterator it = buildConfig.getClasspath().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.
*/
public 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.getClasspath() == null) return "no classpath specified";
for (Iterator it = buildConfig.getClasspath().iterator(); it.hasNext(); ) {
File p = new File( (String)it.next() );
if (p.isFile() && p.getName().equals("aspectjrt.jar")) {
try {
String version = null;
Manifest manifest = new JarFile(p).getManifest();
if (manifest == null) {
return "no manifest found in " + p.getAbsolutePath() +
", expected " + Version.text;
}
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)) {
return "bad version number found in " + p.getAbsolutePath() +
" expected " + Version.text + " found " + version;
}
} catch (IOException ioe) {
return "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe;
}
return null;
} else {
// might want to catch other classpath errors
}
}
return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString();
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("AjBuildManager(");
buf.append(")");
return buf.toString();
}
public void setStructureModel(IHierarchy structureModel) {
this.structureModel = structureModel;
}
/**
* Returns null if there is no structure model
*/
public IHierarchy getStructureModel() {
return structureModel;
}
public IProgressListener getProgressListener() {
return progressListener;
}
public void setProgressListener(IProgressListener progressListener) {
this.progressListener = progressListener;
}
/* (non-Javadoc)
* @see org.aspectj.ajdt.internal.compiler.AjCompiler.IOutputClassFileNameProvider#getOutputClassFileName(char[])
*/
public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) {
String filename = new String(eclipseClassFileName);
filename = filename.replace('/', File.separatorChar) + ".class";
File destinationPath = buildConfig.getOutputDir();
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.eclipse.jdt.internal.compiler.Compiler forCompiler) {
// complete compiler config and return a suitable adapter...
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);
return new AjCompilerAdapter(forCompiler,batchCompile,bcelWorld,bcelWeaver,
factory,
getInterimResultRequestor(),
progressListener,
this, // IOutputFilenameProvider
this, // IBinarySourceProvider
state.binarySourceFiles,
state.resultsFromFile.values(),
buildConfig.isNoWeave());
}
/* (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;
}
} // class AjBuildManager
|
72,154
|
Bug 72154 Support for simple dump file
|
When the compiler terminates abnormally (exception) or behaves unexpectedly (warning/error/abort) a simple dump of the compiler state should be produced to aid problem diagnosis. The content and conditions under which the dump is produced should be configurable by the user but the facility should be enabled by default for exceptions. Consequently its inclusion should have negligible impact on compiler performance and footprint. The file should be attached to bug reports to give a complete and objective description of the users environment and support problem resolution where a testcase cannot be provided. One approach is to write a uniquely name file (using date & time) in the current directory e.g ajcore.20040818.105200.txt which should be human readable (it can be zipped if large) to allow the user to potentially diagnose their own problems or remove potentially sensitive data before submission. It should contain basic information such as AspectJ version, system properties and command line as well as failure information such as _full_ exception stack trace, compiler messages and internal compiler state.
|
resolved fixed
|
f503523
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-23T13:40:31Z
| 2004-08-18T09:06:40Z
|
org.aspectj.ajdt.core/src/org/aspectj/tools/ajc/Main.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.tools.ajc;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.ICommand;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.IMessageHolder;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageHandler;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.ReflectionFactory;
import org.aspectj.bridge.Version;
import org.aspectj.util.FileUtil;
import org.aspectj.util.LangUtil;
/**
* Programmatic and command-line interface to AspectJ compiler.
* The compiler is an ICommand obtained by reflection.
* Not thread-safe.
* By default, messages are printed as they are emitted;
* info messages go to the output stream, and
* warnings and errors go to the error stream.
* <p>
* Clients can handle all messages by registering a holder:
* <pre>Main main = new Main();
* IMessageHolder holder = new MessageHandler();
* main.setHolder(holder);</pre>
* Clients can get control after each command completes
* by installing a Runnable:
* <pre>main.setCompletionRunner(new Runnable() {..});</pre>
*
*/
public class Main {
/** Header used when rendering exceptions for users */
public static final String THROWN_PREFIX
= "Exception thrown from AspectJ "+ Version.text + LangUtil.EOL
+ ""+ LangUtil.EOL
+ "This might be logged as a bug already -- find current bugs at" + LangUtil.EOL
+ " http://bugs.eclipse.org/bugs/buglist.cgi?product=AspectJ&component=Compiler" + LangUtil.EOL
+ "" + LangUtil.EOL
+ "Bugs for exceptions thrown have titles File:line from the top stack, " + LangUtil.EOL
+ "e.g., \"SomeFile.java:243\"" + LangUtil.EOL
+ "" + LangUtil.EOL
+ "If you don't find the exception below in a bug, please add a new bug" + LangUtil.EOL
+ "at http://bugs.eclipse.org/bugs/enter_bug.cgi?product=AspectJ" + LangUtil.EOL
+ "To make the bug a priority, please include a test program" + LangUtil.EOL
+ "that can reproduce this exception." + LangUtil.EOL;
private static final String OUT_OF_MEMORY_MSG
= "AspectJ " + Version.text + " ran out of memory during compilation:" + LangUtil.EOL + LangUtil.EOL
+ "Please increase the memory available to ajc by editing the ajc script " + LangUtil.EOL
+ "found in your AspectJ installation directory. The -Xmx parameter value" + LangUtil.EOL
+ "should be increased from 64M (default) to 128M or even 256M." + LangUtil.EOL + LangUtil.EOL
+ "See the AspectJ FAQ available from the documentation link" + LangUtil.EOL
+ "on the AspectJ home page at http://www.eclipse.org/aspectj";
/** @param args the String[] of command-line arguments */
public static void main(String[] args) throws IOException {
new Main().runMain(args, true);
}
/**
* Convenience method to run ajc and collect String lists of messages.
* This can be reflectively invoked with the
* List collecting parameters supplied by a parent class loader.
* The String messages take the same form as command-line messages.
* @param args the String[] args to pass to the compiler
* @param useSystemExit if true and errors, return System.exit(errs)
* @param fails the List sink, if any, for String failure (or worse) messages
* @param errors the List sink, if any, for String error messages
* @param warnings the List sink, if any, for String warning messages
* @param info the List sink, if any, for String info messages
* @return number of messages reported with level ERROR or above
* @throws any unchecked exceptions the compiler does
*/
public static int bareMain(
String[] args,
boolean useSystemExit,
List fails,
List errors,
List warnings,
List infos) {
Main main = new Main();
MessageHandler holder = new MessageHandler();
main.setHolder(holder);
try {
main.runMain(args, useSystemExit);
} finally {
readMessages(holder, IMessage.FAIL, true, fails);
readMessages(holder, IMessage.ERROR, false, errors);
readMessages(holder, IMessage.WARNING, false, warnings);
readMessages(holder, IMessage.INFO, false, infos);
}
return holder.numMessages(IMessage.ERROR, true);
}
/** Read messages of a given kind into a List as String */
private static void readMessages(
IMessageHolder holder,
IMessage.Kind kind,
boolean orGreater,
List sink) {
if ((null == sink) || (null == holder)) {
return;
}
IMessage[] messages = holder.getMessages(kind, orGreater);
if (!LangUtil.isEmpty(messages)) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < messages.length; i++) {
sink.add(MessagePrinter.render(messages[i]));
}
}
}
/**
* @return String rendering throwable as compiler error for user/console,
* including information on how to report as a bug.
* @throws NullPointerException if thrown is null
*/
public static String renderExceptionForUser(Throwable thrown) {
String m = thrown.getMessage();
return THROWN_PREFIX
+ (null != m ? m + "\n": "")
+ LangUtil.renderException(thrown, true);
}
/** append nothing if numItems is 0,
* numItems + label + (numItems > 1? "s" : "") otherwise,
* prefixing with " " if sink has content
*/
private static void appendNLabel(StringBuffer sink, String label, int numItems) {
if (0 == numItems) {
return;
}
if (0 < sink.length()) {
sink.append(", ");
}
sink.append(numItems + " ");
if (!LangUtil.isEmpty(label)) {
sink.append(label);
}
if (1 < numItems) {
sink.append("s");
}
}
/** control iteration/continuation for command (compiler) */
protected CommandController controller;
/** ReflectionFactory identifier for command (compiler) */
protected String commandName;
/** client-set message sink */
private IMessageHolder clientHolder;
/** internally-set message sink */
protected final MessageHandler ourHandler;
private int lastFails;
private int lastErrors;
/** if not null, run this synchronously after each compile completes */
private Runnable completionRunner;
public Main() {
controller = new CommandController();
commandName = ReflectionFactory.ECLIPSE;
ourHandler = new MessageHandler(true);
}
public MessageHandler getMessageHandler() {
return ourHandler;
}
// for unit testing...
void setController(CommandController controller) {
this.controller = controller;
}
/**
* Run without throwing exceptions but optionally using System.exit(..).
* This sets up a message handler which emits messages immediately,
* so report(boolean, IMessageHandler) only reports total number
* of errors or warnings.
* @param args the String[] command line for the compiler
* @param useSystemExit if true, use System.exit(int) to complete
* unless one of the args is -noExit.
* and signal result (0 no exceptions/error, <0 exceptions, >0 compiler errors).
*/
public void runMain(String[] args, boolean useSystemExit) {
boolean verbose = (-1 != ("" + LangUtil.arrayAsList(args)).indexOf("-verbose"));
IMessageHolder holder = clientHolder;
if (null == holder) {
holder = ourHandler;
if (verbose) {
ourHandler.setInterceptor(MessagePrinter.VERBOSE);
} else {
ourHandler.ignore(IMessage.INFO);
ourHandler.setInterceptor(MessagePrinter.TERSE);
}
}
// make sure we handle out of memory gracefully...
try {
// byte[] b = new byte[100000000]; for testing OoME only!
run(args, holder);
} catch (OutOfMemoryError outOfMemory) {
IMessage outOfMemoryMessage = new Message(OUT_OF_MEMORY_MSG,null,true);
holder.handleMessage(outOfMemoryMessage);
systemExit(holder); // we can't reasonably continue from this point.
}
boolean skipExit = false;
if (useSystemExit && !LangUtil.isEmpty(args)) { // sigh - pluck -noExit
for (int i = 0; i < args.length; i++) {
if ("-noExit".equals(args[i])) {
skipExit = true;
break;
}
}
}
if (useSystemExit && !skipExit) {
systemExit(holder);
}
}
/**
* Run without using System.exit(..), putting all messages in holder:
* <ul>
* <li>ERROR: compiler error</li>
* <li>WARNING: compiler warning</li>
* <li>FAIL: command error (bad arguments, exception thrown)</li>
* </ul>
* This handles incremental behavior:
* <ul>
* <li>If args include "-incremental", repeat for every input char
* until 'q' is entered.<li>
* <li>If args include "-incrementalTagFile {file}", repeat every time
* we detect that {file} modification time has changed. </li>
* <li>Either way, list files recompiled each time if args includes "-verbose".</li>
* <li>Exit when the commmand/compiler throws any Throwable.</li>
* </ul>
* When complete, this contains all the messages of the final
* run of the command and/or any FAIL messages produced in running
* the command, including any Throwable thrown by the command itself.
*
* @param args the String[] command line for the compiler
* @param holder the MessageHandler sink for messages.
*/
public void run(String[] args, IMessageHolder holder) {
if (LangUtil.isEmpty(args)) {
args = new String[] { "-?" };
} else if (controller.running()) {
fail(holder, "already running with controller: " + controller, null);
return;
}
args = controller.init(args, holder);
if (0 < holder.numMessages(IMessage.ERROR, true)) {
return;
}
ICommand command = ReflectionFactory.makeCommand(commandName, holder);
if (0 < holder.numMessages(IMessage.ERROR, true)) {
return;
}
try {
// boolean verbose = (-1 != ("" + Arrays.asList(args)).indexOf("-verbose"));
outer:
while (true) {
boolean passed = command.runCommand(args, holder);
if (report(passed, holder) && controller.incremental()) {
// final boolean onCommandLine = controller.commandLineIncremental();
while (controller.doRepeatCommand(command)) {
holder.clearMessages();
if (controller.buildFresh()) {
continue outer;
} else {
passed = command.repeatCommand(holder);
}
if (!report(passed, holder)) {
break;
}
}
}
break;
}
} catch (AbortException ae) {
if (ae.isSilent()) {
quit();
} else {
IMessage message = ae.getIMessage();
Throwable thrown = ae.getThrown();
if (null == thrown) { // toss AbortException wrapper
if (null != message) {
holder.handleMessage(message);
} else {
fail(holder, "abort without message", ae);
}
} else if (null == message) {
fail(holder, "aborted", thrown);
} else {
String mssg = MessageUtil.MESSAGE_MOST.renderToString(message);
fail(holder, mssg, thrown);
}
}
} catch (Throwable t) {
fail(holder, "unexpected exception", t);
}
}
/** call this to stop after the next iteration of incremental compile */
public void quit() {
controller.quit();
}
/**
* Set holder to be passed all messages.
* When holder is set, messages will not be printed by default.
* @param holder the IMessageHolder sink for all messages
* (use null to restore default behavior)
*/
public void setHolder(IMessageHolder holder) {
clientHolder = holder;
}
/**
* Install a Runnable to be invoked synchronously
* after each compile completes.
* @param runner the Runnable to invoke - null to disable
*/
public void setCompletionRunner(Runnable runner) {
this.completionRunner = runner;
}
/**
* Call System.exit(int) with values derived from the number
* of failures/aborts or errors in messages.
* @param messages the IMessageHolder to interrogate.
* @param messages
*/
protected void systemExit(IMessageHolder messages) {
int num = lastFails; // messages.numMessages(IMessage.FAIL, true);
if (0 < num) {
System.exit(-num);
}
num = lastErrors; // messages.numMessages(IMessage.ERROR, false);
if (0 < num) {
System.exit(num);
}
System.exit(0);
}
/** Messages to the user */
protected void outMessage(String message) { // XXX coordinate with MessagePrinter
System.out.print(message);
System.out.flush();
}
/**
* Report results from a (possibly-incremental) compile run.
* This delegates to any reportHandler or otherwise
* prints summary counts of errors/warnings to System.err (if any errors)
* or System.out (if only warnings).
* WARNING: this silently ignores other messages like FAIL,
* but clears the handler of all messages when returning true. XXX false
*
* This implementation ignores the pass parameter but
* clears the holder after reporting
* on the assumption messages were handled/printed already.
* (ignoring UnsupportedOperationException from holder.clearMessages()).
* @param pass true result of the command
* @param holder IMessageHolder with messages from the command
* @see reportCommandResults(IMessageHolder)
* @return false if the process should abort
*/
protected boolean report(boolean pass, IMessageHolder holder) {
lastFails = holder.numMessages(IMessage.FAIL, true);
boolean result = (0 == lastFails);
final Runnable runner = completionRunner;
if (null != runner) {
runner.run();
}
if (holder == ourHandler) {
lastErrors = holder.numMessages(IMessage.ERROR, false);
int warnings = holder.numMessages(IMessage.WARNING, false);
StringBuffer sb = new StringBuffer();
appendNLabel(sb, "fail|abort", lastFails);
appendNLabel(sb, "error", lastErrors);
appendNLabel(sb, "warning", warnings);
if (0 < sb.length()) {
PrintStream out = (0 < (lastErrors + lastFails)
? System.err
: System.out);
out.println(""); // XXX "wrote class file" messages no eol?
out.println(sb.toString());
}
}
return result;
}
/** convenience API to make fail messages (without MessageUtils's fail prefix) */
protected static void fail(IMessageHandler handler, String message, Throwable thrown) {
handler.handleMessage(new Message(message, IMessage.FAIL, thrown, null));
}
/**
* interceptor IMessageHandler to print as we go.
* This formats all messages to the user.
*/
public static class MessagePrinter implements IMessageHandler {
public static final IMessageHandler VERBOSE
= new MessagePrinter(true);
public static final IMessageHandler TERSE
= new MessagePrinter(false);
final boolean verbose;
protected MessagePrinter(boolean verbose) {
this.verbose = verbose;
}
/**
* Print errors and warnings to System.err,
* and optionally info to System.out,
* rendering message String only.
* @return false always
*/
public boolean handleMessage(IMessage message) {
if (null != message) {
PrintStream out = getStreamFor(message.getKind());
if (null != out) {
out.println(render(message));
}
}
return false;
}
/**
* Render message differently.
* If abort, then prefix stack trace with feedback request.
* If the actual message is empty, then use toString on the whole.
* Prefix message part with file:line;
* If it has context, suffix message with context.
* @param message the IMessage to render
* @return String rendering IMessage (never null)
*/
public static String render(IMessage message) {
// IMessage.Kind kind = message.getKind();
StringBuffer sb = new StringBuffer();
String text = message.getMessage();
if (text.equals(AbortException.NO_MESSAGE_TEXT)) {
text = null;
}
boolean toString = (LangUtil.isEmpty(text));
if (toString) {
text = message.toString();
}
ISourceLocation loc = message.getSourceLocation();
String context = null;
if (null != loc) {
File file = loc.getSourceFile();
if (null != file) {
String name = file.getName();
if (!toString || (-1 == text.indexOf(name))) {
sb.append(FileUtil.getBestPath(file));
if (loc.getLine() > 0) {
sb.append(":" + loc.getLine());
}
int col = loc.getColumn();
if (0 < col) {
sb.append(":" + col);
}
sb.append(" ");
}
}
context = loc.getContext();
}
// per Wes' suggestion on dev...
if (message.getKind() == IMessage.ERROR) {
sb.append("[error] ");
} else if (message.getKind() == IMessage.WARNING) {
sb.append("[warning] ");
}
sb.append(text);
if (null != context) {
sb.append(LangUtil.EOL);
sb.append(context);
}
String details = message.getDetails();
if (details != null) {
sb.append(LangUtil.EOL);
sb.append('\t');
sb.append(details);
}
Throwable thrown = message.getThrown();
if (null != thrown) {
sb.append(LangUtil.EOL);
sb.append(Main.renderExceptionForUser(thrown));
}
if (message.getExtraSourceLocations().isEmpty()) {
return sb.toString();
} else {
return MessageUtil.addExtraSourceLocations(message, sb.toString());
}
}
public boolean isIgnoring(IMessage.Kind kind) {
return (null != getStreamFor(kind));
}
/** @return System.err for FAIL, ABORT, ERROR, and WARNING,
* System.out for INFO if -verbose and WEAVEINFO if -showWeaveInfo.
*/
protected PrintStream getStreamFor(IMessage.Kind kind) {
if (IMessage.WARNING.isSameOrLessThan(kind)) {
return System.err;
} else if (verbose && IMessage.INFO.equals(kind)) {
return System.out;
} else if (IMessage.WEAVEINFO.equals(kind)) {
return System.out;
} else {
return null;
}
}
}
/** controller for repeatable command delays until input or file changed or removed */
public static class CommandController {
public static String TAG_FILE_OPTION = "-XincrementalFile";
public static String INCREMENTAL_OPTION = "-incremental";
/** maximum 10-minute delay between filesystem checks */
public static long MAX_DELAY = 1000 * 600;
/** default 5-second delay between filesystem checks */
public static long DEFAULT_DELAY = 1000 * 5;
/** @see init(String[]) */
private static String[][] OPTIONS = new String[][]
{ new String[] { INCREMENTAL_OPTION },
new String[] { TAG_FILE_OPTION, null } };
/** true between init(String[]) and doRepeatCommand() that returns false */
private boolean running;
/** true after quit() called */
private boolean quit;
/** true if incremental mode, waiting for input other than 'q' */
private boolean incremental;
/** true if incremental mode, waiting for file to change (repeat) or disappear (quit) */
private File tagFile;
/** last modification time for tagFile as of last command - 0 to start */
private long fileModTime;
/** delay between filesystem checks for tagFile modification time */
private long delay;
/** true just after user types 'r' for rebuild */
private boolean buildFresh;
public CommandController() {
delay = DEFAULT_DELAY;
}
/**
* @param argList read and strip incremental args from this
* @param sink IMessageHandler for error messages
* @return String[] remainder of args
*/
public String[] init(String[] args, IMessageHandler sink) {
running = true;
// String[] unused;
if (!LangUtil.isEmpty(args)) {
String[][] options = LangUtil.copyStrings(OPTIONS);
/*unused = */LangUtil.extractOptions(args, options);
incremental = (null != options[0][0]);
if (null != options[1][0]) {
File file = new File(options[1][1]);
if (!file.exists()) {
MessageUtil.abort(sink, "tag file does not exist: " + file);
} else {
tagFile = file;
fileModTime = tagFile.lastModified();
}
}
}
return args;
}
/** @return true if init(String[]) called but doRepeatCommand has not
* returned false */
public boolean running() {
return running;
}
/** @param delay milliseconds between filesystem checks */
public void setDelay(long delay) {
if ((delay > -1) && (delay < MAX_DELAY)) {
this.delay = delay;
}
}
/** @return true if INCREMENTAL_OPTION or TAG_FILE_OPTION was in args */
public boolean incremental() {
return (incremental || (null != tagFile));
}
/** @return true if INCREMENTAL_OPTION was in args */
public boolean commandLineIncremental() {
return incremental;
}
public void quit() {
if (!quit) {
quit = true;
}
}
/** @return true just after user typed 'r' */
boolean buildFresh() {
return buildFresh;
}
/** @return false if we should quit, true to do another command */
boolean doRepeatCommand(ICommand command) {
if (!running) {
return false;
}
boolean result = false;
if (quit) {
result = false;
} else if (incremental) {
try {
if (buildFresh) { // reset before input request
buildFresh = false;
}
System.out.println(" press enter to recompile, r to rebuild, q to quit: ");
System.out.flush();
// boolean doMore = false;
// seek for one q or a series of [\n\r]...
do {
int input = System.in.read();
if ('q' == input) {
break; // result = false;
} else if ('r' == input) {
buildFresh = true;
result = true;
} else if (('\n' == input) || ('\r' == input)) {
result = true;
} // else eat anything else
} while (!result);
System.in.skip(Integer.MAX_VALUE);
} catch (IOException e) { // XXX silence for error?
result = false;
}
} else if (null != tagFile) {
long curModTime;
while (true) {
if (!tagFile.exists()) {
result = false;
break;
} else if (fileModTime == (curModTime = tagFile.lastModified())) {
fileCheckDelay();
} else {
fileModTime = curModTime;
result = true;
break;
}
}
} // else, not incremental - false
if (!result && running) {
running = false;
}
return result;
}
/** delay between filesystem checks, returning if quit is set */
protected void fileCheckDelay() {
// final Thread thread = Thread.currentThread();
long targetTime = System.currentTimeMillis() + delay;
// long curTime;
while (targetTime > System.currentTimeMillis()) {
if (quit) {
return;
}
try { Thread.sleep(300); } // 1/3-second delta for quit check
catch (InterruptedException e) {}
}
}
}
}
|
72,154
|
Bug 72154 Support for simple dump file
|
When the compiler terminates abnormally (exception) or behaves unexpectedly (warning/error/abort) a simple dump of the compiler state should be produced to aid problem diagnosis. The content and conditions under which the dump is produced should be configurable by the user but the facility should be enabled by default for exceptions. Consequently its inclusion should have negligible impact on compiler performance and footprint. The file should be attached to bug reports to give a complete and objective description of the users environment and support problem resolution where a testcase cannot be provided. One approach is to write a uniquely name file (using date & time) in the current directory e.g ajcore.20040818.105200.txt which should be human readable (it can be zipped if large) to allow the user to potentially diagnose their own problems or remove potentially sensitive data before submission. It should contain basic information such as AspectJ version, system properties and command line as well as failure information such as _full_ exception stack trace, compiler messages and internal compiler state.
|
resolved fixed
|
f503523
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-23T13:40:31Z
| 2004-08-18T09:06:40Z
|
org.aspectj.ajdt.core/testdata/DumpTestCase/src/HelloWorld.java
| |
72,154
|
Bug 72154 Support for simple dump file
|
When the compiler terminates abnormally (exception) or behaves unexpectedly (warning/error/abort) a simple dump of the compiler state should be produced to aid problem diagnosis. The content and conditions under which the dump is produced should be configurable by the user but the facility should be enabled by default for exceptions. Consequently its inclusion should have negligible impact on compiler performance and footprint. The file should be attached to bug reports to give a complete and objective description of the users environment and support problem resolution where a testcase cannot be provided. One approach is to write a uniquely name file (using date & time) in the current directory e.g ajcore.20040818.105200.txt which should be human readable (it can be zipped if large) to allow the user to potentially diagnose their own problems or remove potentially sensitive data before submission. It should contain basic information such as AspectJ version, system properties and command line as well as failure information such as _full_ exception stack trace, compiler messages and internal compiler state.
|
resolved fixed
|
f503523
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-23T13:40:31Z
| 2004-08-18T09:06:40Z
|
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/AjdtBatchTests.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.batch;
import junit.framework.*;
public class AjdtBatchTests extends TestCase {
public static Test suite() {
TestSuite suite = new TestSuite(AjdtBatchTests.class.getName());
// Abstract superclass
//suite.addTestSuite(CommandTestCase.class);
//$JUnit-BEGIN$
suite.addTestSuite(BasicCommandTestCase.class);
suite.addTestSuite(BinaryFormsTestCase.class);
suite.addTestSuite(CompileAndRunTestCase.class);
suite.addTestSuite(PerformanceTestCase.class);
suite.addTestSuite(ImageTestCase.class);
suite.addTestSuite(MultipleCompileTestCase.class);
suite.addTestSuite(JavadocTest.class);
suite.addTestSuite(PartiallyExposedHierarchyTestCase.class);
// XXX suite.addTestSuite(VerifyWeaveTestCase.class);
//suite.addTestSuite(WorkingCommandTestCase.class);
//$JUnit-END$
return suite;
}
public AjdtBatchTests(String name) { super(name); }
}
|
72,154
|
Bug 72154 Support for simple dump file
|
When the compiler terminates abnormally (exception) or behaves unexpectedly (warning/error/abort) a simple dump of the compiler state should be produced to aid problem diagnosis. The content and conditions under which the dump is produced should be configurable by the user but the facility should be enabled by default for exceptions. Consequently its inclusion should have negligible impact on compiler performance and footprint. The file should be attached to bug reports to give a complete and objective description of the users environment and support problem resolution where a testcase cannot be provided. One approach is to write a uniquely name file (using date & time) in the current directory e.g ajcore.20040818.105200.txt which should be human readable (it can be zipped if large) to allow the user to potentially diagnose their own problems or remove potentially sensitive data before submission. It should contain basic information such as AspectJ version, system properties and command line as well as failure information such as _full_ exception stack trace, compiler messages and internal compiler state.
|
resolved fixed
|
f503523
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-23T13:40:31Z
| 2004-08-18T09:06:40Z
|
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/CompilerDumpTestCase.java
| |
72,154
|
Bug 72154 Support for simple dump file
|
When the compiler terminates abnormally (exception) or behaves unexpectedly (warning/error/abort) a simple dump of the compiler state should be produced to aid problem diagnosis. The content and conditions under which the dump is produced should be configurable by the user but the facility should be enabled by default for exceptions. Consequently its inclusion should have negligible impact on compiler performance and footprint. The file should be attached to bug reports to give a complete and objective description of the users environment and support problem resolution where a testcase cannot be provided. One approach is to write a uniquely name file (using date & time) in the current directory e.g ajcore.20040818.105200.txt which should be human readable (it can be zipped if large) to allow the user to potentially diagnose their own problems or remove potentially sensitive data before submission. It should contain basic information such as AspectJ version, system properties and command line as well as failure information such as _full_ exception stack trace, compiler messages and internal compiler state.
|
resolved fixed
|
f503523
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-23T13:40:31Z
| 2004-08-18T09:06:40Z
|
weaver/src/org/aspectj/weaver/Dump.java
| |
72,154
|
Bug 72154 Support for simple dump file
|
When the compiler terminates abnormally (exception) or behaves unexpectedly (warning/error/abort) a simple dump of the compiler state should be produced to aid problem diagnosis. The content and conditions under which the dump is produced should be configurable by the user but the facility should be enabled by default for exceptions. Consequently its inclusion should have negligible impact on compiler performance and footprint. The file should be attached to bug reports to give a complete and objective description of the users environment and support problem resolution where a testcase cannot be provided. One approach is to write a uniquely name file (using date & time) in the current directory e.g ajcore.20040818.105200.txt which should be human readable (it can be zipped if large) to allow the user to potentially diagnose their own problems or remove potentially sensitive data before submission. It should contain basic information such as AspectJ version, system properties and command line as well as failure information such as _full_ exception stack trace, compiler messages and internal compiler state.
|
resolved fixed
|
f503523
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-23T13:40:31Z
| 2004-08-18T09:06:40Z
|
weaver/src/org/aspectj/weaver/World.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import org.aspectj.asm.IHierarchy;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.weaver.patterns.DeclarePrecedence;
import org.aspectj.weaver.patterns.Pointcut;
public abstract class World {
protected IMessageHandler messageHandler = IMessageHandler.SYSTEM_ERR;
protected ICrossReferenceHandler xrefHandler = null;
protected TypeMap typeMap = new TypeMap(); // Signature to ResolvedType
protected CrosscuttingMembersSet crosscuttingMembersSet = new CrosscuttingMembersSet(this);
protected IHierarchy model = null;
protected Lint lint = new Lint(this);
protected boolean XnoInline;
protected boolean XlazyTjp;
protected World() {
super();
typeMap.put("B", ResolvedTypeX.BYTE);
typeMap.put("S", ResolvedTypeX.SHORT);
typeMap.put("I", ResolvedTypeX.INT);
typeMap.put("J", ResolvedTypeX.LONG);
typeMap.put("F", ResolvedTypeX.FLOAT);
typeMap.put("D", ResolvedTypeX.DOUBLE);
typeMap.put("C", ResolvedTypeX.CHAR);
typeMap.put("Z", ResolvedTypeX.BOOLEAN);
typeMap.put("V", ResolvedTypeX.VOID);
}
public ResolvedTypeX[] resolve(TypeX[] types) {
int len = types.length;
ResolvedTypeX[] ret = new ResolvedTypeX[len];
for (int i=0; i<len; i++) {
ret[i] = resolve(types[i]);
}
return ret;
}
/**
* 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 ResolvedTypeX resolve(TypeX ty,ISourceLocation isl) {
ResolvedTypeX ret = resolve(ty,true);
if (ty == ResolvedTypeX.MISSING) {
IMessage msg = null;
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;
}
public ResolvedTypeX resolve(TypeX ty) {
return resolve(ty, false);
}
public ResolvedTypeX getCoreType(TypeX tx) {
ResolvedTypeX coreTy = resolve(tx,true);
if (coreTy == ResolvedTypeX.MISSING) {
MessageUtil.error(messageHandler,
WeaverMessages.format(WeaverMessages.CANT_FIND_CORE_TYPE,tx.getName()));
}
return coreTy;
}
public ResolvedTypeX resolve(TypeX ty, boolean allowMissing) {
//System.out.println("resolve: " + ty + " world " + typeMap.keySet());
String signature = ty.getSignature();
ResolvedTypeX ret = typeMap.get(signature);
if (ret != null) return ret;
if (ty.isArray()) {
ret = new ResolvedTypeX.Array(signature, this, resolve(ty.getComponentType(), allowMissing));
} else {
ret = resolveObjectType(ty);
if (!allowMissing && ret == ResolvedTypeX.MISSING) {
//Thread.currentThread().dumpStack();
MessageUtil.error(messageHandler,
WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()));
// + " on classpath " + classPath);
}
}
//System.out.println("ret: " + ret);
typeMap.put(signature, ret);
return ret;
}
//XXX helper method might be bad
public ResolvedTypeX resolve(String name) {
return resolve(TypeX.forName(name));
}
protected final ResolvedTypeX resolveObjectType(TypeX ty) {
ResolvedTypeX.Name name = new ResolvedTypeX.Name(ty.getSignature(), this);
ResolvedTypeX.ConcreteName concreteName = resolveObjectType(name);
if (concreteName == null) return ResolvedTypeX.MISSING;
name.setDelegate(concreteName);
return name;
}
protected abstract ResolvedTypeX.ConcreteName resolveObjectType(ResolvedTypeX.Name ty);
protected final boolean isCoerceableFrom(TypeX type, TypeX other) {
return resolve(type).isCoerceableFrom(other);
}
protected final boolean isAssignableFrom(TypeX type, TypeX other) {
return resolve(type).isAssignableFrom(other);
}
public boolean needsNoConversionFrom(TypeX type, TypeX other) {
return resolve(type).needsNoConversionFrom(other);
}
protected final boolean isInterface(TypeX type) {
return resolve(type).isInterface();
}
protected final ResolvedTypeX getSuperclass(TypeX type) {
return resolve(type).getSuperclass();
}
protected final TypeX[] getDeclaredInterfaces(TypeX type) {
return resolve(type).getDeclaredInterfaces();
}
protected final int getModifiers(TypeX type) {
return resolve(type).getModifiers();
}
protected final ResolvedMember[] getDeclaredFields(TypeX type) {
return resolve(type).getDeclaredFields();
}
protected final ResolvedMember[] getDeclaredMethods(TypeX type) {
return resolve(type).getDeclaredMethods();
}
protected final ResolvedMember[] getDeclaredPointcuts(TypeX type) {
return resolve(type).getDeclaredPointcuts();
}
// ---- members
// XXX should we worry about dealing with context and looking up access?
public ResolvedMember resolve(Member member) {
ResolvedTypeX declaring = member.getDeclaringType().resolve(this);
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);
}
protected int getModifiers(Member member) {
ResolvedMember r = resolve(member);
if (r == null) throw new BCException("bad resolve of " + member);
return r.getModifiers();
}
protected String[] getParameterNames(Member member) {
return resolve(member).getParameterNames();
}
protected TypeX[] getExceptions(Member member) {
return resolve(member).getExceptions();
}
// ---- pointcuts
public ResolvedPointcutDefinition findPointcut(TypeX typeX, String name) {
throw new RuntimeException("not implemented yet");
}
/**
* Get the shadow mungers of this world.
*
* @return a list of {@link IShadowMunger}s appropriate for this world.
*/
//public abstract List getShadowMungers();
// ---- empty world
public static final World EMPTY = new World() {
public List getShadowMungers() { return Collections.EMPTY_LIST; }
public ResolvedTypeX.ConcreteName resolveObjectType(ResolvedTypeX.Name ty) {
return null;
}
public Advice concreteAdvice(AjAttribute.AdviceAttribute attribute, Pointcut p, Member m) {
throw new RuntimeException("unimplemented");
}
public ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedTypeX aspectType) {
throw new RuntimeException("unimplemented");
}
};
public abstract Advice concreteAdvice(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature);
public final Advice concreteAdvice(
AdviceKind kind,
Pointcut p,
Member signature,
int extraParameterFlags,
IHasSourceLocation loc)
{
AjAttribute.AdviceAttribute attribute =
new AjAttribute.AdviceAttribute(kind, p, extraParameterFlags, loc.getStart(), loc.getEnd(), loc.getSourceContext());
return concreteAdvice(attribute, p, signature);
}
public ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField) {
throw new RuntimeException("unimplemented");
}
public abstract ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedTypeX aspectType);
/**
* 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) {
this.messageHandler = messageHandler;
}
public void setXRefHandler(ICrossReferenceHandler xrefHandler) {
this.xrefHandler = xrefHandler;
}
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 addDeclare(ResolvedTypeX onType, Declare declare, boolean forWeaving) {
// // this is not extensible, oh well
// if (declare instanceof DeclareErrorOrWarning) {
// ShadowMunger m = new Checker((DeclareErrorOrWarning)declare);
// onType.addShadowMunger(m);
// } else if (declare instanceof DeclareDominates) {
// declareDominates.add(declare);
// } else if (declare instanceof DeclareParents) {
// declareParents.add(declare);
// } else if (declare instanceof DeclareSoft) {
// DeclareSoft d = (DeclareSoft)declare;
// declareSoft.add(d);
// if (forWeaving) {
// ShadowMunger m = Advice.makeSoftener(this, d.getPointcut().concretize(onType, 0), d.getException());
// onType.addShadowMunger(m);
// }
// } else {
// throw new RuntimeException("unimplemented");
// }
// }
/**
* Same signature as org.aspectj.util.PartialOrder.PartialComparable.compareTo
*/
public int compareByDominates(ResolvedTypeX aspect1, ResolvedTypeX aspect2) {
//System.out.println("dom compare: " + aspect1 + " with " + aspect2);
//System.out.println(crosscuttingMembersSet.getDeclareDominates());
//??? We probably want to cache this result. This is order N where N is the
//??? number of dominates declares in the whole system.
//??? This method can be called a large number of times.
int order = 0;
DeclarePrecedence orderer = null; // Records the declare precedence statement that gives the first ordering
for (Iterator i = crosscuttingMembersSet.getDeclareDominates().iterator(); i.hasNext(); ) {
DeclarePrecedence d = (DeclarePrecedence)i.next();
int thisOrder = d.compare(aspect1, aspect2);
//System.out.println("comparing: " + thisOrder + ": " + d);
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: "+
aspect1.getName()+" and "+aspect2.getName(),null,true,isls);
messageHandler.handleMessage(m);
// throw new BCException("conflicting dominates orders"+d.getSourceLocation());
} else {
order = thisOrder;
}
}
}
return order;
}
public int comparePrecedence(ResolvedTypeX aspect1, ResolvedTypeX aspect2) {
//System.err.println("compare precedence " + aspect1 + ", " + aspect2);
if (aspect1.equals(aspect2)) return 0;
int ret = compareByDominates(aspect1, aspect2);
if (ret != 0) return ret;
if (aspect1.isAssignableFrom(aspect2)) return -1;
else if (aspect2.isAssignableFrom(aspect1)) return +1;
return 0;
}
public List getDeclareParents() {
return crosscuttingMembersSet.getDeclareParents();
}
public List getDeclareSoft() {
return crosscuttingMembersSet.getDeclareSofts();
}
public CrosscuttingMembersSet getCrosscuttingMembersSet() {
return crosscuttingMembersSet;
}
public IHierarchy getModel() {
return model;
}
public void setModel(IHierarchy 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 ResolvedTypeX.Name lookupOrCreateName(TypeX ty) {
String signature = ty.getSignature();
ResolvedTypeX.Name ret = (ResolvedTypeX.Name)typeMap.get(signature);
if (ret == null) {
ret = new ResolvedTypeX.Name(signature, this);
typeMap.put(signature, ret);
}
return ret;
}
// public void clearUnexposed() {
// List toRemove = new ArrayList();
// for (Iterator iter = typeMap.keySet().iterator(); iter.hasNext();) {
// String sig = (String) iter.next();
// ResolvedTypeX x = (ResolvedTypeX) typeMap.get(sig);
// if (!x.isExposedToWeaver() && (!x.isPrimitive())) toRemove.add(sig);
// }
// for (Iterator iter = toRemove.iterator(); iter.hasNext();) {
// typeMap.remove(iter.next());
// }
// }
//
// // for testing...
// public void dumpTypeMap() {
// int exposed = 0;
// for (Iterator iter = typeMap.keySet().iterator(); iter.hasNext();) {
// String sig = (String) iter.next();
// ResolvedTypeX x = (ResolvedTypeX) typeMap.get(sig);
// if (x.isExposedToWeaver()) exposed++;
// }
// System.out.println("type map contains " + typeMap.size() + " entries, " + exposed + " exposed to weaver");
// }
//
// public void deepDumpTypeMap() {
// for (Iterator iter = typeMap.keySet().iterator(); iter.hasNext();) {
// String sig = (String) iter.next();
// ResolvedTypeX x = (ResolvedTypeX) typeMap.get(sig);
// if (! (x instanceof ResolvedTypeX.Name)) {
// System.out.println(sig + " -> " + x.getClass().getName() + ", " + x.getClassName());
// } else {
// ResolvedTypeX.ConcreteName cname = ((ResolvedTypeX.Name)x).getDelegate();
// System.out.println(sig + " -> " + cname.getClass().getName() + ", " + cname.toString());
// }
// }
//
// }
// Map of types in the world, with soft links to expendable ones
protected static class TypeMap {
private Map tMap = new HashMap();
private Map expendableMap = new WeakHashMap();
public ResolvedTypeX put(String key, ResolvedTypeX type) {
if (isExpendable(type)) {
return (ResolvedTypeX) expendableMap.put(key,type);
} else {
return (ResolvedTypeX) tMap.put(key,type);
}
}
public ResolvedTypeX get(String key) {
ResolvedTypeX ret = (ResolvedTypeX) tMap.get(key);
if (ret == null) ret = (ResolvedTypeX) expendableMap.get(key);
return ret;
}
public ResolvedTypeX remove(String key) {
ResolvedTypeX ret = (ResolvedTypeX) tMap.remove(key);
if (ret == null) ret = (ResolvedTypeX) expendableMap.remove(key);
return ret;
}
private boolean isExpendable(ResolvedTypeX type) {
return (
(type != null) &&
(!type.isExposedToWeaver()) &&
(!type.isPrimitive())
);
}
}
}
|
72,154
|
Bug 72154 Support for simple dump file
|
When the compiler terminates abnormally (exception) or behaves unexpectedly (warning/error/abort) a simple dump of the compiler state should be produced to aid problem diagnosis. The content and conditions under which the dump is produced should be configurable by the user but the facility should be enabled by default for exceptions. Consequently its inclusion should have negligible impact on compiler performance and footprint. The file should be attached to bug reports to give a complete and objective description of the users environment and support problem resolution where a testcase cannot be provided. One approach is to write a uniquely name file (using date & time) in the current directory e.g ajcore.20040818.105200.txt which should be human readable (it can be zipped if large) to allow the user to potentially diagnose their own problems or remove potentially sensitive data before submission. It should contain basic information such as AspectJ version, system properties and command line as well as failure information such as _full_ exception stack trace, compiler messages and internal compiler state.
|
resolved fixed
|
f503523
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-23T13:40:31Z
| 2004-08-18T09:06:40Z
|
weaver/testsrc/org/aspectj/weaver/BcweaverTests.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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.File;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.aspectj.util.FileUtil;
public class BcweaverTests extends TestCase {
public static final String TESTDATA_PATH = "../weaver/testdata";
public static final String OUTDIR_PATH = "../weaver/out";
/** @return File outDir (writable) or null if unable to write */
public static File getOutdir() {
File result = new File(OUTDIR_PATH);
if (result.mkdirs()
|| (result.canWrite() && result.isDirectory())) {
return result;
}
return null;
}
/** best efforts to delete the output directory and any contents */
public static void removeOutDir() {
File outDir = getOutdir();
if (null != outDir) {
FileUtil.deleteContents(outDir);
outDir.delete();
}
}
public static Test suite() {
TestSuite suite = new TestSuite(BcweaverTests.class.getName());
// abstract
//suite.addTestSuite(AbstractWorldTestCase.class);
//$JUnit-BEGIN$
suite.addTestSuite(MemberTestCase.class);
suite.addTestSuite(TypeXTestCase.class);
suite.addTestSuite(WeavingURLClassLoaderTest.class);
suite.addTestSuite(WeaverMessagesTestCase.class);
//$JUnit-END$
return suite;
}
public BcweaverTests(String name) { super(name); }
}
|
72,154
|
Bug 72154 Support for simple dump file
|
When the compiler terminates abnormally (exception) or behaves unexpectedly (warning/error/abort) a simple dump of the compiler state should be produced to aid problem diagnosis. The content and conditions under which the dump is produced should be configurable by the user but the facility should be enabled by default for exceptions. Consequently its inclusion should have negligible impact on compiler performance and footprint. The file should be attached to bug reports to give a complete and objective description of the users environment and support problem resolution where a testcase cannot be provided. One approach is to write a uniquely name file (using date & time) in the current directory e.g ajcore.20040818.105200.txt which should be human readable (it can be zipped if large) to allow the user to potentially diagnose their own problems or remove potentially sensitive data before submission. It should contain basic information such as AspectJ version, system properties and command line as well as failure information such as _full_ exception stack trace, compiler messages and internal compiler state.
|
resolved fixed
|
f503523
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-23T13:40:31Z
| 2004-08-18T09:06:40Z
|
weaver/testsrc/org/aspectj/weaver/DumpTestCase.java
| |
72,531
|
Bug 72531 declare warning warns at wrong points
| null |
resolved fixed
|
82eae55
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-24T21:10:56Z
| 2004-08-24T17:53:20Z
|
tests/bugs/pr72531/de/rohith/HelloWorld.java
| |
72,531
|
Bug 72531 declare warning warns at wrong points
| null |
resolved fixed
|
82eae55
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-24T21:10:56Z
| 2004-08-24T17:53:20Z
|
tests/bugs/pr72531/de/rohith/HelloWorldAspect.java
| |
72,531
|
Bug 72531 declare warning warns at wrong points
| null |
resolved fixed
|
82eae55
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-24T21:10:56Z
| 2004-08-24T17:53:20Z
|
tests/bugs/pr72531/de/rohith/PrinterWorld.java
| |
72,531
|
Bug 72531 declare warning warns at wrong points
| null |
resolved fixed
|
82eae55
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-24T21:10:56Z
| 2004-08-24T17:53:20Z
|
tests/src/org/aspectj/systemtest/ajc121/Ajc121Tests.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.systemtest.ajc121;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc121Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc121Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc121/ajc121.xml");
}
public void test001(){
runTest("false ambiguous binding error (introduced in 1.2rc2)");
}
public void test002(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test003(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test004(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test005(){
runTest("compiler aborts with 'conflicting dominates orders' with circular declare precedences");
}
public void test006(){
runTest("'can't bind type' message has $ for . in type name for declare soft");
}
public void test007(){
runTest("Hiding of Instance Methods by static methods");
}
public void test008(){
runTest("if(false) optimisation");
}
public void test009(){
runTest("if(true) optimisation");
}
public void test010(){
runTest("java.lang.NullPointerException in WeaverMessageHandler class");
}
public void test011(){
runTest("ClassCastException at BcelRenderer.java:169");
}
public void test012(){
runTest("Front-end bug, shouldn't allow patterns of the form foo.., should be foo..*");
}
public void test013() {
runTest("Nullpointer-Exception when defining a withincode() pointcut");
}
public void test014() {
runTest("NPE, Incorrect XLint:unmatchedSuperTypeInCall warning");
}
public void test015_invalidXlint() { // keywords: "laurie hendren"
runTest("invalid warning indicating no match when a match really occurs");
}
public void test016_ByteConversionInstructions() {
runTest("RuntimeException thrown: Could not find instruction: org.apache.bcel.generic.B2I");
String output = getLastRunResult().getStdErr();
assertTrue("Expected to find [b2] in this output but didn't:"+output,output.indexOf("[b2]")!=-1);
assertTrue("Expected to find [b127] in this output but didn't:"+output,output.indexOf("[b127]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
assertTrue("Expected to find [c65] in this output but didn't:"+output,output.indexOf("[c65]")!=-1);
assertTrue("Expected to find [c66] in this output but didn't:"+output,output.indexOf("[c66]")!=-1);
assertTrue("Expected to find [c67] in this output but didn't:"+output,output.indexOf("[c67]")!=-1);
assertTrue("Expected to find [s1] in this output but didn't:"+output,output.indexOf("[s1]")!=-1);
assertTrue("Expected to find [s32767] in this output but didn't:"+output,output.indexOf("[s32767]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
}
public void test017_PrivateMethodCallsInAroundAdvice() {
runTest("Cannot advise private method call in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test018_PrivateFieldSetsInAroundAdvice() {
runTest("Cannot advise private field sets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test019_PrivateFieldGetsInAroundAdvice() {
runTest("Cannot advise private field gets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
// test takes over 5 minutes to run, so not included in normal suite run
// public void test020_branchTargetOffsetTooLargeForShort() {
// runTest("Branch target offset too large for short");
// }
// public void test021_BcelFailureWithVeryLargeClasses() {
// runTest("Weaver fails in BCEL for large classes");
// }
//
// public void test022_BcelFailureWithVeryLargeClasses_Binary() {
// runTest("Weaver fails in BCEL for large classes (binary)");
// }
public void test023_proceedInAround1() {
runTest("proceed used as method name in around advice (1)");
}
public void test024_proceedInAround2() {
runTest("proceed used as method name in around advice (2)");
}
public void test025_proceedInAround3() {
runTest("proceed used as method name in around advice (3)");
}
public void test026_bindingThisAndTargetToTheSameFormal() {
runTest("ajc crashes when compiling the following program (binding this() and target())");
}
public void test027_itdsOnInnerClassesAsStatic() {
runTest("ITDs on inner classes should be static context");
}
public void test028_itdsAndInitializers() {
runTest("resolution of IT field inits");
}
public void test029_falseInvalidAbsoluteTypeName() {
runTest("Valid but inaccessible type names should not be flagged by XLint:invalidAbsoluteTypeName");
}
public void test030_privateITDinitialisersBeingMatched() {
runTest("intertype initialisers should match field set pointcuts");
}
public void test031_privateITDinitialisersBeingMatched_OxfordTest() {
runTest("intertype initialisers should match field set pointcuts (oxford testcase)");
//System.err.println(">"+getLastRunResult().getStdErr());
String exp = ":set field set(int C.n):set field set(int C.m):get field get(int C.n):set field set(int C.n)";
assertTrue("Expected output '"+exp+"' but got "+getLastRunResult().getStdErr(),
getLastRunResult().getStdErr().equals(exp));
}
public void test032_stringConcatForDEOW() {
runTest("Compile time declarations (warning and error) do not accept string concatenation (with +)");
}
public void test033_stringConcatForDEOWErrorCase() {
runTest("Compile time declarations (warning and error) do not accept string concatenation (with +) (2)");
}
public void test034_scopeForITDS_pr61768() {
runTest("scope for inter-type methods");
}
public void test035_innerAspectCallsPrivateMethod_pr71372() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test036_innerAspectCallsPrivateMethod_pr71372_2() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (2)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test037_innerAspectCallsPrivateMethod_pr71372_3() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (3)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test038_innerAspectCallsPrivateMethod_pr71372_4() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (4)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test039_privilegedAspectAccessingPrivateMethods_pr67579() {
runTest("NPE on privileged aspect error");
}
public void test040_privilegedAspectAccessingPrivateMethods_pr67579_2() {
runTest("NPE on privileged aspect error (2)");
}
public void test041_ITDaccessingPrivateMethod_pr67578() {
runTest("Privileged Aspect Access Problem Across Packages");
}
public void test042_ITDaccessingPrivateMethod_pr67578_2() {
runTest("Privileged Aspect Access Problem Across Packages (2)");
}
public void test043_pr62642_ExceptionInInitializerError() {
runTest("proper handling of ExceptionInIntializer inside clinit in presence of after throwing advice");
String s = getLastRunResult().getStdErr();
assertTrue("Output should contain java.lang.ExceptionInInitializerError but is '"+s+"'",
s.indexOf("java.lang.ExceptionInInitializerError")!=-1);
// No getCause on 1.3 JVMs
// assertTrue("Output should contain 'CAUSE=org.aspectj.lang.NoAspectBoundException' but is '"+s+"'",
// s.indexOf("CAUSE=org.aspectj.lang.NoAspectBoundException")!=-1);
}
public void test044_ITDnameClashes() {
runTest("ITD name clashes with private members");
}
public void test045_ITDprotectedVisibility() {
runTest("Inconsistency in scoping of protected members in ITDs");
}
public void test045_wrongLineForExecutionJoinPoint() {
runTest("wrong line for method execution join point");
}
public void test046_interfaceITD_pr70794_1() {
runTest("The introduction on interface causes the interface implementation class error (1)");
}
public void test047_interfaceITD_pr70794_2() {
runTest("The introduction on interface causes the interface implementation class error (2)");
}
public void test048_interfaceITD_pr70794_3() {
runTest("The introduction on interface causes the interface implementation class error (3)");
}
public void test049_interfaceITD_pr70794_4() {
runTest("The introduction on interface causes the interface implementation class error (4)");
}
}
|
72,531
|
Bug 72531 declare warning warns at wrong points
| null |
resolved fixed
|
82eae55
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-24T21:10:56Z
| 2004-08-24T17:53:20Z
|
weaver/src/org/aspectj/weaver/patterns/WildTypePattern.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FileUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverMessages;
//XXX need to use dim in matching
public class WildTypePattern extends TypePattern {
NamePattern[] namePatterns;
int ellipsisCount;
String[] importedPrefixes;
String[] knownMatches;
int dim;
WildTypePattern(NamePattern[] namePatterns, boolean includeSubtypes, int dim) {
super(includeSubtypes);
this.namePatterns = namePatterns;
this.dim = dim;
ellipsisCount = 0;
for (int i=0; i<namePatterns.length; i++) {
if (namePatterns[i] == NamePattern.ELLIPSIS) ellipsisCount++;
}
setLocation(namePatterns[0].getSourceContext(), namePatterns[0].getStart(), namePatterns[namePatterns.length-1].getEnd());
}
public WildTypePattern(List names, boolean includeSubtypes, int dim) {
this((NamePattern[])names.toArray(new NamePattern[names.size()]), includeSubtypes, dim);
}
public WildTypePattern(List names, boolean includeSubtypes, int dim, int endPos) {
this(names, includeSubtypes, dim);
this.end = endPos;
}
//XXX inefficient implementation
public static char[][] splitNames(String s) {
List ret = new ArrayList();
int startIndex = 0;
while (true) {
int breakIndex = s.indexOf('.', startIndex); // what about /
if (breakIndex == -1) breakIndex = s.indexOf('$', startIndex); // we treat $ like . here
if (breakIndex == -1) break;
char[] name = s.substring(startIndex, breakIndex).toCharArray();
ret.add(name);
startIndex = breakIndex+1;
}
ret.add(s.substring(startIndex).toCharArray());
return (char[][])ret.toArray(new char[ret.size()][]);
}
/**
* @see org.aspectj.weaver.TypePattern#matchesExactly(IType)
*/
protected boolean matchesExactly(ResolvedTypeX type) {
String targetTypeName = type.getName();
//System.err.println("match: " + targetTypeName + ", " + knownMatches); //Arrays.asList(importedPrefixes));
return matchesExactlyByName(targetTypeName);
}
/**
* @param targetTypeName
* @return
*/
private boolean matchesExactlyByName(String targetTypeName) {
//XXX hack
if (knownMatches == null && importedPrefixes == null) {
return innerMatchesExactly(targetTypeName);
}
// if our pattern is length 1, then known matches are exact matches
// if it's longer than that, then known matches are prefixes of a sort
if (namePatterns.length == 1) {
for (int i=0, len=knownMatches.length; i < len; i++) {
if (knownMatches[i].equals(targetTypeName)) return true;
}
} else {
for (int i=0, len=knownMatches.length; i < len; i++) {
String knownPrefix = knownMatches[i] + "$";
if (targetTypeName.startsWith(knownPrefix)) {
int pos = lastIndexOfDotOrDollar(knownMatches[i]);
if (innerMatchesExactly(targetTypeName.substring(pos+1))) {
return true;
}
}
}
}
// if any prefixes match, strip the prefix and check that the rest matches
// assumes that prefixes have a dot at the end
for (int i=0, len=importedPrefixes.length; i < len; i++) {
String prefix = importedPrefixes[i];
//System.err.println("prefix match? " + prefix + " to " + targetTypeName);
if (targetTypeName.startsWith(prefix)) {
if (innerMatchesExactly(targetTypeName.substring(prefix.length()))) {
return true;
}
}
}
return innerMatchesExactly(targetTypeName);
}
private int lastIndexOfDotOrDollar(String string) {
int dot = string.lastIndexOf('.');
int dollar = string.lastIndexOf('$');
return Math.max(dot, dollar);
}
private boolean innerMatchesExactly(String targetTypeName) {
//??? doing this everytime is not very efficient
char[][] names = splitNames(targetTypeName);
return innerMatchesExactly(names);
}
private boolean innerMatchesExactly(char[][] names) {
int namesLength = names.length;
int patternsLength = namePatterns.length;
int namesIndex = 0;
int patternsIndex = 0;
if (ellipsisCount == 0) {
if (namesLength != patternsLength) return false;
while (patternsIndex < patternsLength) {
if (!namePatterns[patternsIndex++].matches(names[namesIndex++])) {
return false;
}
}
return true;
} else if (ellipsisCount == 1) {
if (namesLength < patternsLength-1) return false;
while (patternsIndex < patternsLength) {
NamePattern p = namePatterns[patternsIndex++];
if (p == NamePattern.ELLIPSIS) {
namesIndex = namesLength - (patternsLength-patternsIndex);
} else {
if (!p.matches(names[namesIndex++])) {
return false;
}
}
}
return true;
} else {
// System.err.print("match(\"" + Arrays.asList(namePatterns) + "\", \"" + Arrays.asList(names) + "\") -> ");
boolean b = outOfStar(namePatterns, names, 0, 0, patternsLength - ellipsisCount, namesLength, ellipsisCount);
// System.err.println(b);
return b;
}
}
private static boolean outOfStar(final NamePattern[] pattern, final char[][] target,
int pi, int ti,
int pLeft, int tLeft,
final int starsLeft) {
if (pLeft > tLeft) return false;
while (true) {
// invariant: if (tLeft > 0) then (ti < target.length && pi < pattern.length)
if (tLeft == 0) return true;
if (pLeft == 0) {
return (starsLeft > 0);
}
if (pattern[pi] == NamePattern.ELLIPSIS) {
return inStar(pattern, target, pi+1, ti, pLeft, tLeft, starsLeft-1);
}
if (! pattern[pi].matches(target[ti])) {
return false;
}
pi++; ti++; pLeft--; tLeft--;
}
}
private static boolean inStar(final NamePattern[] pattern, final char[][] target,
int pi, int ti,
final int pLeft, int tLeft,
int starsLeft) {
// invariant: pLeft > 0, so we know we'll run out of stars and find a real char in pattern
// of course, we probably can't parse multiple ..'s in a row, but this keeps the algorithm
// exactly parallel with that in NamePattern
NamePattern patternChar = pattern[pi];
while (patternChar == NamePattern.ELLIPSIS) {
starsLeft--;
patternChar = pattern[++pi];
}
while (true) {
// invariant: if (tLeft > 0) then (ti < target.length)
if (pLeft > tLeft) return false;
if (patternChar.matches(target[ti])) {
if (outOfStar(pattern, target, pi+1, ti+1, pLeft-1, tLeft-1, starsLeft)) return true;
}
ti++; tLeft--;
}
}
/**
* @see org.aspectj.weaver.TypePattern#matchesInstanceof(IType)
*/
public FuzzyBoolean matchesInstanceof(ResolvedTypeX type) {
//XXX hack to let unmatched types just silently remain so
if (maybeGetSimpleName() != null) return FuzzyBoolean.NO;
type.getWorld().getMessageHandler().handleMessage(
new Message("can't do instanceof matching on patterns with wildcards",
IMessage.ERROR, null, getSourceLocation()));
return FuzzyBoolean.NO;
}
public NamePattern extractName() {
//System.err.println("extract from : " + Arrays.asList(namePatterns));
int len = namePatterns.length;
NamePattern ret = namePatterns[len-1];
NamePattern[] newNames = new NamePattern[len-1];
System.arraycopy(namePatterns, 0, newNames, 0, len-1);
namePatterns = newNames;
//System.err.println(" left : " + Arrays.asList(namePatterns));
return ret;
}
/**
* Method maybeExtractName.
* @param string
* @return boolean
*/
public boolean maybeExtractName(String string) {
int len = namePatterns.length;
NamePattern ret = namePatterns[len-1];
String simple = ret.maybeGetSimpleName();
if (simple != null && simple.equals(string)) {
extractName();
return true;
}
return false;
}
/**
* If this type pattern has no '.' or '*' in it, then
* return a simple string
*
* otherwise, this will return null;
*/
public String maybeGetSimpleName() {
if (namePatterns.length == 1) {
return namePatterns[0].maybeGetSimpleName();
}
return null;
}
/**
* If this type pattern has no '*' or '..' in it
*/
public String maybeGetCleanName() {
if (namePatterns.length == 0) {
throw new RuntimeException("bad name: " + namePatterns);
}
//System.out.println("get clean: " + this);
StringBuffer buf = new StringBuffer();
for (int i=0, len=namePatterns.length; i < len; i++) {
NamePattern p = namePatterns[i];
String simpleName = p.maybeGetSimpleName();
if (simpleName == null) return null;
if (i > 0) buf.append(".");
buf.append(simpleName);
}
//System.out.println(buf);
return buf.toString();
}
/**
* Need to determine if I'm really a pattern or a reference to a formal
*
* We may wish to further optimize the case of pattern vs. non-pattern
*
* We will be replaced by what we return
*/
public TypePattern resolveBindings(IScope scope, Bindings bindings,
boolean allowBinding, boolean requireExactType)
{
if (isStar()) {
return TypePattern.ANY; //??? loses source location
}
String simpleName = maybeGetSimpleName();
if (simpleName != null) {
FormalBinding formalBinding = scope.lookupFormal(simpleName);
if (formalBinding != null) {
if (bindings == null) {
scope.message(IMessage.ERROR, this, "negation doesn't allow binding");
return this;
}
if (!allowBinding) {
scope.message(IMessage.ERROR, this,
"name binding only allowed in target, this, and args pcds");
return this;
}
BindingTypePattern binding = new BindingTypePattern(formalBinding);
binding.copyLocationFrom(this);
bindings.register(binding, scope);
return binding;
}
}
String cleanName = maybeGetCleanName();
String originalName = cleanName;
// if we discover it is 'MISSING' when searching via the scope, this next local var will
// tell us if it is really missing or if it does exist in the world and we just can't
// see it from the current scope.
ResolvedTypeX resolvedTypeInTheWorld = null;
if (cleanName != null) {
TypeX type;
//System.out.println("resolve: " + cleanName);
//??? this loop has too many inefficiencies to count
resolvedTypeInTheWorld = scope.getWorld().resolve(TypeX.forName(cleanName),true);
while ((type = scope.lookupType(cleanName, this)) == ResolvedTypeX.MISSING) {
int lastDot = cleanName.lastIndexOf('.');
if (lastDot == -1) break;
cleanName = cleanName.substring(0, lastDot) + '$' + cleanName.substring(lastDot+1);
if (resolvedTypeInTheWorld == ResolvedTypeX.MISSING)
resolvedTypeInTheWorld = scope.getWorld().resolve(TypeX.forName(cleanName),true);
}
if (type == ResolvedTypeX.MISSING) {
if (requireExactType) {
if (!allowBinding) {
scope.getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_BIND_TYPE,originalName),
getSourceLocation()));
} else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) {
scope.getWorld().getLint().invalidAbsoluteTypeName.signal(originalName, getSourceLocation());
}
return NO;
} else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) {
// Only put the lint warning out if we can't find it in the world
if (resolvedTypeInTheWorld == ResolvedTypeX.MISSING)
scope.getWorld().getLint().invalidAbsoluteTypeName.signal(originalName, getSourceLocation());
}
} else {
if (dim != 0) type = TypeX.makeArray(type, dim);
TypePattern ret = new ExactTypePattern(type, includeSubtypes);
ret.copyLocationFrom(this);
return ret;
}
} else {
if (requireExactType) {
scope.getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.WILDCARD_NOT_ALLOWED),
getSourceLocation()));
return NO;
}
//XXX need to implement behavior for Lint.invalidWildcardTypeName
}
importedPrefixes = scope.getImportedPrefixes();
knownMatches = preMatch(scope.getImportedNames());
return this;
}
public TypePattern resolveBindingsFromRTTI(boolean allowBinding, boolean requireExactType) {
if (isStar()) {
return TypePattern.ANY; //??? loses source location
}
String cleanName = maybeGetCleanName();
if (cleanName != null) {
Class clazz = null;
clazz = maybeGetPrimitiveClass(cleanName);
while (clazz == null) {
try {
clazz = Class.forName(cleanName);
} catch (ClassNotFoundException cnf) {
int lastDotIndex = cleanName.lastIndexOf('.');
if (lastDotIndex == -1) break;
cleanName = cleanName.substring(0, lastDotIndex) + '$' + cleanName.substring(lastDotIndex+1);
}
}
if (clazz == null) {
try {
clazz = Class.forName("java.lang." + cleanName);
} catch (ClassNotFoundException cnf) {
}
}
if (clazz == null) {
if (requireExactType) {
return NO;
}
} else {
TypeX type = TypeX.forName(clazz.getName());
if (dim != 0) type = TypeX.makeArray(type,dim);
TypePattern ret = new ExactTypePattern(type, includeSubtypes);
ret.copyLocationFrom(this);
return ret;
}
} else if (requireExactType) {
return NO;
}
importedPrefixes = SimpleScope.javaLangPrefixArray;
knownMatches = new String[0];
return this;
}
private Class maybeGetPrimitiveClass(String typeName) {
return (Class) ExactTypePattern.primitiveTypesMap.get(typeName);
}
public boolean isStar() {
return namePatterns.length == 1 && namePatterns[0].isAny();
}
/**
* returns those possible matches which I match exactly the last element of
*/
private String[] preMatch(String[] possibleMatches) {
//if (namePatterns.length != 1) return CollectionUtil.NO_STRINGS;
List ret = new ArrayList();
for (int i=0, len=possibleMatches.length; i < len; i++) {
char[][] names = splitNames(possibleMatches[i]); //??? not most efficient
if (namePatterns[0].matches(names[names.length-1])) {
ret.add(possibleMatches[i]);
}
}
return (String[])ret.toArray(new String[ret.size()]);
}
// public void postRead(ResolvedTypeX enclosingType) {
// this.importedPrefixes = enclosingType.getImportedPrefixes();
// this.knownNames = prematch(enclosingType.getImportedNames());
// }
public String toString() {
StringBuffer buf = new StringBuffer();
for (int i=0, len=namePatterns.length; i < len; i++) {
NamePattern name = namePatterns[i];
if (name == null) {
buf.append(".");
} else {
if (i > 0) buf.append(".");
buf.append(name.toString());
}
}
return buf.toString();
}
public boolean equals(Object other) {
if (!(other instanceof WildTypePattern)) return false;
WildTypePattern o = (WildTypePattern)other;
int len = o.namePatterns.length;
if (len != this.namePatterns.length) return false;
for (int i=0; i < len; i++) {
if (!o.namePatterns[i].equals(this.namePatterns[i])) return false;
}
return true;
}
public int hashCode() {
int result = 17;
for (int i = 0, len = namePatterns.length; i < len; i++) {
result = 37*result + namePatterns[i].hashCode();
}
return result;
}
public FuzzyBoolean matchesInstanceof(Class type) {
return FuzzyBoolean.NO;
}
public boolean matchesExactly(Class type) {
return matchesExactlyByName(type.getName());
}
/**
* @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream)
*/
public void write(DataOutputStream s) throws IOException {
s.writeByte(TypePattern.WILD);
s.writeShort(namePatterns.length);
for (int i = 0; i < namePatterns.length; i++) {
namePatterns[i].write(s);
}
s.writeBoolean(includeSubtypes);
s.writeInt(dim);
//??? storing this information with every type pattern is wasteful of .class
// file size. Storing it on enclosing types would be more efficient
FileUtil.writeStringArray(knownMatches, s);
FileUtil.writeStringArray(importedPrefixes, s);
writeLocation(s);
}
public static TypePattern read(DataInputStream s, ISourceContext context) throws IOException {
int len = s.readShort();
NamePattern[] namePatterns = new NamePattern[len];
for (int i=0; i < len; i++) {
namePatterns[i] = NamePattern.read(s);
}
boolean includeSubtypes = s.readBoolean();
int dim = s.readInt();
WildTypePattern ret = new WildTypePattern(namePatterns, includeSubtypes, dim);
ret.knownMatches = FileUtil.readStringArray(s);
ret.importedPrefixes = FileUtil.readStringArray(s);
ret.readLocation(context, s);
return ret;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.