package kotlin.proxy; import org.jetbrains.kotlin.cli.common.ExitCode; import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments; import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocationWithRange; import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity; import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation; import org.jetbrains.kotlin.cli.common.messages.MessageCollector; import org.jetbrains.kotlin.cli.common.messages.MessageCollectorUtil; import org.jetbrains.kotlin.config.JvmTarget; import org.jetbrains.kotlin.config.Services; import org.jetbrains.kotlin.platform.jvm.JvmPlatforms; import org.jetbrains.kotlin.progress.CompilationCanceledStatus; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.FileOutputStream; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.IdentityHashMap; import java.util.Map; import java.util.UUID; /** * Per-method custom return values for the generated stubs. * * Every stub method with a reference return type (other than String) asks * here for its return value (via {@link KotlinProxyLog#returnValue}) before * falling back to the default — a real no-arg instance of the declared return * type, or null. Implement the methods you want the stub to actually do * something for; return {@link #NO_VALUE} for everything else. * * args[i] is the i-th parameter of the call: reference types as-is, * primitives boxed (Integer, Long, Boolean, ...). A param-less method gets * args == null. * * instance is the receiver — the stub instance the method was called on — so * you can keep per-compiler state (identity-keyed; see performanceManagers). * It is null for static methods. Rebuild the jar (steps 2-3) after editing. */ public final class KotlinProxyOverrides { /** Return this from invoke() to keep the default return value. */ public static final Object NO_VALUE = new Object(); /** * Per-compiler-instance state, keyed by the stub receiver instance. * Identity semantics (each K2JVMCompiler instance is its own entry), * synchronized because daemon compilations may run on different threads. */ private static final Map compilers = Collections.synchronizedMap(new IdentityHashMap<>()); private static String KOTLIN_VERSION = "2.4.21"; private static String KOTLIN_NATIVE_IMAGE = "kotlin-native-image-linux-x86_64-" + KOTLIN_VERSION; private static Object NATIVE_IMAGE_LOCK = new Object(); private KotlinProxyOverrides() { } public static Object invoke(String member, String ownerDotName, String returnDotName, Object[] args, Object instance) { if ("org.jetbrains.kotlin.cli.jvm.K2JVMCompiler".equals(ownerDotName)) { Compiler compiler = compilers.computeIfAbsent(instance, (key) -> new Compiler()); if ("createPerformanceManager".equals(member)) { K2JVMCompilerArguments compilerArgs = (K2JVMCompilerArguments) args[0]; // Services services = (Services) args[1]; compiler.performanceManager = new ProxyPerformanceManager(JvmTarget.Companion.fromString(compilerArgs.getJvmTarget())); return compiler.performanceManager; } if ("getPlatform".equals(member)) { return JvmPlatforms.INSTANCE.getDefaultJvmPlatform(); } if ("doExecutePhased".equals(member)) { K2JVMCompilerArguments arguments = (K2JVMCompilerArguments) args[0]; Services services = (Services) args[1]; MessageCollector messageCollector = (MessageCollector) args[2]; CompilationCanceledStatus canceledStatus = services.get(CompilationCanceledStatus.class); String userDir = System.getProperty("user.dir"); if (userDir == null) { messageCollector.report(CompilerMessageSeverity.ERROR, "System property user.dir is not set", null); return ExitCode.INTERNAL_ERROR; } String javaHome = System.getProperty("java.home"); if (javaHome == null) { messageCollector.report(CompilerMessageSeverity.ERROR, "System property java.home is not set", null); return ExitCode.INTERNAL_ERROR; } File nativeImage; // A distribution root such as prepare/compiler-native-image/build/dist in the Kotlin repository. String customNativeImage = System.getProperty("kotlin.proxy.nativeImage"); if (customNativeImage == null) { messageCollector.report(CompilerMessageSeverity.ERROR, "System property kotlin.proxy.nativeImage is not set", null); return ExitCode.INTERNAL_ERROR; } else { nativeImage = new File(customNativeImage, "bin/kotlinc-native-image.sh"); if (!nativeImage.exists()) { messageCollector.report(CompilerMessageSeverity.ERROR, "kotlin.proxy.nativeImage: " + nativeImage + " does not exist", null); return ExitCode.INTERNAL_ERROR; } } ArrayList cmd = new ArrayList(); cmd.add(nativeImage.toString()); // For an image built with --pgo-instrument. Each compile writes its own profile, because parallel // compiles share the working directory and overwrite each other's default.iprof. String pgoProfileDir = System.getProperty("kotlin.proxy.pgoProfileDir"); if (pgoProfileDir != null && !pgoProfileDir.isEmpty()) { new File(pgoProfileDir).mkdirs(); cmd.add("-XX:ProfilesDumpFile=" + new File(pgoProfileDir, UUID.randomUUID() + ".iprof")); } cmd.addAll(GeneratedJvmArguments.buildCommandArgs(arguments)); cmd.addAll(arguments.getFreeArgs()); ProcessBuilder builder = new ProcessBuilder(cmd); builder.environment().put("JAVA_HOME", javaHome); try { Process process = builder.start(); Object lock = new Object(); Thread readOutput = new Thread(new LineCollector(process.getInputStream(), messageCollector, lock, CompilerMessageSeverity.INFO)); Thread readError = new Thread(new LineCollector(process.getErrorStream(), messageCollector, lock, CompilerMessageSeverity.ERROR)); readOutput.start(); readError.start(); process.getOutputStream().close(); canceledStatus.checkCanceled(); int exitvalue = process.waitFor(); readOutput.join(); readError.join(); if (exitvalue == 0) { return ExitCode.OK; } return ExitCode.COMPILATION_ERROR; } catch (Throwable t) { MessageCollectorUtil.reportException(messageCollector, t); return ExitCode.SCRIPT_EXECUTION_ERROR; } } } return NO_VALUE; } private static class Compiler { ProxyPerformanceManager performanceManager; } private static class LineCollector implements Runnable { private final InputStream input; private final MessageCollector collector; private final Object lock; private final CompilerMessageSeverity defaultSeverity; private LineCollector(InputStream input, MessageCollector collector, Object lock, CompilerMessageSeverity defaultSeverity) { this.input = input; this.collector = collector; this.lock = lock; this.defaultSeverity = defaultSeverity; } @Override public void run() { try (BufferedReader reader = new BufferedReader(new InputStreamReader(input))) { String line; while ((line = reader.readLine()) != null) { if (line.isEmpty()) continue; CompilerMessageSeverity severity = null; String message = line; CompilerMessageSourceLocation location = null; String[] parts = line.split(": "); if (parts.length >= 3) { severity = getSeverity(parts[1]); if (severity != null) { String path = parts[0]; int lineStart = -1; int columnStart = -1; String[] locationParts = parts[0].split(":"); if (locationParts.length == 3) { try { lineStart = Integer.parseInt(locationParts[1]); columnStart = Integer.parseInt(locationParts[2]); path = locationParts[0]; } catch (NumberFormatException e) { } } location = CompilerMessageLocationWithRange.Companion.create( path, lineStart, columnStart, /* lineEnd */ null, /* columnEnd */ null, /* lineContent */ null); message = parts[2]; } } if (parts.length >= 2 && severity == null) { severity = getSeverity(parts[0]); if (severity != null) { message = String.join(": ", Arrays.asList(parts).subList(1, parts.length)); } } if (severity == null) { // Both JVM and Kotlin compiler is rather noisy, only output lines that are parsed. continue; } synchronized (lock) { collector.report(severity, message, location); } } } catch (IOException e) { } } } private static CompilerMessageSeverity getSeverity(String value) { switch (value) { case "exception": return CompilerMessageSeverity.EXCEPTION; case "error": return CompilerMessageSeverity.ERROR; case "warning": return CompilerMessageSeverity.WARNING; case "info": return CompilerMessageSeverity.INFO; case "logging": return CompilerMessageSeverity.LOGGING; case "output": return CompilerMessageSeverity.OUTPUT; } return null; } }