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

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