Main.java revision 3344:31c8b18fdc5b
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 try { 178 argv = CommandLine.parse(argv); 179 } catch (FileNotFoundException | NoSuchFileException e) { 180 warning("err.file.not.found", e.getMessage()); 181 return Result.SYSERR; 182 } catch (IOException ex) { 183 log.printLines(PrefixKind.JAVAC, "msg.io"); 184 ex.printStackTrace(log.getWriter(WriterKind.NOTICE)); 185 return Result.SYSERR; 186 } 187 188 Arguments args = Arguments.instance(context); 189 args.init(ownName, argv); 190 191 if (log.nerrors > 0) 192 return Result.CMDERR; 193 194 Options options = Options.instance(context); 195 196 // init Log 197 boolean forceStdOut = options.isSet("stdout"); 198 if (forceStdOut) { 199 log.flush(); 200 log.setWriters(new PrintWriter(System.out, true)); 201 } 202 203 // init CacheFSInfo 204 // allow System property in following line as a Mustang legacy 205 boolean batchMode = (options.isUnset("nonBatchMode") 206 && System.getProperty("nonBatchMode") == null); 207 if (batchMode) 208 CacheFSInfo.preRegister(context); 209 210 boolean ok = true; 211 212 // init file manager 213 fileManager = context.get(JavaFileManager.class); 214 if (fileManager instanceof BaseFileManager) { 215 ((BaseFileManager) fileManager).setContext(context); // reinit with options 216 ok &= ((BaseFileManager) fileManager).handleOptions(args.getDeferredFileManagerOptions()); 217 } 218 219 // handle this here so it works even if no other options given 220 String showClass = options.get("showClass"); 221 if (showClass != null) { 222 if (showClass.equals("showClass")) // no value given for option 223 showClass = "com.sun.tools.javac.Main"; 224 showClass(showClass); 225 } 226 227 ok &= args.validate(); 228 if (!ok || log.nerrors > 0) 229 return Result.CMDERR; 230 231 if (args.isEmpty()) 232 return Result.OK; 233 234 // init Dependencies 235 if (options.isSet("completionDeps")) { 236 Dependencies.GraphDependencies.preRegister(context); 237 } 238 239 // init plugins 240 Set<List<String>> pluginOpts = args.getPluginOpts(); 241 if (!pluginOpts.isEmpty() || context.get(PlatformDescription.class) != null) { 242 BasicJavacTask t = (BasicJavacTask) BasicJavacTask.instance(context); 243 t.initPlugins(pluginOpts); 244 } 245 246 // init multi-release jar handling 247 if (fileManager.isSupportedOption(Option.MULTIRELEASE.text) == 1) { 248 Target target = Target.instance(context); 249 List<String> list = List.of(target.multiReleaseValue()); 250 fileManager.handleOption(Option.MULTIRELEASE.text, list.iterator()); 251 } 252 253 // init JavaCompiler 254 JavaCompiler comp = JavaCompiler.instance(context); 255 256 // init doclint 257 List<String> docLintOpts = args.getDocLintOpts(); 258 if (!docLintOpts.isEmpty()) { 259 BasicJavacTask t = (BasicJavacTask) BasicJavacTask.instance(context); 260 t.initDocLint(docLintOpts); 261 } 262 263 if (options.get(Option.XSTDOUT) != null) { 264 // Stdout reassigned - ask compiler to close it when it is done 265 comp.closeables = comp.closeables.prepend(log.getWriter(WriterKind.NOTICE)); 266 } 267 268 try { 269 comp.compile(args.getFileObjects(), args.getClassNames(), null); 270 271 if (log.expectDiagKeys != null) { 272 if (log.expectDiagKeys.isEmpty()) { 273 log.printRawLines("all expected diagnostics found"); 274 return Result.OK; 275 } else { 276 log.printRawLines("expected diagnostic keys not found: " + log.expectDiagKeys); 277 return Result.ERROR; 278 } 279 } 280 281 return (comp.errorCount() == 0) ? Result.OK : Result.ERROR; 282 283 } catch (OutOfMemoryError | StackOverflowError ex) { 284 resourceMessage(ex); 285 return Result.SYSERR; 286 } catch (FatalError ex) { 287 feMessage(ex, options); 288 return Result.SYSERR; 289 } catch (AnnotationProcessingError ex) { 290 apMessage(ex); 291 return Result.SYSERR; 292 } catch (PropagatedException ex) { 293 // TODO: what about errors from plugins? should not simply rethrow the error here 294 throw ex.getCause(); 295 } catch (Throwable ex) { 296 // Nasty. If we've already reported an error, compensate 297 // for buggy compiler error recovery by swallowing thrown 298 // exceptions. 299 if (comp == null || comp.errorCount() == 0 || options.isSet("dev")) 300 bugMessage(ex); 301 return Result.ABNORMAL; 302 } finally { 303 if (comp != null) { 304 try { 305 comp.close(); 306 } catch (ClientCodeException ex) { 307 throw new RuntimeException(ex.getCause()); 308 } 309 } 310 } 311 } 312 313 /** Print a message reporting an internal error. 314 */ 315 void bugMessage(Throwable ex) { 316 log.printLines(PrefixKind.JAVAC, "msg.bug", JavaCompiler.version()); 317 ex.printStackTrace(log.getWriter(WriterKind.NOTICE)); 318 } 319 320 /** Print a message reporting a fatal error. 321 */ 322 void feMessage(Throwable ex, Options options) { 323 log.printRawLines(ex.getMessage()); 324 if (ex.getCause() != null && options.isSet("dev")) { 325 ex.getCause().printStackTrace(log.getWriter(WriterKind.NOTICE)); 326 } 327 } 328 329 /** Print a message reporting an input/output error. 330 */ 331 void ioMessage(Throwable ex) { 332 log.printLines(PrefixKind.JAVAC, "msg.io"); 333 ex.printStackTrace(log.getWriter(WriterKind.NOTICE)); 334 } 335 336 /** Print a message reporting an out-of-resources error. 337 */ 338 void resourceMessage(Throwable ex) { 339 log.printLines(PrefixKind.JAVAC, "msg.resource"); 340 ex.printStackTrace(log.getWriter(WriterKind.NOTICE)); 341 } 342 343 /** Print a message reporting an uncaught exception from an 344 * annotation processor. 345 */ 346 void apMessage(AnnotationProcessingError ex) { 347 log.printLines(PrefixKind.JAVAC, "msg.proc.annotation.uncaught.exception"); 348 ex.getCause().printStackTrace(log.getWriter(WriterKind.NOTICE)); 349 } 350 351 /** Print a message reporting an uncaught exception from an 352 * annotation processor. 353 */ 354 void pluginMessage(Throwable ex) { 355 log.printLines(PrefixKind.JAVAC, "msg.plugin.uncaught.exception"); 356 ex.printStackTrace(log.getWriter(WriterKind.NOTICE)); 357 } 358 359 /** Display the location and checksum of a class. */ 360 void showClass(String className) { 361 PrintWriter pw = log.getWriter(WriterKind.NOTICE); 362 pw.println("javac: show class: " + className); 363 364 URL url = getClass().getResource('/' + className.replace('.', '/') + ".class"); 365 if (url != null) { 366 pw.println(" " + url); 367 } 368 369 try (InputStream in = getClass().getResourceAsStream('/' + className.replace('.', '/') + ".class")) { 370 final String algorithm = "MD5"; 371 byte[] digest; 372 MessageDigest md = MessageDigest.getInstance(algorithm); 373 try (DigestInputStream din = new DigestInputStream(in, md)) { 374 byte[] buf = new byte[8192]; 375 int n; 376 do { n = din.read(buf); } while (n > 0); 377 digest = md.digest(); 378 } 379 StringBuilder sb = new StringBuilder(); 380 for (byte b: digest) 381 sb.append(String.format("%02x", b)); 382 pw.println(" " + algorithm + " checksum: " + sb); 383 } catch (NoSuchAlgorithmException | IOException e) { 384 pw.println(" cannot compute digest: " + e); 385 } 386 } 387 388 // TODO: update this to JavacFileManager 389 private JavaFileManager fileManager; 390 391 /* ************************************************************************ 392 * Internationalization 393 *************************************************************************/ 394 395 public static final String javacBundleName = 396 "com.sun.tools.javac.resources.javac"; 397} 398