summaryrefslogtreecommitdiff
path: root/tools
diff options
context:
space:
mode:
Diffstat (limited to 'tools')
-rwxr-xr-xtools/collect_metadata.py135
-rw-r--r--tools/gen_arg_table.py1
-rwxr-xr-xtools/ic_check.sh187
3 files changed, 323 insertions, 0 deletions
diff --git a/tools/collect_metadata.py b/tools/collect_metadata.py
new file mode 100755
index 0000000..8192369
--- /dev/null
+++ b/tools/collect_metadata.py
@@ -0,0 +1,135 @@
+#!/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 "<last>")
+ 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 = "<tmpdir>" 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 "<last>"))
+ print("Metadata: %s" % options.out)
+ print("Classes: %s" % output_dir)
+ result = subprocess.run(cmd)
+ return result.returncode
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/gen_arg_table.py b/tools/gen_arg_table.py
index d074ead..4bfe4dc 100644
--- a/tools/gen_arg_table.py
+++ b/tools/gen_arg_table.py
@@ -138,6 +138,7 @@ def render(records, notes):
notes.append(("warn", f"{flag} ({field}): boolean default is "
f"true - a false value cannot be "
f"spelled on the CLI, token omitted"))
+ continue
entries.append(dict(kind="bool", flag=flag,
stmt=f'if ({g}) cmd.add("{flag}");',
note=dep_note))
diff --git a/tools/ic_check.sh b/tools/ic_check.sh
new file mode 100755
index 0000000..c584fad
--- /dev/null
+++ b/tools/ic_check.sh
@@ -0,0 +1,187 @@
+#!/usr/bin/env bash
+# Checks that incremental Kotlin compilation stays correct in the OFA build.
+#
+# The stub runs the native image compiler in a subprocess. The Kotlin daemon
+# then gets no lookup or output data from the compiler. Incremental
+# compilation uses that data to find the files that a change makes dirty.
+# If it is missing, a build can succeed with stale class files.
+#
+# Usage: ic_check.sh proxy|jvm [OFA mobile/mobile dir]
+# proxy uses the kotlinProxy* properties from gradle-local.properties.
+# jvm sets -PkotlinProxyStubJar= to use the JVM compiler. Run it first.
+# It must pass, else the test itself is wrong.
+#
+# The script adds test files to components/annotations and
+# components/coreutils, and removes them on exit.
+
+set -u
+
+MODE=${1:-}
+OFA=${2:-/home/the_jk/opera/head-1/mobile/mobile}
+JAVAP=/usr/lib/jvm/java-25-graalvm/bin/javap
+
+case "$MODE" in
+proxy) EXTRA_ARGS=() ;;
+jvm) EXTRA_ARGS=(-PkotlinProxyStubJar=) ;;
+*)
+ echo "Usage: $0 proxy|jvm [OFA mobile/mobile dir]" >&2
+ exit 2
+ ;;
+esac
+
+if [ ! -x "$OFA/gradlew" ]; then
+ echo "No gradlew in $OFA" >&2
+ exit 2
+fi
+
+ANNOTATIONS_DIR="$OFA/components/annotations/src/main/java/com/opera/android/annotations/ictest"
+COREUTILS_DIR="$OFA/components/coreutils/src/main/java/com/opera/android/ictest"
+CLASSES="$OFA/bin/gradle/components/coreutils/intermediates/built_in_kotlinc/debug/compileDebugKotlin/classes"
+FILE_A="$COREUTILS_DIR/IcTestA.kt"
+FILE_B="$COREUTILS_DIR/IcTestB.kt"
+FILE_C="$COREUTILS_DIR/IcTestC.kt"
+FILE_X="$ANNOTATIONS_DIR/IcTestCross.kt"
+CLASS_B="$CLASSES/com/opera/android/ictest/IcTestBKt.class"
+CLASS_C="$CLASSES/com/opera/android/ictest/IcTestCKt.class"
+
+if [ -e "$ANNOTATIONS_DIR" ] || [ -e "$COREUTILS_DIR" ]; then
+ echo "Test files exist from an earlier run. Remove them first:" >&2
+ echo " $ANNOTATIONS_DIR" >&2
+ echo " $COREUTILS_DIR" >&2
+ exit 2
+fi
+
+LOG_DIR=$(mktemp -d /tmp/ic-check-"$MODE".XXXXXX)
+
+cleanup() {
+ rm -f "$FILE_A" "$FILE_B" "$FILE_C" "$FILE_X"
+ rmdir "$COREUTILS_DIR" "$ANNOTATIONS_DIR" 2>/dev/null
+}
+trap cleanup EXIT
+
+RESULTS=()
+FAILED=0
+
+record() {
+ # record <name> <ok|BAD> <detail>
+ RESULTS+=("$(printf '%-28s %-4s %s' "$1" "$2" "$3")")
+ if [ "$2" != ok ]; then
+ FAILED=1
+ fi
+}
+
+build() {
+ # build <log name>. Returns the Gradle exit code.
+ local log="$LOG_DIR/$1.log"
+ (cd "$OFA" && ./gradlew --console=plain --no-build-cache "${EXTRA_ARGS[@]}" \
+ :components:coreutils:compileDebugKotlin >"$log" 2>&1)
+}
+
+# has_const <class file> <method> <value>: true if the method loads the constant.
+has_const() {
+ "$JAVAP" -c -p "$1" 2>/dev/null | awk -v m="$2" -v want="iconst_$3" '
+ index($0, " " m "(") { inside = 1; next }
+ inside && /^ [a-z].*\(/ { inside = 0 }
+ inside && index($0, want) { found = 1 }
+ END { exit found ? 0 : 1 }'
+}
+
+write_a() {
+ # write_a <signature of icTestValue> <IC_TEST_CONST>
+ cat >"$FILE_A" <<EOF
+package com.opera.android.ictest
+
+$1
+
+const val IC_TEST_CONST = $2
+EOF
+}
+
+write_x() {
+ cat >"$FILE_X" <<EOF
+package com.opera.android.annotations.ictest
+
+const val IC_TEST_CROSS = $1
+EOF
+}
+
+mkdir -p "$COREUTILS_DIR" "$ANNOTATIONS_DIR"
+write_a "fun icTestValue(): Int = 1" 1
+write_x 1
+cat >"$FILE_B" <<'EOF'
+package com.opera.android.ictest
+
+fun icTestUse(): Int = icTestValue()
+
+fun icTestConst(): Int = IC_TEST_CONST
+EOF
+cat >"$FILE_C" <<'EOF'
+package com.opera.android.ictest
+
+import com.opera.android.annotations.ictest.IC_TEST_CROSS
+
+fun icTestCross(): Int = IC_TEST_CROSS
+EOF
+
+echo "Mode: $MODE. Logs: $LOG_DIR"
+
+echo "0/4 setup build"
+if ! build 0-setup; then
+ echo "Setup build failed, see $LOG_DIR/0-setup.log" >&2
+ exit 1
+fi
+
+# 1. A constant is inlined into its users. Only IcTestA.kt changes, so
+# IcTestB.kt is recompiled only if the build finds the dependency.
+echo "1/4 constant in the same module"
+write_a "fun icTestValue(): Int = 1" 2
+if ! build 1-const; then
+ record "1 constant, same module" BAD "build failed, see 1-const.log"
+elif has_const "$CLASS_B" icTestConst 2; then
+ record "1 constant, same module" ok "IcTestB recompiled"
+else
+ record "1 constant, same module" BAD "IcTestBKt.class still has the old constant"
+fi
+
+# 2. The same, but the constant is in components/annotations.
+echo "2/4 constant in a dependency module"
+write_x 2
+if ! build 2-cross; then
+ record "2 constant, other module" BAD "build failed, see 2-cross.log"
+elif has_const "$CLASS_C" icTestCross 2; then
+ record "2 constant, other module" ok "IcTestC recompiled"
+else
+ record "2 constant, other module" BAD "IcTestCKt.class still has the old constant"
+fi
+
+# 3. A signature change must give a compile error in the unchanged caller.
+echo "3/4 signature change"
+write_a "fun icTestValue(x: Int): Int = x" 2
+if build 3-signature; then
+ record "3 signature change" BAD "build succeeded, caller in IcTestB.kt not recompiled"
+elif grep -q "IcTestB.kt" "$LOG_DIR/3-signature.log"; then
+ record "3 signature change" ok "error reported in IcTestB.kt"
+else
+ record "3 signature change" BAD "build failed without an error in IcTestB.kt, see 3-signature.log"
+fi
+write_a "fun icTestValue(): Int = 1" 2
+if ! build 3-restore; then
+ echo "Restore build failed, see $LOG_DIR/3-restore.log" >&2
+ exit 1
+fi
+
+# 4. A deleted source file must also remove its class file.
+echo "4/4 deleted file"
+rm -f "$FILE_B"
+if ! build 4-delete; then
+ record "4 deleted file" BAD "build failed, see 4-delete.log"
+elif [ -e "$CLASS_B" ]; then
+ record "4 deleted file" BAD "IcTestBKt.class still exists"
+else
+ record "4 deleted file" ok "IcTestBKt.class removed"
+fi
+
+echo
+echo "Results ($MODE):"
+printf '%s\n' "${RESULTS[@]}"
+exit $FAILED