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.

Advice.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. * ******************************************************************/
  12. package org.aspectj.weaver;
  13. import java.util.Collections;
  14. import java.util.List;
  15. import org.aspectj.bridge.IMessage;
  16. import org.aspectj.bridge.ISourceLocation;
  17. import org.aspectj.weaver.patterns.AndPointcut;
  18. import org.aspectj.weaver.patterns.PerClause;
  19. import org.aspectj.weaver.patterns.Pointcut;
  20. import org.aspectj.weaver.patterns.TypePattern;
  21. public abstract class Advice extends ShadowMunger {
  22. protected AjAttribute.AdviceAttribute attribute;
  23. protected transient AdviceKind kind; // alias for attribute.getKind()
  24. protected Member signature;
  25. private boolean isAnnotationStyle;
  26. // not necessarily declaring aspect, this is a semantics change from 1.0
  27. protected ResolvedType concreteAspect; // null until after concretize
  28. // Just for Cflow*entry kinds
  29. protected List<ShadowMunger> innerCflowEntries = Collections.emptyList();
  30. protected int nFreeVars;
  31. protected TypePattern exceptionType; // just for Softener kind
  32. // if we are parameterized, these type may be different to the advice
  33. // signature types
  34. protected UnresolvedType[] bindingParameterTypes;
  35. protected boolean hasMatchedAtLeastOnce = false;
  36. // based on annotations on this advice
  37. protected List<Lint.Kind> suppressedLintKinds = null;
  38. public ISourceLocation lastReportedMonitorExitJoinpointLocation = null;
  39. public static Advice makeCflowEntry(World world, Pointcut entry, boolean isBelow, Member stackField, int nFreeVars,
  40. List<ShadowMunger> innerCflowEntries, ResolvedType inAspect) {
  41. Advice ret = world.createAdviceMunger(isBelow ? AdviceKind.CflowBelowEntry : AdviceKind.CflowEntry, entry, stackField, 0,
  42. entry, inAspect);
  43. ret.innerCflowEntries = innerCflowEntries;
  44. ret.nFreeVars = nFreeVars;
  45. ret.setDeclaringType(inAspect); // correct?
  46. return ret;
  47. }
  48. public static Advice makePerCflowEntry(World world, Pointcut entry, boolean isBelow, Member stackField, ResolvedType inAspect,
  49. List<ShadowMunger> innerCflowEntries) {
  50. Advice ret = world.createAdviceMunger(isBelow ? AdviceKind.PerCflowBelowEntry : AdviceKind.PerCflowEntry, entry,
  51. stackField, 0, entry, inAspect);
  52. ret.innerCflowEntries = innerCflowEntries;
  53. ret.concreteAspect = inAspect;
  54. return ret;
  55. }
  56. public static Advice makePerObjectEntry(World world, Pointcut entry, boolean isThis, ResolvedType inAspect) {
  57. Advice ret = world.createAdviceMunger(isThis ? AdviceKind.PerThisEntry : AdviceKind.PerTargetEntry, entry, null, 0, entry,
  58. inAspect);
  59. ret.concreteAspect = inAspect;
  60. return ret;
  61. }
  62. // PTWIMPL per type within entry advice is what initializes the aspect
  63. // instance in the matched type
  64. public static Advice makePerTypeWithinEntry(World world, Pointcut p, ResolvedType inAspect) {
  65. Advice ret = world.createAdviceMunger(AdviceKind.PerTypeWithinEntry, p, null, 0, p, inAspect);
  66. ret.concreteAspect = inAspect;
  67. return ret;
  68. }
  69. public static Advice makeSoftener(World world, Pointcut entry, TypePattern exceptionType, ResolvedType inAspect,
  70. IHasSourceLocation loc) {
  71. Advice ret = world.createAdviceMunger(AdviceKind.Softener, entry, null, 0, loc, inAspect);
  72. ret.exceptionType = exceptionType;
  73. return ret;
  74. }
  75. public Advice(AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature) {
  76. super(pointcut, attribute.getStart(), attribute.getEnd(), attribute.getSourceContext(), ShadowMungerAdvice);
  77. this.attribute = attribute;
  78. this.isAnnotationStyle = signature != null && !signature.getName().startsWith("ajc$");
  79. this.kind = attribute.getKind(); // alias
  80. this.signature = signature;
  81. if (signature != null) {
  82. bindingParameterTypes = signature.getParameterTypes();
  83. } else {
  84. bindingParameterTypes = new UnresolvedType[0];
  85. }
  86. }
  87. @Override
  88. public boolean match(Shadow shadow, World world) {
  89. if (super.match(shadow, world)) {
  90. if (shadow.getKind() == Shadow.ExceptionHandler) {
  91. if (kind.isAfter() || kind == AdviceKind.Around) {
  92. world.showMessage(IMessage.WARNING, WeaverMessages.format(WeaverMessages.ONLY_BEFORE_ON_HANDLER),
  93. getSourceLocation(), shadow.getSourceLocation());
  94. return false;
  95. }
  96. }
  97. if (shadow.getKind() == Shadow.SynchronizationLock || shadow.getKind() == Shadow.SynchronizationUnlock) {
  98. if (kind == AdviceKind.Around
  99. // Don't work, see comments in SynchronizationTests
  100. // && attribute.getProceedCallSignatures()!=null
  101. // && attribute.getProceedCallSignatures().length!=0
  102. ) {
  103. world.showMessage(IMessage.WARNING, WeaverMessages.format(WeaverMessages.NO_AROUND_ON_SYNCHRONIZATION),
  104. getSourceLocation(), shadow.getSourceLocation());
  105. return false;
  106. }
  107. }
  108. if (hasExtraParameter() && kind == AdviceKind.AfterReturning) {
  109. ResolvedType resolvedExtraParameterType = getExtraParameterType().resolve(world);
  110. ResolvedType shadowReturnType = shadow.getReturnType().resolve(world);
  111. boolean matches = (resolvedExtraParameterType.isConvertableFrom(shadowReturnType) && shadow.getKind()
  112. .hasReturnValue());
  113. if (matches && resolvedExtraParameterType.isParameterizedType()) {
  114. maybeIssueUncheckedMatchWarning(resolvedExtraParameterType, shadowReturnType, shadow, world);
  115. }
  116. return matches;
  117. } else if (hasExtraParameter() && kind == AdviceKind.AfterThrowing) { // pr119749
  118. ResolvedType exceptionType = getExtraParameterType().resolve(world);
  119. if (!exceptionType.isCheckedException() || exceptionType.getName().equals("java.lang.Exception")) { // pr292239
  120. return true;
  121. }
  122. UnresolvedType[] shadowThrows = shadow.getSignature().getExceptions(world);
  123. boolean matches = false;
  124. for (int i = 0; i < shadowThrows.length && !matches; i++) {
  125. ResolvedType type = shadowThrows[i].resolve(world);
  126. if (exceptionType.isAssignableFrom(type)) {
  127. matches = true;
  128. }
  129. }
  130. return matches;
  131. } else if (kind == AdviceKind.PerTargetEntry) {
  132. return shadow.hasTarget();
  133. } else if (kind == AdviceKind.PerThisEntry) {
  134. // Groovy Constructors have a strange switch statement in them - this switch statement can leave us in places where
  135. // the
  136. // instance is not initialized (a super ctor hasn't been called yet).
  137. // In these situations it isn't safe to do a perObjectBind, the instance is not initialized and cannot be passed
  138. // over.
  139. if (shadow.getEnclosingCodeSignature().getName().equals("<init>")) {
  140. if (world.resolve(shadow.getEnclosingType()).isGroovyObject()) {
  141. return false;
  142. }
  143. }
  144. return shadow.hasThis();
  145. } else if (kind == AdviceKind.Around) {
  146. if (shadow.getKind() == Shadow.PreInitialization) {
  147. world.showMessage(IMessage.WARNING, WeaverMessages.format(WeaverMessages.AROUND_ON_PREINIT),
  148. getSourceLocation(), shadow.getSourceLocation());
  149. return false;
  150. } else if (shadow.getKind() == Shadow.Initialization) {
  151. world.showMessage(IMessage.WARNING, WeaverMessages.format(WeaverMessages.AROUND_ON_INIT), getSourceLocation(),
  152. shadow.getSourceLocation());
  153. return false;
  154. } else if (shadow.getKind() == Shadow.StaticInitialization
  155. && shadow.getEnclosingType().resolve(world).isInterface()) {
  156. world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AROUND_ON_INTERFACE_STATICINIT, shadow
  157. .getEnclosingType().getName()), getSourceLocation(), shadow.getSourceLocation());
  158. return false;
  159. } else {
  160. // System.err.println(getSignature().getReturnType() +
  161. // " from " + shadow.getReturnType());
  162. if (getSignature().getReturnType().equals(UnresolvedType.VOID)) {
  163. if (!shadow.getReturnType().equals(UnresolvedType.VOID)) {
  164. String s = shadow.toString();
  165. String s2 = WeaverMessages.format(WeaverMessages.NON_VOID_RETURN, s);
  166. world.showMessage(IMessage.ERROR, s2, getSourceLocation(), shadow.getSourceLocation());
  167. return false;
  168. }
  169. } else if (getSignature().getReturnType().equals(UnresolvedType.OBJECT)) {
  170. return true;
  171. } else {
  172. ResolvedType shadowReturnType = shadow.getReturnType().resolve(world);
  173. ResolvedType adviceReturnType = getSignature().getGenericReturnType().resolve(world);
  174. if (shadowReturnType.isParameterizedType() && adviceReturnType.isRawType()) { // Set
  175. // <
  176. // Integer
  177. // >
  178. // and
  179. // Set
  180. ResolvedType shadowReturnGenericType = shadowReturnType.getGenericType(); // Set
  181. ResolvedType adviceReturnGenericType = adviceReturnType.getGenericType(); // Set
  182. if (shadowReturnGenericType.isAssignableFrom(adviceReturnGenericType)
  183. && world.getLint().uncheckedAdviceConversion.isEnabled()) {
  184. world.getLint().uncheckedAdviceConversion.signal(
  185. new String[] { shadow.toString(), shadowReturnType.getName(), adviceReturnType.getName() },
  186. shadow.getSourceLocation(), new ISourceLocation[] { getSourceLocation() });
  187. }
  188. } else if (!shadowReturnType.isAssignableFrom(adviceReturnType)) {
  189. // System.err.println(this + ", " + sourceContext +
  190. // ", " + start);
  191. world.showMessage(IMessage.ERROR,
  192. WeaverMessages.format(WeaverMessages.INCOMPATIBLE_RETURN_TYPE, shadow), getSourceLocation(),
  193. shadow.getSourceLocation());
  194. return false;
  195. }
  196. }
  197. }
  198. }
  199. return true;
  200. } else {
  201. return false;
  202. }
  203. }
  204. /**
  205. * In after returning advice if we are binding the extra parameter to a parameterized type we may not be able to do a type-safe
  206. * conversion.
  207. *
  208. * @param resolvedExtraParameterType the type in the after returning declaration
  209. * @param shadowReturnType the type at the shadow
  210. * @param world
  211. */
  212. private void maybeIssueUncheckedMatchWarning(ResolvedType afterReturningType, ResolvedType shadowReturnType, Shadow shadow,
  213. World world) {
  214. boolean inDoubt = !afterReturningType.isAssignableFrom(shadowReturnType);
  215. if (inDoubt && world.getLint().uncheckedArgument.isEnabled()) {
  216. String uncheckedMatchWith = afterReturningType.getSimpleBaseName();
  217. if (shadowReturnType.isParameterizedType() && (shadowReturnType.getRawType() == afterReturningType.getRawType())) {
  218. uncheckedMatchWith = shadowReturnType.getSimpleName();
  219. }
  220. if (!Utils.isSuppressing(getSignature().getAnnotations(), "uncheckedArgument")) {
  221. world.getLint().uncheckedArgument.signal(new String[] { afterReturningType.getSimpleName(), uncheckedMatchWith,
  222. afterReturningType.getSimpleBaseName(), shadow.toResolvedString(world) }, getSourceLocation(),
  223. new ISourceLocation[] { shadow.getSourceLocation() });
  224. }
  225. }
  226. }
  227. // ----
  228. public AdviceKind getKind() {
  229. return kind;
  230. }
  231. public Member getSignature() {
  232. return signature;
  233. }
  234. public boolean hasExtraParameter() {
  235. return (getExtraParameterFlags() & ExtraArgument) != 0;
  236. }
  237. protected int getExtraParameterFlags() {
  238. return attribute.getExtraParameterFlags();
  239. }
  240. protected int getExtraParameterCount() {
  241. return countOnes(getExtraParameterFlags() & ParameterMask);
  242. }
  243. public UnresolvedType[] getBindingParameterTypes() {
  244. return bindingParameterTypes;
  245. }
  246. public void setBindingParameterTypes(UnresolvedType[] types) {
  247. bindingParameterTypes = types;
  248. }
  249. public static int countOnes(int bits) {
  250. int ret = 0;
  251. while (bits != 0) {
  252. if ((bits & 1) != 0) {
  253. ret += 1;
  254. }
  255. bits = bits >> 1;
  256. }
  257. return ret;
  258. }
  259. public int getBaseParameterCount() {
  260. return getSignature().getParameterTypes().length - getExtraParameterCount();
  261. }
  262. public String[] getBaseParameterNames(World world) {
  263. String[] allNames = getSignature().getParameterNames(world);
  264. int extras = getExtraParameterCount();
  265. if (extras == 0) {
  266. return allNames;
  267. }
  268. String[] result = new String[getBaseParameterCount()];
  269. for (int i = 0; i < result.length; i++) {
  270. result[i] = allNames[i];
  271. }
  272. return result;
  273. }
  274. /**
  275. * Return the type of the 'extra argument'. For either after returning or after throwing advice, the extra argument will be the
  276. * returned value or the thrown exception respectively. With annotation style the user may declare the parameters in any order,
  277. * whereas for code style they are in a well defined order. So there is some extra complexity in here for annotation style that
  278. * looks up the correct parameter in the advice signature by name, based on the name specified in the annotation. If this fails
  279. * then we 'fallback' to guessing at positions, where the extra argument is presumed to come at the end.
  280. *
  281. * @return the type of the extraParameter
  282. */
  283. public UnresolvedType getExtraParameterType() {
  284. if (!hasExtraParameter()) {
  285. return ResolvedType.MISSING;
  286. }
  287. if (signature instanceof ResolvedMember) {
  288. ResolvedMember method = (ResolvedMember) signature;
  289. UnresolvedType[] parameterTypes = method.getGenericParameterTypes();
  290. if (getConcreteAspect().isAnnotationStyleAspect()) {
  291. // Examine the annotation to determine the parameter name then look it up in the parameters for the method
  292. String[] pnames = method.getParameterNames();
  293. if (pnames != null) {
  294. // It is worth attempting to look up the correct parameter
  295. AnnotationAJ[] annos = getSignature().getAnnotations();
  296. String parameterToLookup = null;
  297. if (annos != null && (getKind() == AdviceKind.AfterThrowing || getKind() == AdviceKind.AfterReturning)) {
  298. for (int i = 0; i < annos.length && parameterToLookup == null; i++) {
  299. AnnotationAJ anno = annos[i];
  300. String annosig = anno.getType().getSignature();
  301. if (annosig.equals("Lorg/aspectj/lang/annotation/AfterThrowing;")) {
  302. // the 'throwing' value in the annotation will name the parameter to bind to
  303. parameterToLookup = anno.getStringFormOfValue("throwing");
  304. } else if (annosig.equals("Lorg/aspectj/lang/annotation/AfterReturning;")) {
  305. // the 'returning' value in the annotation will name the parameter to bind to
  306. parameterToLookup = anno.getStringFormOfValue("returning");
  307. }
  308. }
  309. }
  310. if (parameterToLookup != null) {
  311. for (int i = 0; i < pnames.length; i++) {
  312. if (pnames[i].equals(parameterToLookup)) {
  313. return parameterTypes[i];
  314. }
  315. }
  316. }
  317. }
  318. // Don't think this code works so well... why isnt it getBaseParameterCount()-1 ?
  319. int baseParmCnt = getBaseParameterCount();
  320. // bug 122742 - if we're an annotation style aspect then one
  321. // of the extra parameters could be JoinPoint which we want
  322. // to ignore
  323. while ((baseParmCnt + 1 < parameterTypes.length)
  324. && (parameterTypes[baseParmCnt].equals(AjcMemberMaker.TYPEX_JOINPOINT)
  325. || parameterTypes[baseParmCnt].equals(AjcMemberMaker.TYPEX_STATICJOINPOINT) || parameterTypes[baseParmCnt]
  326. .equals(AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT))) {
  327. baseParmCnt++;
  328. }
  329. return parameterTypes[baseParmCnt];
  330. } else {
  331. return parameterTypes[getBaseParameterCount()];
  332. }
  333. } else {
  334. return signature.getParameterTypes()[getBaseParameterCount()];
  335. }
  336. }
  337. public UnresolvedType getDeclaringAspect() {
  338. return getOriginalSignature().getDeclaringType();
  339. }
  340. protected Member getOriginalSignature() {
  341. return signature;
  342. }
  343. protected String extraParametersToString() {
  344. if (getExtraParameterFlags() == 0) {
  345. return "";
  346. } else {
  347. return "(extraFlags: " + getExtraParameterFlags() + ")";
  348. }
  349. }
  350. @Override
  351. public Pointcut getPointcut() {
  352. return pointcut;
  353. }
  354. // ----
  355. /**
  356. * @param fromType is guaranteed to be a non-abstract aspect
  357. * @param clause has been concretized at a higher level
  358. */
  359. @Override
  360. public ShadowMunger concretize(ResolvedType fromType, World world, PerClause clause) {
  361. // assert !fromType.isAbstract();
  362. Pointcut p = pointcut.concretize(fromType, getDeclaringType(), signature.getArity(), this);
  363. if (clause != null) {
  364. Pointcut oldP = p;
  365. p = new AndPointcut(clause, p);
  366. p.copyLocationFrom(oldP);
  367. p.state = Pointcut.CONCRETE;
  368. // FIXME ? ATAJ copy unbound bindings to ignore
  369. p.m_ignoreUnboundBindingForNames = oldP.m_ignoreUnboundBindingForNames;
  370. }
  371. Advice munger = world.getWeavingSupport().createAdviceMunger(attribute, p, signature, fromType);
  372. munger.bindingParameterTypes = bindingParameterTypes;
  373. munger.setDeclaringType(getDeclaringType());
  374. // System.err.println("concretizing here " + p + " with clause " +
  375. // clause);
  376. return munger;
  377. }
  378. // ---- from object
  379. @Override
  380. public String toString() {
  381. StringBuffer sb = new StringBuffer();
  382. sb.append("(").append(getKind()).append(extraParametersToString());
  383. sb.append(": ").append(pointcut).append("->").append(signature).append(")");
  384. return sb.toString();
  385. // return "("
  386. // + getKind()
  387. // + extraParametersToString()
  388. // + ": "
  389. // + pointcut
  390. // + "->"
  391. // + signature
  392. // + ")";
  393. }
  394. // XXX this perhaps ought to take account of the other fields in advice ...
  395. @Override
  396. public boolean equals(Object other) {
  397. if (!(other instanceof Advice)) {
  398. return false;
  399. }
  400. Advice o = (Advice) other;
  401. return o.kind.equals(kind) && ((o.pointcut == null) ? (pointcut == null) : o.pointcut.equals(pointcut))
  402. && ((o.signature == null) ? (signature == null) : o.signature.equals(signature));
  403. // && (AsmManager.getDefault().getHandleProvider().dependsOnLocation() ? ((o.getSourceLocation() == null) ?
  404. // (getSourceLocation() == null)
  405. // : o.getSourceLocation().equals(getSourceLocation()))
  406. // : true) // pr134471 - remove when handles are improved
  407. // // to be independent of location
  408. // ;
  409. }
  410. private volatile int hashCode = 0;
  411. @Override
  412. public int hashCode() {
  413. if (hashCode == 0) {
  414. int result = 17;
  415. result = 37 * result + kind.hashCode();
  416. result = 37 * result + ((pointcut == null) ? 0 : pointcut.hashCode());
  417. result = 37 * result + ((signature == null) ? 0 : signature.hashCode());
  418. hashCode = result;
  419. }
  420. return hashCode;
  421. }
  422. // ---- fields
  423. public static final int ExtraArgument = 0x01;
  424. public static final int ThisJoinPoint = 0x02;
  425. public static final int ThisJoinPointStaticPart = 0x04;
  426. public static final int ThisEnclosingJoinPointStaticPart = 0x08;
  427. public static final int ParameterMask = 0x0f;
  428. // For an if pointcut, this indicates it is hard wired to access a constant of either true or false
  429. public static final int ConstantReference = 0x10;
  430. // When the above flag is set, this indicates whether it is true or false
  431. public static final int ConstantValue = 0x20;
  432. // public static final int CanInline = 0x40; // didnt appear to be getting used
  433. public static final int ThisAspectInstance = 0x40;
  434. // cant use 0x80 ! the value is written out as a byte and -1 has special meaning (-1 is 0x80...)
  435. // for testing only
  436. public void setLexicalPosition(int lexicalPosition) {
  437. start = lexicalPosition;
  438. }
  439. public boolean isAnnotationStyle() {
  440. return isAnnotationStyle;
  441. }
  442. public ResolvedType getConcreteAspect() {
  443. return concreteAspect;
  444. }
  445. public boolean hasMatchedSomething() {
  446. return hasMatchedAtLeastOnce;
  447. }
  448. public void setHasMatchedSomething(boolean hasMatchedSomething) {
  449. hasMatchedAtLeastOnce = hasMatchedSomething;
  450. }
  451. public abstract boolean hasDynamicTests();
  452. }