Main.java revision 3999:ae88ea1b7649
1/* 2 * Copyright (c) 1999, 2017, 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 */ 25 26package com.sun.tools.javac.main; 27 28import java.io.FileNotFoundException; 29import java.io.IOException; 30import java.io.InputStream; 31import java.io.PrintWriter; 32import java.net.URL; 33import java.nio.file.NoSuchFileException; 34import java.security.DigestInputStream; 35import java.security.MessageDigest; 36import java.security.NoSuchAlgorithmException; 37import java.util.Set; 38 39import javax.tools.JavaFileManager; 40 41import com.sun.tools.javac.api.BasicJavacTask; 42import com.sun.tools.javac.file.CacheFSInfo; 43import com.sun.tools.javac.file.BaseFileManager; 44import com.sun.tools.javac.file.JavacFileManager; 45import com.sun.tools.javac.jvm.Target; 46import com.sun.tools.javac.platform.PlatformDescription; 47import com.sun.tools.javac.processing.AnnotationProcessingError; 48import com.sun.tools.javac.util.*; 49import com.sun.tools.javac.util.Log.PrefixKind; 50import com.sun.tools.javac.util.Log.WriterKind; 51 52/** This class provides a command line interface to the javac compiler. 53 * 54 * <p><b>This is NOT part of any supported API. 55 * If you write code that depends on this, you do so at your own risk. 56 * This code and its internal interfaces are subject to change or 57 * deletion without notice.</b> 58 */ 59public class Main { 60 61 /** The name of the compiler, for use in diagnostics. 62 */ 63 String ownName; 64 65 /** The writer to use for normal output. 66 */ 67 PrintWriter stdOut; 68 69 /** The writer to use for diagnostic output. 70 */ 71 PrintWriter stdErr; 72 73 /** The log to use for diagnostic output. 74 */ 75 public Log log; 76 77 /** 78 * If true, certain errors will cause an exception, such as command line 79 * arg errors, or exceptions in user provided code. 80 */ 81 boolean apiMode; 82 83 84 /** Result codes. 85 */ 86 public enum Result { 87 OK(0), // Compilation completed with no errors. 88 ERROR(1), // Completed but reported errors. 89 CMDERR(2), // Bad command-line arguments 90 SYSERR(3), // System error or resource exhaustion. 91 ABNORMAL(4); // Compiler terminated abnormally 92 93 Result(int exitCode) { 94 this.exitCode = exitCode; 95 } 96 97 public boolean isOK() { 98 return (exitCode == 0); 99 } 100 101 public final int exitCode; 102 } 103 104 /** 105 * Construct a compiler instance. 106 * @param name the name of this tool 107 */ 108 public Main(String name) { 109 this.ownName = name; 110 } 111 112 /** 113 * Construct a compiler instance. 114 * @param name the name of this tool 115 * @param out a stream to which to write messages 116 */ 117 public Main(String name, PrintWriter out) { 118 this.ownName = name; 119 this.stdOut = this.stdErr = out; 120 } 121 122 /** 123 * Construct a compiler instance. 124 * @param name the name of this tool 125 * @param out a stream to which to write expected output 126 * @param err a stream to which to write diagnostic output 127 */ 128 public Main(String name, PrintWriter out, PrintWriter err) { 129 this.ownName = name; 130 this.stdOut = out; 131 this.stdErr = err; 132 } 133 134 /** Report a usage error. 135 */ 136 void error(String key, Object... args) { 137 if (apiMode) { 138 String msg = log.localize(PrefixKind.JAVAC, key, args); 139 throw new PropagatedException(new IllegalStateException(msg)); 140 } 141 warning(key, args); 142 log.printLines(PrefixKind.JAVAC, "msg.usage", ownName); 143 } 144 145 /** Report a warning. 146 */ 147 void warning(String key, Object... args) { 148 log.printRawLines(ownName + ": " + log.localize(PrefixKind.JAVAC, key, args)); 149 } 150 151 152 /** 153 * Programmatic interface for main function. 154 * @param args the command line parameters 155 * @return the result of the compilation 156 */ 157 public Result compile(String[] args) { 158 Context context = new Context(); 159 JavacFileManager.preRegister(context); // can't create it until Log has been set up 160 Result result = compile(args, context); 161 if (fileManager instanceof JavacFileManager) { 162 try { 163 // A fresh context was created above, so jfm must be a JavacFileManager 164 ((JavacFileManager)fileManager).close(); 165 } catch (IOException ex) { 166 bugMessage(ex); 167 } 168 } 169 return result; 170 } 171 172 /** 173 * Internal version of compile, allowing context to be provided. 174 * Note that the context needs to have a file manager set up. 175 * @param argv the command line parameters 176 * @param context the context 177 * @return the result of the compilation 178 */ 179 public Result compile(String[] argv, Context context) { 180 if (stdOut != null) { 181 context.put(Log.outKey, stdOut); 182 } 183 184 if (stdErr != null) { 185 context.put(Log.errKey, stdErr); 186 } 187 188 log = Log.instance(context); 189 190 if (argv.length == 0) { 191 OptionHelper h = new OptionHelper.GrumpyHelper(log) { 192 @Override 193 public String getOwnName() { return ownName; } 194 @Override 195 public void put(String name, String value) { } 196 }; 197 try { 198 Option.HELP.process(h, "-help"); 199 } catch (Option.InvalidValueException ignore) { 200 } 201 return Result.CMDERR; 202 } 203 204 // prefix argv with contents of _JAVAC_OPTIONS if set 205 String envOpt = System.getenv("_JAVAC_OPTIONS"); 206 if (envOpt != null && !envOpt.trim().isEmpty()) { 207 String[] envv = envOpt.split("\\s+"); 208 String[] result = new String[envv.length + argv.length]; 209 System.arraycopy(envv, 0, result, 0, envv.length); 210 System.arraycopy(argv, 0, result, envv.length, argv.length); 211 argv = result; 212 } 213 214 // expand @-files 215 try { 216 argv = CommandLine.parse(argv); 217 } catch (FileNotFoundException | NoSuchFileException e) { 218 warning("err.file.not.found", e.getMessage()); 219 return Result.SYSERR; 220 } catch (IOException ex) { 221 log.printLines(PrefixKind.JAVAC, "msg.io"); 222 ex.printStackTrace(log.getWriter(WriterKind.NOTICE)); 223 return Result.SYSERR; 224 } 225 226 Arguments args = Arguments.instance(context); 227 args.init(ownName, argv); 228 229 if (log.nerrors > 0) 230 return Result.CMDERR; 231 232 Options options = Options.instance(context); 233 234 // init Log 235 boolean forceStdOut = options.isSet("stdout"); 236 if (forceStdOut) { 237 log.flush(); 238 log.setWriters(new PrintWriter(System.out, true)); 239 } 240 241 // init CacheFSInfo 242 // allow System property in following line as a Mustang legacy 243 boolean batchMode = (options.isUnset("nonBatchMode") 244 && System.getProperty("nonBatchMode") == null); 245 if (batchMode) 246 CacheFSInfo.preRegister(context); 247 248 boolean ok = true; 249 250 // init file manager 251 fileManager = context.get(JavaFileManager.class); 252 if (fileManager instanceof BaseFileManager) { 253 ((BaseFileManager) fileManager).setContext(context); // reinit with options 254 ok &= ((BaseFileManager) fileManager).handleOptions(args.getDeferredFileManagerOptions()); 255 } 256 257 // handle this here so it works even if no other options given 258 String showClass = options.get("showClass"); 259 if (showClass != null) { 260 if (showClass.equals("showClass")) // no value given for option 261 showClass = "com.sun.tools.javac.Main"; 262 showClass(showClass); 263 } 264 265 ok &= args.validate(); 266 if (!ok || log.nerrors > 0) 267 return Result.CMDERR; 268 269 if (args.isEmpty()) 270 return Result.OK; 271 272 // init Dependencies 273 if (options.isSet("debug.completionDeps")) { 274 Dependencies.GraphDependencies.preRegister(context); 275 } 276 277 // init plugins 278 Set<List<String>> pluginOpts = args.getPluginOpts(); 279 if (!pluginOpts.isEmpty() || context.get(PlatformDescription.class) != null) { 280 BasicJavacTask t = (BasicJavacTask) BasicJavacTask.instance(context); 281 t.initPlugins(pluginOpts); 282 } 283 284 // init multi-release jar handling 285 if (fileManager.isSupportedOption(Option.MULTIRELEASE.primaryName) == 1) { 286 Target target = Target.instance(context); 287 List<String> list = List.of(target.multiReleaseValue()); 288 fileManager.handleOption(Option.MULTIRELEASE.primaryName, list.iterator()); 289 } 290 291 // init JavaCompiler 292 JavaCompiler comp = JavaCompiler.instance(context); 293 294 // init doclint 295 List<String> docLintOpts = args.getDocLintOpts(); 296 if (!docLintOpts.isEmpty()) { 297 BasicJavacTask t = (BasicJavacTask) BasicJavacTask.instance(context); 298 t.initDocLint(docLintOpts); 299 } 300 301 if (options.get(Option.XSTDOUT) != null) { 302 // Stdout reassigned - ask compiler to close it when it is done 303 comp.closeables = comp.closeables.prepend(log.getWriter(WriterKind.NOTICE)); 304 } 305 306 try { 307 comp.compile(args.getFileObjects(), args.getClassNames(), null, List.nil()); 308 309 if (log.expectDiagKeys != null) { 310 if (log.expectDiagKeys.isEmpty()) { 311 log.printRawLines("all expected diagnostics found"); 312 return Result.OK; 313 } else { 314 log.printRawLines("expected diagnostic keys not found: " + log.expectDiagKeys); 315 return Result.ERROR; 316 } 317 } 318 319 return (comp.errorCount() == 0) ? Result.OK : Result.ERROR; 320 321 } catch (OutOfMemoryError | StackOverflowError ex) { 322 resourceMessage(ex); 323 return Result.SYSERR; 324 } catch (FatalError ex) { 325 feMessage(ex, options); 326 return Result.SYSERR; 327 } catch (AnnotationProcessingError ex) { 328 apMessage(ex); 329 return Result.SYSERR; 330 } catch (PropagatedException ex) { 331 // TODO: what about errors from plugins? should not simply rethrow the error here 332 throw ex.getCause(); 333 } catch (Throwable ex) { 334 // Nasty. If we've already reported an error, compensate 335 // for buggy compiler error recovery by swallowing thrown 336 // exceptions. 337 if (comp == null || comp.errorCount() == 0 || options.isSet("dev")) 338 bugMessage(ex); 339 return Result.ABNORMAL; 340 } finally { 341 if (comp != null) { 342 try { 343 comp.close(); 344 } catch (ClientCodeException ex) { 345 throw new RuntimeException(ex.getCause()); 346 } 347 } 348 } 349 } 350 351 /** Print a message reporting an internal error. 352 */ 353 void bugMessage(Throwable ex) { 354 log.printLines(PrefixKind.JAVAC, "msg.bug", JavaCompiler.version()); 355 ex.printStackTrace(log.getWriter(WriterKind.NOTICE)); 356 } 357 358 /** Print a message reporting a fatal error. 359 */ 360 void feMessage(Throwable ex, Options options) { 361 log.printRawLines(ex.getMessage()); 362 if (ex.getCause() != null && options.isSet("dev")) { 363 ex.getCause().printStackTrace(log.getWriter(WriterKind.NOTICE)); 364 } 365 } 366 367 /** Print a message reporting an input/output error. 368 */ 369 void ioMessage(Throwable ex) { 370 log.printLines(PrefixKind.JAVAC, "msg.io"); 371 ex.printStackTrace(log.getWriter(WriterKind.NOTICE)); 372 } 373 374 /** Print a message reporting an out-of-resources error. 375 */ 376 void resourceMessage(Throwable ex) { 377 log.printLines(PrefixKind.JAVAC, "msg.resource"); 378 ex.printStackTrace(log.getWriter(WriterKind.NOTICE)); 379 } 380 381 /** Print a message reporting an uncaught exception from an 382 * annotation processor. 383 */ 384 void apMessage(AnnotationProcessingError ex) { 385 log.printLines(PrefixKind.JAVAC, "msg.proc.annotation.uncaught.exception"); 386 ex.getCause().printStackTrace(log.getWriter(WriterKind.NOTICE)); 387 } 388 389 /** Print a message reporting an uncaught exception from an 390 * annotation processor. 391 */ 392 void pluginMessage(Throwable ex) { 393 log.printLines(PrefixKind.JAVAC, "msg.plugin.uncaught.exception"); 394 ex.printStackTrace(log.getWriter(WriterKind.NOTICE)); 395 } 396 397 /** Display the location and checksum of a class. */ 398 void showClass(String className) { 399 PrintWriter pw = log.getWriter(WriterKind.NOTICE); 400 pw.println("javac: show class: " + className); 401 402 URL url = getClass().getResource('/' + className.replace('.', '/') + ".class"); 403 if (url != null) { 404 pw.println(" " + url); 405 } 406 407 try (InputStream in = getClass().getResourceAsStream('/' + className.replace('.', '/') + ".class")) { 408 final String algorithm = "MD5"; 409 byte[] digest; 410 MessageDigest md = MessageDigest.getInstance(algorithm); 411 try (DigestInputStream din = new DigestInputStream(in, md)) { 412 byte[] buf = new byte[8192]; 413 int n; 414 do { n = din.read(buf); } while (n > 0); 415 digest = md.digest(); 416 } 417 StringBuilder sb = new StringBuilder(); 418 for (byte b: digest) 419 sb.append(String.format("%02x", b)); 420 pw.println(" " + algorithm + " checksum: " + sb); 421 } catch (NoSuchAlgorithmException | IOException e) { 422 pw.println(" cannot compute digest: " + e); 423 } 424 } 425 426 // TODO: update this to JavacFileManager 427 private JavaFileManager fileManager; 428 429 /* ************************************************************************ 430 * Internationalization 431 *************************************************************************/ 432 433 public static final String javacBundleName = 434 "com.sun.tools.javac.resources.javac"; 435} 436