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.

Ajc.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. /* *******************************************************************
  2. * Copyright (c) 2004 IBM Corporation
  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. * Contributors:
  10. * Adrian Colyer,
  11. * ******************************************************************/
  12. package org.aspectj.tools.ajc;
  13. import java.io.ByteArrayOutputStream;
  14. import java.io.File;
  15. import java.io.FilenameFilter;
  16. import java.io.IOException;
  17. import java.io.PrintStream;
  18. import java.util.ArrayList;
  19. import java.util.Collections;
  20. import java.util.List;
  21. import java.util.StringTokenizer;
  22. import org.aspectj.asm.AsmManager;
  23. import org.aspectj.asm.IProgramElement;
  24. import org.aspectj.asm.IRelationship;
  25. import org.aspectj.asm.IRelationshipMap;
  26. import org.aspectj.asm.internal.Relationship;
  27. import org.aspectj.bridge.AbortException;
  28. import org.aspectj.bridge.ICommand;
  29. import org.aspectj.bridge.IMessage;
  30. import org.aspectj.bridge.IMessage.Kind;
  31. import org.aspectj.bridge.IMessageHandler;
  32. import org.aspectj.bridge.MessageHandler;
  33. import org.aspectj.bridge.context.CompilationAndWeavingContext;
  34. import org.aspectj.testing.util.TestUtil;
  35. import org.aspectj.util.FileUtil;
  36. import static java.io.File.pathSeparator;
  37. import static java.io.File.separator;
  38. import static org.aspectj.tools.ajc.AjcTestCase.*;
  39. /**
  40. * The Ajc class is intended for use as part of a unit-test suite, it drives the AspectJ compiler and lets you check the compilation
  41. * results. Compilations run in a sandbox that is created in C:\temp\ajcSandbox or /tmp/ajcSandbox depending on your platform.
  42. * <p>
  43. * The expected usage of Ajc is through the TestCase superclass, AjcTestCase, which provides helper methods that conveniently drive
  44. * the base functions exposed by this class.
  45. * </p>
  46. *
  47. * @see org.aspectj.tools.ajc.AjcTestCase
  48. */
  49. public class Ajc {
  50. private static final String BUILD_OUTPUT_FOLDER = "target";
  51. public static final String outputFolder(String module) {
  52. return pathSeparator + ".." + separator + module + separator + BUILD_OUTPUT_FOLDER + separator + "classes";
  53. }
  54. public static final String outputFolders(String... modules) {
  55. StringBuilder s = new StringBuilder();
  56. for (String module: modules) {
  57. s.append(pathSeparator + ".." + separator + module + separator + BUILD_OUTPUT_FOLDER + separator + "classes");
  58. }
  59. return s.toString();
  60. }
  61. // ALSO SEE ANTSPEC AND AJCTESTCASE
  62. private static final String TESTER_PATH =
  63. outputFolder("testing-client")
  64. + outputFolder("runtime")
  65. + outputFolder("bcel-builder")
  66. + pathSeparator + CLASSPATH_JUNIT
  67. + pathSeparator + CLASSPATH_ASM
  68. + pathSeparator + CLASSPATH_ASM_COMMONS
  69. + outputFolder("bridge")
  70. + outputFolder("loadtime")
  71. + outputFolder("weaver")
  72. + outputFolder("org.aspectj.matcher")
  73. + outputFolder("bridge");
  74. private CompilationResult result;
  75. private File sandbox;
  76. private File baseDir;
  77. private final Main main;
  78. private String[] ajcArgs;
  79. private int incrementalStage = 10;
  80. private boolean shouldEmptySandbox = true;
  81. private final AjcCommandController controller;
  82. public static boolean verbose = System.getProperty("aspectj.tests.verbose", "true").equals("true");
  83. /**
  84. * Constructs a new Ajc instance, with a new AspectJ compiler inside.
  85. */
  86. public Ajc() {
  87. main = new Main();
  88. controller = new AjcCommandController();
  89. main.setController(controller);
  90. }
  91. /**
  92. * By default, each call to <code>compile</code> creates a new sandbox (C:\temp\ajcSandbox\ajtTestxxx.tmp, or
  93. * /tmp/ajcSandbox/ajcTestxxx.tmp depending on your platform). To write a test that performs multiple (non-incremental)
  94. * compiles, building on the results of previous compilations, set 'should empty sandbox' to false after the first compile,
  95. * which will cause subsequent compiles in the test to use the same directory and contents.
  96. */
  97. public void setShouldEmptySandbox(boolean empty) {
  98. this.shouldEmptySandbox = empty;
  99. }
  100. /**
  101. * Call the compiler with the given arguments (args are exactly the same as you would pass to ajc on the command-line). The
  102. * results of the compile are returned in a <code>CompilationResult</code>, which provides for easy testing of results.
  103. * <p>
  104. * The compilation happens in a sandbox (C:\temp\ajcSandbox\ajTestxxx.tmp or /tmp/ajcSandbox/ajcTestxxx.tmp depending on
  105. * platform). Compiler arguments are adapted to the sandbox as follows.
  106. * </p>
  107. * <p>
  108. * For every file or directory listed in an argument (source file, or component of inpath, aspectpath, sourceroots,
  109. * classpath,...), if the file is specified using an absolute path then it is left unchanged, but if the file is specified using
  110. * a relative path, and a base directory (see setBaseDir) has been provided, then files/directories are copied from the base
  111. * directory to the sandbox, and the compiler arguments adjusted to reflect their new location.
  112. * </p>
  113. * <p>
  114. * For example, given a baseDir of "tests/pr12345" and a compile command: "ajc src/A.java src/B.java", the files in
  115. *
  116. * <pre>
  117. * tests/pr12345/
  118. * src/
  119. * A.java
  120. * B.java
  121. * </pre>
  122. *
  123. * are copied to:
  124. *
  125. * <pre>
  126. * ajcSandbox/ajcTestxxx.tmp/
  127. * src/
  128. * A.java
  129. * B.java
  130. * </pre>
  131. * <p>
  132. * If no classpath is specified (no -classpath in the arguments) the classpath will be set to include the sandbox directory,
  133. * testing-client/bin (for the Tester class), and runtime/bin (for the AspectJ runtime). If a classpath <i>is</i> specified,
  134. * then any relative directories in it will be made relative to the sandbox, and the testing-client and runtime bin directories
  135. * are also added.
  136. * </p>
  137. * <p>
  138. * If no output directory is specified (no -d in the arguments), the output directory is set to the sandbox. If a directory is
  139. * specified, and the path is relative, it will be made relative to the sandbox.
  140. * </p>
  141. * <ul>
  142. * </ul>
  143. * </p>
  144. *
  145. * @param args The compiler arguments.
  146. * @return a CompilationResult object with all the messages produced by the compiler, a description of the ajc command that was
  147. * issued, and the standard output and error of the compile (excluding messages which are provided separately)
  148. * @throws IOException
  149. * @see org.aspectj.tools.ajc.CompilationResult
  150. */
  151. public CompilationResult compile(String[] args) throws IOException {
  152. incrementalStage = 10;
  153. return compile(args, false);
  154. }
  155. private CompilationResult compile(String[] args, boolean isIncremental) throws IOException {
  156. result = null;
  157. ajcArgs = args;
  158. ByteArrayOutputStream out = new ByteArrayOutputStream();
  159. PrintStream pout = new PrintStream(out);
  160. ByteArrayOutputStream err = new ByteArrayOutputStream();
  161. PrintStream perr = new PrintStream(err);
  162. PrintStream systemOut = System.out;
  163. PrintStream systemErr = System.err;
  164. System.setOut(pout);
  165. System.setErr(perr);
  166. List<IMessage> fails = new ArrayList<>();
  167. List<IMessage> errors = new ArrayList<>();
  168. List<IMessage> warnings = new ArrayList<>();
  169. List<IMessage> infos = new ArrayList<>();
  170. List<IMessage> weaves = new ArrayList<>();
  171. try {
  172. if (!isIncremental && shouldEmptySandbox) {
  173. sandbox = TestUtil.createEmptySandbox();
  174. }
  175. args = adjustToSandbox(args, !isIncremental);
  176. MessageHandler holder = new MessageHandler();
  177. holder.setInterceptor(new AbortInterceptor());
  178. main.setHolder(holder);
  179. if (incrementalStage == 10 && hasSpecifiedIncremental(args)) {
  180. // important to sleep after preparing the sandbox on first incremental stage (see notes in pr90806)
  181. try {
  182. Thread.sleep(1000);
  183. } catch (Exception e) {
  184. }
  185. }
  186. if (isIncremental) {
  187. controller.doIncremental(holder);
  188. } else {
  189. main.runMain(args, false);
  190. }
  191. addMessagesTo(infos, holder.getMessages(IMessage.INFO, false));
  192. addMessagesTo(warnings, holder.getWarnings());
  193. addMessagesTo(errors, holder.getErrors());
  194. addMessagesTo(fails, holder.getMessages(IMessage.FAIL, true));
  195. addMessagesTo(weaves, holder.getMessages(IMessage.WEAVEINFO, false));
  196. String stdOut = out.toString();
  197. String stdErr = err.toString();
  198. result = new CompilationResult(args, stdOut, stdErr, infos, errors, warnings, fails, weaves);
  199. } finally {
  200. System.setOut(systemOut);
  201. System.setErr(systemErr);
  202. }
  203. if (verbose) {
  204. System.err.println(result.getStandardError());
  205. System.out.println(result.getStandardOutput());
  206. System.out.println(result);
  207. }
  208. return result;
  209. }
  210. private boolean hasSpecifiedIncremental(String[] args) {
  211. if (args == null)
  212. return false;
  213. for (String arg : args) {
  214. if (arg.equals("-incremental"))
  215. return true;
  216. }
  217. return false;
  218. }
  219. /**
  220. * After compiling for the first time with compile(), if the -incremental option was specified you can do as many subsequent
  221. * incremental compiles as you like by calling this method.
  222. * <p>
  223. * Throws an IllegalStateException if you try and call this method without first doing a compile that specified the -incremental
  224. * option.
  225. * </p>
  226. *
  227. * @return A CompilationResult giving the results of the most recent increment.
  228. * @throws IOException
  229. */
  230. public CompilationResult doIncrementalCompile() throws IOException {
  231. if ((ajcArgs == null) || !isIncremental(ajcArgs)) {
  232. throw new IllegalStateException(
  233. "Can't do incremental compile unless -incremental specified and first compile has taken place");
  234. }
  235. incrementalStage += 10;
  236. return compile(ajcArgs, true);
  237. }
  238. /**
  239. * Return the result of the last compile or incremental compile. This is the same as the return value from the compile() or
  240. * doIncrementalCompile() methods.
  241. */
  242. public CompilationResult getLastCompilationResult() {
  243. return result;
  244. }
  245. /**
  246. * Get the sandbox directory used for the compilation.
  247. */
  248. public File getSandboxDirectory() {
  249. if (sandbox == null) {
  250. sandbox = TestUtil.createEmptySandbox();
  251. }
  252. return sandbox;
  253. }
  254. /**
  255. * Set the base directory relative to which all relative paths specified in the arguments to a compile will be interpreted.
  256. */
  257. public void setBaseDir(File dir) {
  258. if ((dir != null) && !dir.isDirectory())
  259. throw new IllegalArgumentException(dir.getPath() + " is not a directory: "+dir.getAbsolutePath());
  260. baseDir = dir;
  261. }
  262. private void addMessagesTo(List<IMessage> aList, IMessage[] messages) {
  263. Collections.addAll(aList, messages);
  264. }
  265. private boolean isIncremental(String[] args) {
  266. for (String arg : args) {
  267. if (arg.trim().equals("-incremental"))
  268. return true;
  269. }
  270. return false;
  271. }
  272. /**
  273. * Make every relative file name and dir be absolute under sandbox Add TESTER_PATH to classpath
  274. */
  275. private String[] adjustToSandbox(String[] args, boolean doCopy) throws IOException {
  276. String[] newArgs = new String[args.length];
  277. boolean hasClasspath = false;
  278. boolean hasOutdir = false;
  279. for (int i = 0; i < args.length; i++) {
  280. newArgs[i] = args[i];
  281. if (FileUtil.hasSourceSuffix(args[i])) {
  282. File f = new File(args[i]);
  283. // newArgs[i] = new File(baseDir,args[i]).getAbsolutePath(); // might be quicker?
  284. newArgs[i] = adjustFileOrDir(f, doCopy, false).getAbsolutePath();
  285. } else if (args[i].endsWith(".xml") && !args[i].startsWith("-")) {
  286. if (i > 0 && args[i - 1].equals("-outxmlfile")) {
  287. // dont adjust it
  288. } else {
  289. File f = new File(args[i]);
  290. // newArgs[i] = new File(baseDir,args[i]).getAbsolutePath(); // might be quicker?
  291. newArgs[i] = adjustFileOrDir(f, doCopy, false).getAbsolutePath();
  292. }
  293. } else {
  294. if ((args[i].equals("-aspectpath") || args[i].equals("-inpath") || args[i].equals("-injars")
  295. || args[i].equals("-outjar") || args[i].equals("-classpath") || args[i].equals("-sourceroots")
  296. || args[i].equals("-Xlintfile") || args[i].equals("-extdirs") || args[i].equals("-d"))
  297. && args.length > (i + 1))
  298. {
  299. newArgs[i] = args[i];
  300. StringBuilder buff = new StringBuilder();
  301. boolean copyThisTime = doCopy;
  302. if (args[i].equals("-d")) {
  303. copyThisTime = false;
  304. hasOutdir = true;
  305. }
  306. boolean isOutjar = args[i].equals("-outjar");
  307. StringTokenizer strTok = new StringTokenizer(args[++i], pathSeparator);
  308. while (strTok.hasMoreTokens()) {
  309. File f = new File(strTok.nextToken());
  310. buff.append(adjustFileOrDir(f, copyThisTime, isOutjar).getAbsolutePath());
  311. if (strTok.hasMoreTokens())
  312. buff.append(pathSeparator);
  313. }
  314. newArgs[i] = buff.toString();
  315. if (args[i - 1].equals("-classpath")) {
  316. hasClasspath = true;
  317. newArgs[i] = newArgs[i] + pathSeparator + TESTER_PATH + pathSeparator
  318. + getSandboxDirectory().getAbsolutePath();
  319. }
  320. } else {
  321. // could be resource file
  322. File f = new File(args[i]);
  323. if (f.exists()) {
  324. newArgs[i] = adjustFileOrDir(f, doCopy, false).getAbsolutePath();
  325. }
  326. }
  327. }
  328. }
  329. if (!hasClasspath) {
  330. String[] oldArgs = newArgs;
  331. newArgs = new String[oldArgs.length + 2];
  332. System.arraycopy(oldArgs, 0, newArgs, 0, oldArgs.length);
  333. newArgs[oldArgs.length] = "-classpath";
  334. newArgs[oldArgs.length + 1] = TESTER_PATH + pathSeparator + getSandboxDirectory().getAbsolutePath();
  335. }
  336. if (!hasOutdir) {
  337. String[] oldArgs = newArgs;
  338. newArgs = new String[oldArgs.length + 2];
  339. System.arraycopy(oldArgs, 0, newArgs, 0, oldArgs.length);
  340. newArgs[oldArgs.length] = "-d";
  341. newArgs[oldArgs.length + 1] = getSandboxDirectory().getPath();
  342. }
  343. return newArgs;
  344. }
  345. private File adjustFileOrDir(File from, boolean doCopy, boolean ensureDirsExist) throws IOException {
  346. File to = from;
  347. File ret = from;
  348. if (!from.isAbsolute()) {
  349. ret = new File(sandbox, from.getPath());
  350. File fromParent = from.getParentFile();
  351. String relativeToPath = (fromParent != null) ? (fromParent.getPath() + separator) : "";
  352. if (baseDir != null) {
  353. from = new File(baseDir, from.getPath());
  354. // if (ensureDirsExist) {
  355. // File toMkdir = (ret.getPath().endsWith(".jar") || ret.getPath().endsWith(".zip"))?ret.getParentFile():ret;
  356. // toMkdir.mkdirs();
  357. // }
  358. }
  359. if (!from.exists())
  360. return ret;
  361. if (doCopy) {
  362. // harness requires that any files with the same name, and a different extension,
  363. // get copied too (e.g. .out, .err, .event files)
  364. if (from.isFile()) {
  365. final String prefix = from.getName().substring(0, from.getName().lastIndexOf('.'));
  366. String[] toCopy = from.getParentFile().list(new FilenameFilter() {
  367. @Override
  368. public boolean accept(File dir, String name) {
  369. if (name.indexOf('.') == -1)
  370. return false;
  371. String toMatch = name.substring(0, name.lastIndexOf('.'));
  372. return (toMatch.equals(prefix));
  373. }
  374. });
  375. for (String s : toCopy) {
  376. String toPath = relativeToPath + s;
  377. to = new File(sandbox, toPath);
  378. FileUtil.copyFile(new File(from.getParentFile(), s), to);
  379. }
  380. } else {
  381. FileUtil.copyFile(from, ret);
  382. }
  383. }
  384. }
  385. return ret;
  386. }
  387. public static void dumpAJDEStructureModel(AsmManager model, String prefix) {
  388. dumpAJDEStructureModel(model, prefix, false);
  389. }
  390. public static void dumpAJDEStructureModel(AsmManager model, String prefix, boolean useHandles) {
  391. System.out.println("======================================");//$NON-NLS-1$
  392. System.out.println("start of AJDE structure model:" + prefix); //$NON-NLS-1$
  393. IRelationshipMap asmRelMap = model.getRelationshipMap();
  394. for (String sourceOfRelationship : asmRelMap.getEntries()) {
  395. System.err.println("Examining source relationship handle: " + sourceOfRelationship);
  396. List<IRelationship> relationships = null;
  397. if (useHandles) {
  398. relationships = asmRelMap.get(sourceOfRelationship);
  399. } else {
  400. IProgramElement ipe = model.getHierarchy().findElementForHandle(sourceOfRelationship);
  401. relationships = asmRelMap.get(ipe);
  402. }
  403. if (relationships != null) {
  404. for (IRelationship relationship : relationships) {
  405. Relationship rel = (Relationship) relationship;
  406. List<String> targets = rel.getTargets();
  407. for (String t : targets) {
  408. IProgramElement link = model.getHierarchy().findElementForHandle(t);
  409. System.out.println(""); //$NON-NLS-1$
  410. System.out.println(" sourceOfRelationship " + sourceOfRelationship); //$NON-NLS-1$
  411. System.out.println(" relationship " + rel.getName()); //$NON-NLS-1$
  412. System.out.println(" target " + link.getName()); //$NON-NLS-1$
  413. }
  414. }
  415. }
  416. }
  417. System.out.println("End of AJDE structure model"); //$NON-NLS-1$
  418. System.out.println("======================================");//$NON-NLS-1$
  419. }
  420. }
  421. /*
  422. * So that we can drive incremental compilation easily from a unit test.
  423. */
  424. class AjcCommandController extends Main.CommandController {
  425. private ICommand command;
  426. /*
  427. * (non-Javadoc)
  428. *
  429. * @see org.aspectj.tools.ajc.Main.CommandController#doRepeatCommand()
  430. */
  431. @Override
  432. boolean doRepeatCommand(ICommand command) {
  433. this.command = command;
  434. return false; // ensure that control returns to caller
  435. }
  436. /*
  437. * (non-Javadoc)
  438. *
  439. * @see org.aspectj.tools.ajc.Main.CommandController#running()
  440. */
  441. @Override
  442. public boolean running() {
  443. return false; // so that we can come back for more...
  444. }
  445. public void doIncremental(IMessageHandler handler) {
  446. if (command == null)
  447. throw new IllegalArgumentException("Can't repeat command until it has executed at least once!");
  448. command.repeatCommand(handler);
  449. }
  450. }
  451. class AbortInterceptor implements IMessageHandler {
  452. @Override
  453. public boolean handleMessage(IMessage message) throws AbortException {
  454. if (message.getKind() == IMessage.ABORT) {
  455. System.err.println("***** Abort Message Received ******");
  456. System.err.println(CompilationAndWeavingContext.getCurrentContext());
  457. System.err.println(message.getMessage());
  458. if (message.getThrown() != null) {
  459. System.err.println("caused by " + message.getThrown().toString());
  460. }
  461. } // allow message to accumulate...
  462. return false;
  463. }
  464. @Override
  465. public boolean isIgnoring(Kind kind) {
  466. if (kind != IMessage.ABORT)
  467. return true;
  468. return false;
  469. }
  470. @Override
  471. public void dontIgnore(Kind kind) {
  472. }
  473. @Override
  474. public void ignore(Kind kind) {
  475. }
  476. }