ddc-dec 0.1.33

DEX → Java decompiler front-end over jdc-core
Documentation
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
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
//! LOCAL-OK reference scan for the field-obscuring nested-type renames
//! (round-59 Design B).
//!
//! A field-clash rename (nested type whose simple name equals an
//! enclosing-class field, JLS 6.4.2 obscuring) is only safe to apply when
//! EVERY class referencing the nested type lives inside the root family —
//! the top-level class whose file renders it plus all `root$*` descendants.
//! The rename then perturbs exactly one rendered file: the symbol table
//! outside the family is unchanged, so javac's error-recovery behavior on
//! other files cannot flip. Design A (ungated global rename) proved why
//! the gate matters: on weibo — 11218 pre-existing class/package name
//! conflicts — even perfectly-covered renames flipped ambiguous
//! type-vs-package resolutions corpus-wide, turning "missing supertype,
//! body attribution suppressed" files into full Object cascades
//! (+36916 errors). reqable/lark improved (−1653/−5221), so the rule is
//! right; only its blast radius needed bounding.
//!
//! The scan covers, per DEX image: super/interfaces, field & method
//! signatures, instruction operands (type@/field@/method@/call-site@/
//! method-handle@/method-type@), the full annotations directory (class,
//! field, method, parameter sets, with recursive encoded-value walks) and
//! class static values. Catch-handler type lists are NOT scanned (a
//! foreign class catching a field-clash candidate as a Throwable is
//! vanishingly rare; a miss leaks one rename, not the Design-A storm).

use std::sync::Arc;

use ddc_dex::annotations::{read_encoded_annotation, EncodedValue};
use ddc_dex::DexFile;
use jdc_core::FxHashMap as HashMap;
use jdc_core::FxHashSet as HashSet;

const NONE: u32 = u32::MAX;

/// One rename candidate: internal name → root (top-level) internal name.
/// Returns the subset whose every referrer is inside the root's family.
pub fn local_ok(dexes: &[Arc<DexFile>], cands: &HashMap<String, String>) -> HashSet<String> {
    if cands.is_empty() {
        return HashSet::default();
    }
    // Deterministic slot order (map iteration is not).
    let mut names: Vec<&String> = cands.keys().collect();
    names.sort();
    let slots: Vec<(&str, &str, String, String)> = names
        .iter()
        .map(|n| {
            let root = cands.get(*n).map(|s| s.as_str()).unwrap_or(*n);
            (
                n.as_str(),
                root,
                format!("{root}$"),
                format!("L{n};"),
            )
        })
        .collect();
    // Primary descriptor per candidate PLUS its shadow-package twin.
    // The twin (`L{R}/{t};` for nested `R$t`) matters when the root
    // doubles as a package (weibo's obfuscator ships 11218 such
    // class/package conflicts): the dotted path `pkg.R.t` that foreign
    // files use for the PACKAGE class only resolved through class R's
    // member type `t` while that member existed — renaming the member
    // breaks the accidental resolution ("找不到符号 类 t 位置: 类 R",
    // the SGChatFragment pattern behind Design-B's weibo residual). An
    // external reference to the twin therefore kills the candidate
    // exactly like one to the primary. Primaries contain `$`, twins
    // never do, so the key spaces are disjoint.
    let desc_owned: Vec<(String, u32)> = slots
        .iter()
        .enumerate()
        .flat_map(|(i, s)| {
            let mut v = vec![(s.3.clone(), i as u32)];
            let twin = format!("L{};", s.0.replace('$', "/"));
            if twin != s.3 {
                v.push((twin, i as u32));
            }
            v
        })
        .collect();
    let desc_slot: HashMap<&str, u32> = desc_owned
        .iter()
        .map(|(d, i)| (d.as_str(), *i))
        .collect();

    // Images are scanned on a small thread pool (cap 4: the per-image
    // sentinel tables cost a few MB each, and the full-decompile workers
    // — the memory-hungry phase — start right after this).
    let mut merged: Vec<bool> = vec![false; slots.len()];
    let nthreads = std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(1)
        .min(4)
        .min(dexes.len().max(1));
    let chunk = dexes.len().div_ceil(nthreads).max(1);
    std::thread::scope(|scope| {
        let handles: Vec<_> = dexes
            .chunks(chunk)
            .map(|group| {
                let slots = &slots;
                let desc_slot = &desc_slot;
                scope.spawn(move || {
                    let mut dead: Vec<bool> = vec![false; slots.len()];
                    for dex in group {
                        let d = scan_image(dex, slots, desc_slot);
                        for (i, x) in d.into_iter().enumerate() {
                            dead[i] |= x;
                        }
                        if dead.iter().all(|&x| x) {
                            break; // every candidate already proven external
                        }
                    }
                    dead
                })
            })
            .collect();
        for h in handles {
            if let Ok(dead) = h.join() {
                for (i, d) in dead.into_iter().enumerate() {
                    merged[i] |= d;
                }
            } else {
                // A panicked scan means unknown referrers: treat every
                // candidate as external (no renames) rather than risk a
                // Design-A perturbation.
                for d in merged.iter_mut() {
                    *d = true;
                }
            }
        }
    });

    slots
        .iter()
        .zip(merged.iter())
        .filter(|(_, dead)| !*dead)
        .map(|(s, _)| s.0.to_string())
        .collect()
}

