Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

Aj.java 12KB

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