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