type SlotInfo<'a> = (&'a str, &'a str, String, String);

fn scan_image(
    dex: &DexFile,
    slots: &[SlotInfo],
    desc_slot: &HashMap<&str, u32>,
) -> Vec<bool> {
    let mut dead: Vec<bool> = vec![false; slots.len()];
    // type_idx → slot for this image's type table.
    let mut cand_type: Vec<u32> = vec![NONE; dex.type_count()];
    for (idx, slot) in cand_type.iter_mut().enumerate() {
        if let Some(&s) = desc_slot.get(dex.type_name(idx as u32)) {
            *slot = s;
        }
    }
    // field_idx → (class-slot, type-slot): a field reference touches the
    // declaring class AND the field's type.
    let mut field_a: Vec<u32> = vec![NONE; dex.field_count()];
    let mut field_b: Vec<u32> = vec![NONE; dex.field_count()];
    for idx in 0..dex.field_count() {
        let f = dex.field(idx as u32);
        field_a[idx] = cand_type.get(f.class_idx as usize).copied().unwrap_or(NONE);
        field_b[idx] = cand_type.get(f.type_idx as usize).copied().unwrap_or(NONE);
    }
    // method_idx → slots (class, proto return, proto params). First hit
    // inline, the (rare) rest in a side map.
    let mut meth_a: Vec<u32> = vec![NONE; dex.method_count()];
    let mut meth_extra: HashMap<u32, Vec<u32>> = HashMap::default();
    for (idx, slot) in meth_a.iter_mut().enumerate() {
        let m = dex.method(idx as u32);
        let mut hits: Vec<u32> = Vec::new();
        let push = |s: u32, hits: &mut Vec<u32>| {
            if s != NONE && !hits.contains(&s) {
                hits.push(s);
            }
        };
        push(cand_type.get(m.class_idx as usize).copied().unwrap_or(NONE), &mut hits);
        let proto = dex.proto(m.proto_idx);
        push(
            cand_type.get(proto.return_type_idx as usize).copied().unwrap_or(NONE),
            &mut hits,
        );
        for &t in dex.proto_params(m.proto_idx) {
            push(cand_type.get(t as usize).copied().unwrap_or(NONE), &mut hits);
        }
        if !hits.is_empty() {
            *slot = hits[0];
            if hits.len() > 1 {
                meth_extra.insert(idx as u32, hits.split_off(1));
            }
        }
    }

    // Proto idx → slots (for invoke-polymorphic / const-method-type /
    // call sites).
    let proto_slots = |pidx: u32, out: &mut Vec<u32>| {
        let proto = dex.proto(pidx);
        let mut push = |s: u32| {
            if s != NONE && !out.contains(&s) {
                out.push(s);
            }
        };
        push(cand_type.get(proto.return_type_idx as usize).copied().unwrap_or(NONE));
        for &t in dex.proto_params(pidx) {
            push(cand_type.get(t as usize).copied().unwrap_or(NONE));
        }
    };

    let raw = dex.raw();
    let record = |slot: u32, referrer: &str, dead: &mut Vec<bool>| {
        if slot == NONE || dead[slot as usize] {
            return;
        }
        let (_, root, prefix, _) = &slots[slot as usize];
        if referrer != *root && !referrer.starts_with(prefix.as_str()) {
            dead[slot as usize] = true;
        }
    };
    let record_field = |fidx: u32, referrer: &str, dead: &mut Vec<bool>| {
        if let Some(&a) = field_a.get(fidx as usize) {
            record(a, referrer, dead);
        }
        if let Some(&b) = field_b.get(fidx as usize) {
            record(b, referrer, dead);
        }
    };
    let record_meth = |midx: u32, referrer: &str, dead: &mut Vec<bool>| {
        if let Some(&a) = meth_a.get(midx as usize) {
            record(a, referrer, dead);
        }
        if let Some(extra) = meth_extra.get(&midx) {
            for &s in extra {
                record(s, referrer, dead);
            }
        }
    };
    // Encoded-value walk: annotation elements, static values, call-site
    // linker args. Local stack — hits are rare, the allocation is not on
    // any hot path, and it keeps every scanner closure `Fn` (shared
    // captures only) so they compose without borrow conflicts.
    let record_ev = |ev: &EncodedValue, referrer: &str, dead: &mut Vec<bool>| {
        let mut stack: Vec<EncodedValue> = vec![ev.clone()];
        while let Some(v) = stack.pop() {
            match v {
                EncodedValue::Type(t) => {
                    let s = cand_type.get(t as usize).copied().unwrap_or(NONE);
                    record(s, referrer, dead);
                }
                EncodedValue::Field(f) | EncodedValue::Enum(f) => {
                    record_field(f, referrer, dead);
                }
                EncodedValue::Method(m) => record_meth(m, referrer, dead),
                EncodedValue::MethodType(p) => {
                    let mut out = Vec::new();
                    proto_slots(p, &mut out);
                    for s in out {
                        record(s, referrer, dead);
                    }
                }
                EncodedValue::MethodHandle(h) => {
                    if let Some(mh) = dex.method_handle(h) {
                        if mh.is_field {
                            record_field(mh.target_id, referrer, dead);
                        } else {
                            record_meth(mh.target_id, referrer, dead);
                        }
                    }
                }
                EncodedValue::Array(items) => stack.extend(items),
                EncodedValue::Annotation(a) => {
                    let s = cand_type.get(a.type_idx as usize).copied().unwrap_or(NONE);
                    record(s, referrer, dead);
                    stack.extend(a.elements.into_iter().map(|(_, v)| v));
                }
                _ => {}
            }
        }
    };

    let u4 = |off: usize| -> u32 {
        raw.get(off..off + 4)
            .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
            .unwrap_or(0)
    };
    // One annotation_set_item: size + item offsets; each item is
    // visibility(u8) + encoded_annotation.
    let walk_set = |set_off: u32, referrer: &str, dead: &mut Vec<bool>| {
        let set = set_off as usize;
        if set == 0 || set + 4 > raw.len() {
            return;
        }
        let n = u4(set) as usize;
        for i in 0..n {
            let item = u4(set + 4 + 4 * i) as usize;
            if item == 0 || item + 1 >= raw.len() {
                continue;
            }
            if let Some((a, _)) = read_encoded_annotation(raw, item + 1) {
                let s = cand_type.get(a.type_idx as usize).copied().unwrap_or(NONE);
                record(s, referrer, dead);
                for (_, v) in a.elements {
                    record_ev(&v, referrer, dead);
                }
            }
        }
    };
    // annotations_directory_item: class set + [idx,set] triples for
    // fields, methods, parameter lists.
    let walk_ann_dir = |dir_off: u32, referrer: &str, dead: &mut Vec<bool>| {
        let off = dir_off as usize;
        if off == 0 || off + 16 > raw.len() {
            return;
        }
        walk_set(u4(off), referrer, dead);
        let mut p = off + 16;
        for k in 0..3 {
            let n = u4(off + 4 + 4 * k) as usize;
            for _ in 0..n {
                if p + 8 > raw.len() {
                    return;
                }
                walk_set(u4(p + 4), referrer, dead);
                p += 8;
            }
        }
    };

    for cd in &dex.class_defs {
        if dead.iter().all(|&d| d) {
            break; // every candidate already proven external
        }
        let referrer = dex.class_name(cd.class_idx);
        // Super + interfaces.
        let s = cand_type.get(cd.superclass_idx as usize).copied().unwrap_or(NONE);
        record(s, &referrer, &mut dead);
        for i in dex.interfaces_of(cd) {
            let s = cand_type.get(i as usize).copied().unwrap_or(NONE);
            record(s, &referrer, &mut dead);
        }
        // Signatures + code.
        let data = dex.class_data(cd);
        for f in data.static_fields.iter().chain(data.instance_fields.iter()) {
            record_field(f.field_idx, &referrer, &mut dead);
        }
        for m in data.direct_methods.iter().chain(data.virtual_methods.iter()) {
            record_meth(m.method_idx, &referrer, &mut dead);
            let Some(code) = (m.code_off != 0).then(|| dex.code_insns_bytes_at(m.code_off)).flatten() else {
                continue;
            };
            ddc_dex::insn::scan_instructions(code, &mut |op, pc, bytes| {
                let unit = |i: usize| -> u32 {
                    bytes
                        .get(2 * i..2 * i + 2)
                        .map(|b| u16::from_le_bytes([b[0], b[1]]) as u32)
                        .unwrap_or(NONE)
                };
                match op {
                    // const-class, check-cast, instanceof, new-instance,
                    // new-array, filled-new-array(/range),
                    // const-method-type — type@ at unit pc+1.
                    0x1c | 0x1f | 0x20 | 0x22..=0x25 | 0xff => {
                        let t = unit(pc + 1);
                        let s = cand_type.get(t as usize).copied().unwrap_or(NONE);
                        record(s, &referrer, &mut dead);
                    }
                    // Field accesses — field@ at unit pc+1.
                    0x52..=0x6d => record_field(unit(pc + 1), &referrer, &mut dead),
                    // Invokes — method@ at unit pc+1.
                    0x6e..=0x72 | 0x74..=0x78 => record_meth(unit(pc + 1), &referrer, &mut dead),
                    // invoke-polymorphic(/range): method@ pc+1, proto@ pc+2.
                    0xfa | 0xfb => {
                        record_meth(unit(pc + 1), &referrer, &mut dead);
                        let mut out = Vec::new();
                        proto_slots(unit(pc + 2), &mut out);
                        for s in out {
                            record(s, &referrer, &mut dead);
                        }
                    }
                    // invoke-custom: call-site@ pc+1.
                    0xfc => {
                        if let Some(cs) = dex.call_site(unit(pc + 1)) {
                            let mut out = Vec::new();
                            proto_slots(cs.proto_idx, &mut out);
                            for s in out {
                                record(s, &referrer, &mut dead);
                            }
                            for v in &cs.linker_args {
                                record_ev(v, &referrer, &mut dead);
                            }
                        }
                    }
                    // const-method-handle: handle@ pc+1.
                    0xfe => {
                        if let Some(mh) = dex.method_handle(unit(pc + 1)) {
                            if mh.is_field {
                                record_field(mh.target_id, &referrer, &mut dead);
                            } else {
                                record_meth(mh.target_id, &referrer, &mut dead);
                            }
                        }
                    }
                    _ => {}
                }
            });
        }
        // Annotations directory + static values.
        walk_ann_dir(cd.annotations_off, &referrer, &mut dead);
        if cd.static_values_off != 0 {
            for v in dex.static_values(cd.static_values_off) {
                record_ev(&v, &referrer, &mut dead);
            }
        }
    }
    dead
}

