#!/usr/bin/env python3 """Collects GraalVM reachability metadata for the Kotlin compiler native image. Replays one compilation from a Kotlin daemon log on the JVM compiler, with the native-image-agent attached. The agent merges what the compiler accesses by reflection into the metadata directory of the native image build. Rebuild the native image after this. The compilation writes its classes to a new temporary directory, not to the Gradle output directory from the log. """ import argparse import glob import os import subprocess import sys import tempfile KOTLIN_REPO = os.path.expanduser("~/source/kotlin") NATIVE_IMAGE_PROJECT = os.path.join(KOTLIN_REPO, "prepare/compiler-native-image") DEFAULT_DIST = os.path.join(NATIVE_IMAGE_PROJECT, "build/dist") DEFAULT_OUT = os.path.join( NATIVE_IMAGE_PROJECT, "resources/META-INF/native-image/org/jetbrains/kotlin/kotlin-compiler-embeddable") MARKER = "Starting compilation with args: " def find_args(log_files, module): """Returns the arguments of the last compilation of module in log_files.""" found = None for log_file in log_files: with open(log_file, encoding="utf-8", errors="replace") as f: for line in f: index = line.find(MARKER) if index == -1: continue args = line[index + len(MARKER):].split() if module is None: found = args continue for i, arg in enumerate(args[:-1]): if arg == "-module-name" and args[i + 1] == module: found = args break return found def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("modules", nargs="*", metavar="module", help="value of -module-name, for example coreutils " "(default: last compilation in the log)") parser.add_argument("--log", action="append", help="Kotlin daemon log (default: all /tmp/kotlin-daemon.*.log, oldest first)") parser.add_argument("--dist", default=DEFAULT_DIST, help="native image distribution, its lib/ is the compiler classpath") parser.add_argument("--graalvm", default="/usr/lib/jvm/java-25-graalvm", help="GraalVM home, it supplies java and native-image-agent") parser.add_argument("--out", default=DEFAULT_OUT, help="metadata directory that the agent merges into") parser.add_argument("--dry-run", action="store_true", help="print the command, do not run it") options = parser.parse_args() log_files = options.log or sorted(glob.glob("/tmp/kotlin-daemon.*.log"), key=os.path.getmtime) if not log_files: sys.exit("No Kotlin daemon logs found") modules = options.modules or [None] module_args = [] for module in modules: args = find_args(log_files, module) if args is None: sys.exit("No compilation of module %s in %s" % (module, ", ".join(log_files))) module_args.append((module, args)) # The native image bundles the plugins, so put their jars on the compiler classpath too. # -Xplugin then loads them through the parent class loader, as in the native image. classpath = sorted(glob.glob(os.path.join(options.dist, "lib", "*.jar"))) if not classpath: sys.exit("No jars in %s/lib" % options.dist) failed = [] for module, args in module_args: if run(options, classpath, module, args) != 0: failed.append(module or "") if failed: print("Compiler failed for: %s. The agent still merged the metadata it saw." % ", ".join(failed)) return 1 return 0 def run(options, classpath, module, args): """Replays one compilation with the agent attached. Returns the compiler exit code.""" output_dir = "" if options.dry_run else tempfile.mkdtemp(prefix="kotlin-metadata-classes-") replayed = [] i = 0 while i < len(args): if args[i] == "-d" and i + 1 < len(args): replayed += ["-d", output_dir] i += 2 continue replayed.append(args[i]) i += 1 cmd = [ os.path.join(options.graalvm, "bin", "java"), "--add-opens", "java.base/java.lang=ALL-UNNAMED", "--add-opens", "java.base/java.io=ALL-UNNAMED", "--add-opens", "java.base/java.nio=ALL-UNNAMED", "--add-opens", "java.base/sun.nio.ch=ALL-UNNAMED", "--add-opens", "java.desktop/javax.swing=ALL-UNNAMED", "-agentlib:native-image-agent=config-merge-dir=" + options.out, "-Dkotlin.home=" + options.dist, # The compiler takes the native image code paths when this is set. "-Dorg.graalvm.nativeimage.imagecode=runtime", "-cp", os.pathsep.join(classpath), "org.jetbrains.kotlin.cli.jvm.K2JVMCompiler", "-Xdisable-default-scripting-plugin", ] + replayed if options.dry_run: print(" ".join(cmd)) return 0 print("Module: %s" % (module or "")) print("Metadata: %s" % options.out) print("Classes: %s" % output_dir) result = subprocess.run(cmd) return result.returncode if __name__ == "__main__": sys.exit(main())