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.

ClassLoaderWeavingAdaptor.java 42KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  1. /*******************************************************************************
  2. * Copyright (c) 2005, 2017 Contributors.
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Eclipse Public License v 2.0
  6. * which accompanies this distribution and is available at
  7. * https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.txt
  8. *******************************************************************************/
  9. package org.aspectj.weaver.loadtime;
  10. import java.io.File;
  11. import java.io.IOException;
  12. import java.io.InputStream;
  13. import java.lang.invoke.MethodHandle;
  14. import java.lang.invoke.MethodHandles;
  15. import java.lang.reflect.AccessibleObject;
  16. import java.lang.reflect.Field;
  17. import java.lang.reflect.Method;
  18. import java.net.MalformedURLException;
  19. import java.net.URL;
  20. import java.security.ProtectionDomain;
  21. import java.util.*;
  22. import java.util.Map.Entry;
  23. import org.aspectj.bridge.AbortException;
  24. import org.aspectj.bridge.Constants;
  25. import org.aspectj.bridge.MessageUtil;
  26. import org.aspectj.util.LangUtil;
  27. import org.aspectj.weaver.IUnwovenClassFile;
  28. import org.aspectj.weaver.Lint;
  29. import org.aspectj.weaver.Lint.Kind;
  30. import org.aspectj.weaver.ResolvedType;
  31. import org.aspectj.weaver.UnresolvedType;
  32. import org.aspectj.weaver.World;
  33. import org.aspectj.weaver.bcel.BcelWeakClassLoaderReference;
  34. import org.aspectj.weaver.bcel.BcelWeaver;
  35. import org.aspectj.weaver.bcel.BcelWorld;
  36. import org.aspectj.weaver.bcel.Utility;
  37. import org.aspectj.weaver.loadtime.definition.Definition;
  38. import org.aspectj.weaver.loadtime.definition.DocumentParser;
  39. import org.aspectj.weaver.ltw.LTWWorld;
  40. import org.aspectj.weaver.patterns.PatternParser;
  41. import org.aspectj.weaver.patterns.TypePattern;
  42. import org.aspectj.weaver.tools.GeneratedClassHandler;
  43. import org.aspectj.weaver.tools.Trace;
  44. import org.aspectj.weaver.tools.TraceFactory;
  45. import org.aspectj.weaver.tools.WeavingAdaptor;
  46. import org.aspectj.weaver.tools.cache.WeavedClassCache;
  47. import org.objectweb.asm.*;
  48. import org.objectweb.asm.commons.ClassRemapper;
  49. import org.objectweb.asm.commons.Remapper;
  50. import sun.misc.Unsafe;
  51. /**
  52. * @author Alexandre Vasseur
  53. * @author Andy Clement
  54. * @author Abraham Nevado
  55. * @author David Knibb
  56. * @author John Kew
  57. */
  58. public class ClassLoaderWeavingAdaptor extends WeavingAdaptor {
  59. private final static String AOP_XML = Constants.AOP_USER_XML + ";" + Constants.AOP_AJC_XML + ";" + Constants.AOP_OSGI_XML;
  60. private boolean initialized;
  61. private List<TypePattern> dumpTypePattern = new ArrayList<>();
  62. private boolean dumpBefore = false;
  63. private boolean dumpDirPerClassloader = false;
  64. private boolean hasExcludes = false;
  65. private List<TypePattern> excludeTypePattern = new ArrayList<>(); // anything
  66. private List<String> excludeStartsWith = new ArrayList<>(); // com.foo..*
  67. private List<String> excludeStarDotDotStar = new ArrayList<>(); // *..*CGLIB*
  68. private List<String> excludeExactName = new ArrayList<>(); // com.foo.Bar
  69. private List<String> excludeEndsWith = new ArrayList<>(); // com.foo.Bar
  70. private List<String[]> excludeSpecial = new ArrayList<>();
  71. private boolean hasIncludes = false;
  72. private List<TypePattern> includeTypePattern = new ArrayList<>();
  73. private List<String> includeStartsWith = new ArrayList<>();
  74. private List<String> includeExactName = new ArrayList<>();
  75. private boolean includeStar = false;
  76. private List<TypePattern> aspectExcludeTypePattern = new ArrayList<>();
  77. private List<String> aspectExcludeStartsWith = new ArrayList<>();
  78. private List<TypePattern> aspectIncludeTypePattern = new ArrayList<>();
  79. private List<String> aspectIncludeStartsWith = new ArrayList<>();
  80. private StringBuffer namespace;
  81. private IWeavingContext weavingContext;
  82. private List<ConcreteAspectCodeGen> concreteAspects = new ArrayList<>();
  83. private static Trace trace = TraceFactory.getTraceFactory().getTrace(ClassLoaderWeavingAdaptor.class);
  84. public ClassLoaderWeavingAdaptor() {
  85. super();
  86. if (trace.isTraceEnabled()) {
  87. trace.enter("<init>", this);
  88. }
  89. if (trace.isTraceEnabled()) {
  90. trace.exit("<init>");
  91. }
  92. }
  93. /**
  94. * We don't need a reference to the class loader and using it during construction can cause problems with recursion. It also
  95. * makes sense to supply the weaving context during initialization to.
  96. *
  97. * @deprecated
  98. */
  99. @Deprecated
  100. public ClassLoaderWeavingAdaptor(final ClassLoader deprecatedLoader, final IWeavingContext deprecatedContext) {
  101. super();
  102. if (trace.isTraceEnabled()) {
  103. trace.enter("<init>", this, new Object[] { deprecatedLoader, deprecatedContext });
  104. }
  105. if (trace.isTraceEnabled()) {
  106. trace.exit("<init>");
  107. }
  108. }
  109. class SimpleGeneratedClassHandler implements GeneratedClassHandler {
  110. private BcelWeakClassLoaderReference loaderRef;
  111. SimpleGeneratedClassHandler(ClassLoader loader) {
  112. loaderRef = new BcelWeakClassLoaderReference(loader);
  113. }
  114. /**
  115. * Callback when we need to define a Closure in the JVM
  116. *
  117. */
  118. @Override
  119. public void acceptClass (String name, byte[] originalBytes, byte[] wovenBytes) {
  120. try {
  121. if (shouldDump(name.replace('/', '.'), false)) {
  122. dump(name, wovenBytes, false);
  123. }
  124. } catch (Throwable throwable) {
  125. throwable.printStackTrace();
  126. }
  127. if (activeProtectionDomain != null) {
  128. defineClass(loaderRef.getClassLoader(), name, wovenBytes, activeProtectionDomain);
  129. } else {
  130. defineClass(loaderRef.getClassLoader(), name, wovenBytes); // could be done lazily using the hook
  131. }
  132. }
  133. }
  134. public void initialize(final ClassLoader classLoader, IWeavingContext context) {
  135. if (initialized) {
  136. return;
  137. }
  138. boolean success = true;
  139. this.weavingContext = context;
  140. if (weavingContext == null) {
  141. weavingContext = new DefaultWeavingContext(classLoader);
  142. }
  143. createMessageHandler();
  144. this.generatedClassHandler = new SimpleGeneratedClassHandler(classLoader);
  145. List<Definition> definitions = weavingContext.getDefinitions(classLoader, this);
  146. if (definitions.isEmpty()) {
  147. disable(); // TODO maw Needed to ensure messages are flushed
  148. if (trace.isTraceEnabled()) {
  149. trace.exit("initialize", definitions);
  150. }
  151. return;
  152. }
  153. // TODO when the world works in terms of the context, we can remove the loader
  154. bcelWorld = new LTWWorld(classLoader, weavingContext, getMessageHandler(), null);
  155. weaver = new BcelWeaver(bcelWorld);
  156. // register the definitions
  157. success = registerDefinitions(weaver, classLoader, definitions);
  158. if (success) {
  159. // after adding aspects
  160. weaver.prepareForWeave();
  161. enable(); // TODO maw Needed to ensure messages are flushed
  162. success = weaveAndDefineConceteAspects();
  163. }
  164. if (success) {
  165. enable();
  166. } else {
  167. disable();
  168. bcelWorld = null;
  169. weaver = null;
  170. }
  171. if (WeavedClassCache.isEnabled()) {
  172. initializeCache(classLoader, getAspectClassNames(definitions), generatedClassHandler, getMessageHandler());
  173. }
  174. initialized = true;
  175. if (trace.isTraceEnabled()) {
  176. trace.exit("initialize", isEnabled());
  177. }
  178. }
  179. /**
  180. * Get the list of all aspects from the defintion list
  181. * @param definitions
  182. * @return
  183. */
  184. List<String> getAspectClassNames(List<Definition> definitions) {
  185. List<String> aspects = new LinkedList<>();
  186. for (Definition def : definitions) {
  187. List<String> defAspects = def.getAspectClassNames();
  188. if (defAspects != null) {
  189. aspects.addAll(defAspects);
  190. }
  191. }
  192. return aspects;
  193. }
  194. /**
  195. * Load and cache the aop.xml/properties according to the classloader visibility rules
  196. *
  197. * @param loader
  198. */
  199. List<Definition> parseDefinitions(final ClassLoader loader) {
  200. if (trace.isTraceEnabled()) {
  201. trace.enter("parseDefinitions", this);
  202. }
  203. List<Definition> definitions = new ArrayList<>();
  204. try {
  205. info("register classloader " + getClassLoaderName(loader));
  206. // TODO av underoptimized: we will parse each XML once per CL that see it
  207. // TODO av dev mode needed ? TBD -Daj5.def=...
  208. if (loader.equals(ClassLoader.getSystemClassLoader())) {
  209. String file = System.getProperty("aj5.def", null);
  210. if (file != null) {
  211. info("using (-Daj5.def) " + file);
  212. definitions.add(DocumentParser.parse((new File(file)).toURI().toURL()));
  213. }
  214. }
  215. String resourcePath = System.getProperty("org.aspectj.weaver.loadtime.configuration", AOP_XML);
  216. if (trace.isTraceEnabled()) {
  217. trace.event("parseDefinitions", this, resourcePath);
  218. }
  219. StringTokenizer st = new StringTokenizer(resourcePath, ";");
  220. while (st.hasMoreTokens()) {
  221. String nextDefinition = st.nextToken();
  222. if (nextDefinition.startsWith("file:")) {
  223. try {
  224. String fpath = new URL(nextDefinition).getFile();
  225. File configFile = new File(fpath);
  226. if (!configFile.exists()) {
  227. warn("configuration does not exist: " + nextDefinition);
  228. } else {
  229. definitions.add(DocumentParser.parse(configFile.toURI().toURL()));
  230. }
  231. } catch (MalformedURLException mue) {
  232. error("malformed definition url: " + nextDefinition);
  233. }
  234. } else {
  235. Enumeration<URL> xmls = weavingContext.getResources(nextDefinition);
  236. // System.out.println("? registerDefinitions: found-aop.xml=" + xmls.hasMoreElements() + ", loader=" + loader);
  237. Set<URL> seenBefore = new HashSet<>();
  238. while (xmls.hasMoreElements()) {
  239. URL xml = xmls.nextElement();
  240. if (trace.isTraceEnabled()) {
  241. trace.event("parseDefinitions", this, xml);
  242. }
  243. if (!seenBefore.contains(xml)) {
  244. info("using configuration " + weavingContext.getFile(xml));
  245. definitions.add(DocumentParser.parse(xml));
  246. seenBefore.add(xml);
  247. } else {
  248. debug("ignoring duplicate definition: " + xml);
  249. }
  250. }
  251. }
  252. }
  253. if (definitions.isEmpty()) {
  254. info("no configuration found. Disabling weaver for class loader " + getClassLoaderName(loader));
  255. }
  256. } catch (Exception e) {
  257. definitions.clear();
  258. warn("parse definitions failed", e);
  259. }
  260. if (trace.isTraceEnabled()) {
  261. trace.exit("parseDefinitions", definitions);
  262. }
  263. return definitions;
  264. }
  265. private boolean registerDefinitions(final BcelWeaver weaver, final ClassLoader loader, List<Definition> definitions) {
  266. if (trace.isTraceEnabled()) {
  267. trace.enter("registerDefinitions", this, definitions);
  268. }
  269. boolean success = true;
  270. try {
  271. registerOptions(weaver, loader, definitions);
  272. registerAspectExclude(weaver, loader, definitions);
  273. registerAspectInclude(weaver, loader, definitions);
  274. success = registerAspects(weaver, loader, definitions);
  275. registerIncludeExclude(weaver, loader, definitions);
  276. registerDump(weaver, loader, definitions);
  277. } catch (Exception ex) {
  278. trace.error("register definition failed", ex);
  279. success = false;
  280. warn("register definition failed", (ex instanceof AbortException) ? null : ex);
  281. }
  282. if (trace.isTraceEnabled()) {
  283. trace.exit("registerDefinitions", success);
  284. }
  285. return success;
  286. }
  287. private String getClassLoaderName(ClassLoader loader) {
  288. return weavingContext.getClassLoaderName();
  289. }
  290. /**
  291. * Configure the weaver according to the option directives TODO av - don't know if it is that good to reuse, since we only allow
  292. * a small subset of options in LTW
  293. *
  294. * @param weaver
  295. * @param loader
  296. * @param definitions
  297. */
  298. private void registerOptions(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) {
  299. StringBuilder allOptions = new StringBuilder();
  300. for (Definition definition : definitions) {
  301. allOptions.append(definition.getWeaverOptions()).append(' ');
  302. }
  303. Options.WeaverOption weaverOption = Options.parse(allOptions.toString(), loader, getMessageHandler());
  304. // configure the weaver and world
  305. // AV - code duplicates AspectJBuilder.initWorldAndWeaver()
  306. World world = weaver.getWorld();
  307. setMessageHandler(weaverOption.messageHandler);
  308. world.setXlazyTjp(weaverOption.lazyTjp);
  309. world.setXHasMemberSupportEnabled(weaverOption.hasMember);
  310. world.setTiming(weaverOption.timers, true);
  311. world.setOptionalJoinpoints(weaverOption.optionalJoinpoints);
  312. world.setPinpointMode(weaverOption.pinpoint);
  313. weaver.setReweavableMode(weaverOption.notReWeavable);
  314. if (weaverOption.loadersToSkip != null && weaverOption.loadersToSkip.length() > 0) {
  315. Aj.loadersToSkip = LangUtil.anySplit(weaverOption.loadersToSkip, ",");
  316. }
  317. if (Aj.loadersToSkip != null) {
  318. MessageUtil.info(world.getMessageHandler(),"no longer creating weavers for these classloaders: "+Aj.loadersToSkip);
  319. }
  320. world.performExtraConfiguration(weaverOption.xSet);
  321. world.setXnoInline(weaverOption.noInline);
  322. // AMC - autodetect as per line below, needed for AtAjLTWTests.testLTWUnweavable
  323. world.setBehaveInJava5Way(true);
  324. world.setAddSerialVerUID(weaverOption.addSerialVersionUID);
  325. /* First load defaults */
  326. bcelWorld.getLint().loadDefaultProperties();
  327. /* Second overlay LTW defaults */
  328. bcelWorld.getLint().adviceDidNotMatch.setKind(null);
  329. /* Third load user file using -Xlintfile so that -Xlint wins */
  330. if (weaverOption.lintFile != null) {
  331. InputStream resource = null;
  332. try {
  333. resource = loader.getResourceAsStream(weaverOption.lintFile);
  334. Exception failure = null;
  335. if (resource != null) {
  336. try {
  337. Properties properties = new Properties();
  338. properties.load(resource);
  339. world.getLint().setFromProperties(properties);
  340. } catch (IOException e) {
  341. failure = e;
  342. }
  343. }
  344. if (failure != null || resource == null) {
  345. warn("Cannot access resource for -Xlintfile:" + weaverOption.lintFile, failure);
  346. // world.getMessageHandler().handleMessage(new Message(
  347. // "Cannot access resource for -Xlintfile:"+weaverOption.lintFile,
  348. // IMessage.WARNING,
  349. // failure,
  350. // null));
  351. }
  352. } finally {
  353. try {
  354. resource.close();
  355. } catch (Throwable t) {
  356. }
  357. }
  358. }
  359. /* Fourth override with -Xlint */
  360. if (weaverOption.lint != null) {
  361. if (weaverOption.lint.equals("default")) {// FIXME should be AjBuildConfig.AJLINT_DEFAULT but yetanother deps..
  362. bcelWorld.getLint().loadDefaultProperties();
  363. } else {
  364. bcelWorld.getLint().setAll(weaverOption.lint);
  365. if (weaverOption.lint.equals("ignore")) {
  366. bcelWorld.setAllLintIgnored();
  367. }
  368. }
  369. }
  370. // TODO proceedOnError option
  371. }
  372. private void registerAspectExclude(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) {
  373. String fastMatchInfo = null;
  374. for (Definition definition : definitions) {
  375. for (String exclude : definition.getAspectExcludePatterns()) {
  376. TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
  377. aspectExcludeTypePattern.add(excludePattern);
  378. fastMatchInfo = looksLikeStartsWith(exclude);
  379. if (fastMatchInfo != null) {
  380. aspectExcludeStartsWith.add(fastMatchInfo);
  381. }
  382. }
  383. }
  384. }
  385. private void registerAspectInclude(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) {
  386. String fastMatchInfo = null;
  387. for (Definition definition : definitions) {
  388. for (String include : definition.getAspectIncludePatterns()) {
  389. TypePattern includePattern = new PatternParser(include).parseTypePattern();
  390. aspectIncludeTypePattern.add(includePattern);
  391. fastMatchInfo = looksLikeStartsWith(include);
  392. if (fastMatchInfo != null) {
  393. aspectIncludeStartsWith.add(fastMatchInfo);
  394. }
  395. }
  396. }
  397. }
  398. protected void lint(String name, String[] infos) {
  399. Lint lint = bcelWorld.getLint();
  400. Kind kind = lint.getLintKind(name);
  401. kind.signal(infos, null, null);
  402. }
  403. @Override
  404. public String getContextId() {
  405. return weavingContext.getId();
  406. }
  407. /**
  408. * Register the aspect, following include / exclude rules
  409. *
  410. * @param weaver
  411. * @param loader
  412. * @param definitions
  413. */
  414. private boolean registerAspects(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) {
  415. if (trace.isTraceEnabled()) {
  416. trace.enter("registerAspects", this, new Object[] { weaver, loader, definitions });
  417. }
  418. boolean success = true;
  419. // TODO: the exclude aspect allow to exclude aspect defined upper in the CL hierarchy - is it what we want ??
  420. // if not, review the getResource so that we track which resource is defined by which CL
  421. // iterate aspectClassNames
  422. // exclude if in any of the exclude list
  423. for (Definition definition : definitions) {
  424. for (String aspectClassName : definition.getAspectClassNames()) {
  425. if (acceptAspect(aspectClassName)) {
  426. info("register aspect " + aspectClassName);
  427. // System.err.println("? ClassLoaderWeavingAdaptor.registerAspects() aspectName=" + aspectClassName +
  428. // ", loader=" + loader + ", bundle=" + weavingContext.getClassLoaderName());
  429. String requiredType = definition.getAspectRequires(aspectClassName);
  430. if (requiredType != null) {
  431. // This aspect expresses that it requires a type to be around, otherwise it should 'switch off'
  432. ((BcelWorld) weaver.getWorld()).addAspectRequires(aspectClassName, requiredType);
  433. }
  434. String definedScope = definition.getScopeForAspect(aspectClassName);
  435. if (definedScope != null) {
  436. ((BcelWorld) weaver.getWorld()).addScopedAspect(aspectClassName, definedScope);
  437. }
  438. // ResolvedType aspect =
  439. weaver.addLibraryAspect(aspectClassName);
  440. // generate key for SC
  441. if (namespace == null) {
  442. namespace = new StringBuffer(aspectClassName);
  443. } else {
  444. namespace = namespace.append(";").append(aspectClassName);
  445. }
  446. } else {
  447. // warn("aspect excluded: " + aspectClassName);
  448. lint("aspectExcludedByConfiguration", new String[] { aspectClassName, getClassLoaderName(loader) });
  449. }
  450. }
  451. }
  452. // iterate concreteAspects
  453. // exclude if in any of the exclude list - note that the user defined name matters for that to happen
  454. for (Definition definition : definitions) {
  455. for (Definition.ConcreteAspect concreteAspect : definition.getConcreteAspects()) {
  456. if (acceptAspect(concreteAspect.name)) {
  457. info("define aspect " + concreteAspect.name);
  458. ConcreteAspectCodeGen gen = new ConcreteAspectCodeGen(concreteAspect, weaver.getWorld());
  459. if (!gen.validate()) {
  460. error("Concrete-aspect '" + concreteAspect.name + "' could not be registered");
  461. success = false;
  462. break;
  463. }
  464. ((BcelWorld) weaver.getWorld()).addSourceObjectType(Utility.makeJavaClass(concreteAspect.name, gen.getBytes()),
  465. true);
  466. concreteAspects.add(gen);
  467. weaver.addLibraryAspect(concreteAspect.name);
  468. // generate key for SC
  469. if (namespace == null) {
  470. namespace = new StringBuffer(concreteAspect.name);
  471. } else {
  472. namespace = namespace.append(";" + concreteAspect.name);
  473. }
  474. }
  475. }
  476. }
  477. /* We couldn't register one or more aspects so disable the adaptor */
  478. if (!success) {
  479. warn("failure(s) registering aspects. Disabling weaver for class loader " + getClassLoaderName(loader));
  480. }
  481. /* We didn't register any aspects so disable the adaptor */
  482. else if (namespace == null) {
  483. success = false;
  484. info("no aspects registered. Disabling weaver for class loader " + getClassLoaderName(loader));
  485. }
  486. if (trace.isTraceEnabled()) {
  487. trace.exit("registerAspects", success);
  488. }
  489. return success;
  490. }
  491. private boolean weaveAndDefineConceteAspects() {
  492. if (trace.isTraceEnabled()) {
  493. trace.enter("weaveAndDefineConceteAspects", this, concreteAspects);
  494. }
  495. boolean success = true;
  496. for (ConcreteAspectCodeGen gen : concreteAspects) {
  497. String name = gen.getClassName();
  498. byte[] bytes = gen.getBytes();
  499. try {
  500. byte[] newBytes = weaveClass(name, bytes, true);
  501. this.generatedClassHandler.acceptClass(name, bytes, newBytes == null ? bytes : newBytes);
  502. } catch (IOException ex) {
  503. trace.error("weaveAndDefineConceteAspects", ex);
  504. error("exception weaving aspect '" + name + "'", ex);
  505. }
  506. }
  507. if (trace.isTraceEnabled()) {
  508. trace.exit("weaveAndDefineConceteAspects", success);
  509. }
  510. return success;
  511. }
  512. /**
  513. * Register the include / exclude filters. We duplicate simple patterns in startWith filters that will allow faster matching
  514. * without ResolvedType
  515. *
  516. * @param weaver
  517. * @param loader
  518. * @param definitions
  519. */
  520. private void registerIncludeExclude(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) {
  521. String fastMatchInfo = null;
  522. for (Definition definition : definitions) {
  523. for (String value : definition.getIncludePatterns()) {
  524. hasIncludes = true;
  525. String include = value;
  526. fastMatchInfo = looksLikeStartsWith(include);
  527. if (fastMatchInfo != null) {
  528. includeStartsWith.add(fastMatchInfo);
  529. } else if (include.equals("*")) {
  530. includeStar = true;
  531. } else if ((fastMatchInfo = looksLikeExactName(include)) != null) {
  532. includeExactName.add(fastMatchInfo);
  533. } else {
  534. TypePattern includePattern = new PatternParser(include).parseTypePattern();
  535. includeTypePattern.add(includePattern);
  536. }
  537. }
  538. for (String s : definition.getExcludePatterns()) {
  539. hasExcludes = true;
  540. String exclude = s;
  541. fastMatchInfo = looksLikeStartsWith(exclude);
  542. if (fastMatchInfo != null) {
  543. excludeStartsWith.add(fastMatchInfo);
  544. } else if ((fastMatchInfo = looksLikeStarDotDotStarExclude(exclude)) != null) {
  545. excludeStarDotDotStar.add(fastMatchInfo);
  546. } else if ((fastMatchInfo = looksLikeExactName(exclude)) != null) {
  547. excludeExactName.add(exclude);
  548. } else if ((fastMatchInfo = looksLikeEndsWith(exclude)) != null) {
  549. excludeEndsWith.add(fastMatchInfo);
  550. } else if (exclude
  551. .equals("org.codehaus.groovy..* && !org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController*")) {
  552. // TODO need a more sophisticated analysis here, to allow for similar situations
  553. excludeSpecial.add(new String[]{"org.codehaus.groovy.",
  554. "org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController"});
  555. // for the related test:
  556. // } else if (exclude.equals("testdata..* && !testdata.sub.Oran*")) {
  557. // excludeSpecial.add(new String[] { "testdata.", "testdata.sub.Oran" });
  558. } else {
  559. TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
  560. excludeTypePattern.add(excludePattern);
  561. }
  562. }
  563. }
  564. }
  565. /**
  566. * Checks if the pattern looks like "*..*XXXX*" and if so returns XXXX. This will enable fast name matching of CGLIB exclusion
  567. *
  568. */
  569. private String looksLikeStarDotDotStarExclude(String typePattern) {
  570. if (!typePattern.startsWith("*..*")) {
  571. return null;
  572. }
  573. if (!typePattern.endsWith("*")) {
  574. return null;
  575. }
  576. String subPattern = typePattern.substring(4, typePattern.length() - 1);
  577. if (hasStarDot(subPattern, 0)) {
  578. return null;
  579. }
  580. return subPattern.replace('$', '.');
  581. }
  582. /**
  583. * Checks if the pattern looks like "com.foo.Bar" - an exact name
  584. */
  585. private String looksLikeExactName(String typePattern) {
  586. if (hasSpaceAnnotationPlus(typePattern, 0) || typePattern.contains("*")) {
  587. return null;
  588. }
  589. return typePattern.replace('$', '.');
  590. }
  591. /**
  592. * Checks if the pattern looks like "*Exception"
  593. */
  594. private String looksLikeEndsWith(String typePattern) {
  595. if (typePattern.charAt(0) != '*') {
  596. return null;
  597. }
  598. if (hasSpaceAnnotationPlus(typePattern, 1) || hasStarDot(typePattern, 1)) {
  599. return null;
  600. }
  601. return typePattern.substring(1).replace('$', '.');
  602. }
  603. /**
  604. * Determine if something in the string is going to affect our ability to optimize. Checks for: ' ' '@' '+'
  605. */
  606. private boolean hasSpaceAnnotationPlus(String string, int pos) {
  607. for (int i = pos, max = string.length(); i < max; i++) {
  608. char ch = string.charAt(i);
  609. if (ch == ' ' || ch == '@' || ch == '+') {
  610. return true;
  611. }
  612. }
  613. return false;
  614. }
  615. /**
  616. * Determine if something in the string is going to affect our ability to optimize. Checks for: '*' '.'
  617. */
  618. private boolean hasStarDot(String string, int pos) {
  619. for (int i = pos, max = string.length(); i < max; i++) {
  620. char ch = string.charAt(i);
  621. if (ch == '*' || ch == '.') {
  622. return true;
  623. }
  624. }
  625. return false;
  626. }
  627. /**
  628. * Checks if the type pattern looks like "com.foo..*"
  629. */
  630. private String looksLikeStartsWith(String typePattern) {
  631. if (hasSpaceAnnotationPlus(typePattern, 0) || typePattern.charAt(typePattern.length() - 1) != '*') {
  632. return null;
  633. }
  634. // now must looks like with "charsss..*" or "cha.rss..*" etc
  635. // note that "*" and "*..*" won't be fast matched
  636. // and that "charsss.*" will not neither
  637. int length = typePattern.length();
  638. if (typePattern.endsWith("..*") && length > 3) {
  639. if (typePattern.indexOf("..") == length - 3 // no ".." before last sequence
  640. && typePattern.indexOf('*') == length - 1) { // no earlier '*'
  641. return typePattern.substring(0, length - 2).replace('$', '.'); // "charsss." or "char.rss." etc
  642. }
  643. }
  644. return null;
  645. }
  646. /**
  647. * Register the dump filter
  648. *
  649. * @param weaver
  650. * @param loader
  651. * @param definitions
  652. */
  653. private void registerDump(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) {
  654. for (Definition definition : definitions) {
  655. for (String dump : definition.getDumpPatterns()) {
  656. TypePattern pattern = new PatternParser(dump).parseTypePattern();
  657. dumpTypePattern.add(pattern);
  658. }
  659. if (definition.shouldDumpBefore()) {
  660. dumpBefore = true;
  661. }
  662. if (definition.createDumpDirPerClassloader()) {
  663. dumpDirPerClassloader = true;
  664. }
  665. }
  666. }
  667. /**
  668. * Determine whether a type should be accepted for weaving, by checking it against any includes/excludes.
  669. *
  670. * @param className the name of the type to possibly accept
  671. * @param bytes the bytecode for the type (in case we need to look inside, eg. annotations)
  672. * @return true if it should be accepted for weaving
  673. */
  674. @Override
  675. protected boolean accept(String className, byte[] bytes) {
  676. if (!hasExcludes && !hasIncludes) {
  677. return true;
  678. }
  679. // still try to avoid ResolvedType if we have simple patterns
  680. String fastClassName = className.replace('/', '.');
  681. for (String excludeStartsWithString : excludeStartsWith) {
  682. if (fastClassName.startsWith(excludeStartsWithString)) {
  683. return false;
  684. }
  685. }
  686. // Fast exclusion of patterns like: "*..*CGLIB*"
  687. if (!excludeStarDotDotStar.isEmpty()) {
  688. for (String namePiece : excludeStarDotDotStar) {
  689. int index = fastClassName.lastIndexOf('.');
  690. if (fastClassName.indexOf(namePiece, index + 1) != -1) {
  691. return false;
  692. }
  693. }
  694. }
  695. fastClassName = fastClassName.replace('$', '.');
  696. if (!excludeEndsWith.isEmpty()) {
  697. for (String lastPiece : excludeEndsWith) {
  698. if (fastClassName.endsWith(lastPiece)) {
  699. return false;
  700. }
  701. }
  702. }
  703. // Fast exclusion of exact names
  704. if (!excludeExactName.isEmpty()) {
  705. for (String name : excludeExactName) {
  706. if (fastClassName.equals(name)) {
  707. return false;
  708. }
  709. }
  710. }
  711. if (!excludeSpecial.isEmpty()) {
  712. for (String[] entry : excludeSpecial) {
  713. String excludeThese = entry[0];
  714. String exceptThese = entry[1];
  715. if (fastClassName.startsWith(excludeThese) && !fastClassName.startsWith(exceptThese)) {
  716. return false;
  717. }
  718. }
  719. }
  720. /*
  721. * Bug 120363 If we have an exclude pattern that cannot be matched using "starts with" then we cannot fast accept
  722. */
  723. boolean didSomeIncludeMatching = false;
  724. if (excludeTypePattern.isEmpty()) {
  725. if (includeStar) {
  726. return true;
  727. }
  728. if (!includeExactName.isEmpty()) {
  729. didSomeIncludeMatching = true;
  730. for (String exactname : includeExactName) {
  731. if (fastClassName.equals(exactname)) {
  732. return true;
  733. }
  734. }
  735. }
  736. boolean fastAccept = false;// defaults to false if no fast include
  737. for (String s : includeStartsWith) {
  738. didSomeIncludeMatching = true;
  739. fastAccept = fastClassName.startsWith(s);
  740. if (fastAccept) {
  741. return true;
  742. }
  743. }
  744. // We may have processed all patterns now... check that and return
  745. if (includeTypePattern.isEmpty()) {
  746. return !didSomeIncludeMatching;
  747. }
  748. }
  749. boolean accept;
  750. try {
  751. ensureDelegateInitialized(className, bytes);
  752. ResolvedType classInfo = delegateForCurrentClass.getResolvedTypeX();
  753. // exclude are "AND"ed
  754. for (TypePattern typePattern : excludeTypePattern) {
  755. if (typePattern.matchesStatically(classInfo)) {
  756. // exclude match - skip
  757. return false;
  758. }
  759. }
  760. // include are "OR"ed
  761. if (includeStar) {
  762. return true;
  763. }
  764. if (!includeExactName.isEmpty()) {
  765. didSomeIncludeMatching = true;
  766. for (String exactname : includeExactName) {
  767. if (fastClassName.equals(exactname)) {
  768. return true;
  769. }
  770. }
  771. }
  772. for (String s : includeStartsWith) {
  773. didSomeIncludeMatching = true;
  774. boolean fastaccept = fastClassName.startsWith(s);
  775. if (fastaccept) {
  776. return true;
  777. }
  778. }
  779. accept = !didSomeIncludeMatching; // only true if no includes at all
  780. for (TypePattern typePattern : includeTypePattern) {
  781. accept = typePattern.matchesStatically(classInfo);
  782. if (accept) {
  783. break;
  784. }
  785. // goes on if this include did not match ("OR"ed)
  786. }
  787. } finally {
  788. this.bcelWorld.demote();
  789. }
  790. return accept;
  791. }
  792. // FIXME we don't use include/exclude of others aop.xml
  793. // this can be nice but very dangerous as well to change that
  794. private boolean acceptAspect(String aspectClassName) {
  795. // avoid ResolvedType if not needed
  796. if (aspectExcludeTypePattern.isEmpty() && aspectIncludeTypePattern.isEmpty()) {
  797. return true;
  798. }
  799. // still try to avoid ResolvedType if we have simple patterns
  800. // EXCLUDE: if one match then reject
  801. String fastClassName = aspectClassName.replace('/', '.').replace('.', '$');
  802. for (String value : aspectExcludeStartsWith) {
  803. if (fastClassName.startsWith(value)) {
  804. return false;
  805. }
  806. }
  807. // INCLUDE: if one match then accept
  808. for (String s : aspectIncludeStartsWith) {
  809. if (fastClassName.startsWith(s)) {
  810. return true;
  811. }
  812. }
  813. // needs further analysis
  814. ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(aspectClassName), true);
  815. // exclude are "AND"ed
  816. for (TypePattern typePattern: aspectExcludeTypePattern) {
  817. if (typePattern.matchesStatically(classInfo)) {
  818. // exclude match - skip
  819. return false;
  820. }
  821. }
  822. // include are "OR"ed
  823. boolean accept = true;// defaults to true if no include
  824. for (TypePattern typePattern: aspectIncludeTypePattern) {
  825. accept = typePattern.matchesStatically(classInfo);
  826. if (accept) {
  827. break;
  828. }
  829. // goes on if this include did not match ("OR"ed)
  830. }
  831. return accept;
  832. }
  833. @Override
  834. protected boolean shouldDump(String className, boolean before) {
  835. // Don't dump before weaving unless asked to
  836. if (before && !dumpBefore) {
  837. return false;
  838. }
  839. // avoid ResolvedType if not needed
  840. if (dumpTypePattern.isEmpty()) {
  841. return false;
  842. }
  843. // TODO AV - optimize for className.startWith only
  844. ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(className), true);
  845. // dump
  846. for (TypePattern typePattern : dumpTypePattern) {
  847. if (typePattern.matchesStatically(classInfo)) {
  848. // dump match
  849. return true;
  850. }
  851. }
  852. return false;
  853. }
  854. @Override
  855. protected String getDumpDir() {
  856. if (dumpDirPerClassloader) {
  857. StringBuilder dir = new StringBuilder();
  858. dir.append("_ajdump").append(File.separator).append(weavingContext.getId());
  859. return dir.toString();
  860. } else {
  861. return super.getDumpDir();
  862. }
  863. }
  864. /*
  865. * shared classes methods
  866. */
  867. /**
  868. * @return Returns the key.
  869. */
  870. public String getNamespace() {
  871. // System.out.println("ClassLoaderWeavingAdaptor.getNamespace() classloader=" + weavingContext.getClassLoaderName() +
  872. // ", namespace=" + namespace);
  873. if (namespace == null) {
  874. return "";
  875. } else {
  876. return new String(namespace);
  877. }
  878. }
  879. /**
  880. * Check to see if any classes are stored in the generated classes cache. Then flush the cache if it is not empty
  881. *
  882. * @param className TODO
  883. * @return true if a class has been generated and is stored in the cache
  884. */
  885. public boolean generatedClassesExistFor(String className) {
  886. // System.err.println("? ClassLoaderWeavingAdaptor.generatedClassesExist() classname=" + className + ", size=" +
  887. // generatedClasses);
  888. if (className == null) {
  889. return !generatedClasses.isEmpty();
  890. } else {
  891. return generatedClasses.containsKey(className);
  892. }
  893. }
  894. /**
  895. * Flush the generated classes cache
  896. */
  897. public void flushGeneratedClasses() {
  898. // System.err.println("? ClassLoaderWeavingAdaptor.flushGeneratedClasses() generatedClasses=" + generatedClasses);
  899. generatedClasses = new HashMap<>();
  900. }
  901. /**
  902. * Remove generated classes based on the supplied className. This will
  903. * remove any entries related to this name - so the class itself plus
  904. * and inner classes.
  905. * @param className a slashed classname (e.g. com/foo/Bar)
  906. */
  907. public void flushGeneratedClassesFor(String className) {
  908. try {
  909. String dottedClassName = className.replace('/', '.');
  910. String dottedClassNameDollar = dottedClassName + "$"; // to pick up inner classes
  911. generatedClasses.entrySet().removeIf(entry -> {
  912. String generatedClassName = entry.getKey();
  913. return generatedClassName.equals(dottedClassName) || generatedClassName.startsWith(dottedClassNameDollar);
  914. });
  915. } catch (Throwable t) {
  916. new RuntimeException("Unexpected problem tidying up generated classes for " + className, t).printStackTrace();
  917. }
  918. }
  919. private static final Object lock = new Object();
  920. /**
  921. * Instance of either {@link sun.misc.Unsafe} or {@link jdk.internal.misc.Unsafe}. Luckily, both types have
  922. * {@code defineClass} methods with identical signatures. I.e., method handle {@link #defineClassMethodHandle} can be
  923. * invoked with the same set of parameters for both types.
  924. */
  925. private static Object unsafeInstance = null;
  926. /**
  927. * Method handle for defining new classes in arbitrary class loaders. For invocation, use in connection with
  928. * {@link #unsafeInstance}.
  929. */
  930. private static MethodHandle defineClassMethodHandle;
  931. static {
  932. try {
  933. createDefineClassMethodHandle();
  934. }
  935. catch (Exception initializationError) {
  936. new RuntimeException(
  937. "The aspect weaver cannot determine any valid method to define auxiliary classes in arbitrary class loaders. " +
  938. "Aspect weaving will *not* work, and you will see subsequent errors. Please search for corresponding " +
  939. "issues at https://github.com/eclipse-aspectj/aspectj/issues. If there are none, please create a new one.",
  940. initializationError
  941. ).printStackTrace();
  942. }
  943. }
  944. /**
  945. * Scaffolding for defining classes in arbitrary class loaders
  946. * <p>
  947. * Inspired by and shamelessly adapted from <a href="https://bit.ly/3w10oH5">Byte Buddy's {@code ClassInjector}</a>.
  948. * Special thanks to Byte Buddy (BB) author Rafael Winterhalter, who briefly mentioned this approach in a
  949. * <a href="https://bit.ly/3SjFOZY">GitHub comment</a> related to JDK issue
  950. * <a href="https://bugs.openjdk.org/browse/JDK-8200559">JDK-8200559</a>.
  951. * <p>
  952. * <b>Background:</b> Instead of BB, we use ASM and reflection as follows:
  953. * <ul>
  954. * <li>
  955. * Create a mirror class for {@link AccessibleObject} with a different package name in a separate, throw-away
  956. * class loader.
  957. * </li>
  958. * <li>
  959. * Use the mirror class to calculate the {@link Unsafe#objectFieldOffset(Field)} for boolean field
  960. * {@link AccessibleObject#override}, which is expected to be identical to the offset of the same field in the
  961. * original class.
  962. * </li>
  963. * <li>
  964. * After we have the offset, we can use it to override the field value in the original class, deactivating access
  965. * checks for {@link jdk.internal.misc.Unsafe#defineClass(String, byte[], int, int, ClassLoader, ProtectionDomain)},
  966. * the method we need to execute using a method handle.
  967. * </li>
  968. * </ul>
  969. * All these serve the sole purpose enable LTW without {@code --add-opens java.base/java.lang=ALL-UNNAMED} on the
  970. * JVM command line on JDK 16+, which was necessary for AspectJ 1.9.7 (Java 16) to 1.9.21 (Java 21).
  971. *
  972. * @throws Exception if anything goes wrong, trying to determine a usable {@code defineClass} method handle from any
  973. * of the inspected classes
  974. */
  975. private static synchronized void createDefineClassMethodHandle() throws Exception {
  976. Unsafe publicUnsafeInstance = null;
  977. try {
  978. Field publicUnsafeField = Unsafe.class.getDeclaredField("theUnsafe");
  979. publicUnsafeField.setAccessible(true);
  980. publicUnsafeInstance = (Unsafe) publicUnsafeField.get(null);
  981. synchronized (lock) {
  982. unsafeInstance = publicUnsafeInstance;
  983. defineClassMethodHandle = createMethodHandle(
  984. "sun.misc.Unsafe", "defineClass",
  985. String.class, byte[].class, int.class, int.class, ClassLoader.class, ProtectionDomain.class
  986. );
  987. }
  988. }
  989. catch (Exception publicUnsafeException) {
  990. if (publicUnsafeInstance == null)
  991. throw publicUnsafeException;
  992. long overrideOffset = getAccessibleObjectOverrideOffset(publicUnsafeInstance);
  993. Class<?> internalUnsafeType = Class.forName("jdk.internal.misc.Unsafe");
  994. Field internalUnsafeField = internalUnsafeType.getDeclaredField("theUnsafe");
  995. publicUnsafeInstance.putBoolean(internalUnsafeField, overrideOffset, true);
  996. Method internalUnsafeDefineClassMethod = internalUnsafeType.getMethod(
  997. "defineClass",
  998. String.class, byte[].class, int.class, int.class, ClassLoader.class, ProtectionDomain.class
  999. );
  1000. publicUnsafeInstance.putBoolean(internalUnsafeDefineClassMethod, overrideOffset, true);
  1001. synchronized (lock) {
  1002. unsafeInstance = internalUnsafeField.get(null);
  1003. defineClassMethodHandle = createMethodHandle(internalUnsafeDefineClassMethod);
  1004. }
  1005. }
  1006. }
  1007. private static long getAccessibleObjectOverrideOffset(Unsafe unsafe)
  1008. throws IOException, ClassNotFoundException, NoSuchFieldException
  1009. {
  1010. Objects.requireNonNull(unsafe);
  1011. Field overrideField;
  1012. try {
  1013. overrideField = AccessibleObject.class.getDeclaredField("override");
  1014. }
  1015. catch (NoSuchFieldException ignored) {
  1016. // On JDK 12+, field AccessibleObject.override is protected from reflection. The work-around is to create a
  1017. // mirror class with the same field layout by transforming the original class, so we can calculate the field
  1018. // offset of 'override' and set a value in the original class using the now known offset.
  1019. Class<?> mirrorClass = getMirrorClass(
  1020. "java.lang.reflect.AccessibleObject", "org.aspectj.mirror.AccessibleObject", true
  1021. );
  1022. overrideField = mirrorClass.getDeclaredField("override");
  1023. }
  1024. return unsafe.objectFieldOffset(overrideField);
  1025. }
  1026. public static MethodHandle createMethodHandle(String className, String methodName, Class<?>... argumentTypes)
  1027. throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException
  1028. {
  1029. Class<?> clazz = Class.forName(className);
  1030. Method method = clazz.getDeclaredMethod(methodName, argumentTypes);
  1031. return createMethodHandle(method, false);
  1032. }
  1033. public static MethodHandle createMethodHandle(Method method) throws IllegalAccessException {
  1034. return createMethodHandle(method, false);
  1035. }
  1036. public static MethodHandle createMethodHandle(Method method, boolean setAccessible)
  1037. throws IllegalAccessException
  1038. {
  1039. // Use Method::setAccessible to access private methods. Caveat: This does not work for classes in packages not
  1040. // exported to the calling module (for LTW usually the unnamed module).
  1041. if (setAccessible)
  1042. method.setAccessible(true);
  1043. return MethodHandles.lookup().unreflect(method);
  1044. }
  1045. @SuppressWarnings("SameParameterValue")
  1046. private static Class<?> getMirrorClass(String originalClass, String mirrorClass, boolean removeMethods)
  1047. throws IOException, ClassNotFoundException
  1048. {
  1049. Objects.requireNonNull(originalClass);
  1050. Objects.requireNonNull(mirrorClass);
  1051. if (mirrorClass.equals(originalClass))
  1052. throw new IllegalArgumentException("Mirror class name must be different from original " + originalClass);
  1053. byte[] mirrorClassBytes = getMirrorClassBytes(originalClass, mirrorClass, removeMethods);
  1054. ClassLoader mirrorClassLoader = new SingleClassLoader(mirrorClass, mirrorClassBytes);
  1055. return mirrorClassLoader.loadClass(mirrorClass);
  1056. }
  1057. private static byte[] getMirrorClassBytes(String originalClass, String mirrorClass, boolean removeMethods)
  1058. throws IOException, ClassNotFoundException
  1059. {
  1060. Class<?> aClass = Class.forName(originalClass);
  1061. try (InputStream input = aClass.getResourceAsStream(aClass.getSimpleName() + ".class")) {
  1062. Objects.requireNonNull(input);
  1063. ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
  1064. ClassRemapper classRemapper = new ClassRemapper(classWriter, new ClassNameRemapper(originalClass, mirrorClass));
  1065. ClassVisitor classVisitor = removeMethods ? new MethodAndConstructorRemover(classRemapper) : classRemapper;
  1066. new ClassReader(input).accept(classVisitor, 0);
  1067. return classWriter.toByteArray();
  1068. }
  1069. }
  1070. private static class ClassNameRemapper extends Remapper {
  1071. private final String originalClass;
  1072. private final String mirrorClass;
  1073. public ClassNameRemapper(String originalClass, String mirrorClass) {
  1074. this.originalClass = originalClass.replace('.', '/');
  1075. this.mirrorClass = mirrorClass.replace('.', '/');
  1076. }
  1077. @Override
  1078. public String map(String internalName) {
  1079. return internalName.equals(originalClass) ? mirrorClass : internalName;
  1080. }
  1081. }
  1082. /**
  1083. * ASM class visitor removing all methods and constructors from the given class, leaving only the original fields
  1084. */
  1085. private static class MethodAndConstructorRemover extends ClassVisitor {
  1086. public MethodAndConstructorRemover(ClassRemapper classRemapper) {
  1087. super(Opcodes.ASM9, classRemapper);
  1088. }
  1089. @Override
  1090. public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
  1091. // Do not visit any methods or constructors, effectively removing them
  1092. return null;
  1093. }
  1094. }
  1095. /**
  1096. * Throw-away child classloader with the sole purpose to define a single {@link Class} from the given bytecode
  1097. */
  1098. private static class SingleClassLoader extends ClassLoader {
  1099. private final String mirrorClass;
  1100. private final byte[] mirrorClassBytes;
  1101. private SingleClassLoader(String mirrorClass, byte[] mirrorClassBytes) {
  1102. super(SingleClassLoader.class.getClassLoader());
  1103. this.mirrorClass = mirrorClass;
  1104. this.mirrorClassBytes = mirrorClassBytes;
  1105. }
  1106. @Override
  1107. public Class<?> loadClass(String name) throws ClassNotFoundException {
  1108. return name.equals(mirrorClass)
  1109. ? super.defineClass(null, mirrorClassBytes, 0, mirrorClassBytes.length)
  1110. : super.loadClass(name);
  1111. }
  1112. }
  1113. protected void defineClass(ClassLoader loader, String name, byte[] bytes) {
  1114. defineClass(loader, name, bytes, null);
  1115. }
  1116. protected void defineClass(ClassLoader loader, String name, byte[] bytes, ProtectionDomain protectionDomain) {
  1117. if (trace.isTraceEnabled())
  1118. trace.enter("defineClass", this, new Object[] { loader, name, bytes });
  1119. debug("generating class '" + name + "'");
  1120. Class<?> definedClass = null;
  1121. try {
  1122. if (defineClassMethodHandle == null)
  1123. throw new RuntimeException("no valid method to define auxiliary classes -> weaver not working");
  1124. definedClass = (Class<?>) defineClassMethodHandle
  1125. .bindTo(unsafeInstance)
  1126. .invokeWithArguments(name, bytes, 0, bytes.length, loader, protectionDomain);
  1127. }
  1128. catch (Throwable t) {
  1129. t.printStackTrace(System.err);
  1130. warn("define generated class failed", t);
  1131. }
  1132. finally {
  1133. if (trace.isTraceEnabled())
  1134. trace.exit("defineClass", definedClass);
  1135. }
  1136. }
  1137. }