summaryrefslogtreecommitdiff
path: root/tools
diff options
context:
space:
mode:
Diffstat (limited to 'tools')
-rwxr-xr-xtools/gen_class.py731
1 files changed, 731 insertions, 0 deletions
diff --git a/tools/gen_class.py b/tools/gen_class.py
new file mode 100755
index 0000000..fb398e9
--- /dev/null
+++ b/tools/gen_class.py
@@ -0,0 +1,731 @@
+#!/usr/bin/env python3
+"""
+kotlin-proxy stub generator — BYTECODE edition.
+
+Instead of emitting Java source and fighting javac's generics checker
+(erasure bridges that the JVM needs for linkage but javac forbids as
+"same erasure, yet neither overrides the other"), this emits the .class
+files DIRECTLY. It copies the real class file's erased structure
+verbatim — exact super/interfaces, every field, every method (including
+synthetic $default and erasure bridges) with its exact name + descriptor
+and access flags — and gives each concrete method a trivial body that
+logs the call via kotlin.proxy.KotlinProxyLog and returns a default value.
+
+The optional Signature attribute is OMITTED entirely, so there are no
+generics in the emitted class files and therefore no generics clashes.
+The JVM links by name + erased descriptor, both of which are copied
+verbatim, so the stub is ABI-identical to the real class.
+
+Bodies are straight-line (no branches), so no StackMapTable frames are
+needed.
+
+Usage:
+ python3 gen_class.py --scan-jars <list> --def-jars <list> --out <dir>
+ [--fallback-jars <list>] [--report <file>]
+"""
+
+import argparse
+import os
+import struct
+import sys
+import zipfile
+
+MAGIC = 0xCAFEBABE
+MAJOR, MINOR = 52, 0 # Java 8
+KPL = "kotlin/proxy/KotlinProxyLog"
+OBJ = "java/lang/Object"
+CALL_DESC = "(Ljava/lang/String;Ljava/lang/String;)V"
+CALL_ARG_DESC = "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Object;)V"
+LOADED_DESC = "(Ljava/lang/String;)V"
+NEW_INST_DESC = "(Ljava/lang/String;)Ljava/lang/Object;"
+
+# access flags
+A_PUBLIC, A_PRIVATE, A_PROTECTED = 0x1, 0x2, 0x4
+A_STATIC, A_FINAL, A_SUPER = 0x8, 0x10, 0x20
+A_BRIDGE, A_SYNTHETIC = 0x40, 0x1000
+A_INTERFACE, A_ABSTRACT, A_ANNOTATION, A_ENUM = 0x200, 0x400, 0x2000, 0x4000
+
+
+# ----------------------------------------------------------------------
+# jar / class-file helpers
+# ----------------------------------------------------------------------
+def read_list(path):
+ """One jar path per line; blank lines and '#' comments ignored."""
+ out = []
+ with open(path) as fh:
+ for line in fh:
+ line = line.strip()
+ if line and not line.startswith("#"):
+ out.append(line)
+ return out
+
+
+def load_jar_classes(jar):
+ """internal name (slash form) -> .class bytes for every entry."""
+ out = {}
+ with zipfile.ZipFile(jar) as z:
+ for n in z.namelist():
+ if n.endswith(".class"):
+ out[n[:-len(".class")]] = z.read(n)
+ return out
+
+
+def parse_class(data):
+ """Parse a class file into the info dict used by emit_class():
+ {access, super, interfaces, fields[{name,desc,access}],
+ methods[{name,desc,access,has_code}], refs[internal names]}.
+ Returns None if unparseable."""
+ try:
+ if len(data) < 10 or struct.unpack_from(">I", data, 0)[0] != MAGIC:
+ return None
+ o = 8
+ cp_count, = struct.unpack_from(">H", data, o)
+ o += 2
+ utf8 = {} # cp idx -> utf8 string
+ cls_names = {} # cp idx -> internal name (for Class constants)
+ i = 1
+ while i < cp_count:
+ tag = data[o]
+ o += 1
+ if tag == 1: # Utf8
+ ln, = struct.unpack_from(">H", data, o)
+ o += 2
+ utf8[i] = data[o:o + ln].decode("utf-8", "replace")
+ o += ln
+ elif tag in (3, 4): # Integer, Float
+ o += 4
+ elif tag in (5, 6): # Long, Double (2 slots)
+ o += 8
+ i += 1
+ elif tag == 7: # Class
+ idx, = struct.unpack_from(">H", data, o)
+ o += 2
+ cls_names[i] = utf8.get(idx, "")
+ elif tag in (8, 16, 19, 20): # String/MethodType/Module/Package
+ o += 2
+ elif tag == 12: # NameAndType (2 indexes = 4 bytes)
+ o += 4
+ elif tag in (9, 10, 11): # Fieldref/Methodref/...
+ o += 4
+ elif tag == 15: # MethodHandle (u1 kind + u2 idx)
+ o += 3
+ elif tag in (17, 18): # DynamicCallSite/InvokeDynamic
+ o += 4 # (u2 bootstrap + u2 nametype)
+ else:
+ return None
+ i += 1
+ access, this, sup = struct.unpack_from(">HHH", data, o)
+ o += 6
+ # Every class named anywhere in the file (this/super/interfaces and
+ # every method/field/annotation target) is a Class constant, so the
+ # set of tag-7 names is the complete reference set for the closure.
+ refs = {nm for nm in cls_names.values() if nm}
+ super_name = cls_names.get(sup) if sup else None
+ interfaces = []
+ n, = struct.unpack_from(">H", data, o)
+ o += 2
+ for _ in range(n):
+ idx, = struct.unpack_from(">H", data, o)
+ o += 2
+ nm = cls_names.get(idx, "")
+ if nm:
+ interfaces.append(nm)
+ fields = []
+ n, = struct.unpack_from(">H", data, o)
+ o += 2
+ for _ in range(n):
+ fa, fn, fd = struct.unpack_from(">HHH", data, o)
+ o += 6
+ fields.append({"name": utf8[fn], "desc": utf8[fd], "access": fa})
+ na, = struct.unpack_from(">H", data, o)
+ o += 2
+ for _ in range(na):
+ ln, = struct.unpack_from(">I", data, o + 2)
+ o += 6 + ln
+ methods = []
+ n, = struct.unpack_from(">H", data, o)
+ o += 2
+ for _ in range(n):
+ ma, mn, md = struct.unpack_from(">HHH", data, o)
+ o += 6
+ has_code = False
+ na, = struct.unpack_from(">H", data, o)
+ o += 2
+ for _ in range(na):
+ an = utf8[struct.unpack_from(">H", data, o)[0]]
+ ln, = struct.unpack_from(">I", data, o + 2)
+ o += 6 + ln
+ if an == "Code":
+ has_code = True
+ methods.append({"name": utf8[mn], "desc": utf8[md],
+ "access": ma, "has_code": has_code})
+ return {"access": access, "super": super_name,
+ "interfaces": interfaces, "fields": fields,
+ "methods": methods, "refs": sorted(refs)}
+ except (struct.error, IndexError, KeyError):
+ return None
+
+
+def kotlin_ref(name):
+ """True if the internal name is a Kotlin-owned class we may stub."""
+ return name.startswith(("org/jetbrains/kotlin/", "kotlin/",
+ "kotlinx/", "org/jetbrains/kotlinx/"))
+
+
+# ----------------------------------------------------------------------
+# constant pool
+# ----------------------------------------------------------------------
+class CP:
+ def __init__(self):
+ self.entries = [] # (tag, payload)
+ self.u = {} # utf8 str -> idx
+ self.c = {} # internal name -> class idx
+ self.s = {} # string str -> idx
+ self._nt = {} # (name,desc) -> idx
+ self.mr = {} # (cls,name,desc) -> methodref idx
+ self.fr = {} # (cls,name,desc) -> fieldref idx
+
+ def _add(self, tag, payload):
+ self.entries.append((tag, payload))
+ return len(self.entries)
+
+ def utf8(self, s):
+ i = self.u.get(s)
+ if i is not None:
+ return i
+ i = self._add(1, s)
+ self.u[s] = i
+ return i
+
+ def cls(self, internal):
+ i = self.c.get(internal)
+ if i is not None:
+ return i
+ i = self._add(7, self.utf8(internal))
+ self.c[internal] = i
+ return i
+
+ def string(self, s):
+ i = self.s.get(s)
+ if i is not None:
+ return i
+ i = self._add(8, self.utf8(s))
+ self.s[s] = i
+ return i
+
+ def nt(self, name, desc):
+ k = (name, desc)
+ i = self._nt.get(k)
+ if i is not None:
+ return i
+ i = self._add(12, (self.utf8(name), self.utf8(desc)))
+ self._nt[k] = i
+ return i
+
+ def methodref(self, internal, name, desc):
+ k = (internal, name, desc)
+ i = self.mr.get(k)
+ if i is not None:
+ return i
+ i = self._add(10, (self.cls(internal), self.nt(name, desc)))
+ self.mr[k] = i
+ return i
+
+ def fieldref(self, internal, name, desc):
+ k = (internal, name, desc)
+ i = self.fr.get(k)
+ if i is not None:
+ return i
+ i = self._add(9, (self.cls(internal), self.nt(name, desc)))
+ self.fr[k] = i
+ return i
+
+ def serialize(self):
+ out = bytearray(struct.pack(">H", len(self.entries) + 1))
+ for tag, p in self.entries:
+ if tag == 1:
+ b = p.encode("utf-8")
+ out += bytes([1]) + struct.pack(">H", len(b)) + b
+ elif tag == 7: # Class
+ out += bytes([7]) + struct.pack(">H", p)
+ elif tag == 8: # String
+ out += bytes([8]) + struct.pack(">H", p)
+ elif tag == 9: # Fieldref
+ out += bytes([9]) + struct.pack(">HH", p[0], p[1])
+ elif tag == 10: # Methodref
+ out += bytes([10]) + struct.pack(">HH", p[0], p[1])
+ elif tag == 12: # NameAndType
+ out += bytes([12]) + struct.pack(">HH", p[0], p[1])
+ else:
+ raise ValueError(f"unhandled cp tag {tag}")
+ return bytes(out)
+
+
+# ----------------------------------------------------------------------
+# bytecode helpers
+# ----------------------------------------------------------------------
+def ldc(idx):
+ if idx <= 0xFF:
+ return bytes([0x12, idx])
+ return bytes([0x13]) + struct.pack(">H", idx)
+
+
+def type_slots(s, i):
+ """(slot count, next index) for the type starting at s[i]."""
+ c = s[i]
+ if c == "L":
+ return 1, s.index(";", i) + 1
+ if c == "[":
+ _, j = type_slots(s, i + 1)
+ return 1, j
+ return (2 if c in "JD" else 1), i + 1
+
+
+def count_locals(desc, is_static):
+ params = desc[1:desc.rindex(")")]
+ n, i = 0, 0
+ while i < len(params):
+ sl, i = type_slots(params, i)
+ n += sl
+ if not is_static:
+ n += 1
+ return n
+
+
+def ret_bytes(desc):
+ """(push-default bytes, return byte) for the return type of desc.
+
+ Opcodes verified byte-for-byte against javac output:
+ iconst_0=03 aconst_null=01 lconst_0=09 fconst_0=0b dconst_0=0e
+ ireturn=ac lreturn=ad freturn=ae dreturn=af areturn=b0 return=b1
+ """
+ r = desc[desc.rindex(")") + 1:]
+ if r == "V":
+ return b"", b"\xb1"
+ if r in ("Z", "B", "S", "C", "I"):
+ return b"\x03", b"\xac"
+ if r == "J":
+ return b"\x09", b"\xad"
+ if r == "F":
+ return b"\x0b", b"\xae"
+ if r == "D":
+ return b"\x0e", b"\xaf"
+ return b"\x01", b"\xb0" # reference / array
+
+
+def code_attr(cp, max_stack, max_locals, code):
+ name = cp.utf8("Code")
+ body = struct.pack(">HHI", max_stack, max_locals, len(code)) + code \
+ + struct.pack(">HH", 0, 0) # no exception table, no sub-attrs
+ return struct.pack(">HI", name, len(body)) + body
+
+
+def aload(slot):
+ """aload bytecode for local slot (reference types)."""
+ if 0 <= slot <= 3:
+ return bytes([0x2a + slot]) # aload_0..aload_3
+ return bytes([0x19, slot]) # aload
+
+
+def first_param_ref_slot(desc, is_static):
+ """(slot, is_reference) for the first parameter, else (None, False).
+
+ Only reference first-params (L... or [..) are logged - they occupy a
+ single slot and can be passed straight to an Object-taking helper.
+ A reference first param is always slot 0 (static) or 1 (instance).
+ """
+ params = desc[1:desc.rindex(")")]
+ if not params or params[0] not in "L[":
+ return None, False
+ return (0 if is_static else 1), True
+
+
+def new_instance_target(desc):
+ """Internal return type to materialize via KotlinProxyLog.newInstance, or
+ None to keep the default null return. Only for class (L...;) returns,
+ excluding String (avoid a ''-for-null behavior change)."""
+ r = desc[desc.rindex(")") + 1:]
+ if not (r.startswith("L") and r.endswith(";") and len(r) > 2):
+ return None
+ internal = r[1:-1]
+ if internal == "java/lang/String":
+ return None
+ return internal
+
+
+def log_body(cp, member, dotname, desc, is_static, call_ref):
+ """Straight-line: log the call (with the first reference param, when
+ there is one), produce the return value, return.
+
+ Reference-class returns materialize a real instance via
+ KotlinProxyLog.newInstance so the daemon can proceed past e.g.
+ createArguments() into doExecute() with a populated args object."""
+ slot, has_arg = first_param_ref_slot(desc, is_static)
+ if has_arg:
+ call_arg_ref = cp.methodref(KPL, "call", CALL_ARG_DESC)
+ b = ldc(cp.string(member)) + ldc(cp.string(dotname)) + aload(slot) \
+ + bytes([0xb8]) + struct.pack(">H", call_arg_ref)
+ max_stack = 3
+ else:
+ b = ldc(cp.string(member)) + ldc(cp.string(dotname)) \
+ + bytes([0xb8]) + struct.pack(">H", call_ref)
+ max_stack = 2
+ ti = new_instance_target(desc)
+ if ti is not None:
+ ni = cp.methodref(KPL, "newInstance", NEW_INST_DESC)
+ # newInstance returns Object; checkcast to the declared return type so
+ # the verifier is happy (null passes checkcast, so un-instantiable
+ # types still just return null).
+ b += ldc(cp.string(ti.replace("/", "."))) \
+ + bytes([0xb8]) + struct.pack(">H", ni) \
+ + bytes([0xc0]) + struct.pack(">H", cp.cls(ti))
+ else:
+ push, _ = ret_bytes(desc)
+ b += push
+ _, ret = ret_bytes(desc)
+ b += ret
+ max_locals = count_locals(desc, is_static)
+ return code_attr(cp, max_stack, max_locals, b)
+
+
+def ctor_body(cp, super_name, member, dotname, desc, call_ref, is_enum):
+ # Enums: java.lang.Enum has no no-arg ctor, so the super call must be
+ # Enum.<init>(String name, int ordinal). The enum ctor's own name/ordinal
+ # params (last two) are ignored — we pass constants; unused params are
+ # legal in a ctor body. Peak stack is 3 (this, name, ordinal).
+ b = b"\x2a" # aload_0
+ if is_enum:
+ b += ldc(cp.string("stub")) + b"\x03" # ldc "stub"; iconst_0
+ sup = cp.methodref("java/lang/Enum", "<init>",
+ "(Ljava/lang/String;I)V")
+ max_stack = 3
+ else:
+ sup = cp.methodref(super_name, "<init>", "()V")
+ max_stack = 2
+ b += bytes([0xb7]) + struct.pack(">H", sup) # invokespecial
+ b += ldc(cp.string(member)) + ldc(cp.string(dotname))
+ b += bytes([0xb8]) + struct.pack(">H", call_ref)
+ b += b"\xb1" # return
+ return code_attr(cp, max_stack, count_locals(desc, False), b)
+
+
+def clinit_body(cp, dotname, loaded_ref):
+ b = ldc(cp.string(dotname))
+ b += bytes([0xb8]) + struct.pack(">H", loaded_ref)
+ b += b"\xb1" # return
+ return code_attr(cp, 2, 0, b)
+
+
+def bridge_body(cp, dotname, name, target_desc, is_static):
+ """Body for a param-less erasure bridge: forward to the concrete sibling
+ (which logs itself) and return its result. Needed because callers
+ compiled against the supertype (e.g. the daemon calling
+ CommonCompiler.createArguments()L.../CommonCompilerArguments;) dispatch
+ to the bridge, whose own return type may be abstract and un-instantiable."""
+ this_internal = dotname.replace(".", "/")
+ b = b""
+ if not is_static:
+ b += b"\x2a" # aload_0
+ mi = cp.methodref(this_internal, name, target_desc)
+ op = 0xb8 if is_static else 0xb6 # invokestatic / invokevirtual
+ b += bytes([op]) + struct.pack(">H", mi)
+ _, ret = ret_bytes(target_desc)
+ b += ret
+ return code_attr(cp, 1, count_locals(target_desc, is_static), b)
+
+
+def method_bytes(cp, name, desc, access, body_code):
+ """body_code is bytes or None (abstract)."""
+ out = struct.pack(">HHH", access, cp.utf8(name), cp.utf8(desc))
+ if body_code is None:
+ out += struct.pack(">H", 0)
+ else:
+ out += struct.pack(">H", 1) + body_code
+ return out
+
+
+def field_bytes(cp, name, desc, access):
+ return struct.pack(">HHH", access, cp.utf8(name), cp.utf8(desc)) \
+ + struct.pack(">H", 0)
+
+
+# ----------------------------------------------------------------------
+# class emission
+# ----------------------------------------------------------------------
+def emit_class(cp, name, info, is_iface, dotname):
+ this_idx = cp.cls(name)
+ super_name = (info.get("super") or OBJ) if not is_iface else OBJ
+ super_idx = cp.cls(super_name)
+ iface_idxs = [cp.cls(x) for x in (info.get("interfaces") or []) if x]
+
+ access = info.get("access", A_PUBLIC)
+ if is_iface:
+ access |= A_INTERFACE | A_ABSTRACT
+ is_enum = bool(access & A_ENUM)
+ if name == OBJ:
+ return None
+
+ call_ref = cp.methodref(KPL, "call", CALL_DESC)
+ loaded_ref = cp.methodref(KPL, "loaded", LOADED_DESC)
+
+ fields = []
+ for f in info.get("fields", []):
+ fields.append(field_bytes(cp, f["name"], f["desc"], f["access"]))
+
+ # param-less concrete (non-bridge) methods, by name. A param-less
+ # erasure bridge with the same name forwards to its concrete sibling
+ # (whose own return type is the instantiable subclass).
+ concrete_noparam = {}
+ for m in info.get("methods", []):
+ if m["name"] in ("<init>", "<clinit>"):
+ continue
+ if m["access"] & (A_BRIDGE | A_ABSTRACT):
+ continue
+ if not m["desc"][1:m["desc"].rindex(")")]:
+ concrete_noparam[m["name"]] = m["desc"]
+
+ methods = []
+ # constructors + concrete methods
+ has_noarg = False
+ for m in info.get("methods", []):
+ mn, md, ma = m["name"], m["desc"], m["access"]
+ if mn == "<clinit>":
+ continue # we synthesize our own
+ abstract = bool(ma & A_ABSTRACT) or (is_iface and not m["has_code"])
+ if mn == "<init>":
+ if md == "()V":
+ has_noarg = True
+ body = ctor_body(cp, super_name, mn, dotname, md, call_ref,
+ is_enum)
+ methods.append(method_bytes(cp, mn, md, ma, body))
+ elif (ma & A_BRIDGE) and not md[1:md.rindex(")")] \
+ and mn in concrete_noparam:
+ # param-less erasure bridge: forward to the concrete sibling
+ body = bridge_body(cp, dotname, mn, concrete_noparam[mn],
+ bool(ma & A_STATIC))
+ methods.append(method_bytes(cp, mn, md, ma, body))
+ else:
+ if abstract:
+ methods.append(method_bytes(cp, mn, md, ma, None))
+ else:
+ body = log_body(cp, mn, dotname, md,
+ bool(ma & A_STATIC), call_ref)
+ methods.append(method_bytes(cp, mn, md, ma, body))
+ if not is_iface:
+ # guarantee a no-arg ctor so child stubs can invokespecial super()
+ if not has_noarg:
+ body = ctor_body(cp, super_name, "<init>", dotname, "()V",
+ call_ref, is_enum)
+ methods.append(method_bytes(cp, "<init>", "()V",
+ A_PUBLIC, body))
+ # synthesized static initializer -> KotlinProxyLog.loaded(name)
+ methods.append(method_bytes(cp, "<clinit>", "()V",
+ A_STATIC | A_PRIVATE,
+ clinit_body(cp, dotname, loaded_ref)))
+
+ out = bytearray()
+ out += struct.pack(">IHH", MAGIC, MINOR, MAJOR)
+ out += cp.serialize()
+ out += struct.pack(">H", access)
+ out += struct.pack(">H", this_idx)
+ out += struct.pack(">H", super_idx)
+ out += struct.pack(">H", len(iface_idxs))
+ for ix in iface_idxs:
+ out += struct.pack(">H", ix)
+ out += struct.pack(">H", len(fields))
+ for fb in fields:
+ out += fb
+ out += struct.pack(">H", len(methods))
+ for mb in methods:
+ out += mb
+ out += struct.pack(">H", 0) # no class attributes
+ return bytes(out)
+
+
+def emit_minimal(cp, name, is_iface):
+ """A class/interface with no definition found: bare structure +
+ (for classes) a no-arg ctor and a loaded() clinit."""
+ info = {"access": A_PUBLIC, "super": OBJ, "interfaces": [],
+ "fields": [], "methods": []}
+ if is_iface:
+ info["access"] |= A_INTERFACE | A_ABSTRACT
+ return emit_class(cp, name, info, is_iface, name.replace("/", "."))
+
+
+# ----------------------------------------------------------------------
+# driver
+# ----------------------------------------------------------------------
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--scan-jars", required=True)
+ ap.add_argument("--def-jars", required=True)
+ ap.add_argument("--fallback-jars", default=None)
+ ap.add_argument("--out", required=True)
+ ap.add_argument("--report", default=None)
+ ap.add_argument("--exclude", default=None,
+ help="comma-separated internal-name prefixes to NOT stub "
+ "(e.g. org/jetbrains/kotlin/gradle/ to leave the KGP "
+ "plugin real so the project can still configure)")
+ ap.add_argument("--seed", default=None,
+ help="comma-separated internal or dotted class names to add "
+ "to the seed set (S0) for the closure "
+ "(e.g. the compiler entry point)")
+ ap.add_argument("--seed-only", action="store_true",
+ help="use only --seed as S0 (ignore scan-jars and the KGP "
+ "plugin entry points) - for a narrow jar such as one "
+ "holding just the compiler entry point")
+ ap.add_argument("--no-closure", action="store_true",
+ help="do not expand the transitive closure - emit exactly "
+ "the seed set only. Use with --seed to stub just the "
+ "compiler entry point; its super/interfaces are then "
+ "resolved from the real jars at load time")
+ args = ap.parse_args()
+
+ exclude = [p for p in (args.exclude.split(",") if args.exclude else [])
+ if p]
+ seeds = []
+ if args.seed:
+ for s in args.seed.split(","):
+ s = s.strip()
+ if not s:
+ continue
+ seeds.append(s.replace(".", "/")
+ if ("." in s and "/" not in s) else s)
+ scan_jars = read_list(args.scan_jars)
+ def_jars = read_list(args.def_jars)
+ fb_jars = read_list(args.fallback_jars) if args.fallback_jars else []
+
+ # defs: internal name -> (jar, info) (first jar wins)
+ defs = {}
+ for jar in def_jars + fb_jars:
+ if not jar or not os.path.exists(jar):
+ print(f"warn: missing def jar {jar}", file=sys.stderr)
+ continue
+ for internal, data in load_jar_classes(jar).items():
+ if internal in defs:
+ continue
+ info = parse_class(data)
+ if info is not None:
+ defs[internal] = (jar, info)
+ print(f"defs: {len(defs)} classes", file=sys.stderr)
+
+ # S0: kotlin refs from AGP scan jars + KGP plugin entry points
+ s0 = set()
+ if not args.seed_only:
+ for jar in scan_jars:
+ if not jar or not os.path.exists(jar):
+ continue
+ for internal, data in load_jar_classes(jar).items():
+ info = parse_class(data)
+ if info is None:
+ continue
+ for r in info["refs"]:
+ if kotlin_ref(r):
+ s0.add(r)
+ for jar in def_jars:
+ if not jar or not os.path.exists(jar):
+ continue
+ try:
+ with zipfile.ZipFile(jar) as z:
+ for n in z.namelist():
+ if n.startswith("META-INF/gradle-plugins/") \
+ and n.endswith(".properties"):
+ for line in z.read(n).decode(
+ "utf-8", "replace").splitlines():
+ if line.startswith("implementation-class="):
+ impl = line.split("=", 1)[1].strip() \
+ .replace(".", "/")
+ if kotlin_ref(impl):
+ s0.add(impl)
+ except (zipfile.BadZipFile, OSError):
+ pass
+ for s in seeds:
+ s0.add(s)
+
+ # transitive closure (skipped with --no-closure: emit exactly the seed set)
+ closure = set(s0)
+ if not args.no_closure:
+ frontier = sorted(s0)
+ while frontier:
+ nxt = []
+ for nm in frontier:
+ e = defs.get(nm)
+ if e is None:
+ continue
+ for r in e[1]["refs"]:
+ if kotlin_ref(r) and r not in closure:
+ closure.add(r)
+ nxt.append(r)
+ frontier = sorted(nxt)
+
+ # kind hint for names without a definition
+ kind_hint = {}
+ for cname, e in defs.items():
+ if cname not in closure:
+ continue
+ info = e[1]
+ if info["access"] & A_ANNOTATION:
+ continue
+ is_iface = bool(info["access"] & A_INTERFACE)
+ for x in info["interfaces"]:
+ kind_hint.setdefault(x, "interface")
+ sup = info.get("super")
+ if sup and sup != OBJ:
+ kind_hint.setdefault(sup, "interface" if is_iface else "class")
+
+ # emit
+ if os.path.exists(args.out):
+ import shutil
+ shutil.rmtree(args.out)
+ os.makedirs(args.out)
+
+ n_full = n_minimal = n_iface = n_excluded = 0
+ minimal = []
+ for name in sorted(closure):
+ if any(name.startswith(p) for p in exclude):
+ n_excluded += 1
+ continue # leave this subtree REAL (not stubbed)
+ e = defs.get(name)
+ dot = name.replace("/", ".")
+ cp = CP()
+ if e is None:
+ is_iface = kind_hint.get(name) == "interface"
+ data = emit_minimal(cp, name, is_iface)
+ minimal.append(name)
+ n_minimal += 1
+ else:
+ _, info = e
+ is_iface = bool(info["access"] & A_INTERFACE)
+ data = emit_class(cp, name, info, is_iface, dot)
+ n_full += 1
+ if is_iface:
+ n_iface += 1
+ if data is None:
+ continue
+ path = os.path.join(args.out, name + ".class")
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "wb") as fh:
+ fh.write(data)
+
+ rep = [
+ "kotlin-proxy stub report (bytecode)",
+ f"scan jars: {len(scan_jars)}; def jars: {len(def_jars)}",
+ f"S0: {len(s0)}",
+ f"closure: {len(closure)}",
+ f"full: {n_full} (interfaces: {n_iface}); minimal: {n_minimal}",
+ "",
+ f"=== S0 ({len(s0)}) ===",
+ *sorted(s0),
+ "",
+ f"=== minimal ({n_minimal}) ===",
+ *sorted(minimal),
+ ]
+ txt = "\n".join(rep)
+ if args.report:
+ with open(args.report, "w") as fh:
+ fh.write(txt + "\n")
+ print(txt[:4000])
+
+
+if __name__ == "__main__":
+ main()