summaryrefslogtreecommitdiff
path: root/stubs/src/kotlin/proxy/KotlinProxyOverrides.java
blob: e03c04da33d909bc272f92e69577737207da21ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
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.net.URL;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
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.stream.Stream;

/**
 * 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<Object, Compiler> 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 && !customNativeImage.isEmpty()) {
                    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;
                    }
                } else {
                    nativeImage = downloadNativeImage(userDir, messageCollector);
                    if (nativeImage == null) {
                        return ExitCode.INTERNAL_ERROR;
                    }
                }
                ArrayList<String> cmd = new ArrayList<String>();
                cmd.add(nativeImage.toString());
                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;

                            int lastSpace = parts[0].lastIndexOf(' ');
                            if (lastSpace != -1 && parts[0].startsWith("(", lastSpace + 1) && parts[0].endsWith(")")) {
                                String[] locationParts = parts[0].substring(lastSpace + 1, parts[0].length() - 1).split(":");
                                if (locationParts.length == 2) {
                                    try {
                                        lineStart = Integer.parseInt(locationParts[0]);
                                        columnStart = Integer.parseInt(locationParts[1]);
                                        path = parts[0].substring(0, lastSpace);
                                    } catch (NumberFormatException e) {
                                    }
                                }
                            }
                            location = CompilerMessageLocationWithRange.Companion.create(
                                    path, lineStart, columnStart, /* lineEnd */ null, /* columnEnd */ null, /* lineContent */ null);
                            message = parts[3];
                        }
                    }
                    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;
    }

    /** Downloads and extracts the JetBrains native image into user.dir. Returns null after it reports an error. */
    private static File downloadNativeImage(String userDir, MessageCollector messageCollector) {
        File nativeImageDir = new File(userDir, "native-image");
        File nativeImage = new File(nativeImageDir, KOTLIN_NATIVE_IMAGE + "/bin/kotlinc-native-image.sh");
        if (!nativeImage.exists()) {
            nativeImageDir.mkdirs();

            synchronized (NATIVE_IMAGE_LOCK) {
                // Check again, now that we have the lock
                if (!nativeImage.exists()) {
                    File nativeImageTar = new File(nativeImageDir, KOTLIN_NATIVE_IMAGE + ".tar.gz");
                    if (!nativeImageTar.exists()) {
                        try (InputStream in = new URL("https://github.com/JetBrains/kotlin/releases/download/v"
                                                      + KOTLIN_VERSION + "/" + KOTLIN_NATIVE_IMAGE + ".tar.gz").openStream()) {
                            Files.copy(in, nativeImageTar.toPath(), StandardCopyOption.REPLACE_EXISTING);
                        } catch (IOException e) {
                            MessageCollectorUtil.reportException(messageCollector, e);
                            return null;
                        }
                    }
                    File nativeImageDirTmp = new File(nativeImageDir, "tmp");
                    nativeImageDirTmp.mkdir();
                    ArrayList<String> cmd = new ArrayList<String>();
                    cmd.add("tar");
                    cmd.add("-x");
                    cmd.add("-f");
                    cmd.add(nativeImageTar.toString());
                    cmd.add("-z");
                    cmd.add("-C");
                    cmd.add(nativeImageDirTmp.toString());
                    ProcessBuilder builder = new ProcessBuilder(cmd);
                    try {
                        Process process = builder.start();
                        int exitvalue = process.waitFor();
                        if (exitvalue != 0) {
                            // TODO: Include error stream
                            messageCollector.report(CompilerMessageSeverity.ERROR, "Unable to extract native image " + nativeImageTar, null);
                            deleteRecursive(nativeImageDirTmp);
                            return null;
                        }
                        File target = new File(nativeImageDir, KOTLIN_NATIVE_IMAGE);
                        deleteRecursive(target);
                        Files.move(new File(nativeImageDirTmp, KOTLIN_NATIVE_IMAGE).toPath(),
                                   target.toPath());
                        nativeImageDirTmp.delete();
                    } catch (Throwable t) {
                        MessageCollectorUtil.reportException(messageCollector, t);
                        deleteRecursive(nativeImageDirTmp);
                        return null;
                    }
                }
            }
        }
        return nativeImage;
    }

    private static void deleteRecursive(File dir) {
        try {
            try (Stream<Path> paths = Files.walk(dir.toPath())) {
                paths.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
            }
        } catch (IOException e) {
        }
    }
}