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