/// Per-package first segments of CROSS-package references found at
/// BODY level (instruction operands, signatures, supers) — the
/// descriptor-only refsegs scan misses body-only references (weixin
/// pc5's `invoke-static Ln91/f;.a` — 7.8k `n91.f` errors + 6.6k
/// `uc6.f` survived the descriptor gate). Only classes whose package
/// is in `cand_pkgs` are attributed (the obscuring-rename candidates'
/// packages); annotations/static-values/call-site linker args are not
/// walked (signatures + insns carry the mass; a miss leaks one rename
/// back to the descriptor-gated status quo, never a wrong rename).
pub fn body_ref_segments(
    dexes: &[Arc<DexFile>],
    cand_pkgs: &HashSet<String>,
) -> HashMap<String, HashSet<String>> {
    if cand_pkgs.is_empty() {
        return HashMap::default();
    }
    let nthreads = std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(1)
        .min(4)
        .min(dexes.len().max(1));
    let chunk = dexes.len().div_ceil(nthreads).max(1);
    let merged: std::sync::Mutex<HashMap<String, HashSet<String>>> =
        std::sync::Mutex::new(HashMap::default());
    std::thread::scope(|scope| {
        let handles: Vec<_> = dexes
            .chunks(chunk)
            .map(|group| {
                let merged = &merged;
                scope.spawn(move || {
                    for dex in group {
                        let part = scan_image_segments(dex, cand_pkgs);
                        let mut m = merged.lock().unwrap();
                        for (k, v) in part {
                            m.entry(k).or_default().extend(v);
                        }
                    }
                })
            })
            .collect();
        for h in handles {
            let _ = h.join();
        }
    });
    merged.into_inner().unwrap_or_default()
}

