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.

Aj.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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.ref.ReferenceQueue;
  14. import java.lang.ref.WeakReference;
  15. import java.util.Collections;
  16. import java.util.HashMap;
  17. import java.util.Iterator;
  18. import java.util.Map;
  19. import java.util.Set;
  20. import org.aspectj.bridge.context.CompilationAndWeavingContext;
  21. import org.aspectj.weaver.Dump;
  22. import org.aspectj.weaver.tools.Trace;
  23. import org.aspectj.weaver.tools.TraceFactory;
  24. import org.aspectj.weaver.tools.WeavingAdaptor;
  25. /**
  26. * Adapter between the generic class pre processor interface and the AspectJ weaver Load time weaving consistency relies on
  27. * Bcel.setRepository
  28. *
  29. * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
  30. */
  31. public class Aj implements ClassPreProcessor {
  32. private IWeavingContext weavingContext;
  33. /**
  34. * References are added to this queue when their associated classloader is removed, and once on here that indicates that we
  35. * should tidy up the adaptor map and remove the adaptor (weaver) from the map we are maintaining from adaptorkey > adaptor
  36. * (weaver)
  37. */
  38. private static ReferenceQueue adaptorQueue = new ReferenceQueue();
  39. private static Trace trace = TraceFactory.getTraceFactory().getTrace(Aj.class);
  40. public Aj() {
  41. this(null);
  42. }
  43. public Aj(IWeavingContext context) {
  44. if (trace.isTraceEnabled())
  45. trace.enter("<init>", this, new Object[] { context, getClass().getClassLoader() });
  46. this.weavingContext = context;
  47. if (trace.isTraceEnabled())
  48. trace.exit("<init>");
  49. }
  50. /**
  51. * Initialization
  52. */
  53. public void initialize() {
  54. }
  55. /**
  56. * Weave
  57. *
  58. * @param className
  59. * @param bytes
  60. * @param loader
  61. * @return weaved bytes
  62. */
  63. public byte[] preProcess(String className, byte[] bytes, ClassLoader loader) {
  64. // TODO AV needs to doc that
  65. if (loader == null || className == null) {
  66. // skip boot loader or null classes (hibernate)
  67. return bytes;
  68. }
  69. if (trace.isTraceEnabled())
  70. trace.enter("preProcess", this, new Object[] { className, bytes, loader });
  71. if (trace.isTraceEnabled())
  72. trace.event("preProcess", this, new Object[] { loader.getParent(), Thread.currentThread().getContextClassLoader() });
  73. try {
  74. synchronized (loader) {
  75. WeavingAdaptor weavingAdaptor = WeaverContainer.getWeaver(loader, weavingContext);
  76. if (weavingAdaptor == null) {
  77. if (trace.isTraceEnabled())
  78. trace.exit("preProcess");
  79. return bytes;
  80. }
  81. byte[] newBytes = weavingAdaptor.weaveClass(className, bytes, false);
  82. Dump.dumpOnExit(weavingAdaptor.getMessageHolder(), true);
  83. if (trace.isTraceEnabled())
  84. trace.exit("preProcess", newBytes);
  85. return newBytes;
  86. }
  87. /* Don't like to do this but JVMTI swallows all exceptions */
  88. } catch (Throwable th) {
  89. trace.error(className, th);
  90. Dump.dumpWithException(th);
  91. // FIXME AV wondering if we should have the option to fail (throw runtime exception) here
  92. // would make sense at least in test f.e. see TestHelper.handleMessage()
  93. if (trace.isTraceEnabled())
  94. trace.exit("preProcess", th);
  95. return bytes;
  96. } finally {
  97. CompilationAndWeavingContext.resetForThread();
  98. }
  99. }
  100. /**
  101. * An AdaptorKey is a WeakReference wrapping a classloader reference that will enqueue to a specified queue when the classloader
  102. * is GC'd. Since the AdaptorKey is used as a key into a hashmap we need to give it a non-varying hashcode/equals
  103. * implementation, and we need that hashcode not to vary even when the internal referent has been GC'd. The hashcode is
  104. * calculated on creation of the AdaptorKey based on the loader instance that it is wrapping. This means even when the referent
  105. * is gone we can still use the AdaptorKey and it will 'point' to the same place as it always did.
  106. */
  107. private static class AdaptorKey extends WeakReference {
  108. private int hashcode = -1;
  109. public AdaptorKey(ClassLoader loader) {
  110. super(loader, adaptorQueue);
  111. hashcode = loader.hashCode() * 37;
  112. }
  113. public ClassLoader getClassLoader() {
  114. ClassLoader instance = (ClassLoader) get();
  115. // Assert instance!=null - shouldn't be asked for after a GC of the referent has occurred !
  116. return instance;
  117. }
  118. public boolean equals(Object obj) {
  119. if (!(obj instanceof AdaptorKey))
  120. return false;
  121. AdaptorKey other = (AdaptorKey) obj;
  122. return other.hashcode == hashcode;
  123. }
  124. public int hashCode() {
  125. return hashcode;
  126. }
  127. }
  128. /**
  129. * The reference queue is only processed when a request is made for a weaver adaptor. This means there can be one or two stale
  130. * weavers left around. If the user knows they have finished all their weaving, they might wish to call removeStaleAdaptors
  131. * which will process anything left on the reference queue containing adaptorKeys for garbage collected classloaders.
  132. *
  133. * @param displayProgress produce System.err info on the tidying up process
  134. * @return number of stale weavers removed
  135. */
  136. public static int removeStaleAdaptors(boolean displayProgress) {
  137. int removed = 0;
  138. synchronized (WeaverContainer.weavingAdaptors) {
  139. if (displayProgress) {
  140. System.err.println("Weaver adaptors before queue processing:");
  141. Map m = WeaverContainer.weavingAdaptors;
  142. Set keys = m.keySet();
  143. for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
  144. Object object = iterator.next();
  145. System.err.println(object + " = " + WeaverContainer.weavingAdaptors.get(object));
  146. }
  147. }
  148. Object o = adaptorQueue.poll();
  149. while (o != null) {
  150. if (displayProgress)
  151. System.err.println("Processing referencequeue entry " + o);
  152. AdaptorKey wo = (AdaptorKey) o;
  153. boolean didit = WeaverContainer.weavingAdaptors.remove(wo) != null;
  154. if (didit) {
  155. removed++;
  156. } else {
  157. throw new RuntimeException("Eh?? key=" + wo);
  158. }
  159. if (displayProgress)
  160. System.err.println("Removed? " + didit);
  161. o = adaptorQueue.poll();
  162. }
  163. if (displayProgress) {
  164. System.err.println("Weaver adaptors after queue processing:");
  165. Map m = WeaverContainer.weavingAdaptors;
  166. Set keys = m.keySet();
  167. for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
  168. Object object = iterator.next();
  169. System.err.println(object + " = " + WeaverContainer.weavingAdaptors.get(object));
  170. }
  171. }
  172. }
  173. return removed;
  174. }
  175. /**
  176. * @return the number of entries still in the weavingAdaptors map
  177. */
  178. public static int getActiveAdaptorCount() {
  179. return WeaverContainer.weavingAdaptors.size();
  180. }
  181. /**
  182. * Process the reference queue that contains stale AdaptorKeys - the keys are put on the queue when their classloader referent
  183. * is garbage collected and so the associated adaptor (weaver) should be removed from the map
  184. */
  185. public static void checkQ() {
  186. synchronized (adaptorQueue) {
  187. Object o = adaptorQueue.poll();
  188. while (o != null) {
  189. AdaptorKey wo = (AdaptorKey) o;
  190. // boolean removed =
  191. WeaverContainer.weavingAdaptors.remove(wo);
  192. // DBG System.err.println("Evicting key " + wo + " = " + didit);
  193. o = adaptorQueue.poll();
  194. }
  195. }
  196. }
  197. /**
  198. * Cache of weaver There is one weaver per classloader
  199. */
  200. static class WeaverContainer {
  201. final static Map weavingAdaptors = Collections.synchronizedMap(new HashMap());
  202. static WeavingAdaptor getWeaver(ClassLoader loader, IWeavingContext weavingContext) {
  203. ExplicitlyInitializedClassLoaderWeavingAdaptor adaptor = null;
  204. AdaptorKey adaptorKey = new AdaptorKey(loader);
  205. synchronized (weavingAdaptors) {
  206. checkQ();
  207. adaptor = (ExplicitlyInitializedClassLoaderWeavingAdaptor) weavingAdaptors.get(adaptorKey);
  208. if (adaptor == null) {
  209. String loaderClassName = loader.getClass().getName();
  210. if (loaderClassName.equals("sun.reflect.DelegatingClassLoader")) {
  211. // we don't weave reflection generated types at all!
  212. return null;
  213. } else {
  214. // create it and put it back in the weavingAdaptors map but avoid any kind of instantiation
  215. // within the synchronized block
  216. ClassLoaderWeavingAdaptor weavingAdaptor = new ClassLoaderWeavingAdaptor();
  217. adaptor = new ExplicitlyInitializedClassLoaderWeavingAdaptor(weavingAdaptor);
  218. weavingAdaptors.put(adaptorKey, adaptor);
  219. }
  220. }
  221. }
  222. // perform the initialization
  223. return adaptor.getWeavingAdaptor(loader, weavingContext);
  224. }
  225. }
  226. static class ExplicitlyInitializedClassLoaderWeavingAdaptor {
  227. private final ClassLoaderWeavingAdaptor weavingAdaptor;
  228. private boolean isInitialized;
  229. public ExplicitlyInitializedClassLoaderWeavingAdaptor(ClassLoaderWeavingAdaptor weavingAdaptor) {
  230. this.weavingAdaptor = weavingAdaptor;
  231. this.isInitialized = false;
  232. }
  233. private void initialize(ClassLoader loader, IWeavingContext weavingContext) {
  234. if (!isInitialized) {
  235. isInitialized = true;
  236. weavingAdaptor.initialize(loader, weavingContext);
  237. }
  238. }
  239. public ClassLoaderWeavingAdaptor getWeavingAdaptor(ClassLoader loader, IWeavingContext weavingContext) {
  240. initialize(loader, weavingContext);
  241. return weavingAdaptor;
  242. }
  243. }
  244. /**
  245. * Returns a namespace based on the contest of the aspects available
  246. */
  247. public String getNamespace(ClassLoader loader) {
  248. ClassLoaderWeavingAdaptor weavingAdaptor = (ClassLoaderWeavingAdaptor) WeaverContainer.getWeaver(loader, weavingContext);
  249. return weavingAdaptor.getNamespace();
  250. }
  251. /**
  252. * Check to see if any classes have been generated for a particular classes loader. Calls
  253. * ClassLoaderWeavingAdaptor.generatedClassesExist()
  254. *
  255. * @param loader the class cloder
  256. * @return true if classes have been generated.
  257. */
  258. public boolean generatedClassesExist(ClassLoader loader) {
  259. return ((ClassLoaderWeavingAdaptor) WeaverContainer.getWeaver(loader, weavingContext)).generatedClassesExistFor(null);
  260. }
  261. public void flushGeneratedClasses(ClassLoader loader) {
  262. ((ClassLoaderWeavingAdaptor) WeaverContainer.getWeaver(loader, weavingContext)).flushGeneratedClasses();
  263. }
  264. }