Wed, 21 Sep 2011 21:56:53 -0700
7092965: javac should not close processorClassLoader before end of compilation
Reviewed-by: darcy
1 /*
2 * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.tools.javac.main;
28 import java.io.File;
29 import java.io.IOException;
30 import java.io.PrintWriter;
31 import java.net.URL;
32 import java.security.DigestInputStream;
33 import java.security.MessageDigest;
34 import java.util.Collection;
35 import java.util.LinkedHashSet;
36 import java.util.MissingResourceException;
37 import java.util.Set;
38 import javax.tools.JavaFileManager;
39 import javax.tools.JavaFileObject;
40 import javax.annotation.processing.Processor;
42 import com.sun.tools.javac.code.Source;
43 import com.sun.tools.javac.file.CacheFSInfo;
44 import com.sun.tools.javac.file.JavacFileManager;
45 import com.sun.tools.javac.jvm.Target;
46 import com.sun.tools.javac.main.JavacOption.Option;
47 import com.sun.tools.javac.main.RecognizedOptions.OptionHelper;
48 import com.sun.tools.javac.util.*;
49 import com.sun.tools.javac.processing.AnnotationProcessingError;
51 import static com.sun.tools.javac.main.OptionName.*;
53 /** This class provides a commandline interface to the GJC compiler.
54 *
55 * <p><b>This is NOT part of any supported API.
56 * If you write code that depends on this, you do so at your own risk.
57 * This code and its internal interfaces are subject to change or
58 * deletion without notice.</b>
59 */
60 public class Main {
62 /** The name of the compiler, for use in diagnostics.
63 */
64 String ownName;
66 /** The writer to use for diagnostic output.
67 */
68 PrintWriter out;
70 /**
71 * If true, certain errors will cause an exception, such as command line
72 * arg errors, or exceptions in user provided code.
73 */
74 boolean apiMode;
77 /** Result codes.
78 */
79 static final int
80 EXIT_OK = 0, // Compilation completed with no errors.
81 EXIT_ERROR = 1, // Completed but reported errors.
82 EXIT_CMDERR = 2, // Bad command-line arguments
83 EXIT_SYSERR = 3, // System error or resource exhaustion.
84 EXIT_ABNORMAL = 4; // Compiler terminated abnormally
86 private Option[] recognizedOptions = RecognizedOptions.getJavaCompilerOptions(new OptionHelper() {
88 public void setOut(PrintWriter out) {
89 Main.this.out = out;
90 }
92 public void error(String key, Object... args) {
93 Main.this.error(key, args);
94 }
96 public void printVersion() {
97 Log.printLines(out, getLocalizedString("version", ownName, JavaCompiler.version()));
98 }
100 public void printFullVersion() {
101 Log.printLines(out, getLocalizedString("fullVersion", ownName, JavaCompiler.fullVersion()));
102 }
104 public void printHelp() {
105 help();
106 }
108 public void printXhelp() {
109 xhelp();
110 }
112 public void addFile(File f) {
113 filenames.add(f);
114 }
116 public void addClassName(String s) {
117 classnames.append(s);
118 }
120 });
122 /**
123 * Construct a compiler instance.
124 */
125 public Main(String name) {
126 this(name, new PrintWriter(System.err, true));
127 }
129 /**
130 * Construct a compiler instance.
131 */
132 public Main(String name, PrintWriter out) {
133 this.ownName = name;
134 this.out = out;
135 }
136 /** A table of all options that's passed to the JavaCompiler constructor. */
137 private Options options = null;
139 /** The list of source files to process
140 */
141 public Set<File> filenames = null; // XXX sb protected
143 /** List of class files names passed on the command line
144 */
145 public ListBuffer<String> classnames = null; // XXX sb protected
147 /** Print a string that explains usage.
148 */
149 void help() {
150 Log.printLines(out, getLocalizedString("msg.usage.header", ownName));
151 for (int i=0; i<recognizedOptions.length; i++) {
152 recognizedOptions[i].help(out);
153 }
154 out.println();
155 }
157 /** Print a string that explains usage for X options.
158 */
159 void xhelp() {
160 for (int i=0; i<recognizedOptions.length; i++) {
161 recognizedOptions[i].xhelp(out);
162 }
163 out.println();
164 Log.printLines(out, getLocalizedString("msg.usage.nonstandard.footer"));
165 }
167 /** Report a usage error.
168 */
169 void error(String key, Object... args) {
170 if (apiMode) {
171 String msg = getLocalizedString(key, args);
172 throw new PropagatedException(new IllegalStateException(msg));
173 }
174 warning(key, args);
175 Log.printLines(out, getLocalizedString("msg.usage", ownName));
176 }
178 /** Report a warning.
179 */
180 void warning(String key, Object... args) {
181 Log.printLines(out, ownName + ": "
182 + getLocalizedString(key, args));
183 }
185 public Option getOption(String flag) {
186 for (Option option : recognizedOptions) {
187 if (option.matches(flag))
188 return option;
189 }
190 return null;
191 }
193 public void setOptions(Options options) {
194 if (options == null)
195 throw new NullPointerException();
196 this.options = options;
197 }
199 public void setAPIMode(boolean apiMode) {
200 this.apiMode = apiMode;
201 }
203 /** Process command line arguments: store all command line options
204 * in `options' table and return all source filenames.
205 * @param flags The array of command line arguments.
206 */
207 public Collection<File> processArgs(String[] flags) { // XXX sb protected
208 int ac = 0;
209 while (ac < flags.length) {
210 String flag = flags[ac];
211 ac++;
213 Option option = null;
215 if (flag.length() > 0) {
216 // quick hack to speed up file processing:
217 // if the option does not begin with '-', there is no need to check
218 // most of the compiler options.
219 int firstOptionToCheck = flag.charAt(0) == '-' ? 0 : recognizedOptions.length-1;
220 for (int j=firstOptionToCheck; j<recognizedOptions.length; j++) {
221 if (recognizedOptions[j].matches(flag)) {
222 option = recognizedOptions[j];
223 break;
224 }
225 }
226 }
228 if (option == null) {
229 error("err.invalid.flag", flag);
230 return null;
231 }
233 if (option.hasArg()) {
234 if (ac == flags.length) {
235 error("err.req.arg", flag);
236 return null;
237 }
238 String operand = flags[ac];
239 ac++;
240 if (option.process(options, flag, operand))
241 return null;
242 } else {
243 if (option.process(options, flag))
244 return null;
245 }
246 }
248 if (!checkDirectory(D))
249 return null;
250 if (!checkDirectory(S))
251 return null;
253 String sourceString = options.get(SOURCE);
254 Source source = (sourceString != null)
255 ? Source.lookup(sourceString)
256 : Source.DEFAULT;
257 String targetString = options.get(TARGET);
258 Target target = (targetString != null)
259 ? Target.lookup(targetString)
260 : Target.DEFAULT;
261 // We don't check source/target consistency for CLDC, as J2ME
262 // profiles are not aligned with J2SE targets; moreover, a
263 // single CLDC target may have many profiles. In addition,
264 // this is needed for the continued functioning of the JSR14
265 // prototype.
266 if (Character.isDigit(target.name.charAt(0))) {
267 if (target.compareTo(source.requiredTarget()) < 0) {
268 if (targetString != null) {
269 if (sourceString == null) {
270 warning("warn.target.default.source.conflict",
271 targetString,
272 source.requiredTarget().name);
273 } else {
274 warning("warn.source.target.conflict",
275 sourceString,
276 source.requiredTarget().name);
277 }
278 return null;
279 } else {
280 target = source.requiredTarget();
281 options.put("-target", target.name);
282 }
283 } else {
284 if (targetString == null && !source.allowGenerics()) {
285 target = Target.JDK1_4;
286 options.put("-target", target.name);
287 }
288 }
289 }
291 // handle this here so it works even if no other options given
292 String showClass = options.get("showClass");
293 if (showClass != null) {
294 if (showClass.equals("showClass")) // no value given for option
295 showClass = "com.sun.tools.javac.Main";
296 showClass(showClass);
297 }
299 return filenames;
300 }
301 // where
302 private boolean checkDirectory(OptionName optName) {
303 String value = options.get(optName);
304 if (value == null)
305 return true;
306 File file = new File(value);
307 if (!file.exists()) {
308 error("err.dir.not.found", value);
309 return false;
310 }
311 if (!file.isDirectory()) {
312 error("err.file.not.directory", value);
313 return false;
314 }
315 return true;
316 }
318 /** Programmatic interface for main function.
319 * @param args The command line parameters.
320 */
321 public int compile(String[] args) {
322 Context context = new Context();
323 JavacFileManager.preRegister(context); // can't create it until Log has been set up
324 int result = compile(args, context);
325 if (fileManager instanceof JavacFileManager) {
326 // A fresh context was created above, so jfm must be a JavacFileManager
327 ((JavacFileManager)fileManager).close();
328 }
329 return result;
330 }
332 public int compile(String[] args, Context context) {
333 return compile(args, context, List.<JavaFileObject>nil(), null);
334 }
336 /** Programmatic interface for main function.
337 * @param args The command line parameters.
338 */
339 public int compile(String[] args,
340 Context context,
341 List<JavaFileObject> fileObjects,
342 Iterable<? extends Processor> processors)
343 {
344 if (options == null)
345 options = Options.instance(context); // creates a new one
347 filenames = new LinkedHashSet<File>();
348 classnames = new ListBuffer<String>();
349 JavaCompiler comp = null;
350 /*
351 * TODO: Logic below about what is an acceptable command line
352 * should be updated to take annotation processing semantics
353 * into account.
354 */
355 try {
356 if (args.length == 0 && fileObjects.isEmpty()) {
357 help();
358 return EXIT_CMDERR;
359 }
361 Collection<File> files;
362 try {
363 files = processArgs(CommandLine.parse(args));
364 if (files == null) {
365 // null signals an error in options, abort
366 return EXIT_CMDERR;
367 } else if (files.isEmpty() && fileObjects.isEmpty() && classnames.isEmpty()) {
368 // it is allowed to compile nothing if just asking for help or version info
369 if (options.isSet(HELP)
370 || options.isSet(X)
371 || options.isSet(VERSION)
372 || options.isSet(FULLVERSION))
373 return EXIT_OK;
374 if (JavaCompiler.explicitAnnotationProcessingRequested(options)) {
375 error("err.no.source.files.classes");
376 } else {
377 error("err.no.source.files");
378 }
379 return EXIT_CMDERR;
380 }
381 } catch (java.io.FileNotFoundException e) {
382 Log.printLines(out, ownName + ": " +
383 getLocalizedString("err.file.not.found",
384 e.getMessage()));
385 return EXIT_SYSERR;
386 }
388 boolean forceStdOut = options.isSet("stdout");
389 if (forceStdOut) {
390 out.flush();
391 out = new PrintWriter(System.out, true);
392 }
394 context.put(Log.outKey, out);
396 // allow System property in following line as a Mustang legacy
397 boolean batchMode = (options.isUnset("nonBatchMode")
398 && System.getProperty("nonBatchMode") == null);
399 if (batchMode)
400 CacheFSInfo.preRegister(context);
402 fileManager = context.get(JavaFileManager.class);
404 comp = JavaCompiler.instance(context);
405 if (comp == null) return EXIT_SYSERR;
407 Log log = Log.instance(context);
409 if (!files.isEmpty()) {
410 // add filenames to fileObjects
411 comp = JavaCompiler.instance(context);
412 List<JavaFileObject> otherFiles = List.nil();
413 JavacFileManager dfm = (JavacFileManager)fileManager;
414 for (JavaFileObject fo : dfm.getJavaFileObjectsFromFiles(files))
415 otherFiles = otherFiles.prepend(fo);
416 for (JavaFileObject fo : otherFiles)
417 fileObjects = fileObjects.prepend(fo);
418 }
419 comp.compile(fileObjects,
420 classnames.toList(),
421 processors);
423 if (log.expectDiagKeys != null) {
424 if (log.expectDiagKeys.isEmpty()) {
425 Log.printLines(log.noticeWriter, "all expected diagnostics found");
426 return EXIT_OK;
427 } else {
428 Log.printLines(log.noticeWriter, "expected diagnostic keys not found: " + log.expectDiagKeys);
429 return EXIT_ERROR;
430 }
431 }
433 if (comp.errorCount() != 0)
434 return EXIT_ERROR;
435 } catch (IOException ex) {
436 ioMessage(ex);
437 return EXIT_SYSERR;
438 } catch (OutOfMemoryError ex) {
439 resourceMessage(ex);
440 return EXIT_SYSERR;
441 } catch (StackOverflowError ex) {
442 resourceMessage(ex);
443 return EXIT_SYSERR;
444 } catch (FatalError ex) {
445 feMessage(ex);
446 return EXIT_SYSERR;
447 } catch (AnnotationProcessingError ex) {
448 if (apiMode)
449 throw new RuntimeException(ex.getCause());
450 apMessage(ex);
451 return EXIT_SYSERR;
452 } catch (ClientCodeException ex) {
453 // as specified by javax.tools.JavaCompiler#getTask
454 // and javax.tools.JavaCompiler.CompilationTask#call
455 throw new RuntimeException(ex.getCause());
456 } catch (PropagatedException ex) {
457 throw ex.getCause();
458 } catch (Throwable ex) {
459 // Nasty. If we've already reported an error, compensate
460 // for buggy compiler error recovery by swallowing thrown
461 // exceptions.
462 if (comp == null || comp.errorCount() == 0 ||
463 options == null || options.isSet("dev"))
464 bugMessage(ex);
465 return EXIT_ABNORMAL;
466 } finally {
467 if (comp != null) {
468 try {
469 comp.close();
470 } catch (ClientCodeException ex) {
471 throw new RuntimeException(ex.getCause());
472 }
473 }
474 filenames = null;
475 options = null;
476 }
477 return EXIT_OK;
478 }
480 /** Print a message reporting an internal error.
481 */
482 void bugMessage(Throwable ex) {
483 Log.printLines(out, getLocalizedString("msg.bug",
484 JavaCompiler.version()));
485 ex.printStackTrace(out);
486 }
488 /** Print a message reporting a fatal error.
489 */
490 void feMessage(Throwable ex) {
491 Log.printLines(out, ex.getMessage());
492 if (ex.getCause() != null && options.isSet("dev")) {
493 ex.getCause().printStackTrace(out);
494 }
495 }
497 /** Print a message reporting an input/output error.
498 */
499 void ioMessage(Throwable ex) {
500 Log.printLines(out, getLocalizedString("msg.io"));
501 ex.printStackTrace(out);
502 }
504 /** Print a message reporting an out-of-resources error.
505 */
506 void resourceMessage(Throwable ex) {
507 Log.printLines(out, getLocalizedString("msg.resource"));
508 // System.out.println("(name buffer len = " + Name.names.length + " " + Name.nc);//DEBUG
509 ex.printStackTrace(out);
510 }
512 /** Print a message reporting an uncaught exception from an
513 * annotation processor.
514 */
515 void apMessage(AnnotationProcessingError ex) {
516 Log.printLines(out,
517 getLocalizedString("msg.proc.annotation.uncaught.exception"));
518 ex.getCause().printStackTrace(out);
519 }
521 /** Display the location and checksum of a class. */
522 void showClass(String className) {
523 out.println("javac: show class: " + className);
524 URL url = getClass().getResource('/' + className.replace('.', '/') + ".class");
525 if (url == null)
526 out.println(" class not found");
527 else {
528 out.println(" " + url);
529 try {
530 final String algorithm = "MD5";
531 byte[] digest;
532 MessageDigest md = MessageDigest.getInstance(algorithm);
533 DigestInputStream in = new DigestInputStream(url.openStream(), md);
534 try {
535 byte[] buf = new byte[8192];
536 int n;
537 do { n = in.read(buf); } while (n > 0);
538 digest = md.digest();
539 } finally {
540 in.close();
541 }
542 StringBuilder sb = new StringBuilder();
543 for (byte b: digest)
544 sb.append(String.format("%02x", b));
545 out.println(" " + algorithm + " checksum: " + sb);
546 } catch (Exception e) {
547 out.println(" cannot compute digest: " + e);
548 }
549 }
550 }
552 private JavaFileManager fileManager;
554 /* ************************************************************************
555 * Internationalization
556 *************************************************************************/
558 /** Find a localized string in the resource bundle.
559 * @param key The key for the localized string.
560 */
561 public static String getLocalizedString(String key, Object... args) { // FIXME sb private
562 try {
563 if (messages == null)
564 messages = new JavacMessages(javacBundleName);
565 return messages.getLocalizedString("javac." + key, args);
566 }
567 catch (MissingResourceException e) {
568 throw new Error("Fatal Error: Resource for javac is missing", e);
569 }
570 }
572 public static void useRawMessages(boolean enable) {
573 if (enable) {
574 messages = new JavacMessages(javacBundleName) {
575 @Override
576 public String getLocalizedString(String key, Object... args) {
577 return key;
578 }
579 };
580 } else {
581 messages = new JavacMessages(javacBundleName);
582 }
583 }
585 private static final String javacBundleName =
586 "com.sun.tools.javac.resources.javac";
588 private static JavacMessages messages;
589 }