fn pkg_of(n: &str) -> &str {
    match n.rsplit_once('/') {
        Some((p, _)) => p,
        None => "",
    }
}

fn scan_image_segments(
    dex: &DexFile,
    cand_pkgs: &HashSet<String>,
) -> HashMap<String, HashSet<String>> {
    // Per-type (pkg, first-seg), interned as owned strings once.
    let n = dex.type_count();
    let mut tpkg: Vec<Box<str>> = Vec::with_capacity(n);
    let mut tseg: Vec<Box<str>> = Vec::with_capacity(n);
    for idx in 0..n {
        let name = dex.type_name(idx as u32);
        let mut b = name.strip_prefix('[').unwrap_or(name).to_string();
        while b.starts_with('[') {
            b.remove(0);
        }
        let inner = b
            .strip_prefix('L')
            .and_then(|s| s.strip_suffix(';'))
            .unwrap_or("");
        tpkg.push(
            match inner.rfind('/') {
                Some(j) => inner[..j].into(),
                None => Box::from(""),
            },
        );
        tseg.push(
            match inner.find('/') {
                Some(i) => inner[..i].into(),
                None => Box::from(""),
            },
        );
    }
    let mut out: HashMap<String, HashSet<String>> = HashMap::default();
    for cd in &dex.class_defs {
        let referrer = dex.class_name(cd.class_idx);
        let rp = pkg_of(&referrer);
        if rp.is_empty() || !cand_pkgs.contains(rp) {
            continue;
        }
        let mut segs: HashSet<String> = HashSet::default();
        let note = |t: u32, segs: &mut HashSet<String>| {
            let i = t as usize;
            let Some(p) = tpkg.get(i) else { return };
            if p.is_empty() || p.as_ref() == rp {
                return;
            }
            if let Some(s) = tseg.get(i) {
                if !s.is_empty() {
                    segs.insert(s.to_string());
                }
            }
        };
        note(cd.superclass_idx, &mut segs);
        for i in dex.interfaces_of(cd) {
            note(i, &mut segs);
        }
        let data = dex.class_data(cd);
        for f in data.static_fields.iter().chain(data.instance_fields.iter()) {
            let fr = dex.field(f.field_idx);
            note(fr.class_idx, &mut segs);
            note(fr.type_idx, &mut segs);
        }
        for m in data.direct_methods.iter().chain(data.virtual_methods.iter()) {
            let mr = dex.method(m.method_idx);
            note(mr.class_idx, &mut segs);
            let proto = dex.proto(mr.proto_idx);
            note(proto.return_type_idx, &mut segs);
            for &t in dex.proto_params(mr.proto_idx) {
                note(t, &mut segs);
            }
            let Some(code) = (m.code_off != 0)
                .then(|| dex.code_insns_bytes_at(m.code_off))
                .flatten()
            else {
                continue;
            };
            ddc_dex::insn::scan_instructions(code, &mut |op, pc, bytes| {
                let unit = |i: usize| -> u32 {
                    bytes
                        .get(2 * i..2 * i + 2)
                        .map(|b| u16::from_le_bytes([b[0], b[1]]) as u32)
                        .unwrap_or(NONE)
                };
                match op {
                    0x1c | 0x1f | 0x20 | 0x22..=0x25 | 0xff => {
                        note(unit(pc + 1), &mut segs);
                    }
                    0x52..=0x6d => {
                        let f = dex.field(unit(pc + 1));
                        note(f.class_idx, &mut segs);
                        note(f.type_idx, &mut segs);
                    }
                    0x6e..=0x72 | 0x74..=0x78 | 0xfa | 0xfb => {
                        let mr = dex.method(unit(pc + 1));
                        note(mr.class_idx, &mut segs);
                        let proto = dex.proto(mr.proto_idx);
                        note(proto.return_type_idx, &mut segs);
                        for &t in dex.proto_params(mr.proto_idx) {
                            note(t, &mut segs);
                        }
                    }
                    _ => {}
                }
            });
        }
        if !segs.is_empty() {
            out.entry(referrer_pkg_string(&referrer))
                .or_default()
                .extend(segs);
        }
    }
    out
}

