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.

WeavingAdaptor.java 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. /* *******************************************************************
  2. * Copyright (c) 2004 IBM Corporation
  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. * Matthew Webster, Adrian Colyer,
  11. * Martin Lippert initial implementation
  12. * ******************************************************************/
  13. package org.aspectj.weaver.tools;
  14. import java.io.File;
  15. import java.io.FileOutputStream;
  16. import java.io.IOException;
  17. import java.io.PrintWriter;
  18. import java.net.URL;
  19. import java.net.URLClassLoader;
  20. import java.security.ProtectionDomain;
  21. import java.util.ArrayList;
  22. import java.util.HashMap;
  23. import java.util.HashSet;
  24. import java.util.Iterator;
  25. import java.util.LinkedList;
  26. import java.util.List;
  27. import java.util.Map;
  28. import java.util.Properties;
  29. import java.util.Set;
  30. import java.util.StringTokenizer;
  31. import org.aspectj.bridge.AbortException;
  32. import org.aspectj.bridge.IMessage;
  33. import org.aspectj.bridge.IMessage.Kind;
  34. import org.aspectj.bridge.IMessageContext;
  35. import org.aspectj.bridge.IMessageHandler;
  36. import org.aspectj.bridge.IMessageHolder;
  37. import org.aspectj.bridge.Message;
  38. import org.aspectj.bridge.MessageHandler;
  39. import org.aspectj.bridge.MessageUtil;
  40. import org.aspectj.bridge.MessageWriter;
  41. import org.aspectj.bridge.Version;
  42. import org.aspectj.bridge.WeaveMessage;
  43. import org.aspectj.util.FileUtil;
  44. import org.aspectj.util.LangUtil;
  45. import org.aspectj.weaver.IClassFileProvider;
  46. import org.aspectj.weaver.IUnwovenClassFile;
  47. import org.aspectj.weaver.IWeaveRequestor;
  48. import org.aspectj.weaver.World;
  49. import org.aspectj.weaver.bcel.BcelObjectType;
  50. import org.aspectj.weaver.bcel.BcelWeaver;
  51. import org.aspectj.weaver.bcel.BcelWorld;
  52. import org.aspectj.weaver.bcel.UnwovenClassFile;
  53. // OPTIMIZE add guards for all the debug/info/etc
  54. /**
  55. * This adaptor allows the AspectJ compiler to be embedded in an existing system to facilitate load-time weaving. It provides an
  56. * interface for a weaving class loader to provide a classpath to be woven by a set of aspects. A callback is supplied to allow a
  57. * class loader to define classes generated by the compiler during the weaving process.
  58. * <p>
  59. * A weaving class loader should create a <code>WeavingAdaptor</code> before any classes are defined, typically during construction.
  60. * The set of aspects passed to the adaptor is fixed for the lifetime of the adaptor although the classpath can be augmented. A
  61. * system property can be set to allow verbose weaving messages to be written to the console.
  62. *
  63. */
  64. public class WeavingAdaptor implements IMessageContext {
  65. /**
  66. * System property used to turn on verbose weaving messages
  67. */
  68. public static final String WEAVING_ADAPTOR_VERBOSE = "aj.weaving.verbose";
  69. public static final String SHOW_WEAVE_INFO_PROPERTY = "org.aspectj.weaver.showWeaveInfo";
  70. public static final String TRACE_MESSAGES_PROPERTY = "org.aspectj.tracing.messages";
  71. private boolean enabled = false;
  72. protected boolean verbose = getVerbose();
  73. protected BcelWorld bcelWorld;
  74. protected BcelWeaver weaver;
  75. private IMessageHandler messageHandler;
  76. private WeavingAdaptorMessageHolder messageHolder;
  77. private boolean abortOnError = false;
  78. protected GeneratedClassHandler generatedClassHandler;
  79. protected Map<String, IUnwovenClassFile> generatedClasses = new HashMap<String, IUnwovenClassFile>();
  80. public BcelObjectType delegateForCurrentClass; // lazily initialized, should be used to prevent parsing bytecode multiple
  81. // times
  82. protected ProtectionDomain activeProtectionDomain;
  83. private boolean haveWarnedOnJavax = false;
  84. private int weavingSpecialTypes = 0;
  85. private static final int INITIALIZED = 0x1;
  86. private static final int WEAVE_JAVA_PACKAGE = 0x2;
  87. private static final int WEAVE_JAVAX_PACKAGE = 0x4;
  88. private static Trace trace = TraceFactory.getTraceFactory().getTrace(WeavingAdaptor.class);
  89. protected WeavingAdaptor() {
  90. }
  91. /**
  92. * Construct a WeavingAdaptor with a reference to a weaving class loader. The adaptor will automatically search the class loader
  93. * hierarchy to resolve classes. The adaptor will also search the hierarchy for WeavingClassLoader instances to determine the
  94. * set of aspects to be used ofr weaving.
  95. *
  96. * @param loader instance of <code>ClassLoader</code>
  97. */
  98. public WeavingAdaptor(WeavingClassLoader loader) {
  99. // System.err.println("? WeavingAdaptor.<init>(" + loader +"," + aspectURLs.length + ")");
  100. generatedClassHandler = loader;
  101. init(getFullClassPath((ClassLoader) loader), getFullAspectPath((ClassLoader) loader/* ,aspectURLs */));
  102. }
  103. /**
  104. * Construct a WeavingAdator with a reference to a <code>GeneratedClassHandler</code>, a full search path for resolving classes
  105. * and a complete set of aspects. The search path must include classes loaded by the class loader constructing the
  106. * WeavingAdaptor and all its parents in the hierarchy.
  107. *
  108. * @param handler <code>GeneratedClassHandler</code>
  109. * @param classURLs the URLs from which to resolve classes
  110. * @param aspectURLs the aspects used to weave classes defined by this class loader
  111. */
  112. public WeavingAdaptor(GeneratedClassHandler handler, URL[] classURLs, URL[] aspectURLs) {
  113. // System.err.println("? WeavingAdaptor.<init>()");
  114. generatedClassHandler = handler;
  115. init(FileUtil.makeClasspath(classURLs), FileUtil.makeClasspath(aspectURLs));
  116. }
  117. private List<String> getFullClassPath(ClassLoader loader) {
  118. List<String> list = new LinkedList<String>();
  119. for (; loader != null; loader = loader.getParent()) {
  120. if (loader instanceof URLClassLoader) {
  121. URL[] urls = ((URLClassLoader) loader).getURLs();
  122. list.addAll(0, FileUtil.makeClasspath(urls));
  123. } else {
  124. warn("cannot determine classpath");
  125. }
  126. }
  127. list.addAll(0, makeClasspath(System.getProperty("sun.boot.class.path")));
  128. return list;
  129. }
  130. private List<String> getFullAspectPath(ClassLoader loader) {
  131. List<String> list = new LinkedList<String>();
  132. for (; loader != null; loader = loader.getParent()) {
  133. if (loader instanceof WeavingClassLoader) {
  134. URL[] urls = ((WeavingClassLoader) loader).getAspectURLs();
  135. list.addAll(0, FileUtil.makeClasspath(urls));
  136. }
  137. }
  138. return list;
  139. }
  140. private static boolean getVerbose() {
  141. try {
  142. return Boolean.getBoolean(WEAVING_ADAPTOR_VERBOSE);
  143. } catch (Throwable t) {
  144. // security exception
  145. return false;
  146. }
  147. }
  148. private void init(List<String> classPath, List<String> aspectPath) {
  149. abortOnError = true;
  150. createMessageHandler();
  151. info("using classpath: " + classPath);
  152. info("using aspectpath: " + aspectPath);
  153. bcelWorld = new BcelWorld(classPath, messageHandler, null);
  154. bcelWorld.setXnoInline(false);
  155. bcelWorld.getLint().loadDefaultProperties();
  156. if (LangUtil.is15VMOrGreater()) {
  157. bcelWorld.setBehaveInJava5Way(true);
  158. }
  159. weaver = new BcelWeaver(bcelWorld);
  160. registerAspectLibraries(aspectPath);
  161. enabled = true;
  162. }
  163. protected void createMessageHandler() {
  164. messageHolder = new WeavingAdaptorMessageHolder(new PrintWriter(System.err));
  165. messageHandler = messageHolder;
  166. if (verbose) {
  167. messageHandler.dontIgnore(IMessage.INFO);
  168. }
  169. if (Boolean.getBoolean(SHOW_WEAVE_INFO_PROPERTY)) {
  170. messageHandler.dontIgnore(IMessage.WEAVEINFO);
  171. }
  172. info("AspectJ Weaver Version " + Version.text + " built on " + Version.time_text); //$NON-NLS-1$
  173. }
  174. protected IMessageHandler getMessageHandler() {
  175. return messageHandler;
  176. }
  177. public IMessageHolder getMessageHolder() {
  178. return messageHolder;
  179. }
  180. protected void setMessageHandler(IMessageHandler mh) {
  181. if (mh instanceof ISupportsMessageContext) {
  182. ISupportsMessageContext smc = (ISupportsMessageContext) mh;
  183. smc.setMessageContext(this);
  184. }
  185. if (mh != messageHolder) {
  186. messageHolder.setDelegate(mh);
  187. }
  188. messageHolder.flushMessages();
  189. }
  190. protected void disable() {
  191. if (trace.isTraceEnabled()) {
  192. trace.enter("disable", this);
  193. }
  194. enabled = false;
  195. messageHolder.flushMessages();
  196. if (trace.isTraceEnabled()) {
  197. trace.exit("disable");
  198. }
  199. }
  200. protected void enable() {
  201. enabled = true;
  202. messageHolder.flushMessages();
  203. }
  204. protected boolean isEnabled() {
  205. return enabled;
  206. }
  207. /**
  208. * Appends URL to path used by the WeavingAdptor to resolve classes
  209. *
  210. * @param url to be appended to search path
  211. */
  212. public void addURL(URL url) {
  213. File libFile = new File(url.getPath());
  214. try {
  215. weaver.addLibraryJarFile(libFile);
  216. } catch (IOException ex) {
  217. warn("bad library: '" + libFile + "'");
  218. }
  219. }
  220. /**
  221. * Weave a class using aspects previously supplied to the adaptor.
  222. *
  223. * @param name the name of the class
  224. * @param bytes the class bytes
  225. * @return the woven bytes
  226. * @exception IOException weave failed
  227. */
  228. public byte[] weaveClass(String name, byte[] bytes) throws IOException {
  229. return weaveClass(name, bytes, false);
  230. }
  231. // Track if the weaver is already running on this thread - don't allow re-entrant calls
  232. private ThreadLocal<Boolean> weaverRunning = new ThreadLocal<Boolean>() {
  233. @Override
  234. protected Boolean initialValue() {
  235. return Boolean.FALSE;
  236. }
  237. };
  238. /**
  239. * Weave a class using aspects previously supplied to the adaptor.
  240. *
  241. * @param name the name of the class
  242. * @param bytes the class bytes
  243. * @param mustWeave if true then this class *must* get woven (used for concrete aspects generated from XML)
  244. * @return the woven bytes
  245. * @exception IOException weave failed
  246. */
  247. public byte[] weaveClass(String name, byte[] bytes, boolean mustWeave) throws IOException {
  248. if (trace == null) {
  249. // Pr231945: we are likely to be under tomcat and ENABLE_CLEAR_REFERENCES hasn't been set
  250. System.err
  251. .println("AspectJ Weaver cannot continue to weave, static state has been cleared. Are you under Tomcat? In order to weave '"
  252. + name
  253. + "' during shutdown, 'org.apache.catalina.loader.WebappClassLoader.ENABLE_CLEAR_REFERENCES=false' must be set (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=231945).");
  254. return bytes;
  255. }
  256. if (weaverRunning.get()) {
  257. // System.out.println("AJC: avoiding re-entrant call to transform " + name);
  258. return bytes;
  259. }
  260. try {
  261. weaverRunning.set(true);
  262. if (trace.isTraceEnabled()) {
  263. trace.enter("weaveClass", this, new Object[] { name, bytes });
  264. }
  265. if (!enabled) {
  266. if (trace.isTraceEnabled()) {
  267. trace.exit("weaveClass", false);
  268. }
  269. return bytes;
  270. }
  271. boolean debugOn = !messageHandler.isIgnoring(Message.DEBUG);
  272. try {
  273. delegateForCurrentClass = null;
  274. name = name.replace('/', '.');
  275. if (couldWeave(name, bytes)) {
  276. if (accept(name, bytes)) {
  277. // TODO @AspectJ problem
  278. // Annotation style aspects need to be included regardless in order to get
  279. // a valid aspectOf()/hasAspect() generated in them. However - if they are excluded
  280. // (via include/exclude in aop.xml) they really should only get aspectOf()/hasAspect()
  281. // and not be included in the full set of aspects being applied by 'this' weaver
  282. if (debugOn) {
  283. debug("weaving '" + name + "'");
  284. }
  285. bytes = getWovenBytes(name, bytes);
  286. // temporarily out - searching for @Aspect annotated types is a slow thing to do - we should
  287. // expect the user to name them if they want them woven - just like code style
  288. // } else if (shouldWeaveAnnotationStyleAspect(name, bytes)) {
  289. // if (mustWeave) {
  290. // if (bcelWorld.getLint().mustWeaveXmlDefinedAspects.isEnabled()) {
  291. // bcelWorld.getLint().mustWeaveXmlDefinedAspects.signal(name, null);
  292. // }
  293. // }
  294. // // an @AspectJ aspect needs to be at least munged by the aspectOf munger
  295. // if (debugOn) {
  296. // debug("weaving '" + name + "'");
  297. // }
  298. // bytes = getAtAspectJAspectBytes(name, bytes);
  299. } else if (debugOn) {
  300. debug("not weaving '" + name + "'");
  301. }
  302. } else if (debugOn) {
  303. debug("cannot weave '" + name + "'");
  304. }
  305. } finally {
  306. delegateForCurrentClass = null;
  307. }
  308. if (trace.isTraceEnabled()) {
  309. trace.exit("weaveClass", bytes);
  310. }
  311. return bytes;
  312. } finally {
  313. weaverRunning.set(false);
  314. }
  315. }
  316. /**
  317. * @param name
  318. * @return true if even valid to weave: either with an accept check or to munge it for @AspectJ aspectof support
  319. */
  320. private boolean couldWeave(String name, byte[] bytes) {
  321. return !generatedClasses.containsKey(name) && shouldWeaveName(name);
  322. }
  323. // ATAJ
  324. protected boolean accept(String name, byte[] bytes) {
  325. return true;
  326. }
  327. protected boolean shouldDump(String name, boolean before) {
  328. return false;
  329. }
  330. private boolean shouldWeaveName(String name) {
  331. if ("osj".indexOf(name.charAt(0)) != -1) {
  332. if ((weavingSpecialTypes & INITIALIZED) == 0) {
  333. weavingSpecialTypes |= INITIALIZED;
  334. // initialize it
  335. Properties p = weaver.getWorld().getExtraConfiguration();
  336. if (p != null) {
  337. boolean b = p.getProperty(World.xsetWEAVE_JAVA_PACKAGES, "false").equalsIgnoreCase("true");
  338. if (b) {
  339. weavingSpecialTypes |= WEAVE_JAVA_PACKAGE;
  340. }
  341. b = p.getProperty(World.xsetWEAVE_JAVAX_PACKAGES, "false").equalsIgnoreCase("true");
  342. if (b) {
  343. weavingSpecialTypes |= WEAVE_JAVAX_PACKAGE;
  344. }
  345. }
  346. }
  347. if (name.startsWith("org.aspectj.")) {
  348. return false;
  349. }
  350. if (name.startsWith("sun.reflect.")) {// JDK reflect
  351. return false;
  352. }
  353. if (name.startsWith("javax.")) {
  354. if ((weavingSpecialTypes & WEAVE_JAVAX_PACKAGE) != 0) {
  355. return true;
  356. } else {
  357. if (!haveWarnedOnJavax) {
  358. haveWarnedOnJavax = true;
  359. warn("javax.* types are not being woven because the weaver option '-Xset:weaveJavaxPackages=true' has not been specified");
  360. }
  361. return false;
  362. }
  363. }
  364. if (name.startsWith("java.")) {
  365. if ((weavingSpecialTypes & WEAVE_JAVA_PACKAGE) != 0) {
  366. return true;
  367. } else {
  368. return false;
  369. }
  370. }
  371. }
  372. // boolean should = !(name.startsWith("org.aspectj.")
  373. // || (name.startsWith("java.") && (weavingSpecialTypes & WEAVE_JAVA_PACKAGE) == 0)
  374. // || (name.startsWith("javax.") && (weavingSpecialTypes & WEAVE_JAVAX_PACKAGE) == 0)
  375. // // || name.startsWith("$Proxy")//JDK proxies//FIXME AV is that 1.3 proxy ? fe. ataspect.$Proxy0 is a java5 proxy...
  376. // || name.startsWith("sun.reflect."));
  377. return true;
  378. }
  379. /**
  380. * We allow @AJ aspect weaving so that we can add aspectOf() as part of the weaving (and not part of the source compilation)
  381. *
  382. * @param name
  383. * @param bytes bytecode (from classloader), allow to NOT lookup stuff on disk again during resolve
  384. * @return true if @Aspect
  385. */
  386. private boolean shouldWeaveAnnotationStyleAspect(String name, byte[] bytes) {
  387. if (delegateForCurrentClass == null) {
  388. // if (weaver.getWorld().isASMAround()) return asmCheckAnnotationStyleAspect(bytes);
  389. // else
  390. ensureDelegateInitialized(name, bytes);
  391. }
  392. return (delegateForCurrentClass.isAnnotationStyleAspect());
  393. }
  394. // private boolean asmCheckAnnotationStyleAspect(byte[] bytes) {
  395. // IsAtAspectAnnotationVisitor detector = new IsAtAspectAnnotationVisitor();
  396. //
  397. // ClassReader cr = new ClassReader(bytes);
  398. // try {
  399. // cr.accept(detector, true);//, ClassReader.SKIP_DEBUG | ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES);
  400. // } catch (Exception spe) {
  401. // // if anything goes wrong, e.g., an NPE, then assume it's NOT an @AspectJ aspect...
  402. // System.err.println("Unexpected problem parsing bytes to discover @Aspect annotation");
  403. // spe.printStackTrace();
  404. // return false;
  405. // }
  406. //
  407. // return detector.isAspect();
  408. // }
  409. protected void ensureDelegateInitialized(String name, byte[] bytes) {
  410. if (delegateForCurrentClass == null) {
  411. BcelWorld world = (BcelWorld) weaver.getWorld();
  412. delegateForCurrentClass = world.addSourceObjectType(name, bytes, false);
  413. }
  414. }
  415. /**
  416. * Weave a set of bytes defining a class.
  417. *
  418. * @param name the name of the class being woven
  419. * @param bytes the bytes that define the class
  420. * @return byte[] the woven bytes for the class
  421. * @throws IOException
  422. */
  423. private byte[] getWovenBytes(String name, byte[] bytes) throws IOException {
  424. WeavingClassFileProvider wcp = new WeavingClassFileProvider(name, bytes);
  425. weaver.weave(wcp);
  426. return wcp.getBytes();
  427. }
  428. /**
  429. * Weave a set of bytes defining a class for only what is needed to turn @AspectJ aspect in a usefull form ie with aspectOf
  430. * method - see #113587
  431. *
  432. * @param name the name of the class being woven
  433. * @param bytes the bytes that define the class
  434. * @return byte[] the woven bytes for the class
  435. * @throws IOException
  436. */
  437. private byte[] getAtAspectJAspectBytes(String name, byte[] bytes) throws IOException {
  438. WeavingClassFileProvider wcp = new WeavingClassFileProvider(name, bytes);
  439. wcp.setApplyAtAspectJMungersOnly();
  440. weaver.weave(wcp);
  441. return wcp.getBytes();
  442. }
  443. private void registerAspectLibraries(List aspectPath) {
  444. // System.err.println("? WeavingAdaptor.registerAspectLibraries(" + aspectPath + ")");
  445. for (Iterator i = aspectPath.iterator(); i.hasNext();) {
  446. String libName = (String) i.next();
  447. addAspectLibrary(libName);
  448. }
  449. weaver.prepareForWeave();
  450. }
  451. /*
  452. * Register an aspect library with this classloader for use during weaving. This class loader will also return (unmodified) any
  453. * of the classes in the library in response to a <code>findClass()</code> request. The library is not required to be on the
  454. * weavingClasspath given when this classloader was constructed.
  455. *
  456. * @param aspectLibraryJarFile a jar file representing an aspect library
  457. *
  458. * @throws IOException
  459. */
  460. private void addAspectLibrary(String aspectLibraryName) {
  461. File aspectLibrary = new File(aspectLibraryName);
  462. if (aspectLibrary.isDirectory() || (FileUtil.isZipFile(aspectLibrary))) {
  463. try {
  464. info("adding aspect library: '" + aspectLibrary + "'");
  465. weaver.addLibraryJarFile(aspectLibrary);
  466. } catch (IOException ex) {
  467. error("exception adding aspect library: '" + ex + "'");
  468. }
  469. } else {
  470. error("bad aspect library: '" + aspectLibrary + "'");
  471. }
  472. }
  473. private static List<String> makeClasspath(String cp) {
  474. List<String> ret = new ArrayList<String>();
  475. if (cp != null) {
  476. StringTokenizer tok = new StringTokenizer(cp, File.pathSeparator);
  477. while (tok.hasMoreTokens()) {
  478. ret.add(tok.nextToken());
  479. }
  480. }
  481. return ret;
  482. }
  483. protected boolean debug(String message) {
  484. return MessageUtil.debug(messageHandler, message);
  485. }
  486. protected boolean info(String message) {
  487. return MessageUtil.info(messageHandler, message);
  488. }
  489. protected boolean warn(String message) {
  490. return MessageUtil.warn(messageHandler, message);
  491. }
  492. protected boolean warn(String message, Throwable th) {
  493. return messageHandler.handleMessage(new Message(message, IMessage.WARNING, th, null));
  494. }
  495. protected boolean error(String message) {
  496. return MessageUtil.error(messageHandler, message);
  497. }
  498. protected boolean error(String message, Throwable th) {
  499. return messageHandler.handleMessage(new Message(message, IMessage.ERROR, th, null));
  500. }
  501. public String getContextId() {
  502. return "WeavingAdaptor";
  503. }
  504. /**
  505. * Dump the given bytcode in _dump/... (dev mode)
  506. *
  507. * @param name
  508. * @param b
  509. * @param before whether we are dumping before weaving
  510. * @throws Throwable
  511. */
  512. protected void dump(String name, byte[] b, boolean before) {
  513. String dirName = getDumpDir();
  514. if (before) {
  515. dirName = dirName + File.separator + "_before";
  516. }
  517. String className = name.replace('.', '/');
  518. final File dir;
  519. if (className.indexOf('/') > 0) {
  520. dir = new File(dirName + File.separator + className.substring(0, className.lastIndexOf('/')));
  521. } else {
  522. dir = new File(dirName);
  523. }
  524. dir.mkdirs();
  525. String fileName = dirName + File.separator + className + ".class";
  526. try {
  527. // System.out.println("WeavingAdaptor.dump() fileName=" + new File(fileName).getAbsolutePath());
  528. FileOutputStream os = new FileOutputStream(fileName);
  529. os.write(b);
  530. os.close();
  531. } catch (IOException ex) {
  532. warn("unable to dump class " + name + " in directory " + dirName, ex);
  533. }
  534. }
  535. /**
  536. * @return the directory in which to dump - default is _ajdump but it
  537. */
  538. protected String getDumpDir() {
  539. return "_ajdump";
  540. }
  541. /**
  542. * Processes messages arising from weaver operations. Tell weaver to abort on any message more severe than warning.
  543. */
  544. protected class WeavingAdaptorMessageHolder extends MessageHandler {
  545. private IMessageHandler delegate;
  546. private List<IMessage> savedMessages;
  547. protected boolean traceMessages = Boolean.getBoolean(TRACE_MESSAGES_PROPERTY);
  548. public WeavingAdaptorMessageHolder(PrintWriter writer) {
  549. this.delegate = new WeavingAdaptorMessageWriter(writer);
  550. super.dontIgnore(IMessage.WEAVEINFO);
  551. }
  552. private void traceMessage(IMessage message) {
  553. if (message instanceof WeaveMessage) {
  554. trace.debug(render(message));
  555. } else if (message.isDebug()) {
  556. trace.debug(render(message));
  557. } else if (message.isInfo()) {
  558. trace.info(render(message));
  559. } else if (message.isWarning()) {
  560. trace.warn(render(message), message.getThrown());
  561. } else if (message.isError()) {
  562. trace.error(render(message), message.getThrown());
  563. } else if (message.isFailed()) {
  564. trace.fatal(render(message), message.getThrown());
  565. } else if (message.isAbort()) {
  566. trace.fatal(render(message), message.getThrown());
  567. } else {
  568. trace.error(render(message), message.getThrown());
  569. }
  570. }
  571. protected String render(IMessage message) {
  572. return "[" + getContextId() + "] " + message.toString();
  573. }
  574. public void flushMessages() {
  575. if (savedMessages == null) {
  576. savedMessages = new ArrayList<IMessage>();
  577. savedMessages.addAll(super.getUnmodifiableListView());
  578. clearMessages();
  579. for (IMessage message : savedMessages) {
  580. delegate.handleMessage(message);
  581. }
  582. }
  583. // accumulating = false;
  584. // messages.clear();
  585. }
  586. public void setDelegate(IMessageHandler messageHandler) {
  587. delegate = messageHandler;
  588. }
  589. /*
  590. * IMessageHandler
  591. */
  592. @Override
  593. public boolean handleMessage(IMessage message) throws AbortException {
  594. if (traceMessages) {
  595. traceMessage(message);
  596. }
  597. super.handleMessage(message);
  598. if (abortOnError && 0 <= message.getKind().compareTo(IMessage.ERROR)) {
  599. throw new AbortException(message);
  600. }
  601. // if (accumulating) {
  602. // boolean result = addMessage(message);
  603. // if (abortOnError && 0 <= message.getKind().compareTo(IMessage.ERROR)) {
  604. // throw new AbortException(message);
  605. // }
  606. // return result;
  607. // }
  608. // else return delegate.handleMessage(message);
  609. if (savedMessages != null) {
  610. delegate.handleMessage(message);
  611. }
  612. return true;
  613. }
  614. @Override
  615. public boolean isIgnoring(Kind kind) {
  616. return delegate.isIgnoring(kind);
  617. }
  618. @Override
  619. public void dontIgnore(IMessage.Kind kind) {
  620. if (null != kind && delegate != null) {
  621. delegate.dontIgnore(kind);
  622. }
  623. }
  624. @Override
  625. public void ignore(Kind kind) {
  626. if (null != kind && delegate != null) {
  627. delegate.ignore(kind);
  628. }
  629. }
  630. /*
  631. * IMessageHolder
  632. */
  633. @Override
  634. public List<IMessage> getUnmodifiableListView() {
  635. // System.err.println("? WeavingAdaptorMessageHolder.getUnmodifiableListView() savedMessages=" + savedMessages);
  636. List<IMessage> allMessages = new ArrayList<IMessage>();
  637. allMessages.addAll(savedMessages);
  638. allMessages.addAll(super.getUnmodifiableListView());
  639. return allMessages;
  640. }
  641. }
  642. protected class WeavingAdaptorMessageWriter extends MessageWriter {
  643. private final Set<IMessage.Kind> ignoring = new HashSet<IMessage.Kind>();
  644. private final IMessage.Kind failKind;
  645. public WeavingAdaptorMessageWriter(PrintWriter writer) {
  646. super(writer, true);
  647. ignore(IMessage.WEAVEINFO);
  648. ignore(IMessage.DEBUG);
  649. ignore(IMessage.INFO);
  650. this.failKind = IMessage.ERROR;
  651. }
  652. @Override
  653. public boolean handleMessage(IMessage message) throws AbortException {
  654. // boolean result =
  655. super.handleMessage(message);
  656. if (abortOnError && 0 <= message.getKind().compareTo(failKind)) {
  657. throw new AbortException(message);
  658. }
  659. return true;
  660. }
  661. @Override
  662. public boolean isIgnoring(Kind kind) {
  663. return ((null != kind) && (ignoring.contains(kind)));
  664. }
  665. /**
  666. * Set a message kind to be ignored from now on
  667. */
  668. @Override
  669. public void ignore(IMessage.Kind kind) {
  670. if ((null != kind) && (!ignoring.contains(kind))) {
  671. ignoring.add(kind);
  672. }
  673. }
  674. /**
  675. * Remove a message kind from the list of those ignored from now on.
  676. */
  677. @Override
  678. public void dontIgnore(IMessage.Kind kind) {
  679. if (null != kind) {
  680. ignoring.remove(kind);
  681. }
  682. }
  683. @Override
  684. protected String render(IMessage message) {
  685. return "[" + getContextId() + "] " + super.render(message);
  686. }
  687. }
  688. private class WeavingClassFileProvider implements IClassFileProvider {
  689. private final UnwovenClassFile unwovenClass;
  690. private final List<UnwovenClassFile> unwovenClasses = new ArrayList<UnwovenClassFile>();
  691. private IUnwovenClassFile wovenClass;
  692. private boolean isApplyAtAspectJMungersOnly = false;
  693. public WeavingClassFileProvider(String name, byte[] bytes) {
  694. ensureDelegateInitialized(name, bytes);
  695. this.unwovenClass = new UnwovenClassFile(name, delegateForCurrentClass.getResolvedTypeX().getName(), bytes);
  696. this.unwovenClasses.add(unwovenClass);
  697. if (shouldDump(name.replace('/', '.'), true)) {
  698. dump(name, bytes, true);
  699. }
  700. }
  701. public void setApplyAtAspectJMungersOnly() {
  702. isApplyAtAspectJMungersOnly = true;
  703. }
  704. public boolean isApplyAtAspectJMungersOnly() {
  705. return isApplyAtAspectJMungersOnly;
  706. }
  707. public byte[] getBytes() {
  708. if (wovenClass != null) {
  709. return wovenClass.getBytes();
  710. } else {
  711. return unwovenClass.getBytes();
  712. }
  713. }
  714. public Iterator<UnwovenClassFile> getClassFileIterator() {
  715. return unwovenClasses.iterator();
  716. }
  717. public IWeaveRequestor getRequestor() {
  718. return new IWeaveRequestor() {
  719. public void acceptResult(IUnwovenClassFile result) {
  720. if (wovenClass == null) {
  721. wovenClass = result;
  722. String name = result.getClassName();
  723. if (shouldDump(name.replace('/', '.'), false)) {
  724. dump(name, result.getBytes(), false);
  725. }
  726. } else {
  727. // Classes generated by weaver e.g. around closure advice
  728. String className = result.getClassName();
  729. generatedClasses.put(className, result);
  730. generatedClasses.put(wovenClass.getClassName(), result);
  731. generatedClassHandler.acceptClass(className, result.getBytes());
  732. }
  733. }
  734. public void processingReweavableState() {
  735. }
  736. public void addingTypeMungers() {
  737. }
  738. public void weavingAspects() {
  739. }
  740. public void weavingClasses() {
  741. }
  742. public void weaveCompleted() {
  743. // ResolvedType.resetPrimitives();
  744. if (delegateForCurrentClass != null) {
  745. delegateForCurrentClass.weavingCompleted();
  746. }
  747. // ResolvedType.resetPrimitives();
  748. // bcelWorld.discardType(typeBeingProcessed.getResolvedTypeX()); // work in progress
  749. }
  750. };
  751. }
  752. }
  753. public void setActiveProtectionDomain(ProtectionDomain protectionDomain) {
  754. activeProtectionDomain = protectionDomain;
  755. }
  756. }