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

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