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