fn referrer_pkg_string(referrer: &str) -> String {
    pkg_of(referrer).to_string()
}

/// Per-FAMILY first segments of cross-package references (supers,
/// interfaces, field descs, method protos, instruction operands).
/// Keyed by referrer internal class name; only families in `cand` are
/// scanned. Field-deshadow gate: a family's field named `s` may only be
/// renamed when the family actually renders `s.`-qualified references.
/// Same-package refs are NOT collected (their shadow handling goes
/// through the FQN fallback, whose first segment is the family's own
/// package root — the caller adds that unconditionally).
/// (cross-package first segments per family, own-nested tails
/// referenced per family root).
pub type SegMaps = (
    HashMap<String, HashSet<String>>,
    HashMap<String, HashSet<String>>,
);

pub fn family_ref_segments(
    dexes: &[Arc<DexFile>],
    cand: &HashSet<String>,
) -> SegMaps {
    if cand.is_empty() {
        return (HashMap::default(), HashMap::default());
    }
    let nthreads = std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(1)
        .min(4)
        .min(dexes.len().max(1));
    let chunk = dexes.len().div_ceil(nthreads).max(1);
    let merged: std::sync::Mutex<SegMaps> =
        std::sync::Mutex::new((HashMap::default(), HashMap::default()));
    std::thread::scope(|scope| {
        let handles: Vec<_> = dexes
            .chunks(chunk)
            .map(|group| {
                let merged = &merged;
                scope.spawn(move || {
                    let mut part: HashMap<String, HashSet<String>> = HashMap::default();
                    let mut part_nest: HashMap<String, HashSet<String>> =
                        HashMap::default();
                    for dex in group {
                        let (a, b) = scan_family_segments(dex, cand);
                        for (k, v) in a {
                            part.entry(k).or_default().extend(v);
                        }
                        for (k, v) in b {
                            part_nest.entry(k).or_default().extend(v);
                        }
                    }
                    let mut m = merged.lock().unwrap();
                    for (k, v) in part {
                        m.0.entry(k).or_default().extend(v);
                    }
                    for (k, v) in part_nest {
                        m.1.entry(k).or_default().extend(v);
                    }
                })
            })
            .collect();
        for h in handles {
            let _ = h.join();
        }
    });
    merged.into_inner().unwrap_or_default()
}

