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.

ConcreteAspectCodeGen.java 37KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  1. /*******************************************************************************
  2. * Copyright (c) 2005 Contributors.
  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://eclipse.org/legal/epl-v10.html
  8. *
  9. * Contributors:
  10. * Alexandre Vasseur initial implementation
  11. *******************************************************************************/
  12. package org.aspectj.weaver.loadtime;
  13. import java.lang.reflect.Modifier;
  14. import java.util.ArrayList;
  15. import java.util.Collection;
  16. import java.util.Collections;
  17. import java.util.HashMap;
  18. import java.util.Iterator;
  19. import java.util.List;
  20. import java.util.Map;
  21. import org.aspectj.apache.bcel.Constants;
  22. import org.aspectj.apache.bcel.classfile.ConstantPool;
  23. import org.aspectj.apache.bcel.classfile.JavaClass;
  24. import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen;
  25. import org.aspectj.apache.bcel.classfile.annotation.ClassElementValue;
  26. import org.aspectj.apache.bcel.classfile.annotation.ElementValue;
  27. import org.aspectj.apache.bcel.classfile.annotation.NameValuePair;
  28. import org.aspectj.apache.bcel.classfile.annotation.SimpleElementValue;
  29. import org.aspectj.apache.bcel.generic.FieldGen;
  30. import org.aspectj.apache.bcel.generic.InstructionConstants;
  31. import org.aspectj.apache.bcel.generic.InstructionFactory;
  32. import org.aspectj.apache.bcel.generic.InstructionHandle;
  33. import org.aspectj.apache.bcel.generic.InstructionList;
  34. import org.aspectj.apache.bcel.generic.LocalVariableTag;
  35. import org.aspectj.apache.bcel.generic.ObjectType;
  36. import org.aspectj.apache.bcel.generic.Type;
  37. import org.aspectj.bridge.IMessage;
  38. import org.aspectj.bridge.Message;
  39. import org.aspectj.weaver.AjAttribute;
  40. import org.aspectj.weaver.AnnotationAJ;
  41. import org.aspectj.weaver.GeneratedReferenceTypeDelegate;
  42. import org.aspectj.weaver.ReferenceType;
  43. import org.aspectj.weaver.ResolvedMember;
  44. import org.aspectj.weaver.ResolvedType;
  45. import org.aspectj.weaver.UnresolvedType;
  46. import org.aspectj.weaver.World;
  47. import org.aspectj.weaver.bcel.BcelAnnotation;
  48. import org.aspectj.weaver.bcel.BcelPerClauseAspectAdder;
  49. import org.aspectj.weaver.bcel.BcelWorld;
  50. import org.aspectj.weaver.bcel.LazyClassGen;
  51. import org.aspectj.weaver.bcel.LazyMethodGen;
  52. import org.aspectj.weaver.loadtime.definition.Definition;
  53. import org.aspectj.weaver.loadtime.definition.Definition.AdviceKind;
  54. import org.aspectj.weaver.loadtime.definition.Definition.DeclareAnnotationKind;
  55. import org.aspectj.weaver.loadtime.definition.Definition.PointcutAndAdvice;
  56. import org.aspectj.weaver.patterns.BasicTokenSource;
  57. import org.aspectj.weaver.patterns.DeclareAnnotation;
  58. import org.aspectj.weaver.patterns.ISignaturePattern;
  59. import org.aspectj.weaver.patterns.ITokenSource;
  60. import org.aspectj.weaver.patterns.PatternParser;
  61. import org.aspectj.weaver.patterns.PerClause;
  62. import org.aspectj.weaver.patterns.TypePattern;
  63. /**
  64. * Generates bytecode for concrete-aspect.
  65. * <p>
  66. * The concrete aspect is generated annotation style aspect (so traditional Java constructs annotated with our AspectJ annotations).
  67. * As it is built during aop.xml definitions registration we perform the type munging for perclause, ie. aspectOf() artifact
  68. * directly, instead of waiting for it to go thru the weaver (that we are in the middle of configuring).
  69. *
  70. * @author Alexandre Vasseur
  71. * @author Andy Clement
  72. */
  73. public class ConcreteAspectCodeGen {
  74. private final static String[] EMPTY_STRINGS = new String[0];
  75. private final static Type[] EMPTY_TYPES = new Type[0];
  76. /**
  77. * Concrete aspect definition we build for
  78. */
  79. private final Definition.ConcreteAspect concreteAspect;
  80. /**
  81. * World for which we build for
  82. */
  83. private final World world;
  84. /**
  85. * Set to true when all is checks are verified
  86. */
  87. private boolean isValid = false;
  88. /**
  89. * The parent aspect, not concretized
  90. */
  91. private ResolvedType parent;
  92. /**
  93. * Aspect perClause, used for direct munging of aspectOf artifacts
  94. */
  95. private PerClause perclause;
  96. /**
  97. * Bytecode for the generated class
  98. */
  99. private byte[] bytes;
  100. /**
  101. * Create a new generator for a concrete aspect
  102. *
  103. * @param concreteAspect the aspect definition
  104. * @param world the related world (for type resolution, etc)
  105. */
  106. ConcreteAspectCodeGen(Definition.ConcreteAspect concreteAspect, World world) {
  107. this.concreteAspect = concreteAspect;
  108. this.world = world;
  109. }
  110. /**
  111. * Checks that concrete aspect is valid.
  112. *
  113. * @return true if ok, false otherwise
  114. */
  115. public boolean validate() {
  116. if (!(world instanceof BcelWorld)) {
  117. reportError("Internal error: world must be of type BcelWorld");
  118. return false;
  119. }
  120. // name must be undefined so far
  121. // TODO only convert the name to signature once, probably earlier than this
  122. ResolvedType current = world.lookupBySignature(UnresolvedType.forName(concreteAspect.name).getSignature());
  123. if (current != null && !current.isMissing()) {
  124. reportError("Attempt to concretize but chosen aspect name already defined: " + stringify());
  125. return false;
  126. }
  127. if (concreteAspect.pointcutsAndAdvice.size() != 0) {
  128. isValid = true;
  129. return true;
  130. }
  131. if (concreteAspect.declareAnnotations.size()!=0) {
  132. isValid = true;
  133. return true;
  134. }
  135. // it can happen that extends is null, for precedence only declaration
  136. if (concreteAspect.extend == null && concreteAspect.precedence != null) {
  137. if (concreteAspect.pointcuts.isEmpty()) {
  138. isValid = true;
  139. // m_perClause = new PerSingleton();
  140. parent = null;
  141. return true;// no need to checks more in that special case
  142. } else {
  143. reportError("Attempt to use nested pointcuts without extends clause: " + stringify());
  144. return false;
  145. }
  146. }
  147. String parentAspectName = concreteAspect.extend;
  148. if (parentAspectName.indexOf("<") != -1) {
  149. // yikes, generic parent
  150. parent = world.resolve(UnresolvedType.forName(parentAspectName), true);
  151. if (parent.isMissing()) {
  152. reportError("Unable to resolve type reference: " + stringify());
  153. return false;
  154. }
  155. if (parent.isParameterizedType()) {
  156. UnresolvedType[] typeParameters = parent.getTypeParameters();
  157. for (int i = 0; i < typeParameters.length; i++) {
  158. UnresolvedType typeParameter = typeParameters[i];
  159. if (typeParameter instanceof ResolvedType && ((ResolvedType) typeParameter).isMissing()) {
  160. reportError("Unablet to resolve type parameter '" + typeParameter.getName() + "' from " + stringify());
  161. return false;
  162. }
  163. }
  164. }
  165. } else {
  166. parent = world.resolve(concreteAspect.extend, true);
  167. }
  168. // handle inner classes
  169. if (parent.isMissing()) {
  170. // fallback on inner class lookup mechanism
  171. String fixedName = concreteAspect.extend;
  172. int hasDot = fixedName.lastIndexOf('.');
  173. while (hasDot > 0) {
  174. char[] fixedNameChars = fixedName.toCharArray();
  175. fixedNameChars[hasDot] = '$';
  176. fixedName = new String(fixedNameChars);
  177. hasDot = fixedName.lastIndexOf('.');
  178. parent = world.resolve(UnresolvedType.forName(fixedName), true);
  179. if (!parent.isMissing()) {
  180. break;
  181. }
  182. }
  183. }
  184. if (parent.isMissing()) {
  185. reportError("Cannot find parent aspect for: " + stringify());
  186. return false;
  187. }
  188. // extends must be abstract (allow for special case of Object where just using aspect for deows)
  189. if (!(parent.isAbstract() || parent.equals(ResolvedType.OBJECT))) {
  190. reportError("Attempt to concretize a non-abstract aspect: " + stringify());
  191. return false;
  192. }
  193. // m_parent must be aspect (allow for special case of Object where just using aspect for deows)
  194. if (!(parent.isAspect() || parent.equals(ResolvedType.OBJECT))) {
  195. reportError("Attempt to concretize a non aspect: " + stringify());
  196. return false;
  197. }
  198. // must have all abstractions defined
  199. List<String> elligibleAbstractions = new ArrayList<String>();
  200. Collection<ResolvedMember> abstractMethods = getOutstandingAbstractMethods(parent);
  201. for (ResolvedMember method : abstractMethods) {
  202. if ("()V".equals(method.getSignature())) {
  203. String n = method.getName();
  204. // Allow for the abstract pointcut being from a code style
  205. // aspect compiled with -1.5 (see test for 128744)
  206. if (n.startsWith("ajc$pointcut")) {
  207. n = n.substring(14);
  208. n = n.substring(0, n.indexOf("$"));
  209. elligibleAbstractions.add(n);
  210. } else if (hasPointcutAnnotation(method)) {
  211. elligibleAbstractions.add(method.getName());
  212. } else {
  213. // error, an outstanding abstract method that can't be
  214. // concretized in XML
  215. reportError("Abstract method '" + method.toString() + "' cannot be concretized in XML: " + stringify());
  216. return false;
  217. }
  218. } else {
  219. if (method.getName().startsWith("ajc$pointcut") || hasPointcutAnnotation(method)) {
  220. // it may be a pointcut but it doesn't meet the requirements for XML concretization
  221. reportError("Abstract method '"
  222. + method.toString()
  223. + "' cannot be concretized as a pointcut (illegal signature, must have no arguments, must return void): "
  224. + stringify());
  225. return false;
  226. } else {
  227. // error, an outstanding abstract method that can't be
  228. // concretized in XML
  229. reportError("Abstract method '" + method.toString() + "' cannot be concretized in XML: " + stringify());
  230. return false;
  231. }
  232. }
  233. }
  234. List<String> pointcutNames = new ArrayList<String>();
  235. for (Definition.Pointcut abstractPc : concreteAspect.pointcuts) {
  236. pointcutNames.add(abstractPc.name);
  237. }
  238. for (String elligiblePc : elligibleAbstractions) {
  239. if (!pointcutNames.contains(elligiblePc)) {
  240. reportError("Abstract pointcut '" + elligiblePc + "' not configured: " + stringify());
  241. return false;
  242. }
  243. }
  244. if (concreteAspect.perclause != null) {
  245. String perclauseString = concreteAspect.perclause;
  246. if (perclauseString.startsWith("persingleton")) {
  247. } else if (perclauseString.startsWith("percflow")) {
  248. } else if (perclauseString.startsWith("pertypewithin")) {
  249. } else if (perclauseString.startsWith("perthis")) {
  250. } else if (perclauseString.startsWith("pertarget")) {
  251. } else if (perclauseString.startsWith("percflowbelow")) {
  252. } else {
  253. reportError("Unrecognized per clause specified " + stringify());
  254. return false;
  255. }
  256. }
  257. isValid = true;
  258. return isValid;
  259. }
  260. private Collection<ResolvedMember> getOutstandingAbstractMethods(ResolvedType type) {
  261. Map<String, ResolvedMember> collector = new HashMap<String, ResolvedMember>();
  262. // let's get to the top of the hierarchy and then walk down ...
  263. // recording abstract methods then removing
  264. // them if they get defined further down the hierarchy
  265. getOutstandingAbstractMethodsHelper(type, collector);
  266. return collector.values();
  267. }
  268. // We are trying to determine abstract methods left over at the bottom of a
  269. // hierarchy that have not been concretized.
  270. private void getOutstandingAbstractMethodsHelper(ResolvedType type, Map<String, ResolvedMember> collector) {
  271. if (type == null) {
  272. return;
  273. }
  274. // Get to the top
  275. if (!type.equals(ResolvedType.OBJECT)) {
  276. if (type.getSuperclass() != null) {
  277. getOutstandingAbstractMethodsHelper(type.getSuperclass(), collector);
  278. }
  279. }
  280. ResolvedMember[] rms = type.getDeclaredMethods();
  281. if (rms != null) {
  282. for (int i = 0; i < rms.length; i++) {
  283. ResolvedMember member = rms[i];
  284. String key = member.getName() + member.getSignature();
  285. if (member.isAbstract()) {
  286. collector.put(key, member);
  287. } else {
  288. collector.remove(key);
  289. }
  290. }
  291. }
  292. }
  293. /**
  294. * Rebuild the XML snip that defines this concrete aspect, for log error purpose
  295. *
  296. * @return string repr.
  297. */
  298. private String stringify() {
  299. StringBuffer sb = new StringBuffer("<concrete-aspect name='");
  300. sb.append(concreteAspect.name);
  301. sb.append("' extends='");
  302. sb.append(concreteAspect.extend);
  303. sb.append("' perclause='");
  304. sb.append(concreteAspect.perclause);
  305. sb.append("'/> in aop.xml");
  306. // TODO needs the extra state from the definition (concretized pointcuts and advice definitions)
  307. return sb.toString();
  308. }
  309. private boolean hasPointcutAnnotation(ResolvedMember member) {
  310. AnnotationAJ[] as = member.getAnnotations();
  311. if (as == null || as.length == 0) {
  312. return false;
  313. }
  314. for (int i = 0; i < as.length; i++) {
  315. if (as[i].getTypeSignature().equals("Lorg/aspectj/lang/annotation/Pointcut;")) {
  316. return true;
  317. }
  318. }
  319. return false;
  320. }
  321. public String getClassName() {
  322. return concreteAspect.name;
  323. }
  324. /**
  325. * @return the bytecode for the concrete aspect
  326. */
  327. public byte[] getBytes() {
  328. if (!isValid) {
  329. throw new RuntimeException("Must validate first");
  330. }
  331. if (bytes != null) {
  332. return bytes;
  333. }
  334. PerClause.Kind perclauseKind = PerClause.SINGLETON;
  335. PerClause parentPerClause = (parent != null ? parent.getPerClause() : null);
  336. if (parentPerClause != null) {
  337. perclauseKind = parentPerClause.getKind();
  338. }
  339. String perclauseString = null;
  340. if (concreteAspect.perclause != null) {
  341. perclauseString = concreteAspect.perclause;
  342. if (perclauseString.startsWith("persingleton")) {
  343. perclauseKind = PerClause.SINGLETON;
  344. } else if (perclauseString.startsWith("percflow")) {
  345. perclauseKind = PerClause.PERCFLOW;
  346. } else if (perclauseString.startsWith("pertypewithin")) {
  347. perclauseKind = PerClause.PERTYPEWITHIN;
  348. } else if (perclauseString.startsWith("perthis")) {
  349. perclauseKind = PerClause.PEROBJECT;
  350. } else if (perclauseString.startsWith("pertarget")) {
  351. perclauseKind = PerClause.PEROBJECT;
  352. } else if (perclauseString.startsWith("percflowbelow")) {
  353. perclauseKind = PerClause.PERCFLOW;
  354. }
  355. }
  356. // @Aspect //inherit clause from m_parent
  357. // @DeclarePrecedence("....") // if any
  358. // public class xxxName [extends xxxExtends] {
  359. // [@Pointcut(xxxExpression-n)
  360. // public void xxxName-n() {}]
  361. // }
  362. String parentName = "java/lang/Object";
  363. if (parent != null) {
  364. if (parent.isParameterizedType()) {
  365. parentName = parent.getGenericType().getName().replace('.', '/');
  366. } else {
  367. parentName = parent.getName().replace('.', '/');
  368. }
  369. }
  370. // @Aspect public class ...
  371. // TODO AV - we could point to the aop.xml that defines it and use JSR-45
  372. LazyClassGen cg = new LazyClassGen(concreteAspect.name.replace('.', '/'), parentName, null, Modifier.PUBLIC
  373. + Constants.ACC_SUPER, EMPTY_STRINGS, world);
  374. if (parent != null && parent.isParameterizedType()) {
  375. cg.setSuperClass(parent);
  376. }
  377. if (perclauseString == null) {
  378. AnnotationGen ag = new AnnotationGen(new ObjectType("org/aspectj/lang/annotation/Aspect"),
  379. Collections.<NameValuePair> emptyList(), true, cg.getConstantPool());
  380. cg.addAnnotation(ag);
  381. } else {
  382. // List elems = new ArrayList();
  383. List<NameValuePair> elems = new ArrayList<NameValuePair>();
  384. elems.add(new NameValuePair("value",
  385. new SimpleElementValue(ElementValue.STRING, cg.getConstantPool(), perclauseString), cg.getConstantPool()));
  386. AnnotationGen ag = new AnnotationGen(new ObjectType("org/aspectj/lang/annotation/Aspect"), elems, true,
  387. cg.getConstantPool());
  388. cg.addAnnotation(ag);
  389. }
  390. if (concreteAspect.precedence != null) {
  391. SimpleElementValue svg = new SimpleElementValue(ElementValue.STRING, cg.getConstantPool(), concreteAspect.precedence);
  392. List<NameValuePair> elems = new ArrayList<NameValuePair>();
  393. elems.add(new NameValuePair("value", svg, cg.getConstantPool()));
  394. AnnotationGen agprec = new AnnotationGen(new ObjectType("org/aspectj/lang/annotation/DeclarePrecedence"), elems, true,
  395. cg.getConstantPool());
  396. cg.addAnnotation(agprec);
  397. }
  398. // default constructor
  399. LazyMethodGen init = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, "<init>", EMPTY_TYPES, EMPTY_STRINGS, cg);
  400. InstructionList cbody = init.getBody();
  401. cbody.append(InstructionConstants.ALOAD_0);
  402. cbody.append(cg.getFactory().createInvoke(parentName, "<init>", Type.VOID, EMPTY_TYPES, Constants.INVOKESPECIAL));
  403. cbody.append(InstructionConstants.RETURN);
  404. cg.addMethodGen(init);
  405. for (Iterator<Definition.Pointcut> it = concreteAspect.pointcuts.iterator(); it.hasNext();) {
  406. Definition.Pointcut abstractPc = (Definition.Pointcut) it.next();
  407. // TODO AV - respect visibility instead of opening up as public?
  408. LazyMethodGen mg = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, abstractPc.name, EMPTY_TYPES, EMPTY_STRINGS, cg);
  409. SimpleElementValue svg = new SimpleElementValue(ElementValue.STRING, cg.getConstantPool(), abstractPc.expression);
  410. List<NameValuePair> elems = new ArrayList<NameValuePair>();
  411. elems.add(new NameValuePair("value", svg, cg.getConstantPool()));
  412. AnnotationGen mag = new AnnotationGen(new ObjectType("org/aspectj/lang/annotation/Pointcut"), elems, true,
  413. cg.getConstantPool());
  414. AnnotationAJ max = new BcelAnnotation(mag, world);
  415. mg.addAnnotation(max);
  416. InstructionList body = mg.getBody();
  417. body.append(InstructionConstants.RETURN);
  418. cg.addMethodGen(mg);
  419. }
  420. // Construct any defined declare error/warnings
  421. if (concreteAspect.deows.size() > 0) {
  422. int counter = 1;
  423. for (Definition.DeclareErrorOrWarning deow : concreteAspect.deows) {
  424. // Building this:
  425. // @DeclareWarning("call(* javax.sql..*(..)) && !within(org.xyz.daos..*)")
  426. // static final String aMessage = "Only DAOs should be calling JDBC.";
  427. FieldGen field = new FieldGen(Modifier.FINAL, ObjectType.STRING, "rule" + (counter++), cg.getConstantPool());
  428. SimpleElementValue svg = new SimpleElementValue(ElementValue.STRING, cg.getConstantPool(), deow.pointcut);
  429. List<NameValuePair> elems = new ArrayList<NameValuePair>();
  430. elems.add(new NameValuePair("value", svg, cg.getConstantPool()));
  431. AnnotationGen mag = new AnnotationGen(new ObjectType("org/aspectj/lang/annotation/Declare"
  432. + (deow.isError ? "Error" : "Warning")), elems, true, cg.getConstantPool());
  433. field.addAnnotation(mag);
  434. field.setValue(deow.message);
  435. cg.addField(field, null);
  436. }
  437. }
  438. if (concreteAspect.pointcutsAndAdvice.size() > 0) {
  439. int adviceCounter = 1;
  440. for (PointcutAndAdvice paa : concreteAspect.pointcutsAndAdvice) {
  441. generateAdviceMethod(paa, adviceCounter, cg);
  442. adviceCounter++;
  443. }
  444. }
  445. if (concreteAspect.declareAnnotations.size()>0) {
  446. int decCounter = 1;
  447. for (Definition.DeclareAnnotation da: concreteAspect.declareAnnotations) {
  448. generateDeclareAnnotation(da,decCounter++,cg);
  449. }
  450. }
  451. // handle the perClause
  452. ReferenceType rt = new ReferenceType(ResolvedType.forName(concreteAspect.name).getSignature(), world);
  453. GeneratedReferenceTypeDelegate grtd = new GeneratedReferenceTypeDelegate(rt);
  454. grtd.setSuperclass(parent);
  455. rt.setDelegate(grtd);
  456. BcelPerClauseAspectAdder perClauseMunger = new BcelPerClauseAspectAdder(rt, perclauseKind);
  457. perClauseMunger.forceMunge(cg, false);
  458. // TODO AV - unsafe cast
  459. // register the fresh new class into the world repository as it does not
  460. // exist on the classpath anywhere
  461. JavaClass jc = cg.getJavaClass((BcelWorld) world);
  462. ((BcelWorld) world).addSourceObjectType(jc, true);
  463. bytes = jc.getBytes();
  464. return bytes;
  465. }
  466. /**
  467. * The DeclareAnnotation object encapsulates an method/field/type descriptor and an annotation. This uses a DeclareAnnotation object
  468. * captured from the XML (something like '<declare-annotation field="* field1(..)" annotation="@Annot(a='a',fred=false,'abc')"/>')
  469. * and builds the same construct that would have existed if the code style variant was used. This involves creating a member upon
  470. * which to hang the real annotation and then creating a classfile level attribute indicating a declare annotation is present
  471. * (that includes the signature pattern and a pointer to the real member holding the annotation).
  472. *
  473. */
  474. private void generateDeclareAnnotation(Definition.DeclareAnnotation da, int decCounter, LazyClassGen cg) {
  475. // Here is an example member from a code style declare annotation:
  476. //void ajc$declare_at_method_1();
  477. // RuntimeInvisibleAnnotations: length = 0x6
  478. // 00 01 00 1B 00 00
  479. // RuntimeVisibleAnnotations: length = 0x15
  480. // 00 01 00 1D 00 03 00 1E 73 00 1F 00 20 73 00 21
  481. // 00 22 73 00 23
  482. // org.aspectj.weaver.MethodDeclarationLineNumber: length = 0x8
  483. // 00 00 00 02 00 00 00 16
  484. // org.aspectj.weaver.AjSynthetic: length = 0x
  485. //
  486. // Code:
  487. // Stack=0, Locals=1, Args_size=1
  488. // 0: return
  489. // and at the class level a Declare attribute:
  490. // org.aspectj.weaver.Declare: length = 0x51
  491. // 05 00 00 00 03 01 00 05 40 41 6E 6E 6F 01 00 17
  492. // 61 6A 63 24 64 65 63 6C 61 72 65 5F 61 74 5F 6D
  493. // 65 74 68 6F 64 5F 31 01 01 00 00 00 00 05 05 00
  494. // 08 73 61 79 48 65 6C 6C 6F 00 01 04 00 00 00 00
  495. // 07 00 00 00 27 00 00 00 34 00 00 00 16 00 00 00
  496. // 3C
  497. AnnotationAJ constructedAnnotation = buildDeclareAnnotation_actualAnnotation(cg, da);
  498. if (constructedAnnotation==null) {
  499. return; // error occurred (and was reported), do not continue
  500. }
  501. String nameComponent = da.declareAnnotationKind.name().toLowerCase();
  502. String declareName = new StringBuilder("ajc$declare_at_").append(nameComponent).append("_").append(decCounter).toString();
  503. LazyMethodGen declareMethod = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, declareName, Type.NO_ARGS, EMPTY_STRINGS, cg);
  504. InstructionList declareMethodBody = declareMethod.getBody();
  505. declareMethodBody.append(InstructionFactory.RETURN);
  506. declareMethod.addAnnotation(constructedAnnotation);
  507. DeclareAnnotation deca = null;
  508. ITokenSource tokenSource = BasicTokenSource.makeTokenSource(da.pattern,null);
  509. PatternParser pp = new PatternParser(tokenSource);
  510. if (da.declareAnnotationKind==DeclareAnnotationKind.Method || da.declareAnnotationKind==DeclareAnnotationKind.Field) {
  511. ISignaturePattern isp = (da.declareAnnotationKind==DeclareAnnotationKind.Method?pp.parseCompoundMethodOrConstructorSignaturePattern(true):pp.parseCompoundFieldSignaturePattern());
  512. deca = new DeclareAnnotation(da.declareAnnotationKind==DeclareAnnotationKind.Method?DeclareAnnotation.AT_METHOD:DeclareAnnotation.AT_FIELD, isp);
  513. } else if (da.declareAnnotationKind==DeclareAnnotationKind.Type) {
  514. TypePattern tp = pp.parseTypePattern();
  515. deca = new DeclareAnnotation(DeclareAnnotation.AT_TYPE,tp);
  516. }
  517. deca.setAnnotationMethod(declareName);
  518. deca.setAnnotationString(da.annotation);
  519. AjAttribute attribute = new AjAttribute.DeclareAttribute(deca);
  520. cg.addAttribute(attribute);
  521. cg.addMethodGen(declareMethod);
  522. }
  523. /**
  524. * Construct the annotation that the declare wants to add to the target.
  525. */
  526. private AnnotationAJ buildDeclareAnnotation_actualAnnotation(LazyClassGen cg, Definition.DeclareAnnotation da) {
  527. AnnotationGen anno = buildAnnotationFromString(cg.getConstantPool(),cg.getWorld(),da.annotation);
  528. if (anno==null) {
  529. return null;
  530. } else {
  531. AnnotationAJ bcelAnnotation = new BcelAnnotation(anno, world);
  532. return bcelAnnotation;
  533. }
  534. }
  535. // TODO support array values
  536. // TODO support annotation values
  537. /**
  538. * Build an AnnotationGen object based on a string, for example "@Foo(35,message='string')". Notice single quotes are fine for
  539. * strings as they don't need special handling in the XML.
  540. */
  541. private AnnotationGen buildAnnotationFromString(ConstantPool cp, World w, String annotationString) {
  542. int paren = annotationString.indexOf('(');
  543. if (paren==-1) {
  544. // the easy case, no values
  545. AnnotationGen aaj = buildBaseAnnotationType(cp,world,annotationString);
  546. return aaj;
  547. } else {
  548. // Discover the name and name/value pairs
  549. String name = annotationString.substring(0,paren);
  550. // break the rest into pieces based on the commas
  551. List<String> values = new ArrayList<String>();
  552. int pos = paren+1;
  553. int depth = 0;
  554. int len = annotationString.length();
  555. int start = pos;
  556. while (pos<len) {
  557. char ch = annotationString.charAt(pos);
  558. if (ch==')' && depth==0) {
  559. break; // reached the end
  560. }
  561. if (ch=='(' || ch=='[') {
  562. depth++;
  563. } else if (ch==')' || ch==']') {
  564. depth--;
  565. }
  566. if (ch==',' && depth==0) {
  567. // found a comma at the right level to end a name/value pair
  568. values.add(annotationString.substring(start,pos).trim());
  569. start=pos+1;
  570. }
  571. pos++;
  572. }
  573. if (start != pos) {
  574. // there is a last bit to add
  575. values.add(annotationString.substring(start,pos).trim());
  576. }
  577. AnnotationGen aaj = buildBaseAnnotationType(cp,world,name);
  578. if (aaj==null) {
  579. return null; // a check failed
  580. }
  581. String typename = aaj.getTypeName();
  582. ResolvedType type = UnresolvedType.forName(typename).resolve(world); // shame it isn't retrievable from the anno
  583. ResolvedMember[] rms = type.getDeclaredMethods();
  584. // Add the values
  585. for (String value: values) {
  586. int equalsIndex = value.indexOf("=");
  587. String key = "value";
  588. if (value.charAt(0)!='\"' && equalsIndex!=-1) {
  589. key = value.substring(0,equalsIndex).trim();
  590. value = value.substring(equalsIndex+1).trim();
  591. }
  592. boolean keyIsOk = false;
  593. for (int m=0;m<rms.length;m++) {
  594. NameValuePair nvp = null;
  595. if (rms[m].getName().equals(key)) {
  596. // found it!
  597. keyIsOk=true;
  598. UnresolvedType rt = rms[m].getReturnType();
  599. if (rt.isPrimitiveType()) {
  600. switch (rt.getSignature().charAt(0)) {
  601. case 'J': // long
  602. try {
  603. long longValue = Long.parseLong(value);
  604. nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_LONG,cp,longValue),cp);
  605. } catch (NumberFormatException nfe) {
  606. reportError("unable to interpret annotation value '"+value+"' as a long");
  607. return null;
  608. }
  609. break;
  610. case 'S': // short
  611. try {
  612. short shortValue = Short.parseShort(value);
  613. nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_SHORT,cp,shortValue),cp);
  614. } catch (NumberFormatException nfe) {
  615. reportError("unable to interpret annotation value '"+value+"' as a short");
  616. return null;
  617. }
  618. break;
  619. case 'F': // float
  620. try {
  621. float floatValue = Float.parseFloat(value);
  622. nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_FLOAT,cp,floatValue),cp);
  623. } catch (NumberFormatException nfe) {
  624. reportError("unable to interpret annotation value '"+value+"' as a float");
  625. return null;
  626. }
  627. break;
  628. case 'D': // double
  629. try {
  630. double doubleValue = Double.parseDouble(value);
  631. nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_DOUBLE,cp,doubleValue),cp);
  632. } catch (NumberFormatException nfe) {
  633. reportError("unable to interpret annotation value '"+value+"' as a double");
  634. return null;
  635. }
  636. break;
  637. case 'I': // integer
  638. try {
  639. int intValue = Integer.parseInt(value);
  640. nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_INT,cp,intValue),cp);
  641. } catch (NumberFormatException nfe) {
  642. reportError("unable to interpret annotation value '"+value+"' as an integer");
  643. return null;
  644. }
  645. break;
  646. case 'B': // byte
  647. try {
  648. byte byteValue = Byte.parseByte(value);
  649. nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_BYTE,cp,byteValue),cp);
  650. } catch (NumberFormatException nfe) {
  651. reportError("unable to interpret annotation value '"+value+"' as a byte");
  652. return null;
  653. }
  654. break;
  655. case 'C': // char
  656. if (value.length()<2) {
  657. reportError("unable to interpret annotation value '"+value+"' as a char");
  658. return null;
  659. }
  660. nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_CHAR,cp,value.charAt(1)),cp);
  661. break;
  662. case 'Z': // boolean
  663. try {
  664. boolean booleanValue = Boolean.parseBoolean(value);
  665. nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_BOOLEAN,cp,booleanValue),cp);
  666. } catch (NumberFormatException nfe) {
  667. reportError("unable to interpret annotation value '"+value+"' as a boolean");
  668. return null;
  669. }
  670. break;
  671. default:
  672. reportError("not yet supporting XML setting of annotation values of type "+rt.getName());
  673. return null;
  674. }
  675. } else if (UnresolvedType.JL_STRING.equals(rt)) {
  676. if (value.length()<2) {
  677. reportError("Invalid string value specified in annotation string: "+annotationString);
  678. return null;
  679. }
  680. value = value.substring(1,value.length()-1); // trim the quotes off
  681. nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.STRING,cp,value),cp);
  682. } else if (UnresolvedType.JL_CLASS.equals(rt)) {
  683. // format of class string:
  684. // Foo.class
  685. // java.lang.Foo.class
  686. if (value.length()<6) {
  687. reportError("Not a well formed class value for an annotation '"+value+"'");
  688. return null;
  689. }
  690. String clazz = value.substring(0,value.length()-6);
  691. boolean qualified = clazz.indexOf(".")!=-1;
  692. if (!qualified) {
  693. // if not qualified, have to assume java.lang
  694. clazz = "java.lang."+clazz;
  695. }
  696. nvp = new NameValuePair(key,new ClassElementValue(new ObjectType(clazz),cp),cp);
  697. }
  698. }
  699. if (nvp!=null) {
  700. aaj.addElementNameValuePair(nvp);
  701. }
  702. }
  703. if (!keyIsOk) {
  704. reportError("annotation @"+typename+" does not have a value named "+key);
  705. return null;
  706. }
  707. }
  708. return aaj;
  709. }
  710. }
  711. private AnnotationGen buildBaseAnnotationType(ConstantPool cp,World world, String typename) {
  712. String annoname = typename;
  713. if (annoname.startsWith("@")) {
  714. annoname= annoname.substring(1);
  715. }
  716. ResolvedType annotationType = UnresolvedType.forName(annoname).resolve(world);
  717. if (!annotationType.isAnnotation()) {
  718. reportError("declare is not specifying an annotation type :"+typename);
  719. return null;
  720. }
  721. if (!annotationType.isAnnotationWithRuntimeRetention()) {
  722. reportError("declare is using an annotation type that does not have runtime retention: "+typename);
  723. return null;
  724. }
  725. List<NameValuePair> elems = new ArrayList<NameValuePair>();
  726. return new AnnotationGen(new ObjectType(annoname), elems, true, cp);
  727. }
  728. /**
  729. * Construct the annotation that indicates this is a declare
  730. */
  731. /**
  732. * The PointcutAndAdvice object encapsulates an advice kind, a pointcut and names a Java method in a particular class. Generate
  733. * an annotation style advice that has that pointcut whose implementation delegates to the Java method.
  734. */
  735. private void generateAdviceMethod(PointcutAndAdvice paa, int adviceCounter, LazyClassGen cg) {
  736. // Check: Verify the class to be called does exist:
  737. ResolvedType delegateClass = world.resolve(UnresolvedType.forName(paa.adviceClass));
  738. if (delegateClass.isMissing()) {
  739. reportError("Class to invoke cannot be found: '" + paa.adviceClass + "'");
  740. return;
  741. }
  742. // Generate a name for this advice, includes advice kind plus a counter
  743. String adviceName = new StringBuilder("generated$").append(paa.adviceKind.toString().toLowerCase()).append("$advice$")
  744. .append(adviceCounter).toString();
  745. // Build the annotation that encapsulates the pointcut
  746. AnnotationAJ aaj = buildAdviceAnnotation(cg, paa);
  747. // Chop up the supplied advice method string into its pieces.
  748. // Example: foo(JoinPoint jp, java.lang.String string)
  749. // JoinPoint and friends are recognized (so dont need fq package)
  750. String method = paa.adviceMethod;
  751. int paren = method.indexOf("(");
  752. String methodName = method.substring(0, paren);
  753. String signature = method.substring(paren);
  754. // Check: signature looks ok
  755. if (signature.charAt(0) != '(' || !signature.endsWith(")")) {
  756. reportError("Badly formatted parameter signature: '" + method + "'");
  757. return;
  758. }
  759. // Extract parameter types and names
  760. List<Type> paramTypes = new ArrayList<Type>();
  761. List<String> paramNames = new ArrayList<String>();
  762. if (signature.charAt(1) != ')') {
  763. // there are parameters to convert into a signature
  764. StringBuilder convertedSignature = new StringBuilder("(");
  765. boolean paramsBroken = false;
  766. int pos = 1;
  767. while (pos < signature.length() && signature.charAt(pos) != ')' && !paramsBroken) {
  768. int nextChunkEndPos = signature.indexOf(',', pos);
  769. if (nextChunkEndPos == -1) {
  770. nextChunkEndPos = signature.indexOf(')', pos);
  771. }
  772. // chunk will be a type plus a space plus a name
  773. String nextChunk = signature.substring(pos, nextChunkEndPos).trim();
  774. int space = nextChunk.indexOf(" ");
  775. ResolvedType resolvedParamType = null;
  776. if (space == -1) {
  777. // There is no parameter name, hopefully not needed!
  778. if (nextChunk.equals("JoinPoint")) {
  779. nextChunk = "org.aspectj.lang.JoinPoint";
  780. } else if (nextChunk.equals("JoinPoint.StaticPart")) {
  781. nextChunk = "org.aspectj.lang.JoinPoint$StaticPart";
  782. } else if (nextChunk.equals("ProceedingJoinPoint")) {
  783. nextChunk = "org.aspectj.lang.ProceedingJoinPoint";
  784. }
  785. UnresolvedType unresolvedParamType = UnresolvedType.forName(nextChunk);
  786. resolvedParamType = world.resolve(unresolvedParamType);
  787. } else {
  788. String typename = nextChunk.substring(0, space);
  789. if (typename.equals("JoinPoint")) {
  790. typename = "org.aspectj.lang.JoinPoint";
  791. } else if (typename.equals("JoinPoint.StaticPart")) {
  792. typename = "org.aspectj.lang.JoinPoint$StaticPart";
  793. } else if (typename.equals("ProceedingJoinPoint")) {
  794. typename = "org.aspectj.lang.ProceedingJoinPoint";
  795. }
  796. UnresolvedType unresolvedParamType = UnresolvedType.forName(typename);
  797. resolvedParamType = world.resolve(unresolvedParamType);
  798. String paramname = nextChunk.substring(space).trim();
  799. paramNames.add(paramname);
  800. }
  801. if (resolvedParamType.isMissing()) {
  802. reportError("Cannot find type specified as parameter: '" + nextChunk + "' from signature '" + signature + "'");
  803. paramsBroken = true;
  804. }
  805. paramTypes.add(Type.getType(resolvedParamType.getSignature()));
  806. convertedSignature.append(resolvedParamType.getSignature());
  807. pos = nextChunkEndPos + 1;
  808. }
  809. convertedSignature.append(")");
  810. signature = convertedSignature.toString();
  811. if (paramsBroken) {
  812. return;
  813. }
  814. }
  815. Type returnType = Type.VOID;
  816. // If around advice we must find the actual delegate method and use its return type
  817. if (paa.adviceKind == AdviceKind.Around) {
  818. ResolvedMember[] methods = delegateClass.getDeclaredMethods();
  819. ResolvedMember found = null;
  820. for (ResolvedMember candidate : methods) {
  821. if (candidate.getName().equals(methodName)) {
  822. UnresolvedType[] cparms = candidate.getParameterTypes();
  823. if (cparms.length == paramTypes.size()) {
  824. boolean paramsMatch = true;
  825. for (int i = 0; i < cparms.length; i++) {
  826. if (!cparms[i].getSignature().equals(paramTypes.get(i).getSignature())) {
  827. paramsMatch = false;
  828. break;
  829. }
  830. }
  831. if (paramsMatch) {
  832. found = candidate;
  833. break;
  834. }
  835. }
  836. }
  837. }
  838. if (found != null) {
  839. returnType = Type.getType(found.getReturnType().getSignature());
  840. } else {
  841. reportError("Unable to find method to invoke. In class: " + delegateClass.getName() + " cant find "
  842. + paa.adviceMethod);
  843. return;
  844. }
  845. }
  846. // Time to construct the method itself:
  847. LazyMethodGen advice = new LazyMethodGen(Modifier.PUBLIC, returnType, adviceName, paramTypes.toArray(new Type[paramTypes
  848. .size()]), EMPTY_STRINGS, cg);
  849. InstructionList adviceBody = advice.getBody();
  850. // Generate code to load the parameters
  851. int pos = 1; // first slot after 'this'
  852. for (int i = 0; i < paramTypes.size(); i++) {
  853. adviceBody.append(InstructionFactory.createLoad(paramTypes.get(i), pos));
  854. pos += paramTypes.get(i).getSize();
  855. }
  856. // Generate the delegate call
  857. adviceBody.append(cg.getFactory().createInvoke(paa.adviceClass, methodName, signature + returnType.getSignature(),
  858. Constants.INVOKESTATIC));
  859. // Generate the right return
  860. if (returnType == Type.VOID) {
  861. adviceBody.append(InstructionConstants.RETURN);
  862. } else {
  863. if (returnType.getSignature().length() < 2) {
  864. String sig = returnType.getSignature();
  865. if (sig.equals("F")) {
  866. adviceBody.append(InstructionConstants.FRETURN);
  867. } else if (sig.equals("D")) {
  868. adviceBody.append(InstructionConstants.DRETURN);
  869. } else if (sig.equals("J")) {
  870. adviceBody.append(InstructionConstants.LRETURN);
  871. } else {
  872. adviceBody.append(InstructionConstants.IRETURN);
  873. }
  874. } else {
  875. adviceBody.append(InstructionConstants.ARETURN);
  876. }
  877. }
  878. // Add the annotation
  879. advice.addAnnotation(aaj);
  880. InstructionHandle start = adviceBody.getStart();
  881. // Setup the local variable targeters so that the binding will work
  882. String sig = concreteAspect.name.replace('.', '/');
  883. start.addTargeter(new LocalVariableTag("L" + sig + ";", "this", 0, start.getPosition()));
  884. if (paramNames.size() > 0) {
  885. for (int i = 0; i < paramNames.size(); i++) {
  886. start.addTargeter(new LocalVariableTag(paramTypes.get(i).getSignature(), paramNames.get(i), i + 1, start
  887. .getPosition()));
  888. }
  889. }
  890. // Record the new method in the class
  891. cg.addMethodGen(advice);
  892. }
  893. /**
  894. * For the given PointcutAndAdvice build the correct advice annotation.
  895. */
  896. private AnnotationAJ buildAdviceAnnotation(LazyClassGen cg, PointcutAndAdvice paa) {
  897. SimpleElementValue svg = new SimpleElementValue(ElementValue.STRING, cg.getConstantPool(), paa.pointcut);
  898. List<NameValuePair> elems = new ArrayList<NameValuePair>();
  899. elems.add(new NameValuePair("value", svg, cg.getConstantPool()));
  900. AnnotationGen mag = new AnnotationGen(new ObjectType("org/aspectj/lang/annotation/" + paa.adviceKind.toString()), elems,
  901. true, cg.getConstantPool());
  902. AnnotationAJ aaj = new BcelAnnotation(mag, world);
  903. return aaj;
  904. }
  905. /**
  906. * Error reporting
  907. *
  908. * @param message
  909. */
  910. private void reportError(String message) {
  911. world.getMessageHandler().handleMessage(new Message(message, IMessage.ERROR, null, null));
  912. }
  913. }