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

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