fn scan_family_segments(dex: &DexFile, cand: &HashSet<String>) -> SegMaps {
    let n = dex.type_count();
    let mut tseg: Vec<Box<str>> = Vec::with_capacity(n);
    let mut tpkg_empty: Vec<bool> = Vec::with_capacity(n);
    for idx in 0..n {
        let name = dex.type_name(idx as u32);
        let mut b = name.strip_prefix('[').unwrap_or(name).to_string();
        while b.starts_with('[') {
            b.remove(0);
        }
        let inner = b
            .strip_prefix('L')
            .and_then(|s| s.strip_suffix(';'))
            .unwrap_or("");
        tpkg_empty.push(!inner.contains('/'));
        tseg.push(
            match inner.find('/') {
                Some(i) => inner[..i].into(),
                None => Box::from(""),
            },
        );
    }
    let mut out: HashMap<String, HashSet<String>> = HashMap::default();
    let mut out_nest: HashMap<String, HashSet<String>> = HashMap::default();
    for cd in &dex.class_defs {
        let referrer = dex.class_name(cd.class_idx);
        if !cand.contains(&referrer) {
            continue;
        }
        let rp = pkg_of(&referrer);
        // Family root for own-nested detection (`a/b/C$x` → `a/b/C`).
        let rroot = match referrer.find('$') {
            Some(i) => &referrer[..i],
            None => referrer.as_str(),
        };
        let mut segs: HashSet<String> = HashSet::default();
        let mut nest: HashSet<String> = HashSet::default();
        let note = |t: u32, segs: &mut HashSet<String>, nest: &mut HashSet<String>| {
            let i = t as usize;
            if tpkg_empty.get(i).copied().unwrap_or(true) {
                return;
            }
            let name = dex.type_name(t);
            let inner = name
                .trim_start_matches('[')
                .strip_prefix('L')
                .and_then(|s| s.strip_suffix(';'))
                .unwrap_or("");
            // Own-family nested ref (`C$x` from inside C's family):
            // record the DIRECT tail under the family root — the
            // private-field-vs-nested-class deshadow trigger requires
            // the body to actually reference the nested type.
            if let Some(d) = inner.find('$') {
                let root = &inner[..d];
                if root == rroot {
                    let rest = &inner[d + 1..];
                    let tail = match rest.find('$') {
                        Some(j) => &rest[..j],
                        None => rest,
                    };
                    if !tail.is_empty() {
                        nest.insert(tail.to_string());
                    }
                    return;
                }
            }
            // Cross-package only; own-package refs are the caller's
            // unconditional root-segment addition.
            if let Some(j) = inner.rfind('/') {
                if &inner[..j] == rp {
                    return;
                }
            }
            if let Some(s) = tseg.get(i) {
                if !s.is_empty() {
                    segs.insert(s.to_string());
                }
            }
        };
        note(cd.superclass_idx, &mut segs, &mut nest);
        for i in dex.interfaces_of(cd) {
            note(i, &mut segs, &mut nest);
        }
        let data = dex.class_data(cd);
        for f in data.static_fields.iter().chain(data.instance_fields.iter()) {
            let fr = dex.field(f.field_idx);
            note(fr.class_idx, &mut segs, &mut nest);
            note(fr.type_idx, &mut segs, &mut nest);
        }
        for m in data.direct_methods.iter().chain(data.virtual_methods.iter()) {
            let mr = dex.method(m.method_idx);
            note(mr.class_idx, &mut segs, &mut nest);
            let proto = dex.proto(mr.proto_idx);
            note(proto.return_type_idx, &mut segs, &mut nest);
            for &t in dex.proto_params(mr.proto_idx) {
                note(t, &mut segs, &mut nest);
            }
            let Some(code) = (m.code_off != 0)
                .then(|| dex.code_insns_bytes_at(m.code_off))
                .flatten()
            else {
                continue;
            };
            ddc_dex::insn::scan_instructions(code, &mut |op, pc, bytes| {
                let unit = |i: usize| -> u32 {
                    bytes
                        .get(2 * i..2 * i + 2)
                        .map(|b| u16::from_le_bytes([b[0], b[1]]) as u32)
                        .unwrap_or(NONE)
                };
                match op {
                    0x1c | 0x1f | 0x20 | 0x22..=0x25 | 0xff => {
                        note(unit(pc + 1), &mut segs, &mut nest);
                    }
                    0x52..=0x6d => {
                        let f = dex.field(unit(pc + 1));
                        note(f.class_idx, &mut segs, &mut nest);
                        note(f.type_idx, &mut segs, &mut nest);
                    }
                    0x6e..=0x72 | 0x74..=0x78 | 0xfa | 0xfb => {
                        let mr = dex.method(unit(pc + 1));
                        note(mr.class_idx, &mut segs, &mut nest);
                        let proto = dex.proto(mr.proto_idx);
                        note(proto.return_type_idx, &mut segs, &mut nest);
                        for &t in dex.proto_params(mr.proto_idx) {
                            note(t, &mut segs, &mut nest);
                        }
                    }
                    _ => {}
                }
            });
        }
        if !segs.is_empty() {
            out.entry(referrer.to_string()).or_default().extend(segs);
        }
        if !nest.is_empty() {
            // Keyed by the FAMILY ROOT: every member of the family
            // renders in the root's file scope where the collision
            // bites.
            out_nest
                .entry(rroot.to_string())
                .or_default()
                .extend(nest);
        }
    }
    (out, out_nest)
}


/// Cross-package access widening census.
///
/// ART tolerates access patterns Java forbids (R8/d8 keep package-
/// private and protected members that are invoked cross-package; the
/// weixin matrix JiffiesSnapshot chain, lark kotlinx.coroutines.k,
/// protobuf unknownFields). The decompiled source must WIDEN those
/// declarations or every foreign referrer fails to compile. This scan
/// collects every type/field/method reference that crosses a package
/// boundary; the installer filters to the actually non-public ones.
#[derive(Default)]
pub struct AccessWidening {
    /// Internal names needing `public` (includes every `$`-outer prefix
    /// of a referenced nested class — an inaccessible intermediate is
    /// "是在不可访问的类或接口中定义的").
    pub classes: HashSet<String>,
    /// owner → (method name, proto descriptor).
    pub methods: HashMap<String, HashSet<(String, String)>>,
    /// owner → field name.
    pub fields: HashMap<String, HashSet<String>>,
    /// (owner, field name) for FINAL fields written OUTSIDE the
    /// declaring class's `<init>`/`<clinit>`. ART tolerates it (and R8
    /// emits it: outer classes initializing nested-class finals,
    /// relocated ctor stores, synthetic accessors); Java forbids it
    /// ("无法为 final 变量 v 分配值", ConstraintLayout$LayoutParams.v).
    /// The declaration renders these without `final`.
    pub unfinal_fields: HashSet<(String, String)>,
}

