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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. /*******************************************************************************
  2. * Copyright (c) 2005 Contributors.
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Eclipse Public License v1.0
  6. * which accompanies this distribution and is available at
  7. * http://eclipse.org/legal/epl-v10.html
  8. *
  9. * Contributors:
  10. * Alexandre Vasseur initial implementation
  11. * David Knibb weaving context enhancments
  12. *******************************************************************************/
  13. package org.aspectj.weaver.loadtime;
  14. import java.io.File;
  15. import java.io.IOException;
  16. import java.io.InputStream;
  17. import java.lang.reflect.InvocationTargetException;
  18. import java.lang.reflect.Method;
  19. import java.net.URL;
  20. import java.util.ArrayList;
  21. import java.util.Enumeration;
  22. import java.util.HashMap;
  23. import java.util.Iterator;
  24. import java.util.List;
  25. import java.util.Properties;
  26. import java.util.StringTokenizer;
  27. import org.aspectj.asm.IRelationship;
  28. import org.aspectj.bridge.AbortException;
  29. import org.aspectj.bridge.ISourceLocation;
  30. import org.aspectj.util.LangUtil;
  31. import org.aspectj.weaver.ICrossReferenceHandler;
  32. import org.aspectj.weaver.Lint;
  33. import org.aspectj.weaver.ResolvedType;
  34. import org.aspectj.weaver.UnresolvedType;
  35. import org.aspectj.weaver.World;
  36. import org.aspectj.weaver.Lint.Kind;
  37. import org.aspectj.weaver.bcel.BcelWeaver;
  38. import org.aspectj.weaver.loadtime.definition.Definition;
  39. import org.aspectj.weaver.loadtime.definition.DocumentParser;
  40. import org.aspectj.weaver.ltw.LTWWorld;
  41. import org.aspectj.weaver.patterns.PatternParser;
  42. import org.aspectj.weaver.patterns.TypePattern;
  43. import org.aspectj.weaver.tools.GeneratedClassHandler;
  44. import org.aspectj.weaver.tools.Trace;
  45. import org.aspectj.weaver.tools.TraceFactory;
  46. import org.aspectj.weaver.tools.WeavingAdaptor;
  47. /**
  48. * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
  49. */
  50. public class ClassLoaderWeavingAdaptor extends WeavingAdaptor {
  51. private final static String AOP_XML = "META-INF/aop.xml";
  52. private boolean initialized;
  53. private List m_dumpTypePattern = new ArrayList();
  54. private boolean m_dumpBefore = false;
  55. private List m_includeTypePattern = new ArrayList();
  56. private List m_excludeTypePattern = new ArrayList();
  57. private List m_includeStartsWith = new ArrayList();
  58. private List m_excludeStartsWith = new ArrayList();
  59. private List m_aspectExcludeTypePattern = new ArrayList();
  60. private List m_aspectExcludeStartsWith = new ArrayList();
  61. private List m_aspectIncludeTypePattern = new ArrayList();
  62. private List m_aspectIncludeStartsWith = new ArrayList();
  63. private StringBuffer namespace;
  64. private IWeavingContext weavingContext;
  65. private static Trace trace = TraceFactory.getTraceFactory().getTrace(ClassLoaderWeavingAdaptor.class);
  66. public ClassLoaderWeavingAdaptor() {
  67. super();
  68. if (trace.isTraceEnabled()) trace.enter("<init>",this);
  69. if (trace.isTraceEnabled()) trace.exit("<init>");
  70. }
  71. /**
  72. * We don't need a reference to the class loader and using it during
  73. * construction can cause problems with recursion. It also makes sense
  74. * to supply the weaving context during initialization to.
  75. * @deprecated
  76. */
  77. public ClassLoaderWeavingAdaptor(final ClassLoader deprecatedLoader, final IWeavingContext deprecatedContext) {
  78. super();
  79. if (trace.isTraceEnabled()) trace.enter("<init>",this,new Object[] { deprecatedLoader, deprecatedContext });
  80. if (trace.isTraceEnabled()) trace.exit("<init>");
  81. }
  82. protected void initialize (final ClassLoader classLoader, IWeavingContext context) {
  83. //super(null);// at this stage we don't have yet a generatedClassHandler to define to the VM the closures
  84. if (initialized) return;
  85. if (trace.isTraceEnabled()) trace.enter("initialize",this,new Object[] { classLoader, context });
  86. this.weavingContext = context;
  87. if (weavingContext == null) {
  88. weavingContext = new DefaultWeavingContext(classLoader);
  89. }
  90. createMessageHandler();
  91. this.generatedClassHandler = new GeneratedClassHandler() {
  92. /**
  93. * Callback when we need to define a Closure in the JVM
  94. *
  95. * @param name
  96. * @param bytes
  97. */
  98. public void acceptClass(String name, byte[] bytes) {
  99. try {
  100. if (shouldDump(name.replace('/', '.'), false)) {
  101. dump(name, bytes, false);
  102. }
  103. } catch (Throwable throwable) {
  104. throwable.printStackTrace();
  105. }
  106. defineClass(classLoader, name, bytes);// could be done lazily using the hook
  107. }
  108. };
  109. List definitions = parseDefinitions(classLoader);
  110. if (!isEnabled()) {
  111. if (trace.isTraceEnabled()) trace.exit("initialize",false);
  112. return;
  113. }
  114. bcelWorld = new LTWWorld(
  115. classLoader, weavingContext, // TODO when the world works in terms of the context, we can remove the loader...
  116. getMessageHandler(), new ICrossReferenceHandler() {
  117. public void addCrossReference(ISourceLocation from, ISourceLocation to, IRelationship.Kind kind, boolean runtimeTest) {
  118. ;// for tools only
  119. }
  120. }
  121. );
  122. // //TODO this AJ code will call
  123. // //org.aspectj.apache.bcel.Repository.setRepository(this);
  124. // //ie set some static things
  125. // //==> bogus as Bcel is expected to be
  126. // org.aspectj.apache.bcel.Repository.setRepository(new ClassLoaderRepository(loader));
  127. weaver = new BcelWeaver(bcelWorld);
  128. // register the definitions
  129. registerDefinitions(weaver, classLoader, definitions);
  130. if (isEnabled()) {
  131. //bcelWorld.setResolutionLoader(loader.getParent());//(ClassLoader)null);//
  132. // after adding aspects
  133. weaver.prepareForWeave();
  134. }
  135. else {
  136. bcelWorld = null;
  137. weaver = null;
  138. }
  139. initialized = true;
  140. if (trace.isTraceEnabled()) trace.exit("initialize",isEnabled());
  141. }
  142. /**
  143. * Load and cache the aop.xml/properties according to the classloader visibility rules
  144. *
  145. * @param weaver
  146. * @param loader
  147. */
  148. private List parseDefinitions(final ClassLoader loader) {
  149. List definitions = new ArrayList();
  150. try {
  151. info("register classloader " + getClassLoaderName(loader));
  152. //TODO av underoptimized: we will parse each XML once per CL that see it
  153. //TODO av dev mode needed ? TBD -Daj5.def=...
  154. if (ClassLoader.getSystemClassLoader().equals(loader)) {
  155. String file = System.getProperty("aj5.def", null);
  156. if (file != null) {
  157. info("using (-Daj5.def) " + file);
  158. definitions.add(DocumentParser.parse((new File(file)).toURL()));
  159. }
  160. }
  161. String resourcePath = System.getProperty("org.aspectj.weaver.loadtime.configuration",AOP_XML);
  162. StringTokenizer st = new StringTokenizer(resourcePath,";");
  163. while(st.hasMoreTokens()){
  164. Enumeration xmls = weavingContext.getResources(st.nextToken());
  165. // System.out.println("? registerDefinitions: found-aop.xml=" + xmls.hasMoreElements() + ", loader=" + loader);
  166. while (xmls.hasMoreElements()) {
  167. URL xml = (URL) xmls.nextElement();
  168. info("using configuration " + weavingContext.getFile(xml));
  169. definitions.add(DocumentParser.parse(xml));
  170. }
  171. }
  172. if (definitions.isEmpty()) {
  173. disable();// will allow very fast skip in shouldWeave()
  174. info("no configuration found. Disabling weaver for class loader " + getClassLoaderName(loader));
  175. }
  176. } catch (Exception e) {
  177. disable();// will allow very fast skip in shouldWeave()
  178. warn("parse definitions failed",e);
  179. }
  180. return definitions;
  181. }
  182. private void registerDefinitions(final BcelWeaver weaver, final ClassLoader loader, List definitions) {
  183. try {
  184. registerOptions(weaver, loader, definitions);
  185. registerAspectExclude(weaver, loader, definitions);
  186. registerAspectInclude(weaver, loader, definitions);
  187. registerAspects(weaver, loader, definitions);
  188. registerIncludeExclude(weaver, loader, definitions);
  189. registerDump(weaver, loader, definitions);
  190. } catch (Exception e) {
  191. disable();// will allow very fast skip in shouldWeave()
  192. warn("register definition failed",(e instanceof AbortException)?null:e);
  193. }
  194. }
  195. private String getClassLoaderName (ClassLoader loader) {
  196. return weavingContext.getClassLoaderName();
  197. }
  198. /**
  199. * Configure the weaver according to the option directives
  200. * TODO av - don't know if it is that good to reuse, since we only allow a small subset of options in LTW
  201. *
  202. * @param weaver
  203. * @param loader
  204. * @param definitions
  205. */
  206. private void registerOptions(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
  207. StringBuffer allOptions = new StringBuffer();
  208. for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
  209. Definition definition = (Definition) iterator.next();
  210. allOptions.append(definition.getWeaverOptions()).append(' ');
  211. }
  212. Options.WeaverOption weaverOption = Options.parse(allOptions.toString(), loader, getMessageHandler());
  213. // configure the weaver and world
  214. // AV - code duplicates AspectJBuilder.initWorldAndWeaver()
  215. World world = weaver.getWorld();
  216. setMessageHandler(weaverOption.messageHandler);
  217. world.setXlazyTjp(weaverOption.lazyTjp);
  218. world.setXHasMemberSupportEnabled(weaverOption.hasMember);
  219. world.setOptionalJoinpoints(weaverOption.optionalJoinpoints);
  220. world.setPinpointMode(weaverOption.pinpoint);
  221. weaver.setReweavableMode(weaverOption.notReWeavable);
  222. world.performExtraConfiguration(weaverOption.xSet);
  223. world.setXnoInline(weaverOption.noInline);
  224. // AMC - autodetect as per line below, needed for AtAjLTWTests.testLTWUnweavable
  225. world.setBehaveInJava5Way(LangUtil.is15VMOrGreater());
  226. world.setAddSerialVerUID(weaverOption.addSerialVersionUID);
  227. /* First load defaults */
  228. bcelWorld.getLint().loadDefaultProperties();
  229. /* Second overlay LTW defaults */
  230. bcelWorld.getLint().adviceDidNotMatch.setKind(null);
  231. /* Third load user file using -Xlintfile so that -Xlint wins */
  232. if (weaverOption.lintFile != null) {
  233. InputStream resource = null;
  234. try {
  235. resource = loader.getResourceAsStream(weaverOption.lintFile);
  236. Exception failure = null;
  237. if (resource != null) {
  238. try {
  239. Properties properties = new Properties();
  240. properties.load(resource);
  241. world.getLint().setFromProperties(properties);
  242. } catch (IOException e) {
  243. failure = e;
  244. }
  245. }
  246. if (failure != null || resource == null) {
  247. warn("Cannot access resource for -Xlintfile:"+weaverOption.lintFile,failure);
  248. // world.getMessageHandler().handleMessage(new Message(
  249. // "Cannot access resource for -Xlintfile:"+weaverOption.lintFile,
  250. // IMessage.WARNING,
  251. // failure,
  252. // null));
  253. }
  254. } finally {
  255. try { resource.close(); } catch (Throwable t) {;}
  256. }
  257. }
  258. /* Fourth override with -Xlint */
  259. if (weaverOption.lint != null) {
  260. if (weaverOption.lint.equals("default")) {//FIXME should be AjBuildConfig.AJLINT_DEFAULT but yetanother deps..
  261. bcelWorld.getLint().loadDefaultProperties();
  262. } else {
  263. bcelWorld.getLint().setAll(weaverOption.lint);
  264. }
  265. }
  266. //TODO proceedOnError option
  267. }
  268. private void registerAspectExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
  269. String fastMatchInfo = null;
  270. for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
  271. Definition definition = (Definition) iterator.next();
  272. for (Iterator iterator1 = definition.getAspectExcludePatterns().iterator(); iterator1.hasNext();) {
  273. String exclude = (String) iterator1.next();
  274. TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
  275. m_aspectExcludeTypePattern.add(excludePattern);
  276. fastMatchInfo = looksLikeStartsWith(exclude);
  277. if (fastMatchInfo != null) {
  278. m_aspectExcludeStartsWith.add(fastMatchInfo);
  279. }
  280. }
  281. }
  282. }
  283. private void registerAspectInclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
  284. String fastMatchInfo = null;
  285. for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
  286. Definition definition = (Definition) iterator.next();
  287. for (Iterator iterator1 = definition.getAspectIncludePatterns().iterator(); iterator1.hasNext();) {
  288. String include = (String) iterator1.next();
  289. TypePattern includePattern = new PatternParser(include).parseTypePattern();
  290. m_aspectIncludeTypePattern.add(includePattern);
  291. fastMatchInfo = looksLikeStartsWith(include);
  292. if (fastMatchInfo != null) {
  293. m_aspectIncludeStartsWith.add(fastMatchInfo);
  294. }
  295. }
  296. }
  297. }
  298. protected void lint (String name, String[] infos) {
  299. Lint lint = bcelWorld.getLint();
  300. Kind kind = lint.getLintKind(name);
  301. kind.signal(infos,null,null);
  302. }
  303. public String getContextId () {
  304. return weavingContext.getId();
  305. }
  306. /**
  307. * Register the aspect, following include / exclude rules
  308. *
  309. * @param weaver
  310. * @param loader
  311. * @param definitions
  312. */
  313. private void registerAspects(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
  314. if (trace.isTraceEnabled()) trace.enter("registerAspects",this, new Object[] { weaver, loader, definitions} );
  315. //TODO: the exclude aspect allow to exclude aspect defined upper in the CL hierarchy - is it what we want ??
  316. // if not, review the getResource so that we track which resource is defined by which CL
  317. //iterate aspectClassNames
  318. //exclude if in any of the exclude list
  319. for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
  320. Definition definition = (Definition) iterator.next();
  321. for (Iterator aspects = definition.getAspectClassNames().iterator(); aspects.hasNext();) {
  322. String aspectClassName = (String) aspects.next();
  323. if (acceptAspect(aspectClassName)) {
  324. info("register aspect " + aspectClassName);
  325. // System.err.println("? ClassLoaderWeavingAdaptor.registerAspects() aspectName=" + aspectClassName + ", loader=" + loader + ", bundle=" + weavingContext.getClassLoaderName());
  326. /*ResolvedType aspect = */weaver.addLibraryAspect(aspectClassName);
  327. //generate key for SC
  328. if(namespace==null){
  329. namespace=new StringBuffer(aspectClassName);
  330. }else{
  331. namespace = namespace.append(";"+aspectClassName);
  332. }
  333. }
  334. else {
  335. // warn("aspect excluded: " + aspectClassName);
  336. lint("aspectExcludedByConfiguration", new String[] { aspectClassName, getClassLoaderName(loader) });
  337. }
  338. }
  339. }
  340. //iterate concreteAspects
  341. //exclude if in any of the exclude list - note that the user defined name matters for that to happen
  342. for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
  343. Definition definition = (Definition) iterator.next();
  344. for (Iterator aspects = definition.getConcreteAspects().iterator(); aspects.hasNext();) {
  345. Definition.ConcreteAspect concreteAspect = (Definition.ConcreteAspect) aspects.next();
  346. if (acceptAspect(concreteAspect.name)) {
  347. ConcreteAspectCodeGen gen = new ConcreteAspectCodeGen(concreteAspect, weaver.getWorld());
  348. if (!gen.validate()) {
  349. error("Concrete-aspect '"+concreteAspect.name+"' could not be registered");
  350. break;
  351. }
  352. this.generatedClassHandler.acceptClass(
  353. concreteAspect.name,
  354. gen.getBytes()
  355. );
  356. /*ResolvedType aspect = */weaver.addLibraryAspect(concreteAspect.name);
  357. //generate key for SC
  358. if(namespace==null){
  359. namespace=new StringBuffer(concreteAspect.name);
  360. }else{
  361. namespace = namespace.append(";"+concreteAspect.name);
  362. }
  363. }
  364. }
  365. }
  366. // System.out.println("ClassLoaderWeavingAdaptor.registerAspects() classloader=" + weavingContext.getClassLoaderName() + ", namespace=" + namespace);
  367. /* We didn't register any aspects so disable the adaptor */
  368. if (namespace == null) {
  369. disable();
  370. info("no aspects registered. Disabling weaver for class loader " + getClassLoaderName(loader));
  371. }
  372. if (trace.isTraceEnabled()) trace.exit("registerAspects",isEnabled());
  373. }
  374. /**
  375. * Register the include / exclude filters
  376. * We duplicate simple patterns in startWith filters that will allow faster matching without ResolvedType
  377. *
  378. * @param weaver
  379. * @param loader
  380. * @param definitions
  381. */
  382. private void registerIncludeExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
  383. String fastMatchInfo = null;
  384. for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
  385. Definition definition = (Definition) iterator.next();
  386. for (Iterator iterator1 = definition.getIncludePatterns().iterator(); iterator1.hasNext();) {
  387. String include = (String) iterator1.next();
  388. TypePattern includePattern = new PatternParser(include).parseTypePattern();
  389. m_includeTypePattern.add(includePattern);
  390. fastMatchInfo = looksLikeStartsWith(include);
  391. if (fastMatchInfo != null) {
  392. m_includeStartsWith.add(fastMatchInfo);
  393. }
  394. }
  395. for (Iterator iterator1 = definition.getExcludePatterns().iterator(); iterator1.hasNext();) {
  396. String exclude = (String) iterator1.next();
  397. TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
  398. m_excludeTypePattern.add(excludePattern);
  399. fastMatchInfo = looksLikeStartsWith(exclude);
  400. if (fastMatchInfo != null) {
  401. m_excludeStartsWith.add(fastMatchInfo);
  402. }
  403. }
  404. }
  405. }
  406. /**
  407. * Checks if the type pattern can be handled as a startswith check
  408. *
  409. * TODO AV - enhance to support "char.sss" ie FQN direclty (match iff equals)
  410. * we could also add support for "*..*charss" endsWith style?
  411. *
  412. * @param typePattern
  413. * @return null if not possible, or the startWith sequence to test against
  414. */
  415. private String looksLikeStartsWith(String typePattern) {
  416. if (typePattern.indexOf('@') >= 0
  417. || typePattern.indexOf('+') >= 0
  418. || typePattern.indexOf(' ') >= 0
  419. || typePattern.charAt(typePattern.length()-1) != '*') {
  420. return null;
  421. }
  422. // now must looks like with "charsss..*" or "cha.rss..*" etc
  423. // note that "*" and "*..*" won't be fast matched
  424. // and that "charsss.*" will not neither
  425. int length = typePattern.length();
  426. if (typePattern.endsWith("..*") && length > 3) {
  427. if (typePattern.indexOf("..") == length-3 // no ".." before last sequence
  428. && typePattern.indexOf('*') == length-1) { // no "*" before last sequence
  429. return typePattern.substring(0, length-2).replace('$', '.');
  430. // ie "charsss." or "char.rss." etc
  431. }
  432. }
  433. return null;
  434. }
  435. /**
  436. * Register the dump filter
  437. *
  438. * @param weaver
  439. * @param loader
  440. * @param definitions
  441. */
  442. private void registerDump(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
  443. for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
  444. Definition definition = (Definition) iterator.next();
  445. for (Iterator iterator1 = definition.getDumpPatterns().iterator(); iterator1.hasNext();) {
  446. String dump = (String) iterator1.next();
  447. TypePattern pattern = new PatternParser(dump).parseTypePattern();
  448. m_dumpTypePattern.add(pattern);
  449. }
  450. if (definition.shouldDumpBefore()) {
  451. m_dumpBefore = true;
  452. }
  453. }
  454. }
  455. protected boolean accept(String className, byte[] bytes) {
  456. // avoid ResolvedType if not needed
  457. if (m_excludeTypePattern.isEmpty() && m_includeTypePattern.isEmpty()) {
  458. return true;
  459. }
  460. // still try to avoid ResolvedType if we have simple patterns
  461. String fastClassName = className.replace('/', '.').replace('$', '.');
  462. for (int i = 0; i < m_excludeStartsWith.size(); i++) {
  463. if (fastClassName.startsWith((String)m_excludeStartsWith.get(i))) {
  464. return false;
  465. }
  466. }
  467. /*
  468. * Bug 120363
  469. * If we have an exclude pattern that cannot be matched using "starts with"
  470. * then we cannot fast accept
  471. */
  472. if (m_excludeTypePattern.isEmpty()) {
  473. boolean fastAccept = false;//defaults to false if no fast include
  474. for (int i = 0; i < m_includeStartsWith.size(); i++) {
  475. fastAccept = fastClassName.startsWith((String)m_includeStartsWith.get(i));
  476. if (fastAccept) {
  477. break;
  478. }
  479. }
  480. }
  481. // needs further analysis
  482. // TODO AV - needs refactoring
  483. // during LTW this calling resolve at that stage is BAD as we do have the bytecode from the classloader hook
  484. // but still go thru resolve that will do a getResourcesAsStream on disk
  485. // this is also problematic for jit stub which are not on disk - as often underlying infra
  486. // does returns null or some other info for getResourceAsStream (f.e. WLS 9 CR248491)
  487. // Instead I parse the given bytecode. But this also means it will be parsed again in
  488. // new WeavingClassFileProvider() from WeavingAdaptor.getWovenBytes()...
  489. ensureDelegateInitialized(className,bytes);
  490. ResolvedType classInfo = delegateForCurrentClass.getResolvedTypeX();//BAD: weaver.getWorld().resolve(UnresolvedType.forName(className), true);
  491. //exclude are "AND"ed
  492. for (Iterator iterator = m_excludeTypePattern.iterator(); iterator.hasNext();) {
  493. TypePattern typePattern = (TypePattern) iterator.next();
  494. if (typePattern.matchesStatically(classInfo)) {
  495. // exclude match - skip
  496. return false;
  497. }
  498. }
  499. //include are "OR"ed
  500. boolean accept = true;//defaults to true if no include
  501. for (Iterator iterator = m_includeTypePattern.iterator(); iterator.hasNext();) {
  502. TypePattern typePattern = (TypePattern) iterator.next();
  503. accept = typePattern.matchesStatically(classInfo);
  504. if (accept) {
  505. break;
  506. }
  507. // goes on if this include did not match ("OR"ed)
  508. }
  509. return accept;
  510. }
  511. //FIXME we don't use include/exclude of others aop.xml
  512. //this can be nice but very dangerous as well to change that
  513. private boolean acceptAspect(String aspectClassName) {
  514. // avoid ResolvedType if not needed
  515. if (m_aspectExcludeTypePattern.isEmpty() && m_aspectIncludeTypePattern.isEmpty()) {
  516. return true;
  517. }
  518. // still try to avoid ResolvedType if we have simple patterns
  519. // EXCLUDE: if one match then reject
  520. String fastClassName = aspectClassName.replace('/', '.').replace('.', '$');
  521. for (int i = 0; i < m_aspectExcludeStartsWith.size(); i++) {
  522. if (fastClassName.startsWith((String)m_aspectExcludeStartsWith.get(i))) {
  523. return false;
  524. }
  525. }
  526. //INCLUDE: if one match then accept
  527. for (int i = 0; i < m_aspectIncludeStartsWith.size(); i++) {
  528. if (fastClassName.startsWith((String)m_aspectIncludeStartsWith.get(i))) {
  529. return true;
  530. }
  531. }
  532. // needs further analysis
  533. ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(aspectClassName), true);
  534. //exclude are "AND"ed
  535. for (Iterator iterator = m_aspectExcludeTypePattern.iterator(); iterator.hasNext();) {
  536. TypePattern typePattern = (TypePattern) iterator.next();
  537. if (typePattern.matchesStatically(classInfo)) {
  538. // exclude match - skip
  539. return false;
  540. }
  541. }
  542. //include are "OR"ed
  543. boolean accept = true;//defaults to true if no include
  544. for (Iterator iterator = m_aspectIncludeTypePattern.iterator(); iterator.hasNext();) {
  545. TypePattern typePattern = (TypePattern) iterator.next();
  546. accept = typePattern.matchesStatically(classInfo);
  547. if (accept) {
  548. break;
  549. }
  550. // goes on if this include did not match ("OR"ed)
  551. }
  552. return accept;
  553. }
  554. protected boolean shouldDump(String className, boolean before) {
  555. // Don't dump before weaving unless asked to
  556. if (before && !m_dumpBefore) {
  557. return false;
  558. }
  559. // avoid ResolvedType if not needed
  560. if (m_dumpTypePattern.isEmpty()) {
  561. return false;
  562. }
  563. //TODO AV - optimize for className.startWith only
  564. ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(className), true);
  565. //dump
  566. for (Iterator iterator = m_dumpTypePattern.iterator(); iterator.hasNext();) {
  567. TypePattern typePattern = (TypePattern) iterator.next();
  568. if (typePattern.matchesStatically(classInfo)) {
  569. // dump match
  570. return true;
  571. }
  572. }
  573. return false;
  574. }
  575. /*
  576. * shared classes methods
  577. */
  578. /**
  579. * @return Returns the key.
  580. */
  581. public String getNamespace() {
  582. // System.out.println("ClassLoaderWeavingAdaptor.getNamespace() classloader=" + weavingContext.getClassLoaderName() + ", namespace=" + namespace);
  583. if(namespace==null) return "";
  584. else return new String(namespace);
  585. }
  586. /**
  587. * Check to see if any classes are stored in the generated classes cache.
  588. * Then flush the cache if it is not empty
  589. * @param className TODO
  590. * @return true if a class has been generated and is stored in the cache
  591. */
  592. public boolean generatedClassesExistFor (String className) {
  593. // System.err.println("? ClassLoaderWeavingAdaptor.generatedClassesExist() classname=" + className + ", size=" + generatedClasses);
  594. if (className == null) return !generatedClasses.isEmpty();
  595. else return generatedClasses.containsKey(className);
  596. }
  597. /**
  598. * Flush the generated classes cache
  599. */
  600. public void flushGeneratedClasses() {
  601. // System.err.println("? ClassLoaderWeavingAdaptor.flushGeneratedClasses() generatedClasses=" + generatedClasses);
  602. generatedClasses = new HashMap();
  603. }
  604. private void defineClass(ClassLoader loader, String name, byte[] bytes) {
  605. if (trace.isTraceEnabled()) trace.enter("defineClass",this,new Object[] {loader,name,bytes});
  606. Object clazz = null;
  607. info("generating class '" + name + "'");
  608. try {
  609. //TODO av protection domain, and optimize
  610. Method defineClass = ClassLoader.class.getDeclaredMethod(
  611. "defineClass", new Class[] { String.class,
  612. bytes.getClass(), int.class, int.class });
  613. defineClass.setAccessible(true);
  614. clazz = defineClass.invoke(loader, new Object[] { name, bytes,
  615. new Integer(0), new Integer(bytes.length) });
  616. } catch (InvocationTargetException e) {
  617. if (e.getTargetException() instanceof LinkageError) {
  618. warn("define generated class failed",e.getTargetException());
  619. //is already defined (happens for X$ajcMightHaveAspect interfaces since aspects are reweaved)
  620. // TODO maw I don't think this is OK and
  621. } else {
  622. warn("define generated class failed",e.getTargetException());
  623. }
  624. } catch (Exception e) {
  625. warn("define generated class failed",e);
  626. }
  627. if (trace.isTraceEnabled()) trace.exit("defineClass",clazz);
  628. }
  629. }