summaryrefslogtreecommitdiff
path: root/tools/gen_class.py
blob: 866576c0d68a2d7500f63825a8a7404e281a4bf2 (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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
#!/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.
Reference-return methods instead ask KotlinProxyLog.returnValue for their
value, which dispatches to kotlin.proxy.KotlinProxyOverrides.invoke (per-method
custom implementations, passed the full argument list and the receiver —
the stub instance the method was called on, null for statics) before falling
back to a real no-arg instance of the declared return type.

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"
# Arg order MUST match KotlinProxyLog.returnValue: the Object[] args array
# comes FIRST — the generated body builds it while the stack is shallowest
# (peak 5 instead of 9 if it were pushed last).  The receiver (the stub
# instance the method was called on; null for statics) comes last.
RETURN_VALUE_DESC = \
    "([Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;" \
    "Ljava/lang/String;Ljava/lang/Object;)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_ref = {}       # cp idx -> utf8 idx (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_ref[i] = idx               # resolve name after full pass
            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
        # A Class constant's name may sit at a HIGHER pool index than the
        # constant itself (the pool is not dependency-ordered), so resolve the
        # names only after the whole pool has been read.
        cls_names = {ix: utf8.get(r, "") for ix, r in cls_ref.items()}
        # 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


# valueOf boxes for primitive params (so Object[] position i is always param i)
BOX = {
    "Z": ("java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;"),
    "B": ("java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;"),
    "S": ("java/lang/Short", "valueOf", "(S)Ljava/lang/Short;"),
    "C": ("java/lang/Character", "valueOf", "(C)Ljava/lang/Character;"),
    "I": ("java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"),
    "J": ("java/lang/Long", "valueOf", "(J)Ljava/lang/Long;"),
    "F": ("java/lang/Float", "valueOf", "(F)Ljava/lang/Float;"),
    "D": ("java/lang/Double", "valueOf", "(D)Ljava/lang/Double;"),
}
# opcodes per the JVMS table (https://javaalmanac.io/bytecode/opcodes/),
# verified byte-for-byte against javac output
LOAD_WIDE = {"Z": 0x15, "B": 0x15, "S": 0x15, "C": 0x15, "I": 0x15,  # iload
             "J": 0x16, "F": 0x17, "D": 0x18}   # lload fload dload
LOAD_SHORT = {"Z": 0x1A, "B": 0x1A, "S": 0x1A, "C": 0x1A, "I": 0x1A,  # iload_0
              "J": 0x1E, "F": 0x22, "D": 0x26}   # lload_0 fload_0 dload_0
AASTORE, ANEWARRAY = 0x53, 0xBD


def int_const(n):
    """Bytes pushing int n (0..65535)."""
    if 0 <= n <= 5:
        return bytes([0x03 + n])                  # iconst_0..iconst_5
    if n <= 0xFF:
        return bytes([0x10, n])                   # bipush
    return bytes([0x11]) + struct.pack(">h", n)   # sipush


def load_param(slot, t):
    """Bytes loading the parameter (first descriptor char t) at slot."""
    if t in "L[":
        return (bytes([0x2A + slot]) if slot <= 3   # aload_0..3 / aload
                else bytes([0x19, slot]))
    wide = LOAD_WIDE[t]
    return (bytes([LOAD_SHORT[t] + slot]) if slot <= 3  # iload_0 et al.
            else bytes([wide, slot]))


def param_layout(desc, is_static):
    """[(type first char, slot)] per parameter, in order."""
    params = desc[1:desc.rindex(")")]
    out, i, s = [], 0, (0 if is_static else 1)
    while i < len(params):
        sl, j = type_slots(params, i)
        out.append((params[i], s))
        i, s = j, s + sl
    return out


def args_array_body(cp, desc, is_static):
    """Bytes pushing an Object[] of the method's parameters — references as
    is, primitives boxed, so position i is always parameter i — or
    aconst_null for a param-less method.  Straight-line; peak stack is 4."""
    p = param_layout(desc, is_static)
    if not p:
        return b"\x01"                              # aconst_null
    b = int_const(len(p)) + bytes([ANEWARRAY]) \
        + struct.pack(">H", cp.cls(OBJ))            # anewarray Object
    for idx, (t, slot) in enumerate(p):
        b += b"\x59" + int_const(idx) + load_param(slot, t)
        if t not in "L[":
            b += bytes([0xB8]) + struct.pack(">H", cp.methodref(*BOX[t]))
        b += bytes([AASTORE])
    return b


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 ask KotlinProxyLog.returnValue, which dispatches
    to KotlinProxyOverrides.invoke (per-method custom implementations, passed
    the full argument list and the receiver — aload_0, or null for statics)
    and falls back to materializing a real instance of the declared return
    type — 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:
        # [argsArray, member, owner, returnType, instance] -> returnValue(...)
        rv = cp.methodref(KPL, "returnValue", RETURN_VALUE_DESC)
        b += args_array_body(cp, desc, is_static)
        b += ldc(cp.string(member)) + ldc(cp.string(dotname)) \
            + ldc(cp.string(ti.replace("/", ".")))
        b += b"\x2a" if not is_static else b"\x01"  # receiver: aload_0 / null
        b += bytes([0xb8]) + struct.pack(">H", rv)
        # returnValue 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 += bytes([0xc0]) + struct.pack(">H", cp.cls(ti))
        max_stack = 5
    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, 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, 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):
    """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, 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)
    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),
        # 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,
                                                name, companion)))

    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)
    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)
    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)
            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
        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()