fn chain_prefixes(internal: &str, out: &mut HashSet<String>) {
    let mut cur = internal;
    loop {
        out.insert(cur.to_string());
        match cur.rfind('$') {
            Some(i) if i > 0 => cur = &cur[..i],
            _ => break,
        }
    }
}

pub fn access_widening_scan(dexes: &[Arc<DexFile>]) -> AccessWidening {
    let nthreads = std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(1)
        .min(4)
        .min(dexes.len().max(1));
    let chunk = dexes.len().div_ceil(nthreads).max(1);
    // Pre-pass: every FINAL field keyed by (raw type descriptor, name),
    // borrowed from the dex string tables. Only finals can suffer the
    // out-of-ctor write violation, and pre-filtering keeps the census
    // small (recording EVERY iput target would be hundreds of
    // thousands of pairs on weixin). PARALLEL per dex-chunk: the pass
    // re-parses class_data (uleb walk) for EVERY class — serial it was
    // the bulk of the scan time on QQ (329k classes / 41 dexes).
    let finals: HashSet<(&str, &str)> = {
        let merged: std::sync::Mutex<HashSet<(&str, &str)>> =
            std::sync::Mutex::new(HashSet::default());
        std::thread::scope(|scope| {
            let handles: Vec<_> = dexes
                .chunks(chunk)
                .map(|group| {
                    let merged = &merged;
                    scope.spawn(move || {
                        let mut part: HashSet<(&str, &str)> = HashSet::default();
                        for dex in group {
                            for cd in &dex.class_defs {
                                let data = dex.class_data(cd);
                                let any_final = data
                                    .instance_fields
                                    .iter()
                                    .chain(data.static_fields.iter())
                                    .any(|f| f.access_flags & crate::access::ACC_FINAL != 0);
                                if !any_final {
                                    continue;
                                }
                                let owner = dex.type_name(cd.class_idx);
                                for f in
                                    data.instance_fields.iter().chain(data.static_fields.iter())
                                {
                                    if f.access_flags & crate::access::ACC_FINAL != 0 {
                                        let fr = dex.field(f.field_idx);
                                        part.insert((owner, dex.string(fr.name_idx)));
                                    }
                                }
                            }
                        }
                        let mut m = merged.lock().unwrap();
                        m.extend(part);
                    })
                })
                .collect();
            for h in handles {
                let _ = h.join();
            }
        });
        merged.into_inner().unwrap()
    };
    let merged: std::sync::Mutex<AccessWidening> =
        std::sync::Mutex::new(AccessWidening::default());
    let finals = &finals;
    std::thread::scope(|scope| {
        let handles: Vec<_> = dexes
            .chunks(chunk)
            .map(|group| {
                let merged = &merged;
                scope.spawn(move || {
                    let mut part = AccessWidening::default();
                    for dex in group {
                        scan_widening_image(dex, &mut part, finals);
                    }
                    let mut m = merged.lock().unwrap();
                    for c in part.classes {
                        m.classes.insert(c);
                    }
                    for (k, v) in part.methods {
                        m.methods.entry(k).or_default().extend(v);
                    }
                    for (k, v) in part.fields {
                        m.fields.entry(k).or_default().extend(v);
                    }
                    m.unfinal_fields.extend(part.unfinal_fields);
                })
            })
            .collect();
        for h in handles {
            let _ = h.join();
        }
    });
    merged.into_inner().unwrap_or_default()
}

