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