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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  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. String dottedClassName = className.replace('/', '.');
  909. generatedClasses.remove(dottedClassName);
  910. }
  911. private static final Object lock = new Object();
  912. /**
  913. * Instance of either {@link sun.misc.Unsafe} or {@link jdk.internal.misc.Unsafe}. Luckily, both types have
  914. * {@code defineClass} methods with identical signatures. I.e., method handle {@link #defineClassMethodHandle} can be
  915. * invoked with the same set of parameters for both types.
  916. */
  917. private static Object unsafeInstance = null;
  918. /**
  919. * Method handle for defining new classes in arbitrary class loaders. For invocation, use in connection with
  920. * {@link #unsafeInstance}.
  921. */
  922. private static MethodHandle defineClassMethodHandle;
  923. static {
  924. try {
  925. createDefineClassMethodHandle();
  926. }
  927. catch (Exception initializationError) {
  928. new RuntimeException(
  929. "The aspect weaver cannot determine any valid method to define auxiliary classes in arbitrary class loaders. " +
  930. "Aspect weaving will *not* work, and you will see subsequent errors. Please search for corresponding " +
  931. "issues at https://github.com/eclipse-aspectj/aspectj/issues. If there are none, please create a new one.",
  932. initializationError
  933. ).printStackTrace();
  934. }
  935. }
  936. /**
  937. * Scaffolding for defining classes in arbitrary class loaders
  938. * <p>
  939. * Inspired by and shamelessly adapted from <a href="https://bit.ly/3w10oH5">Byte Buddy's {@code ClassInjector}</a>.
  940. * Special thanks to Byte Buddy (BB) author Rafael Winterhalter, who briefly mentioned this approach in a
  941. * <a href="https://bit.ly/3SjFOZY">GitHub comment</a> related to JDK issue
  942. * <a href="https://bugs.openjdk.org/browse/JDK-8200559">JDK-8200559</a>.
  943. * <p>
  944. * <b>Background:</b> Instead of BB, we use ASM and reflection as follows:
  945. * <ul>
  946. * <li>
  947. * Create a mirror class for {@link AccessibleObject} with a different package name in a separate, throw-away
  948. * class loader.
  949. * </li>
  950. * <li>
  951. * Use the mirror class to calculate the {@link Unsafe#objectFieldOffset(Field)} for boolean field
  952. * {@link AccessibleObject#override}, which is expected to be identical to the offset of the same field in the
  953. * original class.
  954. * </li>
  955. * <li>
  956. * After we have the offset, we can use it to override the field value in the original class, deactivating access
  957. * checks for {@link jdk.internal.misc.Unsafe#defineClass(String, byte[], int, int, ClassLoader, ProtectionDomain)},
  958. * the method we need to execute using a method handle.
  959. * </li>
  960. * </ul>
  961. * All these serve the sole purpose enable LTW without {@code --add-opens java.base/java.lang=ALL-UNNAMED} on the
  962. * JVM command line on JDK 16+, which was necessary for AspectJ 1.9.7 (Java 16) to 1.9.21 (Java 21).
  963. *
  964. * @throws Exception if anything goes wrong, trying to determine a usable {@code defineClass} method handle from any
  965. * of the inspected classes
  966. */
  967. private static synchronized void createDefineClassMethodHandle() throws Exception {
  968. Unsafe publicUnsafeInstance = null;
  969. try {
  970. Field publicUnsafeField = Unsafe.class.getDeclaredField("theUnsafe");
  971. publicUnsafeField.setAccessible(true);
  972. publicUnsafeInstance = (Unsafe) publicUnsafeField.get(null);
  973. synchronized (lock) {
  974. unsafeInstance = publicUnsafeInstance;
  975. defineClassMethodHandle = createMethodHandle(
  976. "sun.misc.Unsafe", "defineClass",
  977. String.class, byte[].class, int.class, int.class, ClassLoader.class, ProtectionDomain.class
  978. );
  979. }
  980. }
  981. catch (Exception publicUnsafeException) {
  982. if (publicUnsafeInstance == null)
  983. throw publicUnsafeException;
  984. long overrideOffset = getAccessibleObjectOverrideOffset(publicUnsafeInstance);
  985. Class<?> internalUnsafeType = Class.forName("jdk.internal.misc.Unsafe");
  986. Field internalUnsafeField = internalUnsafeType.getDeclaredField("theUnsafe");
  987. publicUnsafeInstance.putBoolean(internalUnsafeField, overrideOffset, true);
  988. Method internalUnsafeDefineClassMethod = internalUnsafeType.getMethod(
  989. "defineClass",
  990. String.class, byte[].class, int.class, int.class, ClassLoader.class, ProtectionDomain.class
  991. );
  992. publicUnsafeInstance.putBoolean(internalUnsafeDefineClassMethod, overrideOffset, true);
  993. synchronized (lock) {
  994. unsafeInstance = internalUnsafeField.get(null);
  995. defineClassMethodHandle = createMethodHandle(internalUnsafeDefineClassMethod);
  996. }
  997. }
  998. }
  999. private static long getAccessibleObjectOverrideOffset(Unsafe unsafe)
  1000. throws IOException, ClassNotFoundException, NoSuchFieldException
  1001. {
  1002. Objects.requireNonNull(unsafe);
  1003. Field overrideField;
  1004. try {
  1005. overrideField = AccessibleObject.class.getDeclaredField("override");
  1006. }
  1007. catch (NoSuchFieldException ignored) {
  1008. // On JDK 12+, field AccessibleObject.override is protected from reflection. The work-around is to create a
  1009. // mirror class with the same field layout by transforming the original class, so we can calculate the field
  1010. // offset of 'override' and set a value in the original class using the now known offset.
  1011. Class<?> mirrorClass = getMirrorClass(
  1012. "java.lang.reflect.AccessibleObject", "org.aspectj.mirror.AccessibleObject", true
  1013. );
  1014. overrideField = mirrorClass.getDeclaredField("override");
  1015. }
  1016. return unsafe.objectFieldOffset(overrideField);
  1017. }
  1018. public static MethodHandle createMethodHandle(String className, String methodName, Class<?>... argumentTypes)
  1019. throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException
  1020. {
  1021. Class<?> clazz = Class.forName(className);
  1022. Method method = clazz.getDeclaredMethod(methodName, argumentTypes);
  1023. return createMethodHandle(method, false);
  1024. }
  1025. public static MethodHandle createMethodHandle(Method method) throws IllegalAccessException {
  1026. return createMethodHandle(method, false);
  1027. }
  1028. public static MethodHandle createMethodHandle(Method method, boolean setAccessible)
  1029. throws IllegalAccessException
  1030. {
  1031. // Use Method::setAccessible to access private methods. Caveat: This does not work for classes in packages not
  1032. // exported to the calling module (for LTW usually the unnamed module).
  1033. if (setAccessible)
  1034. method.setAccessible(true);
  1035. return MethodHandles.lookup().unreflect(method);
  1036. }
  1037. @SuppressWarnings("SameParameterValue")
  1038. private static Class<?> getMirrorClass(String originalClass, String mirrorClass, boolean removeMethods)
  1039. throws IOException, ClassNotFoundException
  1040. {
  1041. Objects.requireNonNull(originalClass);
  1042. Objects.requireNonNull(mirrorClass);
  1043. if (mirrorClass.equals(originalClass))
  1044. throw new IllegalArgumentException("Mirror class name must be different from original " + originalClass);
  1045. byte[] mirrorClassBytes = getMirrorClassBytes(originalClass, mirrorClass, removeMethods);
  1046. ClassLoader mirrorClassLoader = new SingleClassLoader(mirrorClass, mirrorClassBytes);
  1047. return mirrorClassLoader.loadClass(mirrorClass);
  1048. }
  1049. private static byte[] getMirrorClassBytes(String originalClass, String mirrorClass, boolean removeMethods)
  1050. throws IOException, ClassNotFoundException
  1051. {
  1052. Class<?> aClass = Class.forName(originalClass);
  1053. try (InputStream input = aClass.getResourceAsStream(aClass.getSimpleName() + ".class")) {
  1054. Objects.requireNonNull(input);
  1055. ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
  1056. ClassRemapper classRemapper = new ClassRemapper(classWriter, new ClassNameRemapper(originalClass, mirrorClass));
  1057. ClassVisitor classVisitor = removeMethods ? new MethodAndConstructorRemover(classRemapper) : classRemapper;
  1058. new ClassReader(input).accept(classVisitor, 0);
  1059. return classWriter.toByteArray();
  1060. }
  1061. }
  1062. private static class ClassNameRemapper extends Remapper {
  1063. private final String originalClass;
  1064. private final String mirrorClass;
  1065. public ClassNameRemapper(String originalClass, String mirrorClass) {
  1066. this.originalClass = originalClass.replace('.', '/');
  1067. this.mirrorClass = mirrorClass.replace('.', '/');
  1068. }
  1069. @Override
  1070. public String map(String internalName) {
  1071. return internalName.equals(originalClass) ? mirrorClass : internalName;
  1072. }
  1073. }
  1074. /**
  1075. * ASM class visitor removing all methods and constructors from the given class, leaving only the original fields
  1076. */
  1077. private static class MethodAndConstructorRemover extends ClassVisitor {
  1078. public MethodAndConstructorRemover(ClassRemapper classRemapper) {
  1079. super(Opcodes.ASM9, classRemapper);
  1080. }
  1081. @Override
  1082. public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
  1083. // Do not visit any methods or constructors, effectively removing them
  1084. return null;
  1085. }
  1086. }
  1087. /**
  1088. * Throw-away child classloader with the sole purpose to define a single {@link Class} from the given bytecode
  1089. */
  1090. private static class SingleClassLoader extends ClassLoader {
  1091. private final String mirrorClass;
  1092. private final byte[] mirrorClassBytes;
  1093. private SingleClassLoader(String mirrorClass, byte[] mirrorClassBytes) {
  1094. super(SingleClassLoader.class.getClassLoader());
  1095. this.mirrorClass = mirrorClass;
  1096. this.mirrorClassBytes = mirrorClassBytes;
  1097. }
  1098. @Override
  1099. public Class<?> loadClass(String name) throws ClassNotFoundException {
  1100. return name.equals(mirrorClass)
  1101. ? super.defineClass(null, mirrorClassBytes, 0, mirrorClassBytes.length)
  1102. : super.loadClass(name);
  1103. }
  1104. }
  1105. private void defineClass(ClassLoader loader, String name, byte[] bytes) {
  1106. defineClass(loader, name, bytes, null);
  1107. }
  1108. private void defineClass(ClassLoader loader, String name, byte[] bytes, ProtectionDomain protectionDomain) {
  1109. if (trace.isTraceEnabled())
  1110. trace.enter("defineClass", this, new Object[] { loader, name, bytes });
  1111. debug("generating class '" + name + "'");
  1112. Class<?> definedClass = null;
  1113. try {
  1114. if (defineClassMethodHandle == null)
  1115. throw new RuntimeException("no valid method to define auxiliary classes -> weaver not working");
  1116. definedClass = (Class<?>) defineClassMethodHandle
  1117. .bindTo(unsafeInstance)
  1118. .invokeWithArguments(name, bytes, 0, bytes.length, loader, protectionDomain);
  1119. }
  1120. catch (Throwable t) {
  1121. t.printStackTrace(System.err);
  1122. warn("define generated class failed", t);
  1123. }
  1124. finally {
  1125. if (trace.isTraceEnabled())
  1126. trace.exit("defineClass", definedClass);
  1127. }
  1128. }
  1129. }