package com.sun.tools.javac.main;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.CodeSource;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.tools.JavaFileManager;
import com.sun.tools.javac.api.BasicJavacTask;
import com.sun.tools.javac.file.CacheFSInfo;
import com.sun.tools.javac.file.BaseFileManager;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.jvm.Target;
import com.sun.tools.javac.main.CommandLine.UnmatchedQuote;
import com.sun.tools.javac.platform.PlatformDescription;
import com.sun.tools.javac.processing.AnnotationProcessingError;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticInfo;
import com.sun.tools.javac.util.Log.PrefixKind;
import com.sun.tools.javac.util.Log.WriterKind;
public class Main {
String ownName;
PrintWriter stdOut;
PrintWriter stdErr;
public Log log;
boolean apiMode;
private static final String ENV_OPT_NAME = "JDK_JAVAC_OPTIONS";
public enum Result {
OK(0),
ERROR(1),
CMDERR(2),
SYSERR(3),
ABNORMAL(4);
Result(int exitCode) {
this.exitCode = exitCode;
}
public boolean isOK() {
return (exitCode == 0);
}
public final int exitCode;
}
public Main(String name) {
this.ownName = name;
}
public Main(String name, PrintWriter out) {
this.ownName = name;
this.stdOut = this.stdErr = out;
}
public Main(String name, PrintWriter out, PrintWriter err) {
this.ownName = name;
this.stdOut = out;
this.stdErr = err;
}
void reportDiag(DiagnosticInfo diag) {
if (apiMode) {
String msg = log.localize(diag);
throw new PropagatedException(new IllegalStateException(msg));
}
reportHelper(diag);
log.printLines(PrefixKind.JAVAC, "msg.usage", ownName);
}
void reportHelper(DiagnosticInfo diag) {
String msg = log.localize(diag);
String errorPrefix = log.localize(Errors.Error);
msg = msg.startsWith(errorPrefix) ? msg : errorPrefix + msg;
log.printRawLines(msg);
}
public Result compile(String[] args) {
Context context = new Context();
JavacFileManager.preRegister(context);
Result result = compile(args, context);
try {
if (fileManager != null)
fileManager.close();
} catch (IOException ex) {
bugMessage(ex);
}
return result;
}
public Result compile(String[] argv, Context context) {
if (stdOut != null) {
context.put(Log.outKey, stdOut);
}
if (stdErr != null) {
context.put(Log.errKey, stdErr);
}
log = Log.instance(context);
if (argv.length == 0) {
OptionHelper h = new OptionHelper.GrumpyHelper(log) {
@Override
public String getOwnName() { return ownName; }
@Override
public void put(String name, String value) { }
};
try {
Option.HELP.process(h, "-help");
} catch (Option.InvalidValueException ignore) {
}
return Result.CMDERR;
}
try {
argv = CommandLine.parse(ENV_OPT_NAME, argv);
} catch (UnmatchedQuote ex) {
reportDiag(Errors.UnmatchedQuote(ex.variableName));
return Result.CMDERR;
} catch (FileNotFoundException | NoSuchFileException e) {
reportHelper(Errors.FileNotFound(e.getMessage()));
return Result.SYSERR;
} catch (IOException ex) {
log.printLines(PrefixKind.JAVAC, "msg.io");
ex.printStackTrace(log.getWriter(WriterKind.NOTICE));
return Result.SYSERR;
}
Arguments args = Arguments.instance(context);
args.init(ownName, argv);
if (log.nerrors > 0)
return Result.CMDERR;
Options options = Options.instance(context);
boolean forceStdOut = options.isSet("stdout");
if (forceStdOut) {
log.flush();
log.setWriters(new PrintWriter(System.out, true));
}
boolean batchMode = (options.isUnset("nonBatchMode")
&& System.getProperty("nonBatchMode") == null);
if (batchMode)
CacheFSInfo.preRegister(context);
boolean ok = true;
fileManager = context.get(JavaFileManager.class);
JavaFileManager undel = fileManager instanceof DelegatingJavaFileManager ?
((DelegatingJavaFileManager) fileManager).getBaseFileManager() : fileManager;
if (undel instanceof BaseFileManager) {
((BaseFileManager) undel).setContext(context);
ok &= ((BaseFileManager) undel).handleOptions(args.getDeferredFileManagerOptions());
}
String showClass = options.get("showClass");
if (showClass != null) {
if (showClass.equals("showClass"))
showClass = "com.sun.tools.javac.Main";
showClass(showClass);
}
ok &= args.validate();
if (!ok || log.nerrors > 0)
return Result.CMDERR;
if (args.isEmpty())
return Result.OK;
if (options.isSet("debug.completionDeps")) {
Dependencies.GraphDependencies.preRegister(context);
}
Set<List<String>> pluginOpts = args.getPluginOpts();
if (!pluginOpts.isEmpty() || context.get(PlatformDescription.class) != null) {
BasicJavacTask t = (BasicJavacTask) BasicJavacTask.instance(context);
t.initPlugins(pluginOpts);
}
if (fileManager.isSupportedOption(Option.MULTIRELEASE.primaryName) == 1) {
Target target = Target.instance(context);
List<String> list = List.of(target.multiReleaseValue());
fileManager.handleOption(Option.MULTIRELEASE.primaryName, list.iterator());
}
JavaCompiler comp = JavaCompiler.instance(context);
List<String> docLintOpts = args.getDocLintOpts();
if (!docLintOpts.isEmpty()) {
BasicJavacTask t = (BasicJavacTask) BasicJavacTask.instance(context);
t.initDocLint(docLintOpts);
}
if (options.get(Option.XSTDOUT) != null) {
comp.closeables = comp.closeables.prepend(log.getWriter(WriterKind.NOTICE));
}
boolean printArgsToFile = options.isSet("printArgsToFile");
try {
comp.compile(args.getFileObjects(), args.getClassNames(), null, List.nil());
if (log.expectDiagKeys != null) {
if (log.expectDiagKeys.isEmpty()) {
log.printRawLines("all expected diagnostics found");
return Result.OK;
} else {
log.printRawLines("expected diagnostic keys not found: " + log.expectDiagKeys);
return Result.ERROR;
}
}
return (comp.errorCount() == 0) ? Result.OK : Result.ERROR;
} catch (OutOfMemoryError | StackOverflowError ex) {
resourceMessage(ex);
return Result.SYSERR;
} catch (FatalError ex) {
feMessage(ex, options);
return Result.SYSERR;
} catch (AnnotationProcessingError ex) {
apMessage(ex);
return Result.SYSERR;
} catch (PropagatedException ex) {
throw ex.getCause();
} catch (IllegalAccessError iae) {
if (twoClassLoadersInUse(iae)) {
bugMessage(iae);
}
printArgsToFile = true;
return Result.ABNORMAL;
} catch (Throwable ex) {
if (comp == null || comp.errorCount() == 0 || options.isSet("dev"))
bugMessage(ex);
printArgsToFile = true;
return Result.ABNORMAL;
} finally {
if (printArgsToFile) {
printArgumentsToFile(argv);
}
if (comp != null) {
try {
comp.close();
} catch (ClientCodeException ex) {
throw new RuntimeException(ex.getCause());
}
}
}
}
void printArgumentsToFile(String... params) {
Path out = Paths.get(String.format("javac.%s.args",
new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime())));
String strOut = "";
try {
try (Writer w = Files.newBufferedWriter(out)) {
for (String param : params) {
param = param.replaceAll("\\\\", "\\\\\\\\");
if (param.matches(".*\\s+.*")) {
param = "\"" + param + "\"";
}
strOut += param + '\n';
}
w.write(strOut);
}
log.printLines(PrefixKind.JAVAC, "msg.parameters.output", out.toAbsolutePath());
} catch (IOException ioe) {
log.printLines(PrefixKind.JAVAC, "msg.parameters.output.error", out.toAbsolutePath());
System.err.println(strOut);
System.err.println();
}
}
private boolean twoClassLoadersInUse(IllegalAccessError iae) {
String msg = iae.getMessage();
Pattern pattern = Pattern.compile("(?i)(?<=tried to access class )([a-z_$][a-z\\d_$]*\\.)*[a-z_$][a-z\\d_$]*");
Matcher matcher = pattern.matcher(msg);
if (matcher.find()) {
try {
String otherClassName = matcher.group(0);
Class<?> otherClass = Class.forName(otherClassName);
ClassLoader otherClassLoader = otherClass.getClassLoader();
ClassLoader javacClassLoader = this.getClass().getClassLoader();
if (javacClassLoader != otherClassLoader) {
CodeSource otherClassCodeSource = otherClass.getProtectionDomain().getCodeSource();
CodeSource javacCodeSource = this.getClass().getProtectionDomain().getCodeSource();
if (otherClassCodeSource != null && javacCodeSource != null) {
log.printLines(Errors.TwoClassLoaders2(otherClassCodeSource.getLocation(),
javacCodeSource.getLocation()));
} else {
log.printLines(Errors.TwoClassLoaders1);
}
return true;
}
} catch (Throwable t) {
return false;
}
}
return false;
}
void bugMessage(Throwable ex) {
log.printLines(PrefixKind.JAVAC, "msg.bug", JavaCompiler.version());
ex.printStackTrace(log.getWriter(WriterKind.NOTICE));
}
void feMessage(Throwable ex, Options options) {
log.printRawLines(ex.getMessage());
if (ex.getCause() != null && options.isSet("dev")) {
ex.getCause().printStackTrace(log.getWriter(WriterKind.NOTICE));
}
}
void ioMessage(Throwable ex) {
log.printLines(PrefixKind.JAVAC, "msg.io");
ex.printStackTrace(log.getWriter(WriterKind.NOTICE));
}
void resourceMessage(Throwable ex) {
log.printLines(PrefixKind.JAVAC, "msg.resource");
ex.printStackTrace(log.getWriter(WriterKind.NOTICE));
}
void apMessage(AnnotationProcessingError ex) {
log.printLines(PrefixKind.JAVAC, "msg.proc.annotation.uncaught.exception");
ex.getCause().printStackTrace(log.getWriter(WriterKind.NOTICE));
}
void pluginMessage(Throwable ex) {
log.printLines(PrefixKind.JAVAC, "msg.plugin.uncaught.exception");
ex.printStackTrace(log.getWriter(WriterKind.NOTICE));
}
void showClass(String className) {
PrintWriter pw = log.getWriter(WriterKind.NOTICE);
pw.println("javac: show class: " + className);
URL url = getClass().getResource('/' + className.replace('.', '/') + ".class");
if (url != null) {
pw.println(" " + url);
}
try (InputStream in = getClass().getResourceAsStream('/' + className.replace('.', '/') + ".class")) {
final String algorithm = "SHA-256";
byte[] digest;
MessageDigest md = MessageDigest.getInstance(algorithm);
try (DigestInputStream din = new DigestInputStream(in, md)) {
byte[] buf = new byte[8192];
int n;
do { n = din.read(buf); } while (n > 0);
digest = md.digest();
}
StringBuilder sb = new StringBuilder();
for (byte b: digest)
sb.append(String.format("%02x", b));
pw.println(" " + algorithm + " checksum: " + sb);
} catch (NoSuchAlgorithmException | IOException e) {
pw.println(" cannot compute digest: " + e);
}
}
private JavaFileManager fileManager;
public static final String javacBundleName =
"com.sun.tools.javac.resources.javac";
}