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 30KB

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