summaryrefslogtreecommitdiff
path: root/tools
diff options
context:
space:
mode:
Diffstat (limited to 'tools')
-rwxr-xr-xtools/gen_class.py59
-rw-r--r--tools/gen_jar_lists.py235
2 files changed, 288 insertions, 6 deletions
diff --git a/tools/gen_class.py b/tools/gen_class.py
index 8e1e0f4..ba0a92f 100755
--- a/tools/gen_class.py
+++ b/tools/gen_class.py
@@ -495,11 +495,52 @@ def ctor_body(cp, super_name, member, dotname, desc, call_ref, is_enum):
return code_attr(cp, max_stack, count_locals(desc, False), b)
-def clinit_body(cp, dotname, loaded_ref):
+def clinit_body(cp, dotname, loaded_ref, internal, companion=None):
b = ldc(cp.string(dotname))
b += bytes([0xb8]) + struct.pack(">H", loaded_ref)
+ max_stack = 2
+ if companion:
+ # new; dup; aconst_null -> 3 on the stack before invokespecial pops
+ max_stack = 3
+ # mirror the real <clinit>'s companion-object init:
+ # new Companion; dup; aconst_null; invokespecial Companion.<init>;
+ # putstatic Companion
+ # (leaving the static null makes real code touching
+ # <This>.Companion NPE before any stub method is ever called)
+ fname, fdesc, cname, ctor = companion
+ b += bytes([0xbb]) + struct.pack(">H", cp.cls(cname)) # new
+ b += b"\x59" # dup
+ b += b"\x01" # aconst_null
+ b += bytes([0xb7]) + struct.pack(
+ ">H", cp.methodref(cname, "<init>", ctor)) # invokespecial
+ b += bytes([0xb3]) + struct.pack(
+ ">H", cp.fieldref(internal, fname, fdesc)) # putstatic
b += b"\xb1" # return
- return code_attr(cp, 2, 0, b)
+ return code_attr(cp, max_stack, 0, b)
+
+
+def companion_init(name, info, defs):
+ """If class `name` (internal) declares a static `<name>$Companion` field,
+ describe how to instantiate it in <clinit>. Returns
+ (field_name, field_desc, companion_internal, ctor_desc) or None.
+ Kotlin companion objects are built by the enclosing class's real
+ <clinit> through the synthetic DefaultConstructorMarker ctor."""
+ marker_ctor = "(Lkotlin/jvm/internal/DefaultConstructorMarker;)V"
+ for f in info.get("fields", []):
+ if not (f["access"] & A_STATIC):
+ continue
+ t = f["desc"][1:-1]
+ if t != name + "$Companion" or len(f["desc"]) <= 2:
+ continue
+ cname = t
+ ce = defs.get(cname)
+ ctors = {mm["desc"] for mm in ce[1].get("methods", [])
+ if mm["name"] == "<init>"} if ce else set()
+ if marker_ctor in ctors:
+ return (f["name"], f["desc"], cname, marker_ctor)
+ if "()V" in ctors:
+ return (f["name"], f["desc"], cname, "()V")
+ return None
def bridge_body(cp, dotname, name, target_desc, is_static):
@@ -538,7 +579,7 @@ def field_bytes(cp, name, desc, access):
# ----------------------------------------------------------------------
# class emission
# ----------------------------------------------------------------------
-def emit_class(cp, name, info, is_iface, dotname):
+def emit_class(cp, name, info, is_iface, dotname, companion=None):
this_idx = cp.cls(name)
super_name = (info.get("super") or OBJ) if not is_iface else OBJ
super_idx = cp.cls(super_name)
@@ -604,10 +645,12 @@ def emit_class(cp, name, info, is_iface, dotname):
call_ref, is_enum)
methods.append(method_bytes(cp, "<init>", "()V",
A_PUBLIC, body))
- # synthesized static initializer -> KotlinProxyLog.loaded(name)
+ # synthesized static initializer -> KotlinProxyLog.loaded(name),
+ # plus the companion-object init when the class has one
methods.append(method_bytes(cp, "<clinit>", "()V",
A_STATIC | A_PRIVATE,
- clinit_body(cp, dotname, loaded_ref)))
+ clinit_body(cp, dotname, loaded_ref,
+ name, companion)))
out = bytearray()
out += struct.pack(">IHH", MAGIC, MINOR, MAJOR)
@@ -727,6 +770,9 @@ def main():
pass
for s in seeds:
s0.add(s)
+ bad = sorted(s for s in seeds if s not in defs)
+ if bad:
+ sys.exit("error: seed(s) not found in def jars:\n " + "\n ".join(bad))
# transitive closure (skipped with --no-closure: emit exactly the seed set)
closure = set(s0)
@@ -782,7 +828,8 @@ def main():
else:
_, info = e
is_iface = bool(info["access"] & A_INTERFACE)
- data = emit_class(cp, name, info, is_iface, dot)
+ companion = None if is_iface else companion_init(name, info, defs)
+ data = emit_class(cp, name, info, is_iface, dot, companion)
n_full += 1
if is_iface:
n_iface += 1
diff --git a/tools/gen_jar_lists.py b/tools/gen_jar_lists.py
new file mode 100644
index 0000000..06ab026
--- /dev/null
+++ b/tools/gen_jar_lists.py
@@ -0,0 +1,235 @@
+#!/usr/bin/env python3
+"""
+Regenerate the jar list files in jars/ (the input to gen_class.py).
+
+These files used to be written by hand; this script scans the local Gradle
+module cache and rewrites them deterministically, so a Kotlin/AGP upgrade is:
+
+ 1. bump the version in test_project (gradle/libs.versions.toml) and
+ Makefile (KOTLIN_VERSION / AGP_VERSION),
+ 2. run the test_project once so Gradle populates the cache with the new
+ jars (even a red build resolves everything),
+ 3. run this script (or just `make` - it regenerates the lists when the
+ pinned versions drift from jars/.stamp).
+
+Files written (one jar path per line, '#' comments allowed downstream):
+
+ defs.txt every org.jetbrains.kotlin jar at the pinned Kotlin version,
+ sorted by jar name. gen_class.py takes the FIRST jar that
+ contains a class (first-wins), and the KGP jar bundles its
+ own copies of some compiler classes (e.g. K2JVMCompiler)
+ that DIFFER from the ones in kotlin-compiler-embeddable;
+ alphabetical order keeps kotlin-compiler-* ahead of
+ kotlin-gradle-plugin, which is the ordering the daemon
+ actually sees.
+ scan.txt the AGP core jars at the pinned AGP version (the classes
+ "AGP uses" - seed source for the full-closure mode).
+ fallback.txt KGP-plugin-family jars at OTHER cached versions, newest
+ first - definition lookup only, for classes missing from
+ the pinned set.
+
+Also writes <out-dir>/.stamp as "<kotlin-version> <agp-version>" so the
+Makefile can detect version drift without parsing the lists.
+"""
+
+import argparse
+import os
+import re
+import sys
+
+# AGP core jars on the buildscript classpath (seed sources for
+# gen_class.py's full-closure mode). A fixed allowlist rather than "every
+# com.android.tools.build jar" so aaptcompiler/lint/... don't bloat S0.
+SCAN_ARTIFACTS = [
+ "gradle",
+ "gradle-api",
+ "gradle-common-api",
+ "gradle-settings-api",
+ "builder",
+ "builder-model",
+]
+
+# KGP plugin family used for fallback definition lookup (other versions of
+# the plugin that the build actually runs with).
+FALLBACK_ARTIFACTS = [
+ "kotlin-gradle-plugin",
+ "kotlin-gradle-plugin-api",
+ "kotlin-tooling-core",
+]
+
+KOTLIN_GROUP = "org.jetbrains.kotlin"
+AGP_GROUP = "com.android.tools.build"
+
+
+def ver_key(v):
+ """Sortable key for a version string: numeric parts first, then text
+ (so 2.4.10 > 2.4.9 and 2.4.21-rc1 sorts near 2.4.21)."""
+ m = re.match(r"(\d+(?:\.\d+)*)", v)
+ nums = [int(p) for p in m.group(1).split(".")] if m else []
+ return (nums, v)
+
+
+def find_jars(cache, group, artifact, version):
+ """All .jar files for group:artifact:version in the cache layout
+ <cache>/<group>/<artifact>/<version>/<sha1>/<name>.jar."""
+ base = os.path.join(cache, group, artifact, version)
+ if not os.path.isdir(base):
+ return []
+ out = []
+ for sha in os.listdir(base):
+ d = os.path.join(base, sha)
+ if not os.path.isdir(d):
+ continue
+ for f in os.listdir(d):
+ # binary jars only - skip -sources.jar / -javadoc.jar
+ if (f.endswith(".jar") and os.path.isfile(os.path.join(d, f))
+ and "-sources" not in f and "-javadoc" not in f):
+ out.append(os.path.join(d, f))
+ return out
+
+
+def all_versions(cache, group, artifact):
+ base = os.path.join(cache, group, artifact)
+ if not os.path.isdir(base):
+ return []
+ return sorted(
+ (v for v in os.listdir(base)
+ if os.path.isdir(os.path.join(base, v)) and v[0].isdigit()),
+ key=ver_key,
+ )
+
+
+def write_if_changed(path, lines):
+ content = "\n".join(lines) + "\n"
+ old = None
+ if os.path.exists(path):
+ with open(path) as fh:
+ old = fh.read()
+ if old == content:
+ print(f"unchanged {os.path.basename(path)} ({len(lines)} lines)")
+ return False
+ with open(path, "w") as fh:
+ fh.write(content)
+ print(f"wrote {os.path.basename(path)} ({len(lines)} lines)")
+ return True
+
+
+def main():
+ ap = argparse.ArgumentParser(
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--kotlin-version", required=True,
+ help="pinned Kotlin/KGP version, e.g. 2.4.21")
+ ap.add_argument("--agp-version", required=True,
+ help="pinned AGP version, e.g. 9.4.1")
+ ap.add_argument("--gradle-cache",
+ default=os.path.expanduser(
+ "~/.gradle/caches/modules-2/files-2.1"),
+ help="Gradle module cache root "
+ "(default: %(default)s)")
+ ap.add_argument("--out-dir", default="jars",
+ help="directory for defs.txt/scan.txt/fallback.txt "
+ "(default: %(default)s)")
+ args = ap.parse_args()
+ cache = args.gradle_cache
+ if not os.path.isdir(cache):
+ sys.exit(f"error: Gradle cache not found: {cache}")
+
+ # ---- defs.txt: all org.jetbrains.kotlin jars at the pinned version ----
+ defs = []
+ missing = []
+ for artifact in sorted(os.listdir(os.path.join(cache, KOTLIN_GROUP))
+ if os.path.isdir(os.path.join(cache, KOTLIN_GROUP))
+ else []):
+ jars = find_jars(cache, KOTLIN_GROUP, artifact, args.kotlin_version)
+ if not jars:
+ continue
+ defs.extend(jars)
+ # Sanity-check the core artifacts (we can't know the full expected
+ # artifact set; these three must be there or the lists are useless).
+ for core in ("kotlin-compiler-embeddable", "kotlin-gradle-plugin",
+ "kotlin-stdlib"):
+ if not find_jars(cache, KOTLIN_GROUP, core, args.kotlin_version):
+ missing.append(f"{KOTLIN_GROUP}:{core}:{args.kotlin_version}")
+ defs.sort(key=os.path.basename)
+ if missing:
+ sys.exit(
+ "error: cache is missing "
+ + ", ".join(missing)
+ + f"\n run the test_project once with Kotlin {args.kotlin_version} "
+ "so Gradle downloads the jars, then re-run this script.")
+
+ defs_lines = [
+ f"# auto-generated by tools/gen_jar_lists.py - all {KOTLIN_GROUP} "
+ f"{args.kotlin_version} jars, sorted by jar name.",
+ "# First jar wins for duplicate class names; the sort keeps "
+ "kotlin-compiler-* ahead of kotlin-gradle-plugin (which bundles "
+ "its own copies of some compiler classes - the compiler jar must "
+ "win, it is what the daemon loads).",
+ *defs,
+ ]
+
+ # ---- scan.txt: AGP core jars at the pinned AGP version ----
+ scan = []
+ missing_scan = []
+ for artifact in SCAN_ARTIFACTS:
+ jars = find_jars(cache, AGP_GROUP, artifact, args.agp_version)
+ if jars:
+ scan.extend(jars)
+ else:
+ missing_scan.append(f"{AGP_GROUP}:{artifact}:{args.agp_version}")
+ scan.sort(key=os.path.basename)
+ if missing_scan:
+ sys.exit(
+ "error: cache is missing "
+ + ", ".join(missing_scan)
+ + f"\n run the test_project once with AGP {args.agp_version} "
+ "so Gradle downloads the jars, then re-run this script.")
+
+ scan_lines = [
+ f"# auto-generated by tools/gen_jar_lists.py - AGP "
+ f"{args.agp_version} core jars on the buildscript classpath "
+ "(the classes AGP uses; seed source for full-closure mode).",
+ *scan,
+ ]
+
+ # ---- fallback.txt: KGP family at other versions, newest first ----
+ fb = []
+ for artifact in FALLBACK_ARTIFACTS:
+ for v in all_versions(cache, KOTLIN_GROUP, artifact):
+ if v == args.kotlin_version:
+ continue
+ fb.extend((v, j) for j in
+ find_jars(cache, KOTLIN_GROUP, artifact, v))
+ fb.sort(key=lambda t: (t[0], os.path.basename(t[1])), reverse=True)
+ fb_lines = [
+ f"# auto-generated by tools/gen_jar_lists.py - {KOTLIN_GROUP} "
+ f"KGP-plugin-family jars at other cached versions, newest first. "
+ f"Definition lookup only (fallback.txt is scanned after defs.txt).",
+ *(j for _, j in fb),
+ ]
+ if not fb:
+ print("note: no other KGP-plugin versions in cache; "
+ "fallback.txt will be empty")
+
+ # ---- write ----
+ os.makedirs(args.out_dir, exist_ok=True)
+ write_if_changed(os.path.join(args.out_dir, "defs.txt"), defs_lines)
+ write_if_changed(os.path.join(args.out_dir, "scan.txt"), scan_lines)
+ write_if_changed(os.path.join(args.out_dir, "fallback.txt"), fb_lines)
+
+ stamp = os.path.join(args.out_dir, ".stamp")
+ stamp_content = f"{args.kotlin_version} {args.agp_version}\n"
+ old = None
+ if os.path.exists(stamp):
+ with open(stamp) as fh:
+ old = fh.read()
+ if old != stamp_content:
+ with open(stamp, "w") as fh:
+ fh.write(stamp_content)
+ print(f"wrote .stamp ({stamp_content.strip()})")
+ else:
+ print("unchanged .stamp")
+
+
+if __name__ == "__main__":
+ main()