You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BcelAdvice.java 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. /* *******************************************************************
  2. * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Eclipse Public License v1.0
  6. * which accompanies this distribution and is available at
  7. * http://www.eclipse.org/legal/epl-v10.html
  8. *
  9. * Contributors:
  10. * PARC initial implementation
  11. * Alexandre Vasseur support for @AJ aspects
  12. * ******************************************************************/
  13. package org.aspectj.weaver.bcel;
  14. import java.lang.reflect.Modifier;
  15. import java.util.ArrayList;
  16. import java.util.Collection;
  17. import java.util.Collections;
  18. import java.util.Map;
  19. import org.aspectj.apache.bcel.Constants;
  20. import org.aspectj.apache.bcel.classfile.LocalVariable;
  21. import org.aspectj.apache.bcel.classfile.LocalVariableTable;
  22. import org.aspectj.apache.bcel.generic.InstructionConstants;
  23. import org.aspectj.apache.bcel.generic.InstructionFactory;
  24. import org.aspectj.apache.bcel.generic.InstructionHandle;
  25. import org.aspectj.apache.bcel.generic.InstructionList;
  26. import org.aspectj.apache.bcel.generic.LineNumberTag;
  27. import org.aspectj.apache.bcel.generic.LocalVariableTag;
  28. import org.aspectj.bridge.ISourceLocation;
  29. import org.aspectj.bridge.Message;
  30. import org.aspectj.weaver.Advice;
  31. import org.aspectj.weaver.AdviceKind;
  32. import org.aspectj.weaver.AjAttribute;
  33. import org.aspectj.weaver.BCException;
  34. import org.aspectj.weaver.IEclipseSourceContext;
  35. import org.aspectj.weaver.ISourceContext;
  36. import org.aspectj.weaver.Lint;
  37. import org.aspectj.weaver.Member;
  38. import org.aspectj.weaver.ReferenceType;
  39. import org.aspectj.weaver.ReferenceTypeDelegate;
  40. import org.aspectj.weaver.ResolvedMember;
  41. import org.aspectj.weaver.ResolvedMemberImpl;
  42. import org.aspectj.weaver.ResolvedType;
  43. import org.aspectj.weaver.Shadow;
  44. import org.aspectj.weaver.ShadowMunger;
  45. import org.aspectj.weaver.UnresolvedType;
  46. import org.aspectj.weaver.WeaverMessages;
  47. import org.aspectj.weaver.World;
  48. import org.aspectj.weaver.ast.Literal;
  49. import org.aspectj.weaver.ast.Test;
  50. import org.aspectj.weaver.patterns.ExactTypePattern;
  51. import org.aspectj.weaver.patterns.ExposedState;
  52. import org.aspectj.weaver.patterns.PerClause;
  53. import org.aspectj.weaver.patterns.Pointcut;
  54. /**
  55. * Advice implemented for BCEL
  56. *
  57. * @author Erik Hilsdale
  58. * @author Jim Hugunin
  59. * @author Andy Clement
  60. */
  61. class BcelAdvice extends Advice {
  62. /**
  63. * If a match is not entirely statically determinable, this captures the runtime test that must succeed in order for the advice
  64. * to run.
  65. */
  66. private Test runtimeTest;
  67. private ExposedState exposedState;
  68. private int containsInvokedynamic = 0;// 0 = dontknow, 1=no, 2=yes
  69. public BcelAdvice(AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member adviceSignature, ResolvedType concreteAspect) {
  70. super(attribute, pointcut, simplify(attribute.getKind(), adviceSignature));
  71. this.concreteAspect = concreteAspect;
  72. }
  73. /**
  74. * A heavyweight BcelMethod object is only required for around advice that will be inlined. For other kinds of advice it is
  75. * possible to save some space.
  76. */
  77. private static Member simplify(AdviceKind kind, Member adviceSignature) {
  78. if (adviceSignature != null) {
  79. UnresolvedType adviceDeclaringType = adviceSignature.getDeclaringType();
  80. // if it isnt around advice or it is but inlining is turned off then shrink it to a ResolvedMemberImpl
  81. if (kind != AdviceKind.Around
  82. || ((adviceDeclaringType instanceof ResolvedType) && ((ResolvedType) adviceDeclaringType).getWorld()
  83. .isXnoInline())) {
  84. if (adviceSignature instanceof BcelMethod) {
  85. BcelMethod bm = (BcelMethod) adviceSignature;
  86. if (bm.getMethod() != null && bm.getMethod().getAnnotations() != null) {
  87. return adviceSignature;
  88. }
  89. ResolvedMemberImpl simplermember = new ResolvedMemberImpl(bm.getKind(), bm.getDeclaringType(),
  90. bm.getModifiers(), bm.getReturnType(), bm.getName(), bm.getParameterTypes());// ,bm.getExceptions(),bm.getBackingGenericMember()
  91. // );
  92. simplermember.setParameterNames(bm.getParameterNames());
  93. return simplermember;
  94. }
  95. }
  96. }
  97. return adviceSignature;
  98. }
  99. @Override
  100. public ShadowMunger concretize(ResolvedType fromType, World world, PerClause clause) {
  101. if (!world.areAllLintIgnored()) {
  102. suppressLintWarnings(world);
  103. }
  104. ShadowMunger ret = super.concretize(fromType, world, clause);
  105. if (!world.areAllLintIgnored()) {
  106. clearLintSuppressions(world, this.suppressedLintKinds);
  107. }
  108. IfFinder ifinder = new IfFinder();
  109. ret.getPointcut().accept(ifinder, null);
  110. boolean hasGuardTest = ifinder.hasIf && getKind() != AdviceKind.Around;
  111. boolean isAround = getKind() == AdviceKind.Around;
  112. if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
  113. if (!isAround && !hasGuardTest && world.getLint().noGuardForLazyTjp.isEnabled()) {
  114. // can't build tjp lazily, no suitable test...
  115. // ... only want to record it once against the advice(bug 133117)
  116. world.getLint().noGuardForLazyTjp.signal("", getSourceLocation());
  117. }
  118. }
  119. return ret;
  120. }
  121. @Override
  122. public ShadowMunger parameterizeWith(ResolvedType declaringType, Map<String, UnresolvedType> typeVariableMap) {
  123. Pointcut pc = getPointcut().parameterizeWith(typeVariableMap, declaringType.getWorld());
  124. BcelAdvice ret = null;
  125. Member adviceSignature = signature;
  126. // allows for around advice where the return value is a type variable (see pr115250)
  127. if (signature instanceof ResolvedMember && signature.getDeclaringType().isGenericType()) {
  128. adviceSignature = ((ResolvedMember) signature).parameterizedWith(declaringType.getTypeParameters(), declaringType,
  129. declaringType.isParameterizedType());
  130. }
  131. ret = new BcelAdvice(this.attribute, pc, adviceSignature, this.concreteAspect);
  132. return ret;
  133. }
  134. @Override
  135. public boolean match(Shadow shadow, World world) {
  136. if (world.areAllLintIgnored()) {
  137. return super.match(shadow, world);
  138. } else {
  139. suppressLintWarnings(world);
  140. boolean ret = super.match(shadow, world);
  141. clearLintSuppressions(world, this.suppressedLintKinds);
  142. return ret;
  143. }
  144. }
  145. @Override
  146. public void specializeOn(Shadow shadow) {
  147. if (getKind() == AdviceKind.Around) {
  148. ((BcelShadow) shadow).initializeForAroundClosure();
  149. }
  150. // XXX this case is just here for supporting lazy test code
  151. if (getKind() == null) {
  152. exposedState = new ExposedState(0);
  153. return;
  154. }
  155. if (getKind().isPerEntry()) {
  156. exposedState = new ExposedState(0);
  157. } else if (getKind().isCflow()) {
  158. exposedState = new ExposedState(nFreeVars);
  159. } else if (getSignature() != null) {
  160. exposedState = new ExposedState(getSignature());
  161. } else {
  162. exposedState = new ExposedState(0);
  163. return; // XXX this case is just here for supporting lazy test code
  164. }
  165. World world = shadow.getIWorld();
  166. if (!world.areAllLintIgnored()) {
  167. suppressLintWarnings(world);
  168. }
  169. exposedState.setConcreteAspect(concreteAspect);
  170. runtimeTest = getPointcut().findResidue(shadow, exposedState);
  171. if (!world.areAllLintIgnored()) {
  172. clearLintSuppressions(world, this.suppressedLintKinds);
  173. }
  174. // these initializations won't be performed by findResidue, but need to be
  175. // so that the joinpoint is primed for weaving
  176. if (getKind() == AdviceKind.PerThisEntry) {
  177. shadow.getThisVar();
  178. } else if (getKind() == AdviceKind.PerTargetEntry) {
  179. shadow.getTargetVar();
  180. }
  181. // make sure thisJoinPoint parameters are initialized
  182. if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
  183. ((BcelShadow) shadow).getThisJoinPointStaticPartVar();
  184. ((BcelShadow) shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow, getSourceLocation());
  185. }
  186. if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
  187. boolean hasGuardTest = runtimeTest != Literal.TRUE && getKind() != AdviceKind.Around;
  188. boolean isAround = getKind() == AdviceKind.Around;
  189. ((BcelShadow) shadow).requireThisJoinPoint(hasGuardTest, isAround);
  190. ((BcelShadow) shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow, getSourceLocation());
  191. if (!hasGuardTest && world.getLint().multipleAdviceStoppingLazyTjp.isEnabled()) {
  192. // collect up the problematic advice
  193. ((BcelShadow) shadow).addAdvicePreventingLazyTjp(this);
  194. }
  195. }
  196. if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
  197. ((BcelShadow) shadow).getThisEnclosingJoinPointStaticPartVar();
  198. ((BcelShadow) shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow, getSourceLocation());
  199. }
  200. }
  201. private boolean canInline(Shadow s) {
  202. if (attribute.isProceedInInners()) {
  203. return false;
  204. }
  205. // XXX this guard seems to only be needed for bad test cases
  206. if (concreteAspect == null || concreteAspect.isMissing()) {
  207. return false;
  208. }
  209. if (concreteAspect.getWorld().isXnoInline()) {
  210. return false;
  211. }
  212. // System.err.println("isWoven? " + ((BcelObjectType)concreteAspect).getLazyClassGen().getWeaverState());
  213. BcelObjectType boType = BcelWorld.getBcelObjectType(concreteAspect);
  214. if (boType == null) {
  215. // Could be a symptom that the aspect failed to build last build... return the default answer of false
  216. return false;
  217. }
  218. // Need isJava8 check
  219. // Does the advice contain invokedynamic...
  220. if (boType.javaClass.getMajor() == Constants.MAJOR_1_8) {
  221. if (containsInvokedynamic == 0) {
  222. containsInvokedynamic = 1;
  223. LazyMethodGen lmg = boType.getLazyClassGen().getLazyMethodGen(this.signature.getName(), this.signature.getSignature(), true);
  224. // Check Java8 supertypes
  225. ResolvedType searchType = concreteAspect;
  226. while (lmg == null) {
  227. searchType = searchType.getSuperclass();
  228. if (searchType == null) break;
  229. ReferenceTypeDelegate rtd = ((ReferenceType)searchType).getDelegate();
  230. if (rtd instanceof BcelObjectType) {
  231. BcelObjectType bot = (BcelObjectType)rtd;
  232. if (bot.javaClass.getMajor() < Constants.MAJOR_1_8) {
  233. break;
  234. }
  235. lmg = bot.getLazyClassGen().getLazyMethodGen(this.signature.getName(), this.signature.getSignature(), true);
  236. }
  237. }
  238. if (lmg != null) {
  239. InstructionList ilist = lmg.getBody();
  240. for (InstructionHandle src = ilist.getStart(); src != null; src = src.getNext()) {
  241. if (src.getInstruction().opcode == Constants.INVOKEDYNAMIC) {
  242. containsInvokedynamic = 2;
  243. break;
  244. }
  245. }
  246. }
  247. }
  248. }
  249. if (containsInvokedynamic == 2) {
  250. return false;
  251. }
  252. return boType.getLazyClassGen().isWoven();
  253. }
  254. private boolean aspectIsBroken() {
  255. if (concreteAspect instanceof ReferenceType) {
  256. ReferenceTypeDelegate rtDelegate = ((ReferenceType) concreteAspect).getDelegate();
  257. if (!(rtDelegate instanceof BcelObjectType)) {
  258. return true;
  259. }
  260. }
  261. return false;
  262. }
  263. @Override
  264. public boolean implementOn(Shadow s) {
  265. hasMatchedAtLeastOnce = true;
  266. // pr263323 - if the aspect is broken then the delegate will not be usable for weaving
  267. if (aspectIsBroken()) {
  268. return false;
  269. }
  270. BcelShadow shadow = (BcelShadow) s;
  271. // remove any unnecessary exceptions if the compiler option is set to
  272. // error or warning and if this piece of advice throws exceptions
  273. // (bug 129282). This may be expanded to include other compiler warnings
  274. // at the moment it only deals with 'declared exception is not thrown'
  275. if (!shadow.getWorld().isIgnoringUnusedDeclaredThrownException() && !getThrownExceptions().isEmpty()) {
  276. Member member = shadow.getSignature();
  277. if (member instanceof BcelMethod) {
  278. removeUnnecessaryProblems((BcelMethod) member, ((BcelMethod) member).getDeclarationLineNumber());
  279. } else {
  280. // we're in a call shadow therefore need the line number of the
  281. // declared method (which may be in a different type). However,
  282. // we want to remove the problems from the CompilationResult
  283. // held within the current type's EclipseSourceContext so need
  284. // the enclosing shadow too
  285. ResolvedMember resolvedMember = shadow.getSignature().resolve(shadow.getWorld());
  286. if (resolvedMember instanceof BcelMethod && shadow.getEnclosingShadow() instanceof BcelShadow) {
  287. Member enclosingMember = shadow.getEnclosingShadow().getSignature();
  288. if (enclosingMember instanceof BcelMethod) {
  289. removeUnnecessaryProblems((BcelMethod) enclosingMember,
  290. ((BcelMethod) resolvedMember).getDeclarationLineNumber());
  291. }
  292. }
  293. }
  294. }
  295. if (shadow.getIWorld().isJoinpointSynchronizationEnabled() && shadow.getKind() == Shadow.MethodExecution
  296. && (s.getSignature().getModifiers() & Modifier.SYNCHRONIZED) != 0) {
  297. shadow.getIWorld().getLint().advisingSynchronizedMethods.signal(new String[] { shadow.toString() },
  298. shadow.getSourceLocation(), new ISourceLocation[] { getSourceLocation() });
  299. }
  300. // FIXME AV - see #75442, this logic is not enough so for now comment it out until we fix the bug
  301. // // callback for perObject AJC MightHaveAspect postMunge (#75442)
  302. // if (getConcreteAspect() != null
  303. // && getConcreteAspect().getPerClause() != null
  304. // && PerClause.PEROBJECT.equals(getConcreteAspect().getPerClause().getKind())) {
  305. // final PerObject clause;
  306. // if (getConcreteAspect().getPerClause() instanceof PerFromSuper) {
  307. // clause = (PerObject)((PerFromSuper) getConcreteAspect().getPerClause()).lookupConcretePerClause(getConcreteAspect());
  308. // } else {
  309. // clause = (PerObject) getConcreteAspect().getPerClause();
  310. // }
  311. // if (clause.isThis()) {
  312. // PerObjectInterfaceTypeMunger.registerAsAdvisedBy(s.getThisVar().getType(), getConcreteAspect());
  313. // } else {
  314. // PerObjectInterfaceTypeMunger.registerAsAdvisedBy(s.getTargetVar().getType(), getConcreteAspect());
  315. // }
  316. // }
  317. if (runtimeTest == Literal.FALSE) { // not usually allowed, except in one case (260384)
  318. Member sig = shadow.getSignature();
  319. if (sig.getArity() == 0 && shadow.getKind() == Shadow.MethodCall && sig.getName().charAt(0) == 'c'
  320. && sig.getReturnType().equals(ResolvedType.OBJECT) && sig.getName().equals("clone")) {
  321. return false;
  322. }
  323. }
  324. if (getKind() == AdviceKind.Before) {
  325. shadow.weaveBefore(this);
  326. } else if (getKind() == AdviceKind.AfterReturning) {
  327. shadow.weaveAfterReturning(this);
  328. } else if (getKind() == AdviceKind.AfterThrowing) {
  329. UnresolvedType catchType = hasExtraParameter() ? getExtraParameterType() : UnresolvedType.THROWABLE;
  330. shadow.weaveAfterThrowing(this, catchType);
  331. } else if (getKind() == AdviceKind.After) {
  332. shadow.weaveAfter(this);
  333. } else if (getKind() == AdviceKind.Around) {
  334. // Note: under regular LTW the aspect is usually loaded after the first use of any class affected by it.
  335. // This means that as long as the aspect has not been thru the LTW, it's woven state is unknown
  336. // and thus canInline(s) will return false.
  337. // To force inlining (test), ones can do Class aspect = FQNAspect.class in the clinit of the target class
  338. // FIXME AV : for AJC compiled @AJ aspect (or any code style aspect), the woven state can never be known
  339. // if the aspect belongs to a parent classloader. In that case the aspect will never be inlined.
  340. // It might be dangerous to change that especially for @AJ aspect non compiled with AJC since if those
  341. // are not weaved (f.e. use of some limited LTW etc) then they cannot be prepared for inlining.
  342. // One solution would be to flag @AJ aspect with an annotation as "prepared" and query that one.
  343. LazyClassGen enclosingClass = shadow.getEnclosingClass();
  344. if (enclosingClass != null && enclosingClass.isInterface() && shadow.getEnclosingMethod().getName().charAt(0) == '<') {
  345. // Do not add methods with bodies to an interface (252198, 163005)
  346. shadow.getWorld().getLint().cannotAdviseJoinpointInInterfaceWithAroundAdvice.signal(shadow.toString(),
  347. shadow.getSourceLocation());
  348. return false;
  349. }
  350. if (!canInline(s)) {
  351. shadow.weaveAroundClosure(this, hasDynamicTests());
  352. } else {
  353. shadow.weaveAroundInline(this, hasDynamicTests());
  354. }
  355. } else if (getKind() == AdviceKind.InterInitializer) {
  356. shadow.weaveAfterReturning(this);
  357. } else if (getKind().isCflow()) {
  358. shadow.weaveCflowEntry(this, getSignature());
  359. } else if (getKind() == AdviceKind.PerThisEntry) {
  360. shadow.weavePerObjectEntry(this, (BcelVar) shadow.getThisVar());
  361. } else if (getKind() == AdviceKind.PerTargetEntry) {
  362. shadow.weavePerObjectEntry(this, (BcelVar) shadow.getTargetVar());
  363. } else if (getKind() == AdviceKind.Softener) {
  364. shadow.weaveSoftener(this, ((ExactTypePattern) exceptionType).getType());
  365. } else if (getKind() == AdviceKind.PerTypeWithinEntry) {
  366. // PTWIMPL Entry to ptw is the static initialization of a type that matched the ptw type pattern
  367. shadow.weavePerTypeWithinAspectInitialization(this, shadow.getEnclosingType());
  368. } else {
  369. throw new BCException("unimplemented kind: " + getKind());
  370. }
  371. return true;
  372. }
  373. private void removeUnnecessaryProblems(BcelMethod method, int problemLineNumber) {
  374. ISourceContext sourceContext = method.getSourceContext();
  375. if (sourceContext instanceof IEclipseSourceContext) {
  376. ((IEclipseSourceContext) sourceContext).removeUnnecessaryProblems(method, problemLineNumber);
  377. }
  378. }
  379. // ---- implementations
  380. private Collection<ResolvedType> collectCheckedExceptions(UnresolvedType[] excs) {
  381. if (excs == null || excs.length == 0) {
  382. return Collections.emptyList();
  383. }
  384. Collection<ResolvedType> ret = new ArrayList<ResolvedType>();
  385. World world = concreteAspect.getWorld();
  386. ResolvedType runtimeException = world.getCoreType(UnresolvedType.RUNTIME_EXCEPTION);
  387. ResolvedType error = world.getCoreType(UnresolvedType.ERROR);
  388. for (int i = 0, len = excs.length; i < len; i++) {
  389. ResolvedType t = world.resolve(excs[i], true);
  390. if (t.isMissing()) {
  391. world.getLint().cantFindType
  392. .signal(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE, excs[i].getName()),
  393. getSourceLocation());
  394. // IMessage msg = new Message(
  395. // WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE,excs[i].getName()),
  396. // "",IMessage.ERROR,getSourceLocation(),null,null);
  397. // world.getMessageHandler().handleMessage(msg);
  398. }
  399. if (!(runtimeException.isAssignableFrom(t) || error.isAssignableFrom(t))) {
  400. ret.add(t);
  401. }
  402. }
  403. return ret;
  404. }
  405. private Collection<ResolvedType> thrownExceptions = null;
  406. @Override
  407. public Collection<ResolvedType> getThrownExceptions() {
  408. if (thrownExceptions == null) {
  409. // ??? can we really lump in Around here, how does this interact with Throwable
  410. if (concreteAspect != null && concreteAspect.getWorld() != null && // null tests for test harness
  411. (getKind().isAfter() || getKind() == AdviceKind.Before || getKind() == AdviceKind.Around)) {
  412. World world = concreteAspect.getWorld();
  413. ResolvedMember m = world.resolve(signature);
  414. if (m == null) {
  415. thrownExceptions = Collections.emptyList();
  416. } else {
  417. thrownExceptions = collectCheckedExceptions(m.getExceptions());
  418. }
  419. } else {
  420. thrownExceptions = Collections.emptyList();
  421. }
  422. }
  423. return thrownExceptions;
  424. }
  425. /**
  426. * The munger must not check for the advice exceptions to be declared by the shadow in the case of @AJ aspects so that around
  427. * can throws Throwable
  428. *
  429. * @return
  430. */
  431. @Override
  432. public boolean mustCheckExceptions() {
  433. if (getConcreteAspect() == null) {
  434. return true;
  435. }
  436. return !getConcreteAspect().isAnnotationStyleAspect();
  437. }
  438. // only call me after prepare has been called
  439. @Override
  440. public boolean hasDynamicTests() {
  441. // if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) {
  442. // UnresolvedType extraParameterType = getExtraParameterType();
  443. // if (! extraParameterType.equals(UnresolvedType.OBJECT)
  444. // && ! extraParameterType.isPrimitive())
  445. // return true;
  446. // }
  447. return runtimeTest != null && !(runtimeTest == Literal.TRUE);// || pointcutTest == Literal.NO_TEST);
  448. }
  449. /**
  450. * get the instruction list for the really simple version of this advice. Is broken apart for other advice, but if you want it
  451. * in one block, this is the method to call.
  452. *
  453. * @param s The shadow around which these instructions will eventually live.
  454. * @param extraArgVar The var that will hold the return value or thrown exception for afterX advice
  455. * @param ifNoAdvice The instructionHandle to jump to if the dynamic tests for this munger fails.
  456. */
  457. InstructionList getAdviceInstructions(BcelShadow s, BcelVar extraArgVar, InstructionHandle ifNoAdvice) {
  458. BcelShadow shadow = s;
  459. InstructionFactory fact = shadow.getFactory();
  460. BcelWorld world = shadow.getWorld();
  461. InstructionList il = new InstructionList();
  462. // we test to see if we have the right kind of thing...
  463. // after throwing does this just by the exception mechanism.
  464. if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) {
  465. UnresolvedType extraParameterType = getExtraParameterType();
  466. if (!extraParameterType.equals(UnresolvedType.OBJECT) && !extraParameterType.isPrimitiveType()) {
  467. il.append(BcelRenderer.renderTest(fact, world,
  468. Test.makeInstanceof(extraArgVar, getExtraParameterType().resolve(world)), null, ifNoAdvice, null));
  469. }
  470. }
  471. il.append(getAdviceArgSetup(shadow, extraArgVar, null));
  472. il.append(getNonTestAdviceInstructions(shadow));
  473. InstructionHandle ifYesAdvice = il.getStart();
  474. il.insert(getTestInstructions(shadow, ifYesAdvice, ifNoAdvice, ifYesAdvice));
  475. // If inserting instructions at the start of a method, we need a nice line number for this entry
  476. // in the stack trace
  477. if (shadow.getKind() == Shadow.MethodExecution && getKind() == AdviceKind.Before) {
  478. int lineNumber = 0;
  479. // Uncomment this code if you think we should use the method decl line number when it exists...
  480. // // If the advised join point is in a class built by AspectJ, we can use the declaration line number
  481. // boolean b = shadow.getEnclosingMethod().getMemberView().hasDeclarationLineNumberInfo();
  482. // if (b) {
  483. // lineNumber = shadow.getEnclosingMethod().getMemberView().getDeclarationLineNumber();
  484. // } else { // If it wasn't, the best we can do is the line number of the first instruction in the method
  485. lineNumber = shadow.getEnclosingMethod().getMemberView().getLineNumberOfFirstInstruction();
  486. // }
  487. InstructionHandle start = il.getStart();
  488. if (lineNumber > 0) {
  489. start.addTargeter(new LineNumberTag(lineNumber));
  490. }
  491. // Fix up the local variables: find any that have a startPC of 0 and ensure they target the new start of the method
  492. LocalVariableTable lvt = shadow.getEnclosingMethod().getMemberView().getMethod().getLocalVariableTable();
  493. if (lvt != null) {
  494. LocalVariable[] lvTable = lvt.getLocalVariableTable();
  495. for (int i = 0; i < lvTable.length; i++) {
  496. LocalVariable lv = lvTable[i];
  497. if (lv.getStartPC() == 0) {
  498. start.addTargeter(new LocalVariableTag(lv.getSignature(), lv.getName(), lv.getIndex(), 0));
  499. }
  500. }
  501. }
  502. }
  503. return il;
  504. }
  505. public InstructionList getAdviceArgSetup(BcelShadow shadow, BcelVar extraVar, InstructionList closureInstantiation) {
  506. InstructionFactory fact = shadow.getFactory();
  507. BcelWorld world = shadow.getWorld();
  508. InstructionList il = new InstructionList();
  509. // if (targetAspectField != null) {
  510. // il.append(fact.createFieldAccess(
  511. // targetAspectField.getDeclaringType().getName(),
  512. // targetAspectField.getName(),
  513. // BcelWorld.makeBcelType(targetAspectField.getType()),
  514. // Constants.GETSTATIC));
  515. // }
  516. //
  517. // System.err.println("BcelAdvice: " + exposedState);
  518. if (exposedState.getAspectInstance() != null) {
  519. il.append(BcelRenderer.renderExpr(fact, world, exposedState.getAspectInstance()));
  520. }
  521. // pr121385
  522. boolean x = this.getDeclaringAspect().resolve(world).isAnnotationStyleAspect();
  523. final boolean isAnnotationStyleAspect = getConcreteAspect() != null && getConcreteAspect().isAnnotationStyleAspect() && x;
  524. boolean previousIsClosure = false;
  525. for (int i = 0, len = exposedState.size(); i < len; i++) {
  526. if (exposedState.isErroneousVar(i)) {
  527. continue; // Erroneous vars have already had error msgs reported!
  528. }
  529. BcelVar v = (BcelVar) exposedState.get(i);
  530. if (v == null) {
  531. // if not @AJ aspect, go on with the regular binding handling
  532. if (!isAnnotationStyleAspect) {
  533. } else {
  534. // ATAJ: for @AJ aspects, handle implicit binding of xxJoinPoint
  535. // if (getKind() == AdviceKind.Around) {
  536. // previousIsClosure = true;
  537. // il.append(closureInstantiation);
  538. if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) {
  539. // make sure we are in an around, since we deal with the closure, not the arg here
  540. if (getKind() != AdviceKind.Around) {
  541. previousIsClosure = false;
  542. getConcreteAspect()
  543. .getWorld()
  544. .getMessageHandler()
  545. .handleMessage(
  546. new Message("use of ProceedingJoinPoint is allowed only on around advice (" + "arg "
  547. + i + " in " + toString() + ")", this.getSourceLocation(), true));
  548. // try to avoid verify error and pass in null
  549. il.append(InstructionConstants.ACONST_NULL);
  550. } else {
  551. if (previousIsClosure) {
  552. il.append(InstructionConstants.DUP);
  553. } else {
  554. previousIsClosure = true;
  555. il.append(closureInstantiation.copy());
  556. }
  557. }
  558. } else if ("Lorg/aspectj/lang/JoinPoint$StaticPart;".equals(getSignature().getParameterTypes()[i]
  559. .getSignature())) {
  560. previousIsClosure = false;
  561. if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
  562. shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact);
  563. }
  564. } else if ("Lorg/aspectj/lang/JoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) {
  565. previousIsClosure = false;
  566. if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
  567. il.append(shadow.loadThisJoinPoint());
  568. }
  569. } else if ("Lorg/aspectj/lang/JoinPoint$EnclosingStaticPart;".equals(getSignature().getParameterTypes()[i]
  570. .getSignature())) {
  571. previousIsClosure = false;
  572. if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
  573. shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact);
  574. }
  575. } else if (hasExtraParameter()) {
  576. previousIsClosure = false;
  577. extraVar.appendLoadAndConvert(il, fact, getExtraParameterType().resolve(world));
  578. } else {
  579. previousIsClosure = false;
  580. getConcreteAspect()
  581. .getWorld()
  582. .getMessageHandler()
  583. .handleMessage(
  584. new Message("use of ProceedingJoinPoint is allowed only on around advice (" + "arg " + i
  585. + " in " + toString() + ")", this.getSourceLocation(), true));
  586. // try to avoid verify error and pass in null
  587. il.append(InstructionConstants.ACONST_NULL);
  588. }
  589. }
  590. } else {
  591. UnresolvedType desiredTy = getBindingParameterTypes()[i];
  592. v.appendLoadAndConvert(il, fact, desiredTy.resolve(world));
  593. }
  594. }
  595. // ATAJ: for code style aspect, handles the extraFlag as usual ie not
  596. // in the middle of the formal bindings but at the end, in a rock solid ordering
  597. if (!isAnnotationStyleAspect) {
  598. if (getKind() == AdviceKind.Around) {
  599. il.append(closureInstantiation);
  600. } else if (hasExtraParameter()) {
  601. extraVar.appendLoadAndConvert(il, fact, getExtraParameterType().resolve(world));
  602. }
  603. // handle thisJoinPoint parameters
  604. // these need to be in that same order as parameters in
  605. // org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration
  606. if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
  607. shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact);
  608. }
  609. if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
  610. il.append(shadow.loadThisJoinPoint());
  611. }
  612. if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
  613. shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact);
  614. }
  615. }
  616. return il;
  617. }
  618. public InstructionList getNonTestAdviceInstructions(BcelShadow shadow) {
  619. return new InstructionList(Utility.createInvoke(shadow.getFactory(), shadow.getWorld(), getOriginalSignature()));
  620. }
  621. @Override
  622. public Member getOriginalSignature() {
  623. Member sig = getSignature();
  624. if (sig instanceof ResolvedMember) {
  625. ResolvedMember rsig = (ResolvedMember) sig;
  626. if (rsig.hasBackingGenericMember()) {
  627. return rsig.getBackingGenericMember();
  628. }
  629. }
  630. return sig;
  631. }
  632. public InstructionList getTestInstructions(BcelShadow shadow, InstructionHandle sk, InstructionHandle fk, InstructionHandle next) {
  633. // System.err.println("test: " + pointcutTest);
  634. return BcelRenderer.renderTest(shadow.getFactory(), shadow.getWorld(), runtimeTest, sk, fk, next);
  635. }
  636. public int compareTo(Object other) {
  637. if (!(other instanceof BcelAdvice)) {
  638. return 0;
  639. }
  640. BcelAdvice o = (BcelAdvice) other;
  641. // System.err.println("compareTo: " + this + ", " + o);
  642. if (kind.getPrecedence() != o.kind.getPrecedence()) {
  643. if (kind.getPrecedence() > o.kind.getPrecedence()) {
  644. return +1;
  645. } else {
  646. return -1;
  647. }
  648. }
  649. if (kind.isCflow()) {
  650. // System.err.println("sort: " + this + " innerCflowEntries " + innerCflowEntries);
  651. // System.err.println(" " + o + " innerCflowEntries " + o.innerCflowEntries);
  652. boolean isBelow = (kind == AdviceKind.CflowBelowEntry);
  653. if (this.innerCflowEntries.contains(o)) {
  654. return isBelow ? +1 : -1;
  655. } else if (o.innerCflowEntries.contains(this)) {
  656. return isBelow ? -1 : +1;
  657. } else {
  658. return 0;
  659. }
  660. }
  661. if (kind.isPerEntry() || kind == AdviceKind.Softener) {
  662. return 0;
  663. }
  664. // System.out.println("compare: " + this + " with " + other);
  665. World world = concreteAspect.getWorld();
  666. int ret = concreteAspect.getWorld().compareByPrecedence(concreteAspect, o.concreteAspect);
  667. if (ret != 0) {
  668. return ret;
  669. }
  670. ResolvedType declaringAspect = getDeclaringAspect().resolve(world);
  671. ResolvedType o_declaringAspect = o.getDeclaringAspect().resolve(world);
  672. if (declaringAspect == o_declaringAspect) {
  673. if (kind.isAfter() || o.kind.isAfter()) {
  674. return this.getStart() < o.getStart() ? -1 : +1;
  675. } else {
  676. return this.getStart() < o.getStart() ? +1 : -1;
  677. }
  678. } else if (declaringAspect.isAssignableFrom(o_declaringAspect)) {
  679. return -1;
  680. } else if (o_declaringAspect.isAssignableFrom(declaringAspect)) {
  681. return +1;
  682. } else {
  683. return 0;
  684. }
  685. }
  686. public BcelVar[] getExposedStateAsBcelVars(boolean isAround) {
  687. // ATAJ aspect
  688. if (isAround) {
  689. // the closure instantiation has the same mapping as the extracted method from wich it is called
  690. if (getConcreteAspect() != null && getConcreteAspect().isAnnotationStyleAspect()) {
  691. return BcelVar.NONE;
  692. }
  693. }
  694. // System.out.println("vars: " + Arrays.asList(exposedState.vars));
  695. if (exposedState == null) {
  696. return BcelVar.NONE;
  697. }
  698. int len = exposedState.vars.length;
  699. BcelVar[] ret = new BcelVar[len];
  700. for (int i = 0; i < len; i++) {
  701. ret[i] = (BcelVar) exposedState.vars[i];
  702. }
  703. return ret; // (BcelVar[]) exposedState.vars;
  704. }
  705. protected void suppressLintWarnings(World inWorld) {
  706. if (suppressedLintKinds == null) {
  707. if (signature instanceof BcelMethod) {
  708. this.suppressedLintKinds = Utility.getSuppressedWarnings(signature.getAnnotations(), inWorld.getLint());
  709. } else {
  710. this.suppressedLintKinds = Collections.emptyList();
  711. return;
  712. }
  713. }
  714. inWorld.getLint().suppressKinds(suppressedLintKinds);
  715. }
  716. protected void clearLintSuppressions(World inWorld, Collection<Lint.Kind> toClear) {
  717. inWorld.getLint().clearSuppressions(toClear);
  718. }
  719. /**
  720. * For testing only
  721. */
  722. public BcelAdvice(AdviceKind kind, Pointcut pointcut, Member signature, int extraArgumentFlags, int start, int end,
  723. ISourceContext sourceContext, ResolvedType concreteAspect) {
  724. this(new AjAttribute.AdviceAttribute(kind, pointcut, extraArgumentFlags, start, end, sourceContext), pointcut, signature,
  725. concreteAspect);
  726. thrownExceptions = Collections.emptyList(); // !!! interaction with unit tests
  727. }
  728. }