fn scan_widening_image(
    dex: &DexFile,
    out: &mut AccessWidening,
    finals: &HashSet<(&str, &str)>,
) {
    let n = dex.type_count();
    // Per-type: internal class name (arrays stripped) + package.
    let mut tname: Vec<Box<str>> = Vec::with_capacity(n);
    let mut tpkg: Vec<Box<str>> = Vec::with_capacity(n);
    for idx in 0..n {
        let name = dex.type_name(idx as u32);
        let mut b = name.strip_prefix('[').unwrap_or(name).to_string();
        while b.starts_with('[') {
            b.remove(0);
        }
        let inner = b
            .strip_prefix('L')
            .and_then(|s| s.strip_suffix(';'))
            .unwrap_or("");
        let p = match inner.rfind('/') {
            Some(j) => &inner[..j],
            None => "",
        };
        tname.push(inner.into());
        tpkg.push(p.into());
    }
    for cd in &dex.class_defs {
        let referrer = dex.class_name(cd.class_idx);
        let rp = pkg_of(&referrer);
        if rp.is_empty() {
            continue; // default-package refs cannot be expressed anyway
        }
        let note_type = |t: u32, out: &mut AccessWidening| {
            let i = t as usize;
            let Some(nm) = tname.get(i) else { return };
            if nm.is_empty() {
                return;
            }
            let Some(p) = tpkg.get(i) else { return };
            if p.is_empty() || p.as_ref() == rp {
                return;
            }
            chain_prefixes(nm, &mut out.classes);
        };
        note_type(cd.superclass_idx, out);
        for i in dex.interfaces_of(cd) {
            note_type(i, out);
        }
        let data = dex.class_data(cd);
        for f in data.static_fields.iter().chain(data.instance_fields.iter()) {
            let fr = dex.field(f.field_idx);
            note_type(fr.class_idx, out);
            note_type(fr.type_idx, out);
        }
        for m in data.direct_methods.iter().chain(data.virtual_methods.iter()) {
            let mr = dex.method(m.method_idx);
            let mname = dex.string(mr.name_idx);
            note_type(mr.class_idx, out);
            let proto = dex.proto(mr.proto_idx);
            note_type(proto.return_type_idx, out);
            for &t in dex.proto_params(mr.proto_idx) {
                note_type(t, out);
            }
            let Some(code) = (m.code_off != 0)
                .then(|| dex.code_insns_bytes_at(m.code_off))
                .flatten()
            else {
                continue;
            };
            // A STATIC SYNTHETIC method is a compiler-generated bridge —
            // overwhelmingly an `access$NNN` accessor that reads/writes an
            // enclosing class's PRIVATE member on behalf of an inner class.
            // ddc's inline_accessors inlines the call into the inner class,
            // turning the (legal, self-access) private read INSIDE the
            // accessor into a cross-CLASS private access javac rejects
            // ("X 在 Y 中是 private 访问控制" — the single biggest error
            // family, 12.4k). The scan sees the field ref as a SELF-access
            // (owner==referrer) so the cross-package gate misses it; record
            // it here so install_access_widening widens the target.
            let in_accessor = m.access_flags & crate::access::ACC_STATIC != 0
                && m.access_flags & crate::access::ACC_SYNTHETIC != 0;
            // Own-ctor/clinit writes of FINAL fields, counted per
            // method body: one store is the legal blank-final init,
            // but R8 state-machine ctors duplicate the store across
            // switch cases and javac rejects the second sequential
            // assignment ("无法为 final 变量 v 分配值",
            // ConstraintLayout$LayoutParams(Context,AttributeSet)).
            let mut final_init_writes: HashMap<(String, String), u32> = HashMap::default();
            ddc_dex::insn::scan_instructions(code, &mut |op, pc, bytes| {
                let unit = |i: usize| -> u32 {
                    bytes
                        .get(2 * i..2 * i + 2)
                        .map(|b| u16::from_le_bytes([b[0], b[1]]) as u32)
                        .unwrap_or(NONE)
                };
                match op {
                    0x1c | 0x1f | 0x20 | 0x22..=0x25 | 0xff => {
                        note_type(unit(pc + 1), out);
                    }
                    0x52..=0x6d => {
                        let fr = dex.field(unit(pc + 1));
                        let owner = dex.class_name(fr.class_idx);
                        // Final-field write census: an iput outside the
                        // owner's own <init> (or an sput outside its
                        // <clinit>) is a Java "无法为 final 变量赋值" —
                        // the declaration renders without `final`.
                        if matches!(op, 0x59..=0x5f | 0x67..=0x6d) {
                            let fname = dex.string(fr.name_idx);
                            if finals.contains(&(dex.type_name(fr.class_idx), fname)) {
                                let ctor = if op <= 0x5f { "<init>" } else { "<clinit>" };
                                if referrer == owner && mname == ctor {
                                    *final_init_writes
                                        .entry((owner.clone(), fname.to_string()))
                                        .or_default() += 1;
                                } else {
                                    out.unfinal_fields
                                        .insert((owner.clone(), fname.to_string()));
                                }
                            }
                        }
                        let op_pkg = pkg_of(&owner);
                        let xpkg = !op_pkg.is_empty() && op_pkg != rp;
                        if xpkg {
                            note_type(fr.class_idx, out);
                        }
                        if xpkg || in_accessor {
                            out.fields
                                .entry(owner.clone())
                                .or_default()
                                .insert(dex.string(fr.name_idx).to_string());
                        }
                        note_type(fr.type_idx, out);
                    }
                    0x6e..=0x72 | 0x74..=0x78 | 0xfa | 0xfb => {
                        let mr = dex.method(unit(pc + 1));
                        let owner = dex.class_name(mr.class_idx);
                        let op_pkg = pkg_of(&owner);
                        let xpkg = !op_pkg.is_empty() && op_pkg != rp;
                        if xpkg {
                            note_type(mr.class_idx, out);
                        }
                        if xpkg || in_accessor {
                            out.methods
                                .entry(owner.clone())
                                .or_default()
                                .insert((
                                    dex.string(mr.name_idx).to_string(),
                                    dex.proto_desc(mr.proto_idx).to_string(),
                                ));
                        }
                        let proto = dex.proto(mr.proto_idx);
                        note_type(proto.return_type_idx, out);
                        for &t in dex.proto_params(mr.proto_idx) {
                            note_type(t, out);
                        }
                    }
                    _ => {}
                }
            });
            for (k, c) in final_init_writes {
                if c >= 2 {
                    out.unfinal_fields.insert(k);
                }
            }
        }
    }
}