ddc_dec/lib.rs
1//! ddc-dec — DEX → Java decompiler front-end over `jdc-core`.
2//!
3//! Pipeline per method: DEX code units → CFG → per-block register→IR
4//! lifting → `jdc-core` structuring/conversion → refinement passes →
5//! emission. Class-level rendering mirrors jcdc's `classdec` but reads
6//! DEX metadata (no signatures, no generics).
7
8pub mod cfg;
9pub mod classdec;
10pub mod fwdb;
11
12pub use classdec::{sanitize_fq, ClassOptions};
13pub mod ctx;
14pub mod lift;
15pub mod method;
16pub mod passes;
17pub mod platform;
18mod refscan;
19pub mod ssa_census;
20
21use jdc_core::FxHashMap as HashMap;
22
23use ddc_dex::annotations::{self, EncodedValue};
24
25/// A resolved static-field initializer.
26#[derive(Debug, Clone)]
27pub enum StaticValue {
28 Int(i64),
29 Float(f32),
30 Double(f64),
31 Str(String),
32 Type(String),
33 Boolean(bool),
34 Null,
35 /// (declaring class, field name, field descriptor) — enum constants /
36 /// const field refs. The desc participates in the rename-registry key
37 /// (owner, name, desc) so the render site can consult field_display.
38 Field(String, String, String),
39 Other,
40}
41use ddc_dex::{ClassDef, DexFile};
42use jdc_core::types::{
43 parse_field_descriptor, parse_method_descriptor, JavaType, MethodDescriptor,
44};
45
46// ---------------------------------------------------------------------------
47// Access flags (Dalvik numbering, JVM-compatible subset).
48// ---------------------------------------------------------------------------
49pub mod access {
50 pub const ACC_PUBLIC: u32 = 0x1;
51 pub const ACC_PRIVATE: u32 = 0x2;
52 pub const ACC_PROTECTED: u32 = 0x4;
53 pub const ACC_STATIC: u32 = 0x8;
54 pub const ACC_FINAL: u32 = 0x10;
55 pub const ACC_SYNCHRONIZED: u32 = 0x20;
56 pub const ACC_BRIDGE: u32 = 0x40;
57 pub const ACC_VARARGS: u32 = 0x80;
58 pub const ACC_NATIVE: u32 = 0x100;
59 pub const ACC_INTERFACE: u32 = 0x200;
60 pub const ACC_ABSTRACT: u32 = 0x400;
61 pub const ACC_STRICT: u32 = 0x800;
62 pub const ACC_SYNTHETIC: u32 = 0x1000;
63 pub const ACC_ANNOTATION: u32 = 0x2000;
64 pub const ACC_ENUM: u32 = 0x4000;
65 pub const ACC_CONSTRUCTOR: u32 = 0x1_0000;
66 pub const ACC_DECLARED_SYNCHRONIZED: u32 = 0x2_0000;
67}
68
69/// One field of a pooled class.
70#[derive(Debug, Clone)]
71pub struct PoolField {
72 pub name: String,
73 /// Field descriptor (`I`, `Ljava/lang/String;`, ...).
74 pub desc: String,
75 pub access: u32,
76 pub is_static: bool,
77}
78
79/// One method of a pooled class.
80#[derive(Debug, Clone)]
81pub struct PoolMethod {
82 /// Shared with the dex string table (the idx IS the dedup key).
83 pub name: std::sync::Arc<str>,
84 /// Method descriptor, shared per proto (a dex's proto table is the
85 /// descriptor dedup layer — 1.9M methods on lark share ~1 proto
86 /// table's worth of unique descriptors).
87 pub desc: std::sync::Arc<str>,
88 pub access: u32,
89 pub code_off: u32,
90 pub debug_info_off: u32,
91 /// Which DEX image the body lives in.
92 pub dex_idx: usize,
93}
94
95impl PoolMethod {
96 pub fn parsed_desc(&self) -> Option<MethodDescriptor> {
97 parse_method_descriptor(&self.desc)
98 }
99 pub fn is_static(&self) -> bool {
100 self.access & access::ACC_STATIC != 0
101 }
102 pub fn is_abstract_or_native(&self) -> bool {
103 self.access & (access::ACC_ABSTRACT | access::ACC_NATIVE) != 0
104 }
105}
106
107/// One pool entry: either already built, or name-registered with its
108/// (dex index, class_def index) locator for on-demand construction.
109enum ClassEntry {
110 Eager(PoolClass),
111 Lazy {
112 at: (usize, usize),
113 pc: std::sync::OnceLock<PoolClass>,
114 },
115}
116
117/// A class materialized from one `class_def_item` (with ids resolved to
118/// names and the class data expanded).
119#[derive(Debug, Clone)]
120pub struct PoolClass {
121 pub name: String,
122 pub access: u32,
123 /// `None` for `java/lang/Object` roots.
124 pub super_name: Option<String>,
125 pub interfaces: Vec<String>,
126 pub source_file: Option<String>,
127 pub static_fields: Vec<PoolField>,
128 pub instance_fields: Vec<PoolField>,
129 pub direct_methods: Vec<PoolMethod>,
130 pub virtual_methods: Vec<PoolMethod>,
131 /// Static initial values aligned with the head of `static_fields`.
132 pub static_values: Vec<StaticValue>,
133 /// Nesting evidence with annotation ids resolved to names.
134 pub nesting: ResolvedNesting,
135 /// Which DEX image the class body lives in (provenance header).
136 pub dex_idx: usize,
137}
138
139/// Nesting evidence, names resolved at pooling time.
140#[derive(Debug, Clone, Default)]
141pub struct ResolvedNesting {
142 pub enclosing_class: Option<String>,
143 /// (class internal name, method name) of the enclosing method.
144 pub enclosing_method: Option<(String, String)>,
145 pub member_classes: Vec<String>,
146}
147
148impl PoolClass {
149 pub fn is_interface(&self) -> bool {
150 self.access & access::ACC_INTERFACE != 0
151 }
152
153 pub fn is_enum(&self) -> bool {
154 self.access & access::ACC_ENUM != 0
155 }
156
157 pub fn is_synthetic(&self) -> bool {
158 self.access & access::ACC_SYNTHETIC != 0
159 }
160
161 pub fn is_static_nested(&self) -> bool {
162 self.access & access::ACC_STATIC != 0
163 }
164
165 /// All methods in declaration order.
166 pub fn all_methods(&self) -> impl Iterator<Item = &PoolMethod> {
167 self.direct_methods
168 .iter()
169 .chain(self.virtual_methods.iter())
170 }
171
172 /// Find a method by name + descriptor.
173 pub fn find_method(&self, name: &str, desc: &str) -> Option<&PoolMethod> {
174 self.all_methods()
175 .find(|m| &*m.name == name && &*m.desc == desc)
176 }
177
178 /// Constructors `<init>` matching `arity` descriptor arguments.
179 pub fn ctors_by_arity(&self, arity: usize) -> Vec<&PoolMethod> {
180 self.all_methods()
181 .filter(|m| &*m.name == "<init>")
182 .filter(|m| {
183 m.parsed_desc()
184 .map(|d| d.args.len() == arity)
185 .unwrap_or(false)
186 })
187 .collect()
188 }
189
190 pub fn field_flags_of(&self, name: &str) -> Option<u32> {
191 self.static_fields
192 .iter()
193 .chain(self.instance_fields.iter())
194 .find(|f| f.name == name)
195 .map(|f| f.access)
196 }
197}
198
199/// Multi-DEX class pool: classes from all images, first definition wins.
200/// One facade-map entry: the public base plus, for PARTIALLY covered
201/// parts, the exact static members the base declares (None = the whole
202/// part rewrites; Some = per-member gate). Single map = one hash probe
203/// per static reference (two maps measured +2.4s on weibo).
204type FacadeTarget = (
205 String,
206 Option<
207 std::sync::Arc<(
208 jdc_core::FxHashSet<(String, String)>,
209 jdc_core::FxHashSet<String>,
210 )>,
211 >,
212);
213
214pub struct DexPool {
215 /// Images as Arcs: `dex()` hands out snapshots whose borrows stay
216 /// valid for the Arc's lifetime (decompile workers hold them), while
217 /// `release_images` empties the image data through exclusive access
218 /// when all of an image's classes are done (full-decompile driver
219 /// only — progressive callers keep images whole).
220 dexes: Vec<std::sync::Arc<DexFile>>,
221 /// Human label per image ("weibo!classes.dex") for the provenance
222 /// header; defaults to "dex N" until the CLI names the inputs.
223 pub dex_labels: Vec<String>,
224 /// Name → class entry. Eager pools materialize everything at add
225 /// time (full decompile, tests); lazy pools register names only and
226 /// materialize on first `get` (progressive `getclass` — one class's
227 /// PoolClass costs annotation reads, 145k of them cost ~0.2s).
228 classes: HashMap<String, ClassEntry>,
229 /// Class names in insertion order (stable for output).
230 pub order: Vec<String>,
231 /// Per-image remaining class count once `arm_retirement` fires.
232 retire_counts: std::sync::Mutex<Vec<u64>>,
233 retire_armed: std::sync::atomic::AtomicBool,
234 /// name → outer (computed once; `$` heuristic + dalvik annotations).
235 outers: std::sync::OnceLock<HashMap<String, Option<String>>>,
236 /// outer → direct children (computed once).
237 children: std::sync::OnceLock<HashMap<String, Vec<String>>>,
238 /// Per-image hot-reference interning (parallel to `dexes`).
239 ref_caches: Vec<DexRefCache>,
240 /// Synthetic-static accessor code snapshots keyed by (dex_idx,
241 /// code_off). `inline_accessors` reads accessor bodies ACROSS images
242 /// during worker runs; image retirement can release those bytes
243 /// mid-run, making the inline decision — and with it var numbering
244 /// downstream — dependent on worker completion interleaving
245 /// (observed: reqable enum-constant args flipping `var0`/`var1`
246 /// between identical runs; DDC_NORETIRE=1 stable). The full-decompile
247 /// driver fills this BEFORE `arm_retirement`; progressive/lazy pools
248 /// never retire and fall through to live reads.
249 accessor_code: std::sync::OnceLock<AccessorSnapshots>,
250 /// Cached package → direct-class simple names (import-collision gate).
251 pkg_simples: std::sync::OnceLock<jdc_core::FxHashMap<String, jdc_core::FxHashSet<String>>>,
252 /// First path segments of all packages (`v2` for `v2/n`): local or
253 /// field names equal to one capture package-qualified renders
254 /// (`v2.n.a`) — deshadow_locals consults this.
255 root_segs: std::sync::OnceLock<jdc_core::FxHashSet<String>>,
256 /// Partially-covered facade parts (see kotlin_facade_partial_map).
257 /// Kotlin multi-file facade parts → public facade (see
258 /// `kotlin_facade_map`).
259 kotlin_facades: std::sync::OnceLock<jdc_core::FxHashMap<String, FacadeTarget>>,
260 /// Per class internal name: the set of `<init>` ARGUMENT descriptors
261 /// (the `(..)` inner text) REFERENCED through that class anywhere in
262 /// the pool. Dex resolves a `<init>` method-ref up the superclass
263 /// chain, so a subclass `super(..)` may target `C.<init>(sig)` that C
264 /// does NOT declare (an ancestor does) — Java has no inherited ctors,
265 /// so C needs a bridge. Computed once from the method-id tables
266 /// (parsed, survive image retirement). See `inherited_ctor_bridges`.
267 ctor_refs: std::sync::OnceLock<jdc_core::FxHashMap<String, jdc_core::FxHashSet<String>>>,
268}
269
270/// Raw code_item bytes of every synthetic-static accessor, keyed by
271/// (dex_idx, code_off) — see `snapshot_accessor_code`.
272type AccessorSnapshots = HashMap<(usize, u32), std::sync::Arc<[u8]>>;
273
274/// Lazily-filled, thread-shared reference interning for one image.
275///
276/// The lifter used to rebuild class names, field/method names and WHOLE
277/// method descriptors per INSTRUCTION (`method_ref` alone: N param
278/// Strings → `format!` descriptor → re-parse — 6-10 allocations per
279/// invoke). Every entry here is built at most once per (image, table
280/// index); lifts and the endless IR clones downstream are refcount
281/// bumps. Slots are `OnceLock` so worker threads fill them race-free
282/// without a lock on the hot path.
283pub(crate) struct DexRefCache {
284 proto_descs: Box<[std::sync::OnceLock<std::sync::Arc<jdc_core::types::MethodDescriptor>>]>,
285 type_names: Box<[std::sync::OnceLock<std::sync::Arc<str>>]>,
286 type_javas: Box<[std::sync::OnceLock<std::sync::Arc<jdc_core::types::JavaType>>]>,
287}
288
289impl DexRefCache {
290 fn new(protos: usize, types: usize) -> Self {
291 DexRefCache {
292 proto_descs: (0..protos).map(|_| std::sync::OnceLock::new()).collect(),
293 type_names: (0..types).map(|_| std::sync::OnceLock::new()).collect(),
294 type_javas: (0..types).map(|_| std::sync::OnceLock::new()).collect(),
295 }
296 }
297}
298
299impl DexPool {
300 pub fn new() -> Self {
301 DexPool {
302 dexes: Vec::new(),
303 retire_armed: std::sync::atomic::AtomicBool::new(false),
304 dex_labels: Vec::new(),
305 classes: HashMap::default(),
306 order: Vec::new(),
307 retire_counts: std::sync::Mutex::new(Vec::new()),
308 outers: std::sync::OnceLock::new(),
309 children: std::sync::OnceLock::new(),
310 ref_caches: Vec::new(),
311 accessor_code: std::sync::OnceLock::new(),
312 pkg_simples: std::sync::OnceLock::new(),
313 root_segs: std::sync::OnceLock::new(),
314 kotlin_facades: std::sync::OnceLock::new(),
315 ctor_refs: std::sync::OnceLock::new(),
316 }
317 }
318
319 /// Referenced `<init>` argument-descriptor set for a class internal
320 /// name (see `ctor_refs`). Builds the whole index on first call by
321 /// scanning every image's method-id table for `<init>` refs — cheap
322 /// (flat table, integer name-idx compare against the interned
323 /// "<init>" string) and done once for the whole decompile.
324 pub fn ctor_ref_sigs(&self, class: &str) -> Option<&jdc_core::FxHashSet<String>> {
325 self.ctor_refs
326 .get_or_init(|| {
327 let mut map: jdc_core::FxHashMap<String, jdc_core::FxHashSet<String>> =
328 jdc_core::FxHashMap::default();
329 for dex in &self.dexes {
330 let n = dex.method_count();
331 for i in 0..n {
332 let m = dex.method(i as u32);
333 if dex.string(m.name_idx) != "<init>" {
334 continue;
335 }
336 let desc = dex.proto_desc(m.proto_idx);
337 let (Some(lo), Some(hi)) = (desc.find('('), desc.find(')')) else {
338 continue;
339 };
340 map.entry(dex.class_name(m.class_idx))
341 .or_default()
342 .insert(desc[lo + 1..hi].to_string());
343 }
344 }
345 map
346 })
347 .get(class)
348 }
349
350 /// Shared `MethodDescriptor` of a proto (one parse per image).
351 pub fn proto_desc_parsed(
352 &self,
353 di: usize,
354 proto_idx: u32,
355 ) -> std::sync::Arc<jdc_core::types::MethodDescriptor> {
356 let Some(dex) = self.dexes.get(di) else {
357 return std::sync::Arc::new(jdc_core::types::MethodDescriptor {
358 args: Vec::new(),
359 ret: jdc_core::types::JavaType::Void,
360 });
361 };
362 let build = || {
363 std::sync::Arc::new(parse_proto_desc(dex, proto_idx))
364 };
365 match self
366 .ref_caches
367 .get(di)
368 .and_then(|c| c.proto_descs.get(proto_idx as usize))
369 {
370 Some(slot) => slot.get_or_init(build).clone(),
371 None => build(),
372 }
373 }
374
375 /// Shared internal class name of a type id (one strip+alloc per image).
376 pub fn type_name_arc(&self, di: usize, type_idx: u32) -> std::sync::Arc<str> {
377 let Some(dex) = self.dexes.get(di) else {
378 return std::sync::Arc::from("");
379 };
380 let build = || std::sync::Arc::from(dex.class_name(type_idx).as_str());
381 match self
382 .ref_caches
383 .get(di)
384 .and_then(|c| c.type_names.get(type_idx as usize))
385 {
386 Some(slot) => slot.get_or_init(build).clone(),
387 None => build(),
388 }
389 }
390
391 /// Shared parsed type of a type id.
392 pub fn type_java(&self, di: usize, type_idx: u32) -> std::sync::Arc<jdc_core::types::JavaType> {
393 let Some(dex) = self.dexes.get(di) else {
394 return std::sync::Arc::new(jdc_core::types::JavaType::Object(
395 std::sync::Arc::from("java/lang/Object"),
396 ));
397 };
398 let build = || std::sync::Arc::new(desc_type(dex.type_name(type_idx)));
399 match self
400 .ref_caches
401 .get(di)
402 .and_then(|c| c.type_javas.get(type_idx as usize))
403 {
404 Some(slot) => slot.get_or_init(build).clone(),
405 None => build(),
406 }
407 }
408
409 /// name → outer map, computed lazily once.
410 fn outer_map(&self) -> &HashMap<String, Option<String>> {
411 self.outers.get_or_init(|| {
412 self.order
413 .iter()
414 .map(|n| (n.clone(), find_outer_name(self, n)))
415 .collect()
416 })
417 }
418
419 /// The outer class of `name`, from the cached map (borrowed).
420 pub fn outer_of(&self, name: &str) -> Option<&str> {
421 self.outer_map().get(name).and_then(|o| o.as_deref())
422 }
423
424 /// Direct nested children of `internal` (any `$` depth 1), cached.
425 /// (Perf: returns a borrowed slice — the owned-Vec clone ran once per
426 /// class on 98k-class runs.)
427 pub fn children_of(&self, internal: &str) -> &[String] {
428 if self.children.get().is_none() {
429 // Build FIRST, set ONCE: the previous shape set an empty map
430 // to claim the OnceLock and then silently failed to store the
431 // real index (`let _ = set(...)` on an initialized lock) —
432 // children_of returned [] forever, so member nested classes
433 // were neither inlined nor emitted as files (Guard$Report
434 // vanished whole; every corpus run since the borrow refactor
435 // dropped them, invisible to the syntax-only gate).
436 let mut idx: HashMap<String, Vec<String>> = HashMap::default();
437 for name in &self.order {
438 if let Some(outer) = self.outer_of(name).map(str::to_string) {
439 idx.entry(outer).or_default().push(name.clone());
440 }
441 }
442 // A racing thread may have set an identical map first — the
443 // index is a pure function of `order`, so either copy is right.
444 let _ = self.children.set(idx);
445 }
446 self.children
447 .get()
448 .and_then(|m| m.get(internal))
449 .map(|v| v.as_slice())
450 .unwrap_or(&[])
451 }
452
453 /// Adds one image; duplicate class names keep their first definition.
454 /// Returns the image's index — call `set_dex_label` with it to give the
455 /// provenance header a real origin instead of the default "dex N".
456 pub fn add_dex(&mut self, dex: DexFile) -> usize {
457 let dex_idx = self.dexes.len();
458 // Pre-size the name map: 240k-entry growth rehashed repeatedly
459 // (reserve_rehash showed up in corpus profiles).
460 self.classes.reserve(dex.class_defs.len());
461 // The annotation reader borrows the image; pool classes are built
462 // before ownership moves into `self.dexes` (no full-image copy).
463 for cd in &dex.class_defs {
464 let name = dex.class_name(cd.class_idx);
465 if self.classes.contains_key(&name) {
466 continue;
467 }
468 let pc = pool_class_of(&dex, dex.raw(), cd, dex_idx);
469 self.classes.insert(name.clone(), ClassEntry::Eager(pc));
470 self.order.push(name);
471 }
472 self.ref_caches
473 .push(DexRefCache::new(dex.proto_count(), dex.type_count()));
474 self.dexes.push(std::sync::Arc::new(dex));
475 self.retire_counts.lock().unwrap().push(0);
476 self.dex_labels.push(format!("dex {}", dex_idx));
477 dex_idx
478 }
479
480 /// Registers class NAMES only; the PoolClass (annotation reads
481 /// included) is materialized on first `get`. Duplicate class names
482 /// keep their first definition, matching `add_dex`.
483 pub fn add_dex_lazy(&mut self, dex: DexFile) -> usize {
484 let dex_idx = self.dexes.len();
485 self.classes.reserve(dex.class_defs.len());
486 for (ci, cd) in dex.class_defs.iter().enumerate() {
487 let name = dex.class_name(cd.class_idx);
488 if self.classes.contains_key(&name) {
489 continue;
490 }
491 self.classes.insert(
492 name.clone(),
493 ClassEntry::Lazy {
494 at: (dex_idx, ci),
495 pc: std::sync::OnceLock::new(),
496 },
497 );
498 self.order.push(name);
499 }
500 self.ref_caches
501 .push(DexRefCache::new(dex.proto_count(), dex.type_count()));
502 self.dexes.push(std::sync::Arc::new(dex));
503 self.retire_counts.lock().unwrap().push(0);
504 self.dex_labels.push(format!("dex {}", dex_idx));
505 dex_idx
506 }
507
508 /// Label the image at `idx` (see `add_dex`).
509 pub fn set_dex_label(&mut self, idx: usize, label: impl Into<String>) {
510 if let Some(slot) = self.dex_labels.get_mut(idx) {
511 *slot = label.into();
512 }
513 }
514
515 pub fn len(&self) -> usize {
516 self.classes.len()
517 }
518
519 pub fn is_empty(&self) -> bool {
520 self.classes.is_empty()
521 }
522
523 pub fn get(&self, internal: &str) -> Option<&PoolClass> {
524 self.get_inner(internal, None)
525 }
526
527 /// `get` with optional pre-taken raw-image snapshots (one per
528 /// image). `materialize_all` hoists the `DexFile::raw()` lock out of
529 /// the per-class loop — the parallel materialize used to take the
530 /// same per-image lock once PER CLASS across all threads.
531 fn get_inner(&self, internal: &str, raws: Option<&[&[u8]]>) -> Option<&PoolClass> {
532 match self.classes.get(internal)? {
533 ClassEntry::Eager(pc) => Some(pc),
534 ClassEntry::Lazy { at, pc } => {
535 if let Some(built) = pc.get() {
536 return Some(built);
537 }
538 let (di, ci) = *at;
539 let dex = self.dexes.get(di)?;
540 let cd = dex.class_defs.get(ci)?;
541 let raw = match raws {
542 Some(r) => r.get(di).copied().unwrap_or(&[]),
543 None => dex.raw(),
544 };
545 let built = pool_class_of(dex, raw, cd, di);
546 Some(pc.get_or_init(move || built))
547 }
548 }
549 }
550
551 /// Materialize every lazy entry (parallel across the given chunk
552 /// count). After this the pool is observationally identical to an
553 /// eagerly-built one — including the annotation-aware outer-map —
554 /// while the annotation reads ran on worker threads instead of the
555 /// serial pool build (~0.2s on weibo).
556 pub fn materialize_all(&self, threads: usize) {
557 let keys: Vec<String> = self
558 .classes
559 .iter()
560 .filter(|(_, e)| matches!(e, ClassEntry::Lazy { .. }))
561 .map(|(k, _)| k.clone())
562 .collect();
563 if keys.is_empty() {
564 return;
565 }
566 // One raw() snapshot per image for the whole sweep (see
567 // get_inner). Safe window: materialize_all completes before
568 // retirement is armed, so no image releases while these slices
569 // are alive.
570 let raws: Vec<&[u8]> = self.dexes.iter().map(|d| d.raw()).collect();
571 let threads = threads.max(1);
572 let next = std::sync::atomic::AtomicUsize::new(0);
573 std::thread::scope(|scope| {
574 for _ in 0..threads {
575 scope.spawn(|| loop {
576 let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
577 let Some(k) = keys.get(i) else { break };
578 let _ = self.get_inner(k, Some(&raws));
579 });
580 }
581 });
582 }
583
584 /// `get` without materializing: None for not-yet-built lazy entries.
585 fn get_if_materialized(&self, internal: &str) -> Option<&PoolClass> {
586 match self.classes.get(internal)? {
587 ClassEntry::Eager(pc) => Some(pc),
588 ClassEntry::Lazy { pc, .. } => pc.get(),
589 }
590 }
591
592 /// Name registered (no materialization).
593 pub fn has_name(&self, internal: &str) -> bool {
594 self.classes.contains_key(internal)
595 }
596
597 /// One image as an Arc snapshot (borrows of the snapshot live as
598 /// long as the caller holds the Arc).
599 pub fn dex(&self, idx: usize) -> Option<std::sync::Arc<DexFile>> {
600 self.dexes.get(idx).cloned()
601 }
602
603 pub fn dex_count(&self) -> usize {
604 self.dexes.len()
605 }
606
607 /// Raw image list (install-phase whole-program scans).
608 pub fn dexes(&self) -> &[std::sync::Arc<ddc_dex::DexFile>] {
609 &self.dexes
610 }
611
612 /// First path segments of every package in the pool (cached once).
613 pub fn root_pkg_segs(&self) -> &jdc_core::FxHashSet<String> {
614 self.root_segs.get_or_init(|| {
615 self.order
616 .iter()
617 .filter_map(|n| n.find('/').map(|i| n[..i].to_string()))
618 .collect()
619 })
620 }
621
622 /// Package → simple names of its direct classes, cached once per
623 /// pool (the import-collision gate consults it per class — the
624 /// uncached scan was O(classes²) and 10×'d weixin's wall time).
625 pub fn package_simples(&self) -> &jdc_core::FxHashMap<String, jdc_core::FxHashSet<String>> {
626 self.pkg_simples.get_or_init(|| {
627 let mut m: jdc_core::FxHashMap<String, jdc_core::FxHashSet<String>> =
628 jdc_core::FxHashMap::default();
629 for n in &self.order {
630 if let Some((pkg, simple)) = n.rsplit_once('/') {
631 m.entry(pkg.to_string())
632 .or_default()
633 .insert(simple.to_string());
634 }
635 }
636 m
637 })
638 }
639
640 /// Kotlin multi-file class facades: the compiler splits a file facade
641 /// (`kotlin.text.StringsKt`) into package-private parts
642 /// (`StringsKt__StringsKt`, `StringsKt__StringsJVMKt`) and call sites
643 /// target the PARTS directly. Java cannot access a package-private
644 /// class cross-package ("StringsKt__StringsKt在kotlin.text中不是公共的"
645 /// — 1.4k lark root errors), but the public facade EXTENDS the parts,
646 /// so static members resolve through it: rewrite the reference's owner
647 /// class to the facade. part → base, gated on base existing, being
648 /// public, and transitively extending the part (static inheritance is
649 /// the resolution guarantee).
650 pub fn kotlin_facade_map(&self) -> &jdc_core::FxHashMap<String, FacadeTarget> {
651 self.kotlin_facades.get_or_init(|| {
652 let t_fb = std::time::Instant::now();
653 let mut m: jdc_core::FxHashMap<String, FacadeTarget> =
654 jdc_core::FxHashMap::default();
655 let mut npartial = 0usize;
656 for name in &self.order {
657 let Some(i) = name.find("__") else { continue };
658 let base = &name[..i];
659 if base.is_empty() {
660 continue;
661 }
662 let Some(basec) = self.get(base) else {
663 continue;
664 };
665 if basec.access & crate::access::ACC_PUBLIC == 0 {
666 continue;
667 }
668 // base must transitively extend the part...
669 let mut cur = basec.super_name.clone();
670 let mut hops = 0u32;
671 let mut reaches = false;
672 while let Some(c) = cur {
673 if c == *name {
674 reaches = true;
675 break;
676 }
677 if hops >= 8 {
678 break;
679 }
680 hops += 1;
681 cur = self.get(&c).and_then(|cc| cc.super_name.clone());
682 }
683 // ...OR cover the part's static members: the Kotlin
684 // compiler MERGES every part's statics into the public
685 // facade, but the facade's super chain only includes ONE
686 // part — lark's `CollectionsKt extends
687 // CollectionsKt___CollectionsKt` leaves
688 // `CollectionsKt__CollectionsJVMKt` uncovered (463
689 // 不是公共的 errors). Member coverage (name+desc for
690 // methods, name for fields) is the precise rewrite
691 // condition: every reference through the facade then
692 // resolves exactly as through the part.
693 if reaches {
694 m.insert(name.clone(), (base.to_string(), None));
695 continue;
696 }
697 // Member-coverage fallback: the Kotlin compiler MERGES
698 // the parts' statics into the public facade, but R8 can
699 // sever the super chain (lark: `CollectionsKt extends
700 // CollectionsKt___CollectionsKt extends
701 // kotlin/collections/s` — `__CollectionsJVMKt` is off
702 // the chain, 463 不是公共的 errors) and may drop facade
703 // members no direct facade call needed. Map at (name,
704 // desc) granularity then: covered members rewrite, the
705 // rest keep the part owner (a latent error either way —
706 // Java cannot access the package-private part).
707 let Some(part) = self.get(name) else {
708 continue;
709 };
710 let base_methods: jdc_core::FxHashSet<(&str, &str)> = basec
711 .direct_methods
712 .iter()
713 .chain(basec.virtual_methods.iter())
714 .map(|mm| (&*mm.name, &*mm.desc))
715 .collect();
716 let base_fields: jdc_core::FxHashSet<&str> =
717 basec.static_fields.iter().map(|f| &*f.name).collect();
718 let mut methods: jdc_core::FxHashSet<(String, String)> =
719 jdc_core::FxHashSet::default();
720 let mut fields: jdc_core::FxHashSet<String> =
721 jdc_core::FxHashSet::default();
722 let mut all = true;
723 for mm in part
724 .direct_methods
725 .iter()
726 .chain(part.virtual_methods.iter())
727 .filter(|mm| mm.access & crate::access::ACC_STATIC != 0)
728 {
729 if base_methods.contains(&(&*mm.name, &*mm.desc)) {
730 methods.insert((mm.name.to_string(), mm.desc.to_string()));
731 } else {
732 all = false;
733 }
734 }
735 for pf in &part.static_fields {
736 if base_fields.contains(&*pf.name) {
737 fields.insert(pf.name.to_string());
738 } else {
739 all = false;
740 }
741 }
742 if all {
743 m.insert(name.clone(), (base.to_string(), None));
744 } else if !methods.is_empty() || !fields.is_empty() {
745 npartial += 1;
746 m.insert(
747 name.clone(),
748 (base.to_string(), Some(std::sync::Arc::new((methods, fields)))),
749 );
750 }
751 }
752 if std::env::var("DDC_STATS").is_ok() {
753 eprintln!(
754 "[renames] facade map: entries={} partial={} build={:?}",
755 m.len(),
756 npartial,
757 t_fb.elapsed()
758 );
759 }
760 m
761 })
762 }
763
764 pub fn class_names(&self) -> impl Iterator<Item = &str> {
765 self.order.iter().map(|s| s.as_str())
766 }
767
768 /// True when `sub` is assignable to `sup` (internal names), walking the
769 /// pool's hierarchy. Unknown classes are never assignable (conservative).
770 pub fn is_subtype(&self, sub: &str, sup: &str) -> bool {
771 if sub == sup {
772 return true;
773 }
774 // Arrays: covariance by element type when both are arrays.
775 if let (Some(sub_elem), Some(sup_elem)) = (array_elem(sub), array_elem(sup)) {
776 if sub_elem.starts_with('L')
777 && sup_elem.starts_with('L')
778 && sub_elem.ends_with(';')
779 && sup_elem.ends_with(';')
780 {
781 return self.is_subtype(
782 &sub_elem[1..sub_elem.len() - 1],
783 &sup_elem[1..sup_elem.len() - 1],
784 );
785 }
786 return sub_elem == sup_elem;
787 }
788 // Everything reference-typed is Object-assignable (the pool walk
789 // used to fall off the chain end and answer false for
790 // String <: Object — the hand-written Object-formal special case
791 // in the ambiguity pin existed for exactly this hole).
792 if sup == "java/lang/Object" {
793 return !matches!(
794 sub,
795 "I" | "Z" | "B" | "S" | "C" | "J" | "F" | "D" | "V"
796 );
797 }
798 let mut cur = self.get(sub);
799 if cur.is_none() {
800 // `sub` is a framework (or phantom) type: the embedded API
801 // database decides (phantoms are absent there too → false).
802 return crate::fwdb::is_subtype(sub, sup);
803 }
804 let mut hops = 0;
805 while let Some(c) = cur {
806 hops += 1;
807 if hops > 64 {
808 return false;
809 }
810 for i in &c.interfaces {
811 if i == sup || self.is_subtype(i, sup) {
812 return true;
813 }
814 }
815 match &c.super_name {
816 Some(s) if s == sup => return true,
817 Some(s) if s != "java/lang/Object" => {
818 match self.get(s) {
819 Some(sc) => cur = Some(sc),
820 // Framework boundary: continue in the embedded DB.
821 None => return crate::fwdb::is_subtype(s, sup),
822 }
823 }
824 _ => return false,
825 }
826 }
827 false
828 }
829}
830
831impl Default for DexPool {
832 fn default() -> Self {
833 Self::new()
834 }
835}
836
837fn array_elem(desc: &str) -> Option<&str> {
838 desc.strip_prefix('[')
839}
840
841fn resolve_static_value(v: &EncodedValue, dex: &DexFile) -> StaticValue {
842 match v {
843 EncodedValue::Byte(x) => StaticValue::Int(*x as i64),
844 EncodedValue::Short(x) => StaticValue::Int(*x as i64),
845 EncodedValue::Char(x) => StaticValue::Int(*x as i64),
846 EncodedValue::Int(x) => StaticValue::Int(*x as i64),
847 EncodedValue::Long(x) => StaticValue::Int(*x),
848 EncodedValue::Float(x) => StaticValue::Float(*x),
849 EncodedValue::Double(x) => StaticValue::Double(*x),
850 EncodedValue::String(i) => StaticValue::Str(dex.string(*i).to_string()),
851 EncodedValue::Type(i) => StaticValue::Type(dex.class_name(*i)),
852 EncodedValue::Boolean(b) => StaticValue::Boolean(*b),
853 EncodedValue::Null => StaticValue::Null,
854 EncodedValue::Enum(i) | EncodedValue::Field(i) => {
855 let f = dex.field(*i);
856 StaticValue::Field(
857 dex.class_name(f.class_idx),
858 dex.string(f.name_idx).to_string(),
859 dex.type_name(f.type_idx).to_string(),
860 )
861 }
862 _ => StaticValue::Other,
863 }
864}
865
866fn pool_class_of(dex: &DexFile, raw: &[u8], cd: &ClassDef, dex_idx: usize) -> PoolClass {
867 let name = dex.class_name(cd.class_idx);
868 let super_name = if cd.superclass_idx == ddc_dex::NO_INDEX {
869 None
870 } else {
871 let s = dex.class_name(cd.superclass_idx);
872 if s.is_empty() || s == "java/lang/Object" {
873 None
874 } else {
875 Some(s)
876 }
877 };
878 let interfaces = dex
879 .interfaces_of(cd)
880 .into_iter()
881 .map(|t| dex.class_name(t))
882 .collect();
883 let source_file = if cd.source_file_idx == ddc_dex::NO_INDEX {
884 None
885 } else {
886 Some(dex.string(cd.source_file_idx).to_string())
887 };
888
889 let data = dex.class_data(cd);
890 let mk_field = |ef: &ddc_dex::EncodedField, is_static: bool| {
891 let f = dex.field(ef.field_idx);
892 PoolField {
893 name: dex.string(f.name_idx).to_string(),
894 desc: dex.type_name(f.type_idx).to_string(),
895 access: ef.access_flags,
896 is_static,
897 }
898 };
899 let static_fields: Vec<PoolField> = data
900 .static_fields
901 .iter()
902 .map(|f| mk_field(f, true))
903 .collect();
904 let instance_fields: Vec<PoolField> = data
905 .instance_fields
906 .iter()
907 .map(|f| mk_field(f, false))
908 .collect();
909 let mk_method = |em: &ddc_dex::EncodedMethod| {
910 let m = dex.method(em.method_idx);
911 let (code_off, debug_info_off) = match dex.debug_info_off_at(em.code_off) {
912 Some(d) => (em.code_off, d),
913 None => (0, 0),
914 };
915 PoolMethod {
916 name: dex.string_arc(m.name_idx),
917 desc: dex.proto_desc(m.proto_idx),
918 access: em.access_flags,
919 code_off,
920 debug_info_off,
921 dex_idx,
922 }
923 };
924 let direct_methods: Vec<PoolMethod> = data.direct_methods.iter().map(&mk_method).collect();
925 let virtual_methods: Vec<PoolMethod> = data.virtual_methods.iter().map(&mk_method).collect();
926
927 let static_values: Vec<StaticValue> = dex
928 .static_values(cd.static_values_off)
929 .into_iter()
930 .map(|v| resolve_static_value(&v, dex))
931 .collect();
932 let anns = if cd.annotations_off != 0 {
933 annotations::read_class_annotations(raw, cd.annotations_off)
934 } else {
935 Vec::new()
936 };
937 let raw = annotations::nesting_from(&anns, &|t: u32| dex.type_name(t).to_string());
938 let nesting = ResolvedNesting {
939 enclosing_class: raw.enclosing_class.map(|t| dex.class_name(t)),
940 enclosing_method: raw.enclosing_method.map(|m| {
941 let mid = dex.method(m);
942 (
943 dex.class_name(mid.class_idx),
944 dex.string(mid.name_idx).to_string(),
945 )
946 }),
947 member_classes: raw
948 .member_classes
949 .into_iter()
950 .map(|t| dex.class_name(t))
951 .collect(),
952 };
953
954 PoolClass {
955 name,
956 access: cd.access_flags,
957 super_name,
958 interfaces,
959 source_file,
960 static_fields,
961 instance_fields,
962 direct_methods,
963 virtual_methods,
964 static_values,
965 nesting,
966 dex_idx,
967 }
968}
969
970/// JavaType for a field/method descriptor segment.
971/// Parse a proto's descriptor into a MethodDescriptor straight from the
972/// tables (no string round-trip).
973fn parse_proto_desc(
974 dex: &ddc_dex::DexFile,
975 proto_idx: u32,
976) -> jdc_core::types::MethodDescriptor {
977 let proto = dex.proto(proto_idx);
978 let args = dex
979 .proto_params(proto_idx)
980 .iter()
981 .map(|&t| desc_type(dex.type_name(t)))
982 .collect();
983 jdc_core::types::MethodDescriptor {
984 args,
985 ret: desc_type(dex.type_name(proto.return_type_idx)),
986 }
987}
988
989pub fn desc_type(desc: &str) -> JavaType {
990 parse_field_descriptor(desc).unwrap_or(JavaType::Object("java/lang/Object".into()))
991}
992
993/// Nesting evidence for `internal`: dalvik annotations first, then the
994/// `$`-name heuristic against the pool.
995pub fn find_outer_name(pool: &DexPool, internal: &str) -> Option<String> {
996 // Annotation refinement only for ALREADY-MATERIALIZED classes: eager
997 // pools (full decompile) behave exactly as before; lazy pools
998 // (progressive getclass) fall straight to the `$` chain without
999 // materializing the world.
1000 if let Some(pc) = pool.get_if_materialized(internal) {
1001 if let Some(enc) = &pc.nesting.enclosing_class {
1002 // The annotation outer must still EXIST: R8 deletes whole
1003 // outer classes and leaves the nestlings as flat `$` files
1004 // (weixin matrix JiffiesMonitorFeature deleted,
1005 // $JiffiesSnapshot survives) — an unresolved annotation
1006 // outer made refs render dotted THROUGH a missing type
1007 // ("是在不可访问的类或接口中定义的"). Fall through to the
1008 // existence-checked `$` walk.
1009 if pool.has_name(enc) {
1010 return Some(enc.clone());
1011 }
1012 }
1013 }
1014 let mut rest = internal;
1015 while let Some(d) = rest.rfind('$') {
1016 // A `$` followed by `/` is a PACKAGE-path dollar (desugar's
1017 // `j$/util/...`), never a nesting boundary: without this the
1018 // whole j$ tree attached to a root-package class `j` as family
1019 // members (deepseek's 62k-line j.java absorbing 549 desugar
1020 // classes, double-emitted against their flat j$/ files).
1021 if rest.as_bytes().get(d + 1) == Some(&b'/') {
1022 rest = &rest[..d];
1023 continue;
1024 }
1025 let cand = &rest[..d];
1026 if pool.has_name(cand) {
1027 return Some(cand.to_string());
1028 }
1029 rest = cand;
1030 }
1031 None
1032}
1033
1034/// True when the `$` tail names a plain member class (not anonymous/local/
1035/// lambda), i.e. the class renders inside its outer's compilation unit.
1036fn clean_member_tail(rest: &str) -> bool {
1037 if rest.starts_with('-') {
1038 return false;
1039 }
1040 // A member tail can never contain `/` — that is a package-path
1041 // fragment from a package-dollar name (`j$/util/X` stripped against
1042 // a root class `j`); defensive backstop for the find_outer_name
1043 // guard.
1044 if rest.contains('/') {
1045 return false;
1046 }
1047 // d8's synthetic outline/lambda/backport classes (`X$$ExternalSynthetic…`)
1048 // are TOP-LEVEL synthetics, not nested members: `$$` is d8's marker, and
1049 // find_outer_name's `$`-chain walk mistakes them for children of `X`.
1050 // Emitting them nested strands every cross-package reference on a bare
1051 // simple name ("找不到符号 变量 ExternalSyntheticBackportWithForwarding0",
1052 // weibo ×467). Targeted at `ExternalSynthetic` only — Kotlin's
1053 // `$$serializer` / `$$delegate` stay nested members.
1054 if rest.starts_with("$ExternalSynthetic") {
1055 return false;
1056 }
1057 let tail = rest.rsplit('$').next().unwrap_or(rest);
1058 if tail.is_empty() || tail.starts_with(|c: char| c.is_ascii_digit()) {
1059 return false;
1060 }
1061 true
1062}
1063
1064/// Classes to emit as their own compilation units: top-level classes plus
1065/// anonymous/local/lambda-shaped ones (clean members render inline).
1066impl DexPool {
1067 /// Arm image retirement (full-decompile driver only): count one
1068 /// pending class per image by pool ownership.
1069 /// Snapshot every synthetic-static accessor body (the exact predicate
1070 /// `inline_accessors` uses) as RAW code_item bytes, so cross-image
1071 /// accessor reads during worker runs survive image retirement.
1072 /// Call AFTER materialization and BEFORE `arm_retirement`; idempotent
1073 /// (first fill wins). Raw memcpy, no decode — accessors are numerous
1074 /// (weixin ~100k) but only a fraction are ever inlined, so decoding
1075 /// stays lazy at the use site. The slice bound covers the fixed
1076 /// header + insns + try items with generous handler slack (accessor
1077 /// tries are vanishingly rare; the snapshot is a deterministic
1078 /// function of the image either way).
1079 pub fn snapshot_accessor_code(&self) {
1080 let mut snap: AccessorSnapshots = HashMap::default();
1081 let mut bytes_total = 0usize;
1082 for name in &self.order {
1083 let Some(pc) = self.get_if_materialized(name) else {
1084 continue;
1085 };
1086 for m in pc.direct_methods.iter().chain(pc.virtual_methods.iter()) {
1087 if m.code_off == 0
1088 || !m.is_static()
1089 || m.access & crate::access::ACC_SYNTHETIC == 0
1090 {
1091 continue;
1092 }
1093 if snap.contains_key(&(m.dex_idx, m.code_off)) {
1094 continue;
1095 }
1096 let Some(dex) = self.dex(m.dex_idx) else {
1097 continue;
1098 };
1099 let raw = dex.raw();
1100 let off = m.code_off as usize;
1101 if off + 16 > raw.len() {
1102 continue;
1103 }
1104 let u2 = |o: usize| u16::from_le_bytes([raw[o], raw[o + 1]]) as usize;
1105 let u4 = |o: usize| {
1106 u32::from_le_bytes([raw[o], raw[o + 1], raw[o + 2], raw[o + 3]]) as usize
1107 };
1108 let tries = u2(off + 6);
1109 let insns = u4(off + 12);
1110 let mut end = off + 16 + 2 * insns;
1111 if tries > 0 {
1112 // pad to 4-align + try_item[tries] + handler blobs
1113 // (uleb-coded; slack covers realistic accessor shapes).
1114 end = end.next_multiple_of(4) + 8 * tries + 256 + 64 * tries;
1115 }
1116 let end = end.min(raw.len());
1117 let slice: std::sync::Arc<[u8]> = raw[off..end].into();
1118 bytes_total += slice.len();
1119 snap.insert((m.dex_idx, m.code_off), slice);
1120 }
1121 }
1122 if std::env::var("DDC_WALL").is_ok() {
1123 eprintln!(
1124 "[wall] accessor snapshot: {} entries, {} KB",
1125 snap.len(),
1126 bytes_total / 1024
1127 );
1128 }
1129 let _ = self.accessor_code.set(snap);
1130 }
1131
1132 /// Snapshotted accessor code_item bytes, when the snapshot was taken.
1133 /// Parse with `CodeItem::parse(&bytes, 0)`.
1134 pub fn accessor_code(&self, dex_idx: usize, code_off: u32) -> Option<std::sync::Arc<[u8]>> {
1135 self.accessor_code.get()?.get(&(dex_idx, code_off)).cloned()
1136 }
1137
1138 pub fn arm_retirement(&self) {
1139 self.retire_armed
1140 .store(true, std::sync::atomic::Ordering::Release);
1141 let mut counts = self.retire_counts.lock().unwrap();
1142 for c in counts.iter_mut() {
1143 *c = 0;
1144 }
1145 for entry in self.classes.values() {
1146 let di = match entry {
1147 ClassEntry::Eager(pc) => pc.dex_idx,
1148 ClassEntry::Lazy { at, .. } => at.0,
1149 };
1150 if let Some(c) = counts.get_mut(di) {
1151 *c += 1;
1152 }
1153 }
1154 }
1155
1156 /// Report one class finished; Some(image) when it was the image's
1157 /// last class (driver batches these into release_images).
1158 pub fn report_class_done(&self, class_name: &str) -> Option<usize> {
1159 if !self.retire_armed.load(std::sync::atomic::Ordering::Acquire) {
1160 return None;
1161 }
1162 let entry = self.classes.get(class_name)?;
1163 let di = match entry {
1164 ClassEntry::Eager(pc) => pc.dex_idx,
1165 ClassEntry::Lazy { at, .. } => at.0,
1166 };
1167 let mut counts = self.retire_counts.lock().unwrap();
1168 match counts.get_mut(di) {
1169 Some(c) => {
1170 *c = c.saturating_sub(1);
1171 if *c == 0 {
1172 Some(di)
1173 } else {
1174 None
1175 }
1176 }
1177 None => None,
1178 }
1179 }
1180
1181 /// Release the images' inflated bytes. Safe: the driver calls this
1182 /// only when every class of each image is emitted or failed; new
1183 /// `dex()` snapshots still work (tables valid, code accessors empty).
1184 pub fn release_images(&self, indexes: &[usize]) {
1185 let mut counts = self.retire_counts.lock().unwrap();
1186 for &i in indexes {
1187 if let Some(dex) = self.dexes.get(i) {
1188 // Mark the shared image: code accessors go empty
1189 // immediately; the bytes drop when the last snapshot
1190 // drops (workers hold snapshots only mid-class).
1191 dex.mark_released();
1192 }
1193 if let Some(c) = counts.get_mut(i) {
1194 *c = u64::MAX; // released marker
1195 }
1196 }
1197 }
1198}
1199
1200pub fn top_level_classes(pool: &DexPool) -> Vec<String> {
1201 pool.class_names()
1202 .filter(|name| match pool.outer_of(name) {
1203 None => true,
1204 Some(outer) => {
1205 if pool.get(outer).is_none() {
1206 return true;
1207 }
1208 // The outer can come from an ANNOTATION (EnclosingClass)
1209 // with no naming relationship to this class — obfuscated
1210 // apps pair a 1-char name with a long enclosing descriptor
1211 // (weixin), which made the old blind slice panic. Only a
1212 // real `outer$tail` prefix yields a member tail; anything
1213 // else is a standalone unit.
1214 let rest = name
1215 .strip_prefix(outer)
1216 .and_then(|t| t.strip_prefix('$'))
1217 .unwrap_or("");
1218 !clean_member_tail(rest)
1219 }
1220 })
1221 .map(|n| n.to_string())
1222 .collect()
1223}
1224
1225/// Sanitized form of one internal-name segment — the shared mapping the
1226/// declaration site (`print_class_name` → `sanitize_ref`), the CLASS
1227/// lookup and the CLI writer must all agree on. Exported so the writer
1228/// cannot drift from the declaration (see `sanitize_fq`).
1229pub fn sanitize_seg(seg: &str) -> String {
1230 classdec::sanitize_fq(seg)
1231}
1232
1233/// Sanitized internal PATH form of a class name: the exact on-disk
1234/// identity `source_path` writes and the declaration claims.
1235pub fn sanitize_internal(internal: &str) -> String {
1236 internal
1237 .split('/')
1238 .map(classdec::sanitize_fq)
1239 .collect::<Vec<_>>()
1240 .join("/")
1241}
1242
1243/// Deterministic case-collision renames over the FILE-emission set:
1244/// classes whose internal names differ only in letter case cannot share
1245/// one case-insensitive directory; the first (sorted) member of each
1246/// group keeps its name, the others gain `_2`, `_3`, … on the simple
1247/// segment. The map carries identity entries for unrenamed file-level
1248/// classes (they anchor nested prefix walks in apply_class_rename).
1249pub fn case_rename_map(pool: &DexPool) -> HashMap<String, String> {
1250 use std::collections::HashMap;
1251 let mut groups: HashMap<String, Vec<String>> = HashMap::default();
1252 for t in top_level_classes(pool) {
1253 groups.entry(t.to_lowercase()).or_default().push(t);
1254 }
1255 let folds: std::collections::HashSet<String> = groups.keys().cloned().collect();
1256 let mut map = HashMap::default();
1257 for (_, mut members) in groups {
1258 members.sort();
1259 for (i, m) in members.iter().enumerate() {
1260 if i == 0 {
1261 map.insert(m.clone(), m.clone());
1262 continue;
1263 }
1264 // Suffix the simple segment; keep incrementing if the fold
1265 // of the suffixed name is already taken by a real class.
1266 let cut = m.rfind('/').map(|x| x + 1).unwrap_or(0);
1267 let mut n = i + 1;
1268 loop {
1269 let cand = format!("{}{}_{}", &m[..cut], &m[cut..], n);
1270 let fold = cand.to_lowercase();
1271 if !folds.contains(&fold) {
1272 map.insert(m.clone(), cand);
1273 break;
1274 }
1275 n += 1;
1276 }
1277 }
1278 }
1279 map
1280}
1281
1282/// Display-level renames for two nested-class shapes that render
1283/// uncompilable or inconsistent output:
1284///
1285/// 1. A member class whose simple tail equals its rendered parent's
1286/// tail (`x0$a$a` inside `x0$a`): javac rejects a member class with
1287/// the same simple name as its immediately enclosing class ("已在类
1288/// x0中定义了类 x0.a") — a shape Kotlin lambda families hit by the
1289/// thousand (lark alone: 22k). Bump the tail: `a` → `a2`, `a3`, …
1290/// 2. An orphaned intermediate (`x0$a$b` with `x0$a` absent from the
1291/// pool): the member DECLARES as `b` inside `x0` but references
1292/// printed `x0.a$b` — a type that exists nowhere. Flatten the
1293/// display name to `x0$b` so every site agrees.
1294///
1295/// Both are pure display renames keyed by internal name; declarations,
1296/// ctor names, file names and every type reference funnel through
1297/// apply_class_rename, so one map keeps all sites consistent. Children
1298/// Display-level renames for nested member classes that render
1299/// uncompilable or inconsistent output:
1300///
1301/// 1. A member whose simple tail equals ANY enclosing class's simple
1302/// name in its nesting chain. javac rejects more than the immediate
1303/// parent (`class a { static class a2 { static class a {} } }` —
1304/// member `a` two levels under `a` — is "已在类 X中定义了类 X.a");
1305/// Kotlin lambda families (`x0$a$a` inside `x0$a`) hit it by the
1306/// thousand (lark alone: 22k). Bump the tail until it clears every
1307/// ancestor name: `a` → `a3`.
1308/// 2. An orphaned intermediate (`x0$a$b` with `x0$a` absent): the
1309/// member DECLARES as `b` inside `x0` but references printed
1310/// `x0.a$b` — a type that exists nowhere. Flatten the display to
1311/// `x0$b` so every site agrees.
1312///
1313/// Candidates build on the parent's DISPLAY name (ancestors are
1314/// renamed first — ascending `$`-depth order), so declarations,
1315/// constructor names, file names and every type reference stay
1316/// consistent through apply_class_rename. All are pure display
1317/// renames keyed by internal name.
1318/// In-progress-map display composition, mirroring
1319/// `rename::apply_class_rename`'s ancestor walk (the registry is not
1320/// installed yet during map construction, so mint rules must compose
1321/// through renamed ancestors themselves). A nested name whose DIRECT
1322/// parent has no entry still inherits every renamed higher prefix:
1323/// grandparent `yN5` -> `yN5_3` must turn minted `yN5$a$a2` into
1324/// `yN5_3$a$a2` (xingye case-quads: the raw-prefix entry short-
1325/// circuited the render walk — 程序包ddcroot.yN5.a不存在 ×134-family).
1326fn display_of(name: &str, map: &HashMap<String, String>) -> String {
1327 // EXACT hit first — the walk truncates the full name before ever
1328 // consulting it, and an identity entry on an ancestor prefix
1329 // (case_rename_map seeds those for every fold-group first member)
1330 // would short-circuit to the raw name (lark aa2/d$c17 minted, then
1331 // aa2/d$c$a composed against the identity of aa2/d — the child
1332 // stranded on the dead `c` prefix, 找不到符号 类 a ×1,874).
1333 if let Some(d) = map.get(name) {
1334 return d.clone();
1335 }
1336 let mut s = name;
1337 while let Some(i) = s.rfind('$') {
1338 s = &s[..i];
1339 match map.get(s) {
1340 Some(d) if d.as_str() != s => return format!("{d}{}", &name[s.len()..]),
1341 Some(_) => return name.to_string(),
1342 None => continue,
1343 }
1344 }
1345 map.get(name).cloned().unwrap_or_else(|| name.to_string())
1346}
1347
1348fn nested_collision_renames(
1349 pool: &DexPool,
1350 map: &mut HashMap<String, String>,
1351 fam_segs: &SegMap,
1352) {
1353 // Ancestors before descendants: a parent's rename must be in the
1354 // map when its children compute their display chains.
1355 let mut names: Vec<&String> = pool.order.iter().collect();
1356 names.sort_by_key(|n| n.matches('$').count());
1357 let mut assigned: jdc_core::FxHashSet<String> = jdc_core::FxHashSet::default();
1358 // Top-level package segments. A nested member type DISPLAYED as `a2`
1359 // shadows package `a2` for every qualified `a2.x` reference in its
1360 // file (member types outrank package names in class scope), so a
1361 // renamed tail must not become a package shadow — round 47's failure
1362 // mode at nested level: candidate `a2` (for j2/g$a) broke the SAME
1363 // file's `extends a2.a` ("找不到符号 类 a" + a 9450-error Object
1364 // cascade as every dependent of the corrupt head failed too).
1365 let mut pkg_segments: jdc_core::FxHashSet<String> = jdc_core::FxHashSet::default();
1366 for n in &pool.order {
1367 if let Some((seg, _)) = n.split_once('/') {
1368 pkg_segments.insert(seg.to_string());
1369 }
1370 }
1371 // LOCAL-OK gate (round-59 Design B): a field-obscuring rename may
1372 // only fire when every class referencing the candidate lives inside
1373 // the root file's family, so the rename perturbs exactly ONE rendered
1374 // file. Ungated (Design A) the rule netted reqable −1653 / lark −5221
1375 // but weibo +36916: renames there flipped ambiguous type-vs-package
1376 // resolutions across thousands of pre-existing conflict families and
1377 // javac's error recovery turned "missing supertype, body suppressed"
1378 // files into full Object cascades. Lazy (progressive-browse) pools
1379 // skip the gate AND the rule — the multi-second image scan must not
1380 // stall single-class queries; the full-decompile pipeline always
1381 // materializes everything before installing renames.
1382 // Round-59 Design B stands: ungated field-clash renames were
1383 // retried AFTER the package-obscuring rules landed (weibo gate,
1384 // DDC_FC_UNGATED A/B) and still exploded to the 500k error cap —
1385 // fifth falsification of the ungated rename route.
1386 let local_ok: jdc_core::FxHashSet<String> = if pool_majority_materialized(pool) {
1387 refscan::local_ok(&pool.dexes, &field_clash_cands(pool, map))
1388 } else {
1389 jdc_core::FxHashSet::default()
1390 };
1391 let mut taken_sibling_displays: jdc_core::FxHashSet<String> =
1392 map.values().cloned().collect();
1393 // Stage-2 queue: nested tails equal to a top-level package segment
1394 // whose family showed NO descriptor-level trigger — the victim ref
1395 // may live in method bodies only (weixin e32/a2's `a.b.c()` bound
1396 // to its own nested `class a`, 位置: 类 a ×169).
1397 let mut body_cands: Vec<(String, String, String)> = Vec::new();
1398 for name in names {
1399 if !name.contains('$') || map.contains_key(name) {
1400 continue;
1401 }
1402 let Some(parent) = find_outer_name(pool, name) else {
1403 continue;
1404 };
1405 // Only a REAL `parent$rest` name renders as an inline member;
1406 // anonymous/local/lambda tails keep their flat own-file names.
1407 let Some(rest) = name
1408 .strip_prefix(parent.as_str())
1409 .and_then(|t| t.strip_prefix('$'))
1410 else {
1411 continue;
1412 };
1413 if !clean_member_tail(rest) {
1414 continue;
1415 }
1416 // Display simple names of every enclosing level, bottom-up; `cur`
1417 // ends at the ROOT (the top-level class whose file renders this
1418 // nested type — the scope the renamed tail lives in).
1419 let mut chain: Vec<String> = Vec::new();
1420 let mut cur = parent.clone();
1421 loop {
1422 let disp = map.get(&cur).cloned().unwrap_or_else(|| cur.clone());
1423 let simple = disp.rsplit('/').next().unwrap_or(&disp);
1424 chain.push(simple.rsplit('$').next().unwrap_or(simple).to_string());
1425 match find_outer_name(pool, &cur) {
1426 Some(o) if o != cur => cur = o,
1427 _ => break,
1428 }
1429 }
1430 let root: &str = &cur;
1431 let disp_parent = display_of(&parent, map);
1432 let tail = rest.rsplit('$').next().unwrap_or(rest);
1433 let orphan = rest.contains('$');
1434 // Field obscuring (JLS 6.4.2): a nested type whose simple name
1435 // equals an enclosing-class field is OBSCURED by it in a
1436 // `<Parent>.<tail>` qualified reference — `io/flutter/view/g$i`
1437 // (a `static enum i`) renders `g.i.t`, but g also declares an
1438 // instance field `i`, so javac resolves `g.i` to the field:
1439 // "无法从静态上下文中引用非静态 变量 i" (975 of 1140 reqable
1440 // static-context errors). The fix renames the NESTED TYPE (the
1441 // registry carries every render path: shorten, inner_simple —
1442 // whose bypass was the round-55 blowup, fixed in jdc-core —
1443 // classdec declarations), gated to LOCAL-OK candidates by the
1444 // refscan above. PoC: in-file rename of flutter g's `enum i`
1445 // took the class from 2452 errors to 1.
1446 let field_clash = local_ok.contains(name.as_str());
1447 // Package shadow (JLS 6.4.2 at nested level): a nested type
1448 // DISPLAYED with a simple name equal to the first segment of a
1449 // package its FAMILY references binds every `s.x` qualified ref
1450 // in the root file to the member type — the family's own outer
1451 // rename can EXPOSE this (e/b → e/b2 un-collided the nested `b`,
1452 // which then hijacked `b.b2` — 循环继承). The round-47 candidate
1453 // guard only kept RENAMED tails off package segments; pre-
1454 // existing shadows need the rename too, family-gated: fire only
1455 // when this family's own descriptors reference the segment.
1456 // Orphans INCLUDED: an `Outer$$x` orphan normalizes to the
1457 // nested display `x` (k=1 invisible rename), and a clean tail
1458 // renders BARE in the family file — same package shadow as a
1459 // true nested (weixin li/u0$$r → `class r` hijacked `r.a` for
1460 // root package r).
1461 let pkg_shadow = fam_segs
1462 .get(root)
1463 .is_some_and(|segs| segs.contains(tail));
1464 let clash = chain.iter().any(|c| c == tail) || field_clash || pkg_shadow;
1465 // Stage-2 queue: NO descriptor trigger, but the tail equals a
1466 // top-level package segment — the victim ref may be body-level
1467 // only. ORPHANS included: their pass-1 k=1 mint is the invisible
1468 // normalization (`a$$a` → display `a`), which leaves the package
1469 // shadow fully alive (weixin e32/a$$a hijacking `a.b.c()` ×169).
1470 if !clash && pkg_segments.contains(tail) {
1471 body_cands.push((name.clone(), root.to_string(), tail.to_string()));
1472 }
1473 if !orphan && !clash {
1474 continue;
1475 }
1476 // The enclosing class's field names (sanitized like the renderer)
1477 // — only needed once a rename actually fires, to keep the new
1478 // tail from being obscured again. Computed lazily so progressive
1479 // pools don't materialize parents for rules that don't rename.
1480 let mut enc_fields: jdc_core::FxHashSet<String> = jdc_core::FxHashSet::default();
1481 if field_clash || pkg_shadow {
1482 if let Some(pc) = pool.get(&parent) {
1483 for f in pc.static_fields.iter().chain(pc.instance_fields.iter()) {
1484 enc_fields.insert(crate::classdec::java_ident(&f.name).into_owned());
1485 }
1486 }
1487 }
1488 let mut k = 0u32;
1489 loop {
1490 k += 1;
1491 let cand_tail = if k == 1 {
1492 tail.to_string()
1493 } else {
1494 format!("{tail}{k}")
1495 };
1496 // The candidate must clear every ancestor display name (javac
1497 // checks the whole chain) AND every enclosing field name (else
1498 // the renamed type is just obscured again). Sibling nested
1499 // tails are covered by the pool.has_name check below.
1500 if chain.contains(&cand_tail) || enc_fields.contains(&cand_tail) {
1501 continue;
1502 }
1503 // Package shadow: the renamed tail becomes a member type of
1504 // the root file's class, outranking any package of the same
1505 // name for qualified refs in that file. Same-package top-level
1506 // classes likewise outrank-then-break in-file simple refs.
1507 // BOTH checks apply to field-clash renames only: for the
1508 // orphan rule the k=1 candidate is the natural display name
1509 // (`g0$$r` → `g0$r` renders identically — an invisible rename),
1510 // and rejecting it forced weixin's whole `g0$$X` Runnable
1511 // family to visible `X17` renames, breaking every lucky
1512 // `g0.r`-style resolution corpus-wide (+2911 `变量 r` — the
1513 // orphan rule is ungated by design, predating LOCAL-OK).
1514 if field_clash || pkg_shadow {
1515 if pkg_segments.contains(&cand_tail) {
1516 continue;
1517 }
1518 if pkg_shadow
1519 && fam_segs
1520 .get(root)
1521 .is_some_and(|segs| segs.contains(cand_tail.as_str()))
1522 {
1523 continue;
1524 }
1525 if let Some((root_pkg, _)) = root.rsplit_once('/') {
1526 let sib = format!("{root_pkg}/{cand_tail}");
1527 if pool.has_name(&sib) || taken_sibling_displays.contains(&sib)
1528 {
1529 // A top-level sibling exists — or an EARLIER rule
1530 // minted that display (obscuring_class_renames
1531 // moved ssosdk/b → ssosdk/b2 while this loop was
1532 // about to mint nested $b → b2: two `b2`s in one
1533 // scope, member type outranks the package sibling
1534 // and hijacked every bare `b2.b(..)` call).
1535 continue;
1536 }
1537 taken_sibling_displays.insert(sib);
1538 }
1539 }
1540 let cand = format!("{disp_parent}${cand_tail}");
1541 if pool.has_name(&cand) || assigned.contains(&cand) {
1542 continue;
1543 }
1544 assigned.insert(cand.clone());
1545 map.insert(name.clone(), cand);
1546 break;
1547 }
1548 }
1549 // Stage 2 (body-gated package shadow): one body-level image scan
1550 // over the queued families (family_ref_segments — the field-
1551 // deshadow mechanism; instruction-level, cross-package refs), then
1552 // mint for the families whose members actually reference the
1553 // segment. Mirrors obscuring_class_renames' two-stage design at
1554 // family level. Lazy pools skip (same gate as stage 1's scan).
1555 let mut body_renamed = 0usize;
1556 if !body_cands.is_empty() && pool_majority_materialized(pool) {
1557 let roots: jdc_core::FxHashSet<&str> =
1558 body_cands.iter().map(|(_, r, _)| r.as_str()).collect();
1559 let mut members: jdc_core::FxHashSet<String> = jdc_core::FxHashSet::default();
1560 for n in &pool.order {
1561 let r = match n.find('$') {
1562 Some(i) => &n[..i],
1563 None => n.as_str(),
1564 };
1565 if roots.contains(r) {
1566 members.insert(n.clone());
1567 }
1568 }
1569 let t0 = std::time::Instant::now();
1570 let (by_referrer, _) = refscan::family_ref_segments(&pool.dexes, &members);
1571 // Referrer-keyed → family-root-keyed: every member renders in
1572 // the root file's scope.
1573 let mut root_segs: jdc_core::FxHashMap<&str, jdc_core::FxHashSet<&str>> =
1574 jdc_core::FxHashMap::default();
1575 for (referrer, segs) in &by_referrer {
1576 let r = referrer.split('$').next().unwrap_or(referrer);
1577 root_segs.entry(r).or_default().extend(segs.iter().map(|s| s.as_str()));
1578 }
1579 if std::env::var("DDC_STATS").is_ok() {
1580 eprintln!(
1581 "[renames] nested body-shadow scan: cands={} families={} scan={:?}",
1582 body_cands.len(),
1583 root_segs.len(),
1584 t0.elapsed()
1585 );
1586 }
1587 for (name, root, tail) in &body_cands {
1588 if !root_segs
1589 .get(root.as_str())
1590 .is_some_and(|s| s.contains(tail.as_str()))
1591 {
1592 continue;
1593 }
1594 if let Some(d) = map.get(name) {
1595 // Pass-1 orphan mints are invisible (display tail ==
1596 // tail) — those get re-minted visibly here. Anything
1597 // already visibly renamed stays as the earlier rule set it.
1598 let cur_tail = d.rsplit(['/', '$']).next().unwrap_or("");
1599 if cur_tail != tail.as_str() {
1600 continue;
1601 }
1602 }
1603 // Fresh display context: stage-1 renames may have moved the
1604 // parent/chain since this candidate was queued.
1605 let Some(parent) = find_outer_name(pool, name) else {
1606 continue;
1607 };
1608 let Some(rest) = name
1609 .strip_prefix(parent.as_str())
1610 .and_then(|t| t.strip_prefix('$'))
1611 else {
1612 continue;
1613 };
1614 if !clean_member_tail(rest) {
1615 continue;
1616 }
1617 let mut chain: Vec<String> = Vec::new();
1618 let mut cur = parent.clone();
1619 loop {
1620 let disp = map.get(&cur).cloned().unwrap_or_else(|| cur.clone());
1621 let simple = disp.rsplit('/').next().unwrap_or(&disp);
1622 chain.push(simple.rsplit('$').next().unwrap_or(simple).to_string());
1623 match find_outer_name(pool, &cur) {
1624 Some(o) if o != cur => cur = o,
1625 _ => break,
1626 }
1627 }
1628 let disp_parent = display_of(&parent, map);
1629 let mut enc_fields: jdc_core::FxHashSet<String> =
1630 jdc_core::FxHashSet::default();
1631 if let Some(pc) = pool.get(&parent) {
1632 for f in pc.static_fields.iter().chain(pc.instance_fields.iter()) {
1633 enc_fields.insert(crate::classdec::java_ident(&f.name).into_owned());
1634 }
1635 }
1636 let mut k = 0u32;
1637 loop {
1638 k += 1;
1639 let cand_tail = if k == 1 {
1640 tail.clone()
1641 } else {
1642 format!("{tail}{k}")
1643 };
1644 if chain.contains(&cand_tail) || enc_fields.contains(&cand_tail) {
1645 continue;
1646 }
1647 // The renamed tail stays a member type of the root
1648 // file — it must not shadow ANOTHER package segment the
1649 // family references (descriptor OR body level) nor a
1650 // same-package top-level sibling.
1651 if pkg_segments.contains(&cand_tail) {
1652 continue;
1653 }
1654 if fam_segs
1655 .get(root.as_str())
1656 .is_some_and(|segs| segs.contains(cand_tail.as_str()))
1657 {
1658 continue;
1659 }
1660 if root_segs
1661 .get(root.as_str())
1662 .is_some_and(|segs| segs.contains(cand_tail.as_str()))
1663 {
1664 continue;
1665 }
1666 if let Some((root_pkg, _)) = root.rsplit_once('/') {
1667 let sib = format!("{root_pkg}/{cand_tail}");
1668 if pool.has_name(&sib) || taken_sibling_displays.contains(&sib) {
1669 continue;
1670 }
1671 taken_sibling_displays.insert(sib);
1672 }
1673 let cand = format!("{disp_parent}${cand_tail}");
1674 if pool.has_name(&cand) || assigned.contains(&cand) {
1675 continue;
1676 }
1677 // Repair pass-1 mints whose display chain ran through
1678 // THIS name's old display: stage 2 renames ancestors
1679 // after descendants were minted (weibo mobileads k$a →
1680 // a5 left pass-1's k$a$b$a → "k$a$b$a2" pointing through
1681 // the dead `a` — 找不到符号 类 a ×48). Ancestor-first
1682 // within each pass, but stage 2 as a whole runs last.
1683 let old_disp = format!("{disp_parent}${tail}");
1684 if old_disp != cand {
1685 for (mk, mv) in map.iter_mut() {
1686 if mk == name {
1687 continue;
1688 }
1689 if let Some(rest) = mv.strip_prefix(old_disp.as_str()) {
1690 if rest.starts_with('$') {
1691 let repaired = format!("{cand}{rest}");
1692 assigned.insert(repaired.clone());
1693 *mv = repaired;
1694 }
1695 }
1696 }
1697 }
1698 assigned.insert(cand.clone());
1699 map.insert(name.clone(), cand);
1700 body_renamed += 1;
1701 break;
1702 }
1703 }
1704 }
1705 if body_renamed > 0 && std::env::var("DDC_STATS").is_ok() {
1706 eprintln!("[renames] nested body-shadow renames: {body_renamed}");
1707 }
1708}
1709
1710/// Field-obscuring rename candidates: nested member types whose simple
1711/// name equals a field of the enclosing class, mapped to the top-level
1712/// class whose file renders them (the LOCAL-OK family root). Mirrors the
1713/// skip conditions of `nested_collision_renames` (same-name entries must
1714/// agree, or the gate proves locality for a rename that never fires — or
1715/// worse, skips one that does).
1716fn field_clash_cands(pool: &DexPool, map: &HashMap<String, String>) -> HashMap<String, String> {
1717 let mut out: HashMap<String, String> = HashMap::default();
1718 for name in &pool.order {
1719 if !name.contains('$') || map.contains_key(name) {
1720 continue;
1721 }
1722 let Some(parent) = find_outer_name(pool, name) else {
1723 continue;
1724 };
1725 let Some(rest) = name
1726 .strip_prefix(parent.as_str())
1727 .and_then(|t| t.strip_prefix('$'))
1728 else {
1729 continue;
1730 };
1731 if !clean_member_tail(rest) {
1732 continue;
1733 }
1734 let tail = rest.rsplit('$').next().unwrap_or(rest);
1735 let Some(pc) = pool.get(&parent) else {
1736 continue;
1737 };
1738 let clash = pc
1739 .static_fields
1740 .iter()
1741 .chain(pc.instance_fields.iter())
1742 .any(|f| crate::classdec::java_ident(&f.name).as_ref() == tail);
1743 if !clash {
1744 continue;
1745 }
1746 let mut root = parent.clone();
1747 loop {
1748 match find_outer_name(pool, &root) {
1749 Some(o) if o != root => root = o,
1750 _ => break,
1751 }
1752 }
1753 out.insert(name.clone(), root);
1754 }
1755 out
1756}
1757
1758/// Whether the pool is (majority-)materialized: full-decompile pipelines
1759/// call `materialize_all` before installing renames, progressive browse
1760/// pools materialize a handful of classes on demand. The refscan gate
1761/// must not run (or stall startup) in the progressive case.
1762fn pool_majority_materialized(pool: &DexPool) -> bool {
1763 let (mut mat, mut lazy) = (0usize, 0usize);
1764 for e in pool.classes.values() {
1765 match e {
1766 ClassEntry::Eager(_) => mat += 1,
1767 ClassEntry::Lazy { pc, .. } => {
1768 if pc.get().is_some() {
1769 mat += 1;
1770 } else {
1771 lazy += 1;
1772 }
1773 }
1774 }
1775 }
1776 lazy == 0 || mat >= lazy
1777}
1778
1779/// Compute and install the registry (call before worker threads spawn).
1780pub fn install_case_renames(pool: &DexPool) {
1781 let mut map = case_rename_map(pool);
1782 // Cross-package reference first segments (descriptor level). Lazy
1783 // (progressive-browse) pools skip the scan — materializing every
1784 // class must not stall single-class queries; the obscuring rules
1785 // then simply never fire (browse mode has no whole-program javac).
1786 let (pkg_segs, fam_segs) = if pool_majority_materialized(pool) {
1787 ref_segments(pool)
1788 } else {
1789 (
1790 jdc_core::FxHashMap::default(),
1791 jdc_core::FxHashMap::default(),
1792 )
1793 };
1794 // Package-leaf shadows FIRST: the nested-collision renames compute
1795 // display chains off the (renamed) parent display names — running
1796 // them before the parent rename left both rules minting the same
1797 // display (`a2` twice in weibo's AIDL families).
1798 pkg_leaf_shadow_renames(pool, &mut map);
1799 class_pkg_collision_renames(pool, &mut map);
1800 obscuring_class_renames(pool, &mut map, &pkg_segs);
1801 nested_collision_renames(pool, &mut map, &fam_segs);
1802 // LAST: lossy-sanitize collisions key on the display form every rule
1803 // above has already settled (`l.᩻ܶ` → `l/__.java`, 22,636 classes onto
1804 // 3 paths on bin.mt.plus — the silent-overwrite data loss).
1805 lossy_sanitize_renames(pool, &mut map);
1806 // Default-package relocation keys on the settled displays too (it
1807 // PREFIXES them with the synthetic package) — runs after every
1808 // simple-name rule has minted.
1809 root_pkg_relocation(pool, &mut map);
1810 jdc_core::rename::set_class_renames(map);
1811 jdc_core::rename::set_field_renames(combined_field_renames(pool));
1812 if pool_majority_materialized(pool) {
1813 crate::classdec::install_access_widening(pool);
1814 }
1815}
1816
1817/// A top-level class `P/s` whose simple name equals the FIRST PACKAGE
1818/// SEGMENT of types that other classes in P reference cross-package.
1819/// Such a reference renders as the FQN `s.rest...`, and javac binds the
1820/// first segment to the nearest type in scope — the same-package class
1821/// `P/s` (JLS 6.4.2): `n91.f.a(x)` inside pc5/bd looks up member `f` OF
1822/// CLASS pc5.n91 (weixin's n0/n91/uc6/vc6 protobuf cluster: ~12k root
1823/// files, ~90k cascade lines; weibo's `a.g.b.a.b` chains root the same
1824/// way — class a beside subpackage a/ inside package a/g/b). No Java
1825/// syntax escapes an obscured first segment (imports can bypass it, but
1826/// single-type imports are blocked exactly where obfuscated leaf names
1827/// collide with same-package siblings), so the class moves: the r66
1828/// rename mechanism at a new trigger. Gated on DESCRIPTOR-level refs of
1829/// the candidate's own package (supers/fields/protos) — body-only refs
1830/// are missed by design; the import layer covers unblocked leaves there.
1831/// Descriptor-level cross-package reference first segments, aggregated
1832/// per PACKAGE (top-level obscurers: every file in P shares the scope)
1833/// and per FAMILY root (nested obscurers: a nested simple name is in
1834/// scope only inside its own root file). Raw `L..;` scans — no JavaType
1835/// parsing. Body-level refs are missed by design (the import layer
1836/// catches unblocked leaves there); descriptors cover supers, field
1837/// types and method protos — the header positions whose breakage starts
1838/// the error-type cascades.
1839/// Package (or family) → first segments of the cross-package types its
1840/// classes reference at descriptor level. Obscuring-rename trigger sets.
1841type SegMap<'a> = jdc_core::FxHashMap<&'a str, jdc_core::FxHashSet<&'a str>>;
1842
1843fn ref_segments(pool: &DexPool) -> (SegMap<'_>, SegMap<'_>) {
1844 fn pkg_of(n: &str) -> &str {
1845 match n.rsplit_once('/') {
1846 Some((p, _)) => p,
1847 None => "",
1848 }
1849 }
1850 fn note<'a>(
1851 pkg_segs: &mut jdc_core::FxHashMap<&'a str, jdc_core::FxHashSet<&'a str>>,
1852 fam_segs: &mut jdc_core::FxHashMap<&'a str, jdc_core::FxHashSet<&'a str>>,
1853 pkg: &'a str,
1854 fam: &'a str,
1855 t: &'a str,
1856 ) {
1857 if !t.contains('/') {
1858 return; // root-package target: unreferenceable from named pkgs
1859 }
1860 let _ = pkg; // same-package refs COUNT: ddc renders headers/field
1861 // types fully qualified (print_class_name), so `a.g.b.a.b`
1862 // inside package a/g/b is obscured by class a/g/b/a just
1863 // like a cross-package FQN (weibo's whole `a`-tree family).
1864 let seg = t.split('/').next().unwrap_or("");
1865 if !seg.is_empty() {
1866 pkg_segs.entry(pkg).or_default().insert(seg);
1867 fam_segs.entry(fam).or_default().insert(seg);
1868 }
1869 }
1870 fn scan<'a>(
1871 pkg_segs: &mut jdc_core::FxHashMap<&'a str, jdc_core::FxHashSet<&'a str>>,
1872 fam_segs: &mut jdc_core::FxHashMap<&'a str, jdc_core::FxHashSet<&'a str>>,
1873 pkg: &'a str,
1874 fam: &'a str,
1875 desc: &'a str,
1876 ) {
1877 let b = desc.as_bytes();
1878 let mut i = 0usize;
1879 while i < b.len() {
1880 if b[i] == b'L' {
1881 if let Some(end) = desc[i + 1..].find(';') {
1882 note(pkg_segs, fam_segs, pkg, fam, &desc[i + 1..i + 1 + end]);
1883 i += end + 2;
1884 continue;
1885 }
1886 }
1887 i += 1;
1888 }
1889 }
1890 let mut pkg_segs: jdc_core::FxHashMap<&str, jdc_core::FxHashSet<&str>> =
1891 jdc_core::FxHashMap::default();
1892 let mut fam_segs: jdc_core::FxHashMap<&str, jdc_core::FxHashSet<&str>> =
1893 jdc_core::FxHashMap::default();
1894 for name in &pool.order {
1895 let Some(c) = pool.get(name) else { continue };
1896 let pkg = pkg_of(name);
1897 let fam = match name.find('$') {
1898 Some(i) => &name[..i],
1899 None => name.as_str(),
1900 };
1901 if let Some(sup) = &c.super_name {
1902 note(&mut pkg_segs, &mut fam_segs, pkg, fam, sup);
1903 }
1904 for sup in c.interfaces.iter() {
1905 note(&mut pkg_segs, &mut fam_segs, pkg, fam, sup);
1906 }
1907 for f in c.static_fields.iter().chain(c.instance_fields.iter()) {
1908 scan(&mut pkg_segs, &mut fam_segs, pkg, fam, &f.desc);
1909 }
1910 for m in c.direct_methods.iter().chain(c.virtual_methods.iter()) {
1911 scan(&mut pkg_segs, &mut fam_segs, pkg, fam, &m.desc);
1912 }
1913 }
1914 (pkg_segs, fam_segs)
1915}
1916
1917/// A top-level class `P/s` whose simple name equals the FIRST PACKAGE
1918/// SEGMENT of types that classes in P reference cross-package. Such a
1919/// reference renders as the FQN `s.rest...`, and javac binds the first
1920/// segment to the nearest type in scope — the same-package class `P/s`
1921/// (JLS 6.4.2, no package fallback — verified): `n91.f.a(x)` inside
1922/// pc5/bd looks up member `f` OF CLASS pc5.n91 (weixin's n0/n91/uc6/vc6
1923/// protobuf cluster: ~12k root files, ~90k cascade lines; weibo's
1924/// `a.g.b.a.b` chains root the same way). No Java syntax escapes an
1925/// obscured first segment, so the class moves: the r66 rename mechanism
1926/// at a new trigger, gated on DESCRIPTOR-level refs of the candidate's
1927/// package (body-only refs go to the import layer). Nested obscurers
1928/// (a nested simple name shadowing a package inside its family file)
1929/// are the companion trigger in nested_collision_renames.
1930fn obscuring_class_renames(
1931 pool: &DexPool,
1932 map: &mut HashMap<String, String>,
1933 pkg_segs: &SegMap,
1934) {
1935 fn pkg_of(n: &str) -> &str {
1936 match n.rsplit_once('/') {
1937 Some((p, _)) => p,
1938 None => "",
1939 }
1940 }
1941 // Root package first segments (segments some class lives under).
1942 let mut root_segs: jdc_core::FxHashSet<&str> = jdc_core::FxHashSet::default();
1943 for n in &pool.order {
1944 if let Some(i) = n.find('/') {
1945 root_segs.insert(&n[..i]);
1946 }
1947 }
1948 let mut cands: Vec<&String> = Vec::new();
1949 for name in &pool.order {
1950 let simple = name.rsplit('/').next().unwrap_or(name);
1951 let pkg = pkg_of(name);
1952 if simple.is_empty() || simple.contains('$') || pkg.is_empty() {
1953 continue;
1954 }
1955 if !root_segs.contains(simple) {
1956 continue;
1957 }
1958 if map.get(name).is_some_and(|v| v != name) {
1959 continue; // an earlier rule moved it
1960 }
1961 // NB: NO "class lives under the s tree" exclusion. weibo's
1962 // a/a/b/c/l/a shadowed the FQN refs `a.a.a.a2` that its own
1963 // package files render for cross-subpackage targets (the
1964 // starts_with("a/") skip left the WHOLE a-tree unrenamed —
1965 // 找不到符号 类 a chains). The two-stage refsegs gates below
1966 // require an actual cross-package FQN ref for the trigger.
1967 cands.push(name);
1968 }
1969 let ncands = cands.len();
1970 if std::env::var("DDC_STATS").is_ok() {
1971 eprintln!(
1972 "[renames] obscuring candidates={ncands} pkgs-with-segs={}",
1973 pkg_segs.len()
1974 );
1975 }
1976 if cands.is_empty() {
1977 return;
1978 }
1979 // Fast collision oracle: sorted names + prefix range scan (the r66
1980 // candidate loop's `order.iter().any(starts_with)` is O(n) per
1981 // candidate — this rule can mint tens of thousands of renames).
1982 let mut sorted: Vec<&String> = pool.order.iter().collect();
1983 sorted.sort_unstable();
1984 let prefix_free = |cand: &str| -> bool {
1985 // No class named cand, nothing nested under cand$..., no package cand/...
1986 let idx = sorted.partition_point(|n| n.as_str() < cand);
1987 !sorted[idx..].first().is_some_and(|n| n.starts_with(cand))
1988 };
1989 let pkg_simples = pool.package_simples();
1990 let mut taken_displays: jdc_core::FxHashSet<String> = map.values().cloned().collect();
1991 let mut renamed = 0usize;
1992 // Stage 1: descriptor-level hits rename now; the rest queue for the
1993 // BODY-level image scan (weixin pc5's `invoke-static Ln91/f;.a` —
1994 // 7.8k+6.6k error lines the descriptor gate cannot see).
1995 let mut stage2: Vec<&String> = Vec::new();
1996 for name in cands {
1997 let pkg = pkg_of(name);
1998 let simple = name.rsplit('/').next().unwrap_or(name);
1999 if !pkg_segs.get(pkg).is_some_and(|segs| segs.contains(simple)) {
2000 stage2.push(name);
2001 continue;
2002 }
2003 let siblings = pkg_simples.get(pkg);
2004 let mut k = 1u32;
2005 loop {
2006 k += 1;
2007 let new_simple = format!("{simple}{k}");
2008 let cand = if pkg.is_empty() {
2009 new_simple.clone()
2010 } else {
2011 format!("{pkg}/{new_simple}")
2012 };
2013 // Exact/prefix pool clash, another rule's display target, the
2014 // package's own referenced segments (the new name must not
2015 // obscure ANOTHER package the same files reference), or a
2016 // case-insensitive clash with a same-package sibling
2017 // (case-insensitive filesystems fold the files).
2018 let clash = !prefix_free(&cand)
2019 || taken_displays.contains(&cand)
2020 || pkg_segs
2021 .get(pkg)
2022 .is_some_and(|segs| segs.contains(new_simple.as_str()))
2023 || siblings.is_some_and(|s| {
2024 s.iter()
2025 .any(|p| p.eq_ignore_ascii_case(&new_simple) && *p != simple)
2026 });
2027 if !clash {
2028 taken_displays.insert(cand.clone());
2029 map.insert(name.clone(), cand);
2030 renamed += 1;
2031 break;
2032 }
2033 }
2034 }
2035 let mut body_renamed = 0usize;
2036 if !stage2.is_empty() && pool_majority_materialized(pool) {
2037 let stage2_pkgs: jdc_core::FxHashSet<String> =
2038 stage2.iter().map(|n| pkg_of(n).to_string()).collect();
2039 let body_segs = crate::refscan::body_ref_segments(&pool.dexes, &stage2_pkgs);
2040 for name in stage2 {
2041 let pkg = pkg_of(name);
2042 let simple = name.rsplit('/').next().unwrap_or(name);
2043 if !body_segs
2044 .get(pkg)
2045 .is_some_and(|segs| segs.contains(simple))
2046 {
2047 continue;
2048 }
2049 let siblings = pkg_simples.get(pkg);
2050 let mut k = 1u32;
2051 loop {
2052 k += 1;
2053 let new_simple = format!("{simple}{k}");
2054 let cand = format!("{pkg}/{new_simple}");
2055 let clash = !prefix_free(&cand)
2056 || taken_displays.contains(&cand)
2057 || pkg_segs
2058 .get(pkg)
2059 .is_some_and(|segs| segs.contains(new_simple.as_str()))
2060 || body_segs
2061 .get(pkg)
2062 .is_some_and(|segs| segs.contains(new_simple.as_str()))
2063 || siblings.is_some_and(|s| {
2064 s.iter()
2065 .any(|p| p.eq_ignore_ascii_case(&new_simple) && *p != simple)
2066 });
2067 if !clash {
2068 taken_displays.insert(cand.clone());
2069 map.insert(name.clone(), cand);
2070 renamed += 1;
2071 body_renamed += 1;
2072 break;
2073 }
2074 }
2075 }
2076 }
2077 if std::env::var("DDC_STATS").is_ok() {
2078 eprintln!(
2079 "[renames] obscuring-class renames: {renamed} (body-gated {body_renamed}; pkgs-with-segs={}, cands={ncands})",
2080 pkg_segs.len()
2081 );
2082 }
2083}
2084
2085/// Class-level counterpart of the non-ASCII rule already applied to
2086/// MEMBERS by `member_collision_renames`, kept as the SAFETY NET behind
2087/// the injective `sanitize_fq`.
2088///
2089/// `sanitize_fq` escapes non-identifier characters as `_u<hex>`, so two
2090/// distinct classes normally reach two distinct file names. It cannot be
2091/// injective against *lookalikes*, because ident-safe ASCII must pass
2092/// through unchanged: a literal class named `_u1a7b` collides with the
2093/// class whose single character is U+1A7B, and the pre-existing keyword
2094/// repair makes `_do` collide with `do`. Without this pass those pairs
2095/// repeat the original disaster — the writer opens with `create_new`,
2096/// takes EEXIST, unlinks and rewrites, so one class is destroyed with
2097/// exit code 0 (on bin.mt.plus the lossy predecessor of this rule hid
2098/// 22,633 of 30,768 classes exactly this way).
2099///
2100/// Groups are keyed by the SANITIZED path — the exact string both the
2101/// declaration site (`sanitize_ref`) and the writer (`source_path`)
2102/// produce. The first (sorted) member of each group keeps its name; the
2103/// rest become `<sanitized>_2`, `<sanitized>_3`, … Pure ASCII, so a
2104/// minted name is a fixed point of the sanitizer: it cannot silently
2105/// join a second collision group, and the declaration, every reference
2106/// and the file name agree by construction through `apply_class_rename`.
2107///
2108/// Costs nothing on a healthy pool: one pass over the emission set, and
2109/// it returns before touching the registry when every key is unique.
2110/// Runs LAST in `install_case_renames`: it keys on the display form the
2111/// earlier rules have already settled.
2112fn lossy_sanitize_renames(pool: &DexPool, map: &mut HashMap<String, String>) {
2113 let names = top_level_classes(pool);
2114 // Current display of an emission-set name. `case_rename_map` has
2115 // already inserted an entry for every one of these (identity or
2116 // renamed) and an exact registry hit short-circuits
2117 // `apply_class_rename`, so `map` already holds the final display —
2118 // no `$`-prefix walk is needed here.
2119 fn key_of(map: &HashMap<String, String>, n: &str) -> String {
2120 let disp = map.get(n).map(|s| s.as_str()).unwrap_or(n);
2121 sanitize_internal(disp)
2122 }
2123 let mut counts: HashMap<String, u32> = HashMap::default();
2124 for n in &names {
2125 *counts.entry(key_of(map, n)).or_insert(0) += 1;
2126 }
2127 if counts.values().all(|c| *c == 1) {
2128 return;
2129 }
2130 // Every sanitized path in the POOL is off-limits for a minted name,
2131 // not just the emission set: an inlined nested class still owns the
2132 // display it renders under inside its outer's file.
2133 let mut taken: jdc_core::FxHashSet<String> = pool
2134 .order
2135 .iter()
2136 .map(|n| sanitize_internal(map.get(n).map(|s| s.as_str()).unwrap_or(n)))
2137 .collect();
2138 let mut sorted: Vec<&String> = names.iter().collect();
2139 sorted.sort();
2140 let mut seen: jdc_core::FxHashSet<String> = jdc_core::FxHashSet::default();
2141 let mut renamed = 0usize;
2142 for n in sorted {
2143 let key = key_of(map, n);
2144 if counts.get(&key).copied().unwrap_or(0) < 2 {
2145 continue;
2146 }
2147 if seen.insert(key.clone()) {
2148 continue; // first (sorted) member of the group keeps its name
2149 }
2150 let (pkg, simple) = match key.rsplit_once('/') {
2151 Some((p, s)) => (p, s),
2152 None => ("", key.as_str()),
2153 };
2154 let mut i = 1u32;
2155 loop {
2156 i += 1;
2157 let cand = if pkg.is_empty() {
2158 format!("{simple}_{i}")
2159 } else {
2160 format!("{pkg}/{simple}_{i}")
2161 };
2162 if !taken.insert(cand.clone()) {
2163 continue; // already owned by a real class or another mint
2164 }
2165 // The minted display IS the sanitized name, so
2166 // sanitize_internal(cand) == cand and the writer's file name
2167 // matches the declaration it writes into it.
2168 map.insert(n.clone(), cand);
2169 renamed += 1;
2170 break;
2171 }
2172 }
2173 if std::env::var("DDC_STATS").is_ok() {
2174 eprintln!("[renames] lossy-sanitize collisions renamed={renamed}");
2175 }
2176}
2177
2178/// A class named `P/s` while OTHER classes live under `P/s/` — the dex
2179/// namespace is flat, so obfuscators freely mint a class whose simple
2180/// name equals a subpackage of its own package (`ptr.a` +
2181/// `ptr.a.a`, weibo rsplay/ptr families). That namespace is
2182/// unrepresentable in Java: the declaration itself is
2183/// "类 a与带有相同名称的程序包冲突" and every qualified reference
2184/// through the segment becomes unresolvable (the 53.8k weibo
2185/// missing-class errors root here, with Object/getClass cascades on
2186/// top). Rename the class — the registry carries declarations and
2187/// references — with a candidate that cannot recreate the shape (not a
2188/// class, not a package, not a nested-class prefix, not another rule's
2189/// target).
2190fn class_pkg_collision_renames(pool: &DexPool, map: &mut HashMap<String, String>) {
2191 // Every package that exists in the pool — ALL ancestor prefixes of
2192 // every class path, not just direct parents: Java sees package
2193 // `z` as existing when any class lives at `z/a/b` (the weibo
2194 // `com.sina.weibo.z` interface collides with a subpackage-only
2195 // `z/` that has no directly-resident class).
2196 let mut pkgs: jdc_core::FxHashSet<String> = jdc_core::FxHashSet::default();
2197 for n in &pool.order {
2198 let mut rest = n.as_str();
2199 while let Some(i) = rest.rfind('/') {
2200 rest = &rest[..i];
2201 pkgs.insert(rest.to_string());
2202 }
2203 }
2204 for name in &pool.order {
2205 let Some((pkg, simple)) = name.rsplit_once('/') else {
2206 continue;
2207 };
2208 if simple.is_empty() || pkg.is_empty() || simple.contains('$') {
2209 // Nested classes render dotted (`Outer.a`) — no package
2210 // effect from their `$` tail.
2211 continue;
2212 }
2213 if !pkgs.contains(name) || map.get(name).is_some_and(|v| v != name) {
2214 continue; // no subpackage under it, or an earlier rule moved it
2215 }
2216 let mut k = 1u32;
2217 loop {
2218 k += 1;
2219 let cand = format!("{pkg}/{simple}{k}");
2220 let clash = pkgs.contains(&cand)
2221 || pool.order.iter().any(|n| n.starts_with(&cand))
2222 || map.values().any(|v| *v == cand);
2223 if !clash {
2224 map.insert(name.clone(), cand);
2225 break;
2226 }
2227 }
2228 }
2229}
2230
2231/// Obfuscators can name a class after its own package leaf (`package k;`
2232/// `class k extends EditText`). Every SAME-PACKAGE reference to `k.Anything`
2233/// then resolves the first segment to the CLASS, not the package —
2234/// javac looks for `Anything` as a member of class k ("找不到符号 class p2,
2235/// location: class k"). Renaming the class (display-level, the registry
2236/// carries declarations and references) makes the package the only
2237/// thing the leaf name resolves to.
2238fn pkg_leaf_shadow_renames(pool: &DexPool, map: &mut HashMap<String, String>) {
2239 let taken: jdc_core::FxHashSet<String> = pool.order.iter().cloned().collect();
2240 for name in &pool.order {
2241 let Some((pkg, simple)) = name.rsplit_once('/') else {
2242 continue;
2243 };
2244 if simple.is_empty() || pkg.is_empty() {
2245 continue;
2246 }
2247 let leaf = pkg.rsplit('/').next().unwrap_or(pkg);
2248 // class name == package leaf, and the package really exists
2249 // (more classes than just this one live under it).
2250 if simple != leaf {
2251 continue;
2252 }
2253 let prefix = format!("{pkg}/");
2254 let siblings = pool
2255 .order
2256 .iter()
2257 .filter(|n| n.starts_with(&prefix) && **n != *name)
2258 .count();
2259 if siblings == 0 || map.get(name).is_some_and(|v| v != name) {
2260 continue; // already renamed by an earlier rule; identity anchors are fine to overwrite
2261 }
2262 let mut k = 1u32;
2263 loop {
2264 k += 1;
2265 let cand = format!("{pkg}/{simple}{k}");
2266 if !taken.contains(&cand) && !map.values().any(|v| *v == cand) {
2267 map.insert(name.clone(), cand);
2268 break;
2269 }
2270 }
2271 }
2272}
2273
2274/// Member-level collision renames (fields AND methods of one class).
2275/// Two sources collapse onto one display name: obfuscators renaming a
2276/// synthetic outer reference (`this$0`) onto a real field's name, and
2277/// the identifier sanitizer mapping non-ASCII to `_` (whole
2278/// `ERROR_中文` families render one `ERROR________`).
2279/// Both are legal in bytecode (members resolve by index) and both are
2280/// javac "already defined" errors in source. Policy per colliding group
2281/// (fields keep the first non-synthetic name; a synthetic outer
2282/// reference restores `this$0`; everything else gets `2`/`3` suffixes;
2283/// method keys include erased parameter types):
2284/// Keys stay ORIGINAL (name, descriptor) so references resolve exactly;
2285/// only the rendered identifier changes.
2286/// Descriptor type string → internal class name (arrays/primitives →
2287/// None).
2288fn desc_internal(r: &str) -> Option<&str> {
2289 if r.len() > 2 && r.starts_with('L') && r.ends_with(';') {
2290 Some(&r[1..r.len() - 1])
2291 } else {
2292 None
2293 }
2294}
2295
2296/// Return type of a method descriptor as an internal class name
2297/// (arrays/primitives → None).
2298fn ret_internal(desc: &str) -> Option<&str> {
2299 let hi = desc.find(')')?;
2300 let r = &desc[hi + 1..];
2301 if r.len() > 2 && r.starts_with('L') && r.ends_with(';') {
2302 Some(&r[1..r.len() - 1])
2303 } else {
2304 None
2305 }
2306}
2307
2308/// Raw name → (argsig, ret) JVM-descriptor slices of one class's own
2309/// virtual methods — the key space the collision queries use.
2310type AncMethods = jdc_core::FxHashMap<
2311 std::sync::Arc<str>,
2312 Vec<(std::sync::Arc<str>, std::sync::Arc<str>)>,
2313>;
2314
2315/// One provenance bucket of an analyzed class's ancestor chain (cached
2316/// layers, no merge — see `layer_rets`).
2317type AncLayers = Vec<std::sync::Arc<AncEntry>>;
2318
2319/// Parsed direct virtual methods of one ancestor class + its chain
2320/// edges, cached per class name for the member-collision walk. The
2321/// framework chains (View/Activity/Fragment…) and pool hub supers repeat
2322/// across thousands of analyzed classes — parsing each ancestor's
2323/// descriptors ONCE per run (instead of per analyzed subclass) removes
2324/// the dominant main-loop cost.
2325struct AncEntry {
2326 methods: AncMethods,
2327 /// Provenance bucket: FRAMEWORK ancestors (fwdb classes AND
2328 /// desugared `java.*`/`javax.*` pool copies — javac compiles against
2329 /// the android.jar originals, the covariant source truth) vs POOL
2330 /// ancestors (rendered RAW — the erased bridge is what satisfies the
2331 /// raw interface). The keeper preference flips on this axis (weibo
2332 /// Function0.invoke bridge must keep the name; WhatsApp SortedMap
2333 /// .keySet real override must).
2334 is_fw: bool,
2335 /// super + direct interfaces (chain continuation), Object-stripped.
2336 supers: Vec<std::sync::Arc<str>>,
2337}
2338
2339fn parse_anc_entry(pool: &DexPool, cn: &str) -> std::sync::Arc<AncEntry> {
2340 let mut methods: AncMethods = jdc_core::FxHashMap::default();
2341 let mut supers: Vec<std::sync::Arc<str>> = Vec::new();
2342 let is_fw;
2343 if let Some(ac) = pool.get_if_materialized(cn) {
2344 // Desugared `java.*`/`javax.*` copies in the dex are
2345 // pool-materialized, but javac compiles against the android.jar
2346 // ORIGINALS (covariant generics truth) — their declarations
2347 // belong to the fw bucket (WhatsApp bundles desugared
2348 // java.util.SortedMap; the pool bucket kept the
2349 // flattened-erasure bridge and renamed the real SortedSet
2350 // keySet).
2351 is_fw = cn.starts_with("java/") || cn.starts_with("javax/");
2352 for m in ac.all_methods() {
2353 if m.is_static() || &*m.name == "<init>" || &*m.name == "<clinit>"
2354 {
2355 continue;
2356 }
2357 let d: &str = &m.desc;
2358 let lo = d.find('(').map(|i| i + 1).unwrap_or(0);
2359 let hi = d.find(')').unwrap_or(d.len());
2360 methods
2361 .entry(m.name.clone())
2362 .or_default()
2363 .push((
2364 std::sync::Arc::from(&d[lo..hi]),
2365 std::sync::Arc::from(&d[hi + 1..]),
2366 ));
2367 }
2368 if let Some(s) = &ac.super_name {
2369 if s != "java/lang/Object" {
2370 supers.push(std::sync::Arc::from(s.as_str()));
2371 }
2372 }
2373 supers.extend(ac.interfaces.iter().map(|i| std::sync::Arc::from(i.as_str())));
2374 } else {
2375 // FRAMEWORK ancestors bind names too: a group member
2376 // implementing a framework declaration must keep the original
2377 // name (renaming WhatsApp's Map.keySet-style overrides broke
2378 // the interface chain — cannot-find:变量 ×18.6k). fwdb
2379 // descriptors are erased JVM form — directly comparable with
2380 // dex descs. A class that is NEITHER pool nor fwdb (phantom)
2381 // parses to an empty entry — a chain dead-end, same as before.
2382 is_fw = true;
2383 crate::fwdb::for_each_method(cn, |d, f| {
2384 if f & crate::fwdb::MF_STATIC != 0 {
2385 return;
2386 }
2387 let Some(open) = d.find('(') else {
2388 return;
2389 };
2390 let lo = open + 1;
2391 let hi = d.find(')').unwrap_or(0);
2392 // NOTE: hi == lo is the zero-arg case, not malformed; and
2393 // the name slice ends at `open` (a `d[..lo]` cut kept the
2394 // `(` — every fw key missed its gkey lookup).
2395 if hi == 0 || hi + 1 >= d.len() {
2396 return;
2397 }
2398 methods
2399 .entry(std::sync::Arc::from(&d[..open]))
2400 .or_default()
2401 .push((
2402 std::sync::Arc::from(&d[lo..hi]),
2403 std::sync::Arc::from(&d[hi + 1..]),
2404 ));
2405 });
2406 if let Some(sup) = crate::fwdb::super_of(cn) {
2407 if sup != "java/lang/Object" {
2408 supers.push(std::sync::Arc::from(sup));
2409 }
2410 }
2411 crate::fwdb::for_each_interface(cn, |i| supers.push(std::sync::Arc::from(i)));
2412 }
2413 std::sync::Arc::new(AncEntry {
2414 methods,
2415 is_fw,
2416 supers,
2417 })
2418}
2419
2420/// Rets declared for `(name, argsig)` by any layer of a chain — lazy,
2421/// no merge (every consumer is an "any ancestor declares this" query,
2422/// so a per-layer scan replaces the old per-class eager map build).
2423/// Alloc-free: `Arc<str>: Borrow<str>` keys the hash lookup by `&str`.
2424fn layer_rets<'a>(
2425 layers: &'a [std::sync::Arc<AncEntry>],
2426 name: &'a str,
2427 argsig: &'a str,
2428) -> impl Iterator<Item = &'a str> {
2429 layers
2430 .iter()
2431 .filter_map(move |e| e.methods.get(name))
2432 .flatten()
2433 .filter(move |(a, _)| &**a == argsig)
2434 .map(|(_, r)| &**r)
2435}
2436
2437fn member_collision_renames(
2438 pool: &DexPool,
2439) -> HashMap<std::sync::Arc<str>, Vec<jdc_core::rename::FieldRename>> {
2440 let mut out: HashMap<std::sync::Arc<str>, Vec<jdc_core::rename::FieldRename>> =
2441 HashMap::default();
2442 // Direct nested tails per base class (`C$a` → a for base C), for
2443 // the companion-field rule below.
2444 let mut child_tails: jdc_core::FxHashMap<&str, Vec<&str>> =
2445 jdc_core::FxHashMap::default();
2446 // Per-package RENAMED class display heads: a MINTED field display
2447 // equal to one of these shadows same-package qualified type refs
2448 // (`a2.changeQuickRedirect` binds to the field when the class a2's
2449 // display is a2 — the inherited rule minting field a→a2 ONTO the
2450 // pkg-renamed class display created exactly this: weibo +194
2451 // cannot-find). Keyed on the POST-rename display (what refs render),
2452 // covering each class's own display too.
2453 let root_segs = pool.root_pkg_segs();
2454 let mut pkg_displays: jdc_core::FxHashMap<&str, jdc_core::FxHashSet<String>> =
2455 jdc_core::FxHashMap::default();
2456 for n in &pool.order {
2457 let renamed = crate::apply_class_rename(n);
2458 let (pkg, simple) = match renamed.rfind('/') {
2459 Some(i) => (renamed[..i].to_string(), renamed[i + 1..].to_string()),
2460 None => (String::new(), renamed.to_string()),
2461 };
2462 let head = simple.split('$').next().unwrap_or(&simple).to_string();
2463 if !head.is_empty() {
2464 let pkg_key = n.rfind('/').map(|i| &n[..i]).unwrap_or("");
2465 let _ = pkg;
2466 pkg_displays.entry(pkg_key).or_default().insert(head);
2467 }
2468 }
2469 // Reverse super map — the obscuring rename must register under every
2470 // transitive subclass (dex refs of an inherited field may name any
2471 // hierarchy class as owner).
2472 let mut subs: jdc_core::FxHashMap<&str, Vec<&str>> = jdc_core::FxHashMap::default();
2473 for n in &pool.order {
2474 if let Some(i) = n.find('$') {
2475 let base = &n[..i];
2476 let rest = &n[i + 1..];
2477 let tail = match rest.find('$') {
2478 Some(j) => &rest[..j],
2479 None => rest,
2480 };
2481 if !tail.is_empty() {
2482 child_tails.entry(base).or_default().push(tail);
2483 }
2484 }
2485 if let Some(pc) = pool.get_if_materialized(n) {
2486 if let Some(sup) = &pc.super_name {
2487 if sup != "java/lang/Object" {
2488 subs.entry(sup.as_str()).or_default().push(n.as_str());
2489 }
2490 }
2491 }
2492 }
2493 // Per-ancestor parse cache (function-local: lives exactly as long
2494 // as this rename install, so materialization state is consistent by
2495 // construction; freed on return — no cross-run staleness, no RSS
2496 // tail).
2497 let mut anc_cache: jdc_core::FxHashMap<
2498 std::sync::Arc<str>,
2499 std::sync::Arc<AncEntry>,
2500 > = jdc_core::FxHashMap::default();
2501 for name in &pool.order {
2502 let Some(pc) = pool.get_if_materialized(name) else {
2503 continue;
2504 };
2505 let outer_ref_desc = find_outer_name(pool, name)
2506 .filter(|o| o != name)
2507 .map(|o| format!("L{o};"));
2508 // ---- fields: one shared namespace (static + instance) ----
2509 let fields: Vec<&PoolField> = pc
2510 .static_fields
2511 .iter()
2512 .chain(pc.instance_fields.iter())
2513 .collect();
2514 let fgroups: HashMap<String, Vec<&PoolField>> = HashMap::default();
2515 let mut fgroups = fgroups;
2516 for f in &fields {
2517 let disp = crate::classdec::java_ident(&f.name).into_owned();
2518 fgroups.entry(disp).or_default().push(f);
2519 }
2520 let f_taken: jdc_core::FxHashSet<String> = fields
2521 .iter()
2522 .map(|f| crate::classdec::java_ident(&f.name).into_owned())
2523 .collect();
2524 let mut f_taken = f_taken;
2525 for group in fgroups.values() {
2526 if group.len() < 2 {
2527 continue;
2528 }
2529 let keeper_pos = group
2530 .iter()
2531 .position(|f| f.access & crate::access::ACC_SYNTHETIC == 0)
2532 .unwrap_or(0);
2533 for (gi, f) in group.iter().enumerate() {
2534 if gi == keeper_pos {
2535 continue;
2536 }
2537 let base = crate::classdec::java_ident(&f.name).into_owned();
2538 let display: String = match &outer_ref_desc {
2539 Some(ord)
2540 if f.access & crate::access::ACC_SYNTHETIC != 0
2541 && !f.is_static
2542 && *ord == f.desc =>
2543 {
2544 let mut k = 0u32;
2545 loop {
2546 let cand = if k == 0 {
2547 "this$0".to_string()
2548 } else {
2549 format!("this$0{k}")
2550 };
2551 if f_taken.insert(cand.clone()) {
2552 break cand;
2553 }
2554 k += 1;
2555 }
2556 }
2557 _ => suffix_unique(&base, &mut f_taken),
2558 };
2559 out.entry(std::sync::Arc::from(name.as_str()))
2560 .or_default()
2561 .push(jdc_core::rename::FieldRename {
2562 name: std::sync::Arc::from(f.name.as_str()),
2563 desc: std::sync::Arc::from(f.desc.as_str()),
2564 display: std::sync::Arc::from(display.as_str()),
2565 });
2566 }
2567 }
2568 // ---- fields obscuring nested types (JLS 6.4.2) ----
2569 // `C.b.a(..)` with BOTH a field `b` and a member class `C$b`
2570 // binds to the FIELD — the qualified type reading is obscured
2571 // ("无法从静态上下文中引用非静态 变量 b" + the paired cannot-find
2572 // cascade; lark LKEvent/MotionLayout family, static-ctx ×1,154).
2573 // The CHILD-side rule (nested_collision_renames) already renames
2574 // colliding children when its local_ok gate passes (`a$a` renders
2575 // as `a2`); this field-side rule covers the gate-REJECTED residual
2576 // (child keeps display `b`, program-wide refs block its rename).
2577 // A field's refs all funnel through field_display (lift call
2578 // sites, declarations, const inits), so the field side needs no
2579 // locality gate. TWO invariants the first attempt violated (lark
2580 // +8,129): fire on the child's FINAL DISPLAY last segment, not
2581 // the raw tail (a child the child-side rule already renamed does
2582 // NOT obscure), and mint avoiding every child display (`a`→`a2`
2583 // landed on the existing `interface a2`, minting a fresh
2584 // obscuring pair).
2585 {
2586 let tails: &[&str] = child_tails
2587 .get(name.as_str())
2588 .map(|v| v.as_slice())
2589 .unwrap_or(&[]);
2590 let mut member_displays: jdc_core::FxHashSet<String> =
2591 jdc_core::FxHashSet::default();
2592 let mut obscuring: jdc_core::FxHashSet<String> =
2593 jdc_core::FxHashSet::default();
2594 for t in tails {
2595 let full = format!("{name}${t}");
2596 let renamed = crate::apply_class_rename(&full);
2597 let last = renamed
2598 .rsplit('/')
2599 .next()
2600 .unwrap_or(&renamed)
2601 .rsplit('$')
2602 .next()
2603 .unwrap_or(t)
2604 .to_string();
2605 member_displays.insert(last.clone());
2606 // Only an INLINE-rendered member is reachable by the bare
2607 // simple name (own-file children are referenced by their
2608 // flat `$` form, which fields cannot obscure).
2609 let member_rendered = clean_member_tail(t)
2610 && crate::find_outer_name(pool, &full).as_deref()
2611 == Some(name.as_str());
2612 if member_rendered {
2613 obscuring.insert(last);
2614 }
2615 }
2616 // The class's OWN simple display name joins the obscuring
2617 // set: a field named like its class captures every
2618 // qualified self-static ref from nested scopes
2619 // (`a2.changeQuickRedirect` bound to the String FIELD a2 —
2620 // weibo robust refs ×317; bare refs survive via the
2621 // variable namespace, the qualified form does not).
2622 let self_renamed = crate::apply_class_rename(name);
2623 let self_simple = self_renamed
2624 .rsplit('/')
2625 .next()
2626 .unwrap_or(&self_renamed)
2627 .rsplit('$')
2628 .next()
2629 .unwrap_or("")
2630 .to_string();
2631 if !self_simple.is_empty() {
2632 obscuring.insert(crate::classdec::java_ident(&self_simple).into_owned());
2633 }
2634 let self_pkg = name.rfind('/').map(|i| &name[..i]).unwrap_or("");
2635 let pkg_names = pkg_displays.get(self_pkg);
2636 for f in &fields {
2637 let fdisp = crate::classdec::java_ident(&f.name).into_owned();
2638 if fdisp.starts_with("this$") || !obscuring.contains(fdisp.as_str()) {
2639 continue;
2640 }
2641 let mut k = 1u32;
2642 let display = loop {
2643 k += 1;
2644 let cand = format!("{fdisp}{k}");
2645 // root_segs: a minted display equal to a PACKAGE
2646 // first segment captures every qualified ref to
2647 // that package inside the family's file (field e2
2648 // ate `e2.c.b(..)` — lark pq/e "变量 c" ×47). The
2649 // deshadow builder cannot repair this after the
2650 // fact: it scans RAW names, and the collision is
2651 // born here in display space.
2652 if !f_taken.contains(&cand)
2653 && !member_displays.contains(&cand)
2654 && !root_segs.contains(&cand)
2655 && !pkg_names.is_some_and(|p| p.contains(cand.as_str()))
2656 {
2657 f_taken.insert(cand.clone());
2658 member_displays.insert(cand.clone());
2659 break cand;
2660 }
2661 };
2662 register_field_rename_with_subs(
2663 pool, &subs, &mut out, name, &f.name, &f.desc, &display,
2664 );
2665 if std::env::var("DDC_OBSCURE_STATS").is_ok() {
2666 eprintln!("[obscure] {name} field {} -> {}", f.name, display);
2667 }
2668 }
2669 }
2670 // ---- companion-holder fields vs nested types (JLS 6.4.2 in
2671 // expression context): Kotlin compiles `object`/companion
2672 // holders as a static field whose name EQUALS the nested class
2673 // it instances (`static final j$a a`), and static members of the
2674 // nested are invoked as `j.a.c(..)` — but `j.a` in an EXPRESSION
2675 // resolves to the FIELD (variables outrank member types), so the
2676 // call becomes a member lookup on the instance type... which is
2677 // the same class, yet javac reports 找不到符号 for statics
2678 // reached through the shadowed path, and the whole file
2679 // error-types (weibo feed/business/j: 654 errors + closure
2680 // cascade; the nested-side rename for this is the LOCAL-OK-gated
2681 // rule that explodes ungated — the FIELD side is safe because
2682 // dex field refs always carry the declaring class, so this
2683 // registry keys every consumer). Gate: the nested class has
2684 // static members (companion shape) and the field's descriptor
2685 // is exactly the nested type.
2686 if let Some(tails) = child_tails.get(name.as_str()) {
2687 for tail in tails {
2688 let nested = format!("{name}${tail}");
2689 let Some(nc) = pool.get_if_materialized(&nested) else {
2690 continue;
2691 };
2692 // Only CLEAN tails render dotted (`j.a`); flat-rendered
2693 // tails (`j$1`) carry the `$` and never clash.
2694 if !clean_member_tail(tail) {
2695 continue;
2696 }
2697 let has_statics = nc
2698 .static_fields
2699 .iter()
2700 .chain(nc.instance_fields.iter())
2701 .any(|f| f.is_static)
2702 || nc.all_methods().any(|m| m.access & crate::access::ACC_STATIC != 0);
2703 if !has_statics {
2704 continue;
2705 }
2706 // STRICT companion shape: the field's descriptor IS the
2707 // nested type (`static final j$a a`). The relaxed form
2708 // (any same-named field beside a statics-bearing nested)
2709 // minted thousands of renames on weibo and exploded the
2710 // battery to the 500k cap — the field funnel does not
2711 // hold at that scale (改名面 vs 引用覆盖面, again).
2712 let want_desc = format!("L{nested};");
2713 for f in pc.static_fields.iter().chain(pc.instance_fields.iter()) {
2714 if f.desc != want_desc {
2715 continue;
2716 }
2717 let disp = crate::classdec::java_ident(&f.name).into_owned();
2718 if disp != crate::classdec::java_ident(tail) {
2719 continue;
2720 }
2721 // Already renamed by the duplicate-group rule above?
2722 let already = out
2723 .get(&std::sync::Arc::from(name.as_str()))
2724 .is_some_and(|v| {
2725 v.iter().any(|fr| *fr.name == *f.name && *fr.desc == *f.desc)
2726 });
2727 if already {
2728 continue;
2729 }
2730 let display = suffix_unique(&disp, &mut f_taken);
2731 f_taken.insert(display.clone());
2732 out.entry(std::sync::Arc::from(name.as_str()))
2733 .or_default()
2734 .push(jdc_core::rename::FieldRename {
2735 name: std::sync::Arc::from(f.name.as_str()),
2736 desc: std::sync::Arc::from(f.desc.as_str()),
2737 display: std::sync::Arc::from(display.as_str()),
2738 });
2739 }
2740 }
2741 }
2742 // ---- methods: display key = sanitized name + erased params ----
2743 let methods: Vec<&PoolMethod> = pc.all_methods().collect();
2744 // Ancestor virtual-method returns per (name, argsig) — one
2745 // chain walk per non-interface class, shared by the
2746 // covariant-keeper selection and the impostor-override
2747 // detection below. Layers stay PER-ANCESTOR (cached Arcs, no
2748 // merge): every consumer is an "any ancestor declares
2749 // (name, argsig) → ret" query, so a per-layer scan replaces
2750 // the old per-class eager map build. Provenance splits the
2751 // chain into fw / pool buckets (see AncEntry.is_fw).
2752 let mut anc_chain: Option<(AncLayers, AncLayers)> = None;
2753 if pc.access & crate::access::ACC_INTERFACE == 0 {
2754 let mut fw_layers: AncLayers = Vec::new();
2755 let mut pool_layers: AncLayers = Vec::new();
2756 let mut stack: Vec<std::sync::Arc<str>> = Vec::new();
2757 if let Some(sup) = &pc.super_name {
2758 if sup != "java/lang/Object" {
2759 stack.push(std::sync::Arc::from(sup.as_str()));
2760 }
2761 }
2762 stack.extend(
2763 pc.interfaces
2764 .iter()
2765 .map(|i| std::sync::Arc::from(i.as_str())),
2766 );
2767 let mut seen_cls: jdc_core::FxHashSet<std::sync::Arc<str>> =
2768 jdc_core::FxHashSet::default();
2769 while let Some(cn) = stack.pop() {
2770 if !seen_cls.insert(cn.clone()) {
2771 continue;
2772 }
2773 let entry = match anc_cache.get(cn.as_ref()) {
2774 Some(e) => e.clone(),
2775 None => {
2776 let e = parse_anc_entry(pool, &cn);
2777 anc_cache.insert(cn.clone(), e.clone());
2778 e
2779 }
2780 };
2781 if !entry.methods.is_empty() {
2782 if entry.is_fw {
2783 fw_layers.push(entry.clone());
2784 } else {
2785 pool_layers.push(entry.clone());
2786 }
2787 }
2788 stack.extend(entry.supers.iter().cloned());
2789 }
2790 anc_chain = Some((fw_layers, pool_layers));
2791 }
2792 let mut m_taken: jdc_core::FxHashSet<String> = methods
2793 .iter()
2794 .map(|m| crate::classdec::java_ident(&m.name).into_owned())
2795 .collect();
2796 let mut mgroups: HashMap<(String, String), Vec<&PoolMethod>> = HashMap::default();
2797 for m in &methods {
2798 let d: &str = &m.desc;
2799 let lo = d.find('(').map(|i| i + 1).unwrap_or(0);
2800 let hi = d.find(')').unwrap_or(d.len());
2801 let key = (
2802 crate::classdec::java_ident(&m.name).into_owned(),
2803 d[lo..hi].to_string(),
2804 );
2805 mgroups.entry(key).or_default().push(m);
2806 }
2807 for ((base, _), group) in &mgroups {
2808 if group.len() < 2 {
2809 continue;
2810 }
2811 // R8 return-type specialization: a non-isolated class carries
2812 // `M(args)void` (the real logic) beside the interface bridge
2813 // `M(args)R` (unbox → call void → return Unit). Same erasure,
2814 // so Java source can't hold both, and `void` never satisfies
2815 // the interface's `R` — the claim map keeps the void side and
2816 // drops the bridge, yielding "X不是抽象的, 并且未覆盖…invoke"
2817 // (Kotlin suspend lambdas, weixin/lark ×1.1k). This is NOT the
2818 // covariant-override shape below (void has no subtype
2819 // relation): keep the BRIDGE under the original name so it
2820 // satisfies the interface, and rename the void specialization
2821 // so both render and the bridge's call to it resolves to the
2822 // renamed method.
2823 let ret_void = |m: &PoolMethod| m.desc.ends_with(")V");
2824 let isolated = pc
2825 .super_name
2826 .as_ref()
2827 .is_none_or(|s| s == "java/lang/Object")
2828 && pc.interfaces.is_empty();
2829 let has_void = group.iter().any(|m| ret_void(m) && &*m.name != "<init>");
2830 let has_nonvoid = group.iter().any(|m| !ret_void(m));
2831 if !isolated && has_void && has_nonvoid {
2832 let keeper_desc: Option<&str> = group
2833 .iter()
2834 .copied()
2835 .find(|m| {
2836 m.access & crate::access::ACC_BRIDGE != 0
2837 && !ret_void(m)
2838 && &*m.name != "<init>"
2839 })
2840 .or_else(|| {
2841 group
2842 .iter()
2843 .copied()
2844 .find(|m| !ret_void(m) && &*m.name != "<init>")
2845 })
2846 .map(|m| &*m.desc);
2847 let mut seen_orig: jdc_core::FxHashSet<(&str, &str)> =
2848 jdc_core::FxHashSet::default();
2849 for m in group.iter().copied() {
2850 if keeper_desc == Some(&*m.desc) {
2851 seen_orig.insert((&*m.name, &*m.desc));
2852 continue; // bridge keeps the interface name
2853 }
2854 if !seen_orig.insert((&*m.name, &*m.desc)) {
2855 continue; // exact duplicate: emitter drops it
2856 }
2857 let display = suffix_unique(base, &mut m_taken);
2858 out.entry(std::sync::Arc::from(name.as_str()))
2859 .or_default()
2860 .push(jdc_core::rename::FieldRename {
2861 name: m.name.clone(),
2862 desc: m.desc.clone(),
2863 display: std::sync::Arc::from(display.as_str()),
2864 });
2865 }
2866 continue;
2867 }
2868 // A COVARIANT override pair (same ORIGINAL name, different
2869 // descriptors — the compiler's bridge shape: the interface's
2870 // `deserialize(e)` plus the narrower implementation). Renaming
2871 // either side breaks @Override ("is not abstract and does not
2872 // override abstract method deserialize(e)", ~2.2k on reqable);
2873 // the emitter's claim logic already renders only the
2874 // non-bridge member of the pair. An ISOLATED class (extends
2875 // Object, implements nothing — d8's ExternalSyntheticApiModel
2876 // Outline shells) overrides nothing: its same-(name,params)
2877 // pairs differing only by RETURN type are dex-legal distinct
2878 // methods, and dropping one strands its callers on the
2879 // survivor (`HalfKt$$…0.m()Class` vs `.m()V` — "void无法
2880 // 转换为Class", weibo ×85+).
2881 let covariant = !isolated
2882 && group
2883 .iter()
2884 .any(|m| group.iter().any(|o| o.name == m.name && o.desc != m.desc));
2885 if covariant {
2886 // Return-type-only clash in a class WITH a hierarchy:
2887 // Java cannot declare both, and the claim logic would
2888 // keep an arbitrary one — when that is NOT the member
2889 // an ancestor declares, every concrete subclass fails
2890 // "X不是抽象的, 并且未覆盖…" (weibo ×590: viewmodel.a
2891 // kept getUsageInfo()e while interface d declares
2892 // getUsageInfo()g; the kept side also strands the
2893 // dropped side's callers). Keep the ancestor-declared
2894 // member under the original name and rename the rest —
2895 // the registry carries every call site, and the
2896 // propagation below shares the display down the family.
2897 // 0 or 2+ ancestor-matched members = the shape Java
2898 // cannot express at all (two interfaces demanding
2899 // different returns): keep the old claim behavior.
2900 let keepers: Vec<&&PoolMethod> = group
2901 .iter()
2902 .filter(|m| {
2903 let d: &str = &m.desc;
2904 let lo = d.find('(').map(|i| i + 1).unwrap_or(0);
2905 let hi = d.find(')').unwrap_or(d.len());
2906 if let Some((fwl, pll)) = &anc_chain {
2907 layer_rets(fwl, &m.name, &d[lo..hi])
2908 .chain(layer_rets(pll, &m.name, &d[lo..hi]))
2909 .any(|r| r == &d[hi + 1..])
2910 } else {
2911 false
2912 }
2913 })
2914 .collect();
2915 if keepers.len() >= 2 {
2916 // The shape Java cannot express at all (2+
2917 // ancestors demanding different returns): no
2918 // rename target — keep the claim behavior.
2919 continue;
2920 }
2921 // fwdb flattens JDK covariant overrides to the erased
2922 // declaring return (SortedMap.keySet records Set, the
2923 // source return is SortedSet) — the sole "keeper" can
2924 // be the synthetic BRIDGE while the real override is
2925 // the non-bridge sibling whose return is a subtype of
2926 // the recorded one. Keeping the bridge renamed the
2927 // real method and broke the interface chain (WhatsApp
2928 // X/Jl2 SortedMap, cannot-find:变量 ×18.6k). Prefer the
2929 // non-bridge in that shape: the claim map dropped the
2930 // bridge before this machinery existed anyway.
2931 // Keeper selection by ancestor PROVENANCE:
2932 // - POOL ancestor matches (raw-rendered): the member
2933 // whose return EXACTLY matches a pool erasure that
2934 // is NOT purely framework-sourced keeps the name —
2935 // the erased bridge is what satisfies the raw
2936 // interface (weibo Function0.invoke / GlideRequest
2937 // .load; renaming the real one instead cost +375).
2938 // - FRAMEWORK-only match: javac reads the compiled
2939 // covariant truth (SortedMap.keySet→SortedSet) while
2940 // fwdb records the flattened erasure (→Set) that the
2941 // BRIDGE matches — prefer the non-bridge sibling
2942 // whose return is a subtype (WhatsApp X/Jl2).
2943 // - no ancestor: first non-bridge (the old claim
2944 // survivor), else dex order.
2945 fn ret_desc(m: &PoolMethod) -> &str {
2946 let d: &str = &m.desc;
2947 &d[d.find(')').map(|i| i + 1).unwrap_or(d.len())..]
2948 }
2949 let gkey = {
2950 let d: &str = &group[0].desc;
2951 let lo = d.find('(').map(|i| i + 1).unwrap_or(0);
2952 let hi = d.find(')').unwrap_or(d.len());
2953 (
2954 crate::classdec::java_ident(&group[0].name).into_owned(),
2955 d[lo..hi].to_string(),
2956 )
2957 };
2958 // fw match: a NON-BRIDGE member whose return is
2959 // assignable to a framework ret (covariant source
2960 // truth — it satisfies the raw pool ancestor too,
2961 // overrides being covariant-legal in Java).
2962 let fw_i = anc_chain.as_ref().and_then(|(fwl, _)| {
2963 let fws: Vec<&str> =
2964 layer_rets(fwl, &gkey.0, &gkey.1).collect();
2965 if fws.is_empty() {
2966 return None;
2967 }
2968 group.iter().position(|m| {
2969 m.access & crate::access::ACC_BRIDGE == 0
2970 && fws.iter().any(|fr| {
2971 match (ret_internal(&m.desc), desc_internal(fr)) {
2972 (Some(a), Some(b)) => pool.is_subtype(a, b),
2973 _ => ret_desc(m) == *fr,
2974 }
2975 })
2976 })
2977 });
2978 let pool_i = anc_chain.as_ref().and_then(|(_, pll)| {
2979 let rets: Vec<&str> =
2980 layer_rets(pll, &gkey.0, &gkey.1).collect();
2981 if rets.is_empty() {
2982 return None;
2983 }
2984 group
2985 .iter()
2986 .position(|m| rets.iter().any(|r| *r == ret_desc(m)))
2987 });
2988 let keeper_idx = match (fw_i, pool_i) {
2989 (Some(fi), _) => fi,
2990 (None, Some(pi)) => pi,
2991 (None, None) => group
2992 .iter()
2993 .position(|m| m.access & crate::access::ACC_BRIDGE == 0)
2994 .unwrap_or(0),
2995 };
2996 // keepers==1: the ancestor-declared member keeps the
2997 // original name. keepers==0: NOTHING in the POOL binds
2998 // the name — keep the member the old claim map would
2999 // have kept (first NON-BRIDGE, else dex order) and
3000 // rename the rest through the registry: letting the
3001 // claim map silently drop a side stranded its callers
3002 // on the survivor's incompatible return (weibo xiaomi
3003 // push gk/dq/hj/hf/gt: `boolean b()Z` dropped beside
3004 // `String b()` — every `boolean v = this.b()` bound to
3005 // the String twin, "String无法转换为boolean" ×300+ in
3006 // the push package alone). NON-bridge preference is
3007 // load-bearing: a framework-ancestor covariant pair
3008 // (emoji2 n extends SpannableStringBuilder, Editable-
3009 // bridge beside the real override) satisfies the
3010 // ancestor through the REAL method — bridge-preference
3011 // renamed it and broke the override chain (reqable +8
3012 // "无法覆盖…返回类型不兼容").
3013 let keep_desc: &str = &group[keeper_idx].desc;
3014 let mut seen_orig: jdc_core::FxHashSet<(&str, &str)> =
3015 jdc_core::FxHashSet::default();
3016 for m in group.iter().copied() {
3017 if m.desc.as_ref() == keep_desc {
3018 seen_orig.insert((&*m.name, &*m.desc));
3019 continue;
3020 }
3021 if !seen_orig.insert((&*m.name, &*m.desc)) {
3022 continue;
3023 }
3024 let display = suffix_unique(base, &mut m_taken);
3025 out.entry(std::sync::Arc::from(name.as_str()))
3026 .or_default()
3027 .push(jdc_core::rename::FieldRename {
3028 name: m.name.clone(),
3029 desc: m.desc.clone(),
3030 display: std::sync::Arc::from(display.as_str()),
3031 });
3032 }
3033 continue;
3034 }
3035 // Real re-declarations (same original name AND descriptor —
3036 // R8 duplicates) are already deduped by the emitter's claim
3037 // logic; only SANITIZER collapses reach here and every one of
3038 // them is a distinct method.
3039 let mut base = base.clone();
3040 let mut seen_orig: jdc_core::FxHashSet<(&str, &str)> =
3041 jdc_core::FxHashSet::default();
3042 for m in group {
3043 if !seen_orig.insert((&m.name, &m.desc)) {
3044 continue; // exact duplicate: emitter drops it
3045 }
3046 let display = suffix_unique(&base, &mut m_taken);
3047 out.entry(std::sync::Arc::from(name.as_str()))
3048 .or_default()
3049 .push(jdc_core::rename::FieldRename {
3050 name: m.name.clone(),
3051 desc: m.desc.clone(),
3052 display: std::sync::Arc::from(display.as_str()),
3053 });
3054 // The base stays the sanitized ORIGINAL so the first
3055 // occurrence keeps the plain name.
3056 let _ = &mut base;
3057 }
3058 }
3059 // ---- impostor overrides (R8 generic specialization) ----
3060 // A class method whose (name, argsig) matches an ancestor
3061 // declaration but whose return type satisfies NONE of the
3062 // ancestor returns is not an override Java can express: the
3063 // pair shares an erasure, so the class cannot declare both, and
3064 // ART never resolved it either (interface dispatch matches
3065 // name+descriptor — the missing proto throws AbstractMethodError
3066 // at runtime; weibo IStreamPresenter.getView()IStreamView vs the
3067 // impl's getView()IPageView with no subtype edge, ×258 across
3068 // getView/getWidget/getListView families). Rename the impostor
3069 // (the registry carries every caller and the propagation below
3070 // carries subclasses) and let synth_missing_interface_stubs add
3071 // the ART-faithful stub — rename-aware provision makes the
3072 // requirement missing again.
3073 if let Some((fwl, pll)) = &anc_chain {
3074 for m in &methods {
3075 if m.is_static()
3076 || &*m.name == "<init>"
3077 || &*m.name == "<clinit>"
3078 {
3079 continue;
3080 }
3081 let d: &str = &m.desc;
3082 let lo = d.find('(').map(|i| i + 1).unwrap_or(0);
3083 let hi = d.find(')').unwrap_or(d.len());
3084 let m_ret = &d[hi + 1..];
3085 // Lazy per-layer scan: `found` replaces the old
3086 // `map.get(key)` presence gate (no ancestor declares
3087 // (name, argsig) ⇒ nothing to violate ⇒ skip).
3088 let mut found = false;
3089 let mut satisfied = false;
3090 'lay: for e in fwl.iter().chain(pll.iter()) {
3091 let Some(rets) = e.methods.get(m.name.as_ref()) else {
3092 continue;
3093 };
3094 for (a, r) in rets {
3095 if **a != d[lo..hi] {
3096 continue;
3097 }
3098 found = true;
3099 if &**r == m_ret
3100 || match (
3101 r.strip_prefix('L')
3102 .and_then(|x| x.strip_suffix(';')),
3103 m_ret
3104 .strip_prefix('L')
3105 .and_then(|x| x.strip_suffix(';')),
3106 ) {
3107 (Some(rc), Some(mc)) => pool.is_subtype(mc, rc),
3108 _ => false,
3109 }
3110 {
3111 satisfied = true;
3112 break 'lay;
3113 }
3114 }
3115 }
3116 if !found || satisfied {
3117 continue;
3118 }
3119 // Already renamed by a clash-group rule above?
3120 let already = out
3121 .get(&std::sync::Arc::from(name.as_str()))
3122 .is_some_and(|v| {
3123 v.iter().any(|fr| *fr.name == *m.name && *fr.desc == *m.desc)
3124 });
3125 if already {
3126 continue;
3127 }
3128 let base = crate::classdec::java_ident(&m.name).into_owned();
3129 let display = suffix_unique(&base, &mut m_taken);
3130 out.entry(std::sync::Arc::from(name.as_str()))
3131 .or_default()
3132 .push(jdc_core::rename::FieldRename {
3133 name: m.name.clone(),
3134 desc: m.desc.clone(),
3135 display: std::sync::Arc::from(display.as_str()),
3136 });
3137 }
3138 }
3139 }
3140 // ---- method-rename propagation down the hierarchy ----
3141 // A renamed method must keep ONE display across its whole override
3142 // family: the parent's abstract declaration and every subclass
3143 // implementation/caller render through the registry, and a missed
3144 // link re-breaks the override ("未覆盖" at each concrete subclass)
3145 // or the call site (cannot-find). Register each method entry on the
3146 // full transitive subclass + implementer closure — a subclass that
3147 // does NOT declare the method still serves as a dex ref owner for
3148 // the inherited method, so it needs the entry too (same reasoning
3149 // as register_field_rename_with_subs for fields). Ancestor-forced
3150 // displays win; a colliding local entry re-mints off the original
3151 // method name and re-propagates.
3152 {
3153 let mut down: jdc_core::FxHashMap<&str, Vec<&str>> =
3154 jdc_core::FxHashMap::default();
3155 for (sup, children) in subs.iter() {
3156 down.entry(*sup).or_default().extend(children.iter().copied());
3157 }
3158 for n in &pool.order {
3159 if let Some(pc) = pool.get_if_materialized(n) {
3160 for i in pc.interfaces.iter() {
3161 down.entry(i.as_str()).or_default().push(n.as_str());
3162 }
3163 }
3164 }
3165 type PropEntry = (
3166 std::sync::Arc<str>,
3167 std::sync::Arc<str>,
3168 std::sync::Arc<str>,
3169 std::sync::Arc<str>,
3170 );
3171 let mut queue: std::collections::VecDeque<PropEntry> =
3172 std::collections::VecDeque::new();
3173 {
3174 // Sorted seed: `out` is a std HashMap (RandomState) — an
3175 // unsorted seed would make conflicting ancestor forces
3176 // resolve in per-process order (display names flipping
3177 // run-to-run).
3178 let mut seed: Vec<PropEntry> = Vec::new();
3179 for (cls, entries) in out.iter() {
3180 for fr in entries {
3181 if fr.desc.contains('(') {
3182 seed.push((
3183 cls.clone(),
3184 fr.name.clone(),
3185 fr.desc.clone(),
3186 fr.display.clone(),
3187 ));
3188 }
3189 }
3190 }
3191 seed.sort();
3192 for t in seed {
3193 queue.push_back(t);
3194 }
3195 }
3196 let mut guard = 0usize;
3197 while let Some((cls, n, d, disp)) = queue.pop_front() {
3198 guard += 1;
3199 if guard > 2_000_000 {
3200 break;
3201 }
3202 let Some(children) = down.get(cls.as_ref()).cloned() else {
3203 continue;
3204 };
3205 for child in children {
3206 let mut changed = false;
3207 let mut reminted: Vec<PropEntry> = Vec::new();
3208 {
3209 let child_key: std::sync::Arc<str> = std::sync::Arc::from(child);
3210 let entries = out.entry(child_key.clone()).or_default();
3211 // A raw method of the child literally named `disp`
3212 // with a different signature blocks the force —
3213 // renaming that raw method instead is the over-reach
3214 // class (500k blowup history); skip this child.
3215 let raw_blocked = pool
3216 .get_if_materialized(child)
3217 .is_some_and(|pc| {
3218 pc.all_methods().any(|m| {
3219 crate::classdec::java_ident(&m.name) == disp.as_ref()
3220 && m.desc != d
3221 })
3222 });
3223 if raw_blocked {
3224 continue;
3225 }
3226 match entries
3227 .iter_mut()
3228 .find(|fr| *fr.name == *n && *fr.desc == *d)
3229 {
3230 Some(e) if e.display == disp => {}
3231 Some(e) => {
3232 e.display = disp.clone();
3233 changed = true;
3234 }
3235 None => {
3236 entries.push(jdc_core::rename::FieldRename {
3237 name: n.clone(),
3238 desc: d.clone(),
3239 display: disp.clone(),
3240 });
3241 changed = true;
3242 }
3243 }
3244 if changed {
3245 // Display collisions inside the child: the
3246 // ancestor-forced entry keeps `disp`; others
3247 // re-mint from their original method name.
3248 let mut taken: jdc_core::FxHashSet<String> =
3249 jdc_core::FxHashSet::default();
3250 if let Some(pc) = pool.get_if_materialized(child) {
3251 for m in pc.all_methods() {
3252 taken.insert(
3253 crate::classdec::java_ident(&m.name).into_owned(),
3254 );
3255 }
3256 }
3257 for e in entries.iter() {
3258 taken.insert(e.display.to_string());
3259 }
3260 let mut seen: jdc_core::FxHashSet<String> =
3261 jdc_core::FxHashSet::default();
3262 seen.insert(disp.to_string());
3263 for e in entries.iter_mut() {
3264 if *e.name == *n && *e.desc == *d {
3265 continue;
3266 }
3267 if seen.insert(e.display.to_string()) {
3268 continue;
3269 }
3270 let base =
3271 crate::classdec::java_ident(&e.name).into_owned();
3272 let nd: std::sync::Arc<str> = std::sync::Arc::from(
3273 suffix_unique(&base, &mut taken).as_str(),
3274 );
3275 e.display = nd.clone();
3276 reminted.push((
3277 child_key.clone(),
3278 e.name.clone(),
3279 e.desc.clone(),
3280 nd,
3281 ));
3282 }
3283 }
3284 }
3285 if changed {
3286 let child_key: std::sync::Arc<str> = std::sync::Arc::from(child);
3287 queue.push_back((child_key.clone(), n.clone(), d.clone(), disp.clone()));
3288 for r in reminted {
3289 queue.push_back(r);
3290 }
3291 }
3292 }
3293 }
3294 }
3295 inherited_obscuring_renames(pool, &mut out, &pkg_displays);
3296 out
3297}
3298
3299/// Inherited-field variant of the obscuring rule: class C renders a
3300/// member nested type `d` while INHERITING a field `d` from a pool
3301/// superclass — `C.d.b(..)` binds to the inherited variable (fields
3302/// obscure types, JLS 6.4.2) and fails ("无法从静态上下文中引用非静态
3303/// 变量 d" + "无法取消引用int" pairs, LynxBaseScrollViewDragging ×84 —
3304/// latent behind the broken-superclass hub until the same-class rule
3305/// healed it). The rename lands on the DECLARING class (one declaration
3306/// to re-render) and is registered under every transitive subclass as
3307/// well, because dex field refs may name any subclass as owner and the
3308/// lift-time consult keys on the ref's owner.
3309/// Register a field rename under the declaring class AND every transitive
3310/// subclass: dex field refs for an inherited access may name ANY class in
3311/// the hierarchy as owner (`iput Lh$a;->a` inside the constant-subclass
3312/// ctor of `h`), and the lift-time consult keys on the ref's owner — a
3313/// declaring-class-only entry leaves those refs stale (org/a/c/h ×3).
3314/// Subclasses that REDECLARE (name, desc) hide the field — their own
3315/// field is distinct and must keep its name (and their own obscuring,
3316/// if any, is handled when the loop reaches them).
3317fn register_field_rename_with_subs(
3318 pool: &DexPool,
3319 subs: &jdc_core::FxHashMap<&str, Vec<&str>>,
3320 out: &mut HashMap<std::sync::Arc<str>, Vec<jdc_core::rename::FieldRename>>,
3321 owner: &str,
3322 fname: &str,
3323 fdesc: &str,
3324 display: &str,
3325) {
3326 let mut queue: Vec<&str> = vec![owner];
3327 let mut seen: jdc_core::FxHashSet<&str> = jdc_core::FxHashSet::default();
3328 seen.insert(owner);
3329 let mut first = true;
3330 while let Some(c) = queue.pop() {
3331 let redeclares = if first {
3332 first = false;
3333 false // the declaring class itself: always register
3334 } else {
3335 pool.get_if_materialized(c)
3336 .map(|pc| {
3337 pc.static_fields
3338 .iter()
3339 .chain(pc.instance_fields.iter())
3340 .any(|f| f.name == fname && f.desc == fdesc)
3341 })
3342 .unwrap_or(false)
3343 };
3344 if redeclares {
3345 continue; // hidden below this point: its subtree refs bind to its own field
3346 }
3347 out.entry(std::sync::Arc::from(c))
3348 .or_default()
3349 .push(jdc_core::rename::FieldRename {
3350 name: std::sync::Arc::from(fname),
3351 desc: std::sync::Arc::from(fdesc),
3352 display: std::sync::Arc::from(display),
3353 });
3354 if let Some(children) = subs.get(c) {
3355 for ch in children {
3356 if seen.insert(*ch) {
3357 queue.push(*ch);
3358 }
3359 }
3360 }
3361 }
3362}
3363
3364fn inherited_obscuring_renames(
3365 pool: &DexPool,
3366 out: &mut HashMap<std::sync::Arc<str>, Vec<jdc_core::rename::FieldRename>>,
3367 pkg_displays: &jdc_core::FxHashMap<&str, jdc_core::FxHashSet<String>>,
3368) {
3369 let root_segs = pool.root_pkg_segs();
3370 // Reverse super map over materialized classes.
3371 let mut subs: jdc_core::FxHashMap<&str, Vec<&str>> = jdc_core::FxHashMap::default();
3372 for n in &pool.order {
3373 let Some(pc) = pool.get_if_materialized(n) else {
3374 continue;
3375 };
3376 if let Some(sup) = &pc.super_name {
3377 if sup != "java/lang/Object" {
3378 subs.entry(sup.as_str()).or_default().push(n.as_str());
3379 }
3380 }
3381 }
3382 let mut renamed: jdc_core::FxHashSet<(String, String, String)> =
3383 jdc_core::FxHashSet::default();
3384 for n in &pool.order {
3385 let Some(pc) = pool.get_if_materialized(n) else {
3386 continue;
3387 };
3388 if pc.is_interface() {
3389 continue;
3390 }
3391 // Member-rendered child displays of THIS class.
3392 let mut child_displays: Vec<String> = Vec::new();
3393 for child in pool.children_of(n.as_str()) {
3394 let Some(rest) = child
3395 .strip_prefix(n.as_str())
3396 .and_then(|t| t.strip_prefix('$'))
3397 else {
3398 continue;
3399 };
3400 if !clean_member_tail(rest) {
3401 continue;
3402 }
3403 if crate::find_outer_name(pool, child).as_deref() != Some(n.as_str()) {
3404 continue;
3405 }
3406 let renamed_disp = crate::apply_class_rename(child);
3407 let last = renamed_disp
3408 .rsplit('/')
3409 .next()
3410 .unwrap_or(&renamed_disp)
3411 .rsplit('$')
3412 .next()
3413 .unwrap_or(rest)
3414 .to_string();
3415 child_displays.push(last);
3416 }
3417 if child_displays.is_empty() {
3418 continue;
3419 }
3420 // Walk the super chain for an inherited field whose display
3421 // collides; own fields are the same-class rule's job.
3422 let own: jdc_core::FxHashSet<String> = pc
3423 .static_fields
3424 .iter()
3425 .chain(pc.instance_fields.iter())
3426 .map(|f| crate::classdec::java_ident(&f.name).into_owned())
3427 .collect();
3428 let mut sup = pc.super_name.clone();
3429 while let Some(sname) = sup {
3430 if sname == "java/lang/Object" {
3431 break;
3432 }
3433 let Some(sc) = pool.get_if_materialized(&sname) else {
3434 break;
3435 };
3436 for f in sc.static_fields.iter().chain(sc.instance_fields.iter()) {
3437 let fdisp = crate::classdec::java_ident(&f.name).into_owned();
3438 if fdisp.starts_with("this$") || !child_displays.contains(&fdisp) {
3439 continue;
3440 }
3441 if !renamed.insert((sname.clone(), f.name.to_string(), f.desc.clone())) {
3442 continue;
3443 }
3444 // Mint in the DECLARING class's namespace: avoid its
3445 // fields + its own member-rendered child displays.
3446 let mut avoid: jdc_core::FxHashSet<String> = sc
3447 .static_fields
3448 .iter()
3449 .chain(sc.instance_fields.iter())
3450 .map(|g| crate::classdec::java_ident(&g.name).into_owned())
3451 .collect();
3452 // The declaring class's PACKAGE class displays (post-
3453 // rename): minting onto one shadows its qualified refs
3454 // from inside the class (the a→a2-onto-display-a2 bug).
3455 if let Some(names) = pkg_displays
3456 .get(sname.rfind('/').map(|i| &sname[..i]).unwrap_or(""))
3457 {
3458 avoid.extend(names.iter().cloned());
3459 }
3460 for child in pool.children_of(sname.as_str()) {
3461 let Some(rest) = child
3462 .strip_prefix(sname.as_str())
3463 .and_then(|t| t.strip_prefix('$'))
3464 else {
3465 continue;
3466 };
3467 if !clean_member_tail(rest) {
3468 continue;
3469 }
3470 let rd = crate::apply_class_rename(child);
3471 avoid.insert(
3472 rd.rsplit('/')
3473 .next()
3474 .unwrap_or(&rd)
3475 .rsplit('$')
3476 .next()
3477 .unwrap_or(rest)
3478 .to_string(),
3479 );
3480 }
3481 let mut k = 1u32;
3482 let display = loop {
3483 k += 1;
3484 let cand = format!("{fdisp}{k}");
3485 // root_segs: see the own-field mint site — a
3486 // package first segment must never be minted.
3487 if !avoid.contains(&cand) && !root_segs.contains(&cand) {
3488 break cand;
3489 }
3490 };
3491 register_field_rename_with_subs(
3492 pool, &subs, out, &sname, &f.name, &f.desc, &display,
3493 );
3494 if std::env::var("DDC_OBSCURE_STATS").is_ok() {
3495 eprintln!("[obscure-inh] {sname} field {} -> {display} (child of {n})", f.name);
3496 }
3497 }
3498 sup = sc.super_name.clone();
3499 }
3500 let _ = &own;
3501 }
3502}
3503
3504fn suffix_unique(base: &str, taken: &mut jdc_core::FxHashSet<String>) -> String {
3505 let mut k = 1u32;
3506 loop {
3507 k += 1;
3508 let cand = format!("{base}{k}");
3509 if taken.insert(cand.clone()) {
3510 return cand;
3511 }
3512 }
3513}
3514
3515/// member_collision_renames + field_deshadow_renames, collision-registry
3516/// entries winning per (owner, name, desc).
3517fn combined_field_renames(
3518 pool: &DexPool,
3519) -> HashMap<std::sync::Arc<str>, Vec<jdc_core::rename::FieldRename>> {
3520 let mut base = member_collision_renames(pool);
3521 let extra = field_deshadow_renames(pool);
3522 let mut merged = 0usize;
3523 for (owner, v) in extra {
3524 let e = base.entry(owner).or_default();
3525 for fr in v {
3526 if !e.iter().any(|x| x.name == fr.name && x.desc == fr.desc) {
3527 e.push(fr);
3528 merged += 1;
3529 }
3530 }
3531 }
3532 if std::env::var("DDC_STATS").is_ok() {
3533 eprintln!("[renames] field-deshadow renames: {merged}");
3534 }
3535 base
3536}
3537
3538/// Field deshadow (JLS 6.4.2, expression position): a FIELD whose display
3539/// name equals a root package first segment captures package-qualified
3540/// renders inside its family's file — androidx z2's field `j` binds the
3541/// `j` of `j.a.a` (找不到符号 变量 a). Rename through the field registry
3542/// (declaration and every reference funnel through field_display).
3543/// Gate: only when the family actually references that segment
3544/// (family_ref_segments body scan) or the segment is the family's OWN
3545/// package root (same-package refs fall back to `root.x` FQN renders) —
3546/// ungated field renames are the six-times-falsified blast radius.
3547fn field_deshadow_renames(
3548 pool: &DexPool,
3549) -> HashMap<std::sync::Arc<str>, Vec<jdc_core::rename::FieldRename>> {
3550 let mut out: HashMap<std::sync::Arc<str>, Vec<jdc_core::rename::FieldRename>> =
3551 HashMap::default();
3552 let root_segs = pool.root_pkg_segs();
3553 if root_segs.is_empty() {
3554 return out;
3555 }
3556 // Candidate fields per family (display, original name, desc).
3557 let mut cand: HashMap<
3558 String,
3559 Vec<(String, String, String, u32)>,
3560 > = HashMap::default();
3561 for name in &pool.order {
3562 let Some(pc) = pool.get_if_materialized(name) else {
3563 continue;
3564 };
3565 for f in pc.static_fields.iter().chain(pc.instance_fields.iter()) {
3566 let disp = crate::classdec::java_ident(&f.name).into_owned();
3567 if root_segs.contains(&disp) {
3568 cand
3569 .entry(name.clone())
3570 .or_default()
3571 .push((disp, f.name.clone(), f.desc.clone(), f.access));
3572 }
3573 }
3574 }
3575 if cand.is_empty() {
3576 return out;
3577 }
3578 let cand_set: jdc_core::FxHashSet<String> = cand.keys().cloned().collect();
3579 let t0 = std::time::Instant::now();
3580 let (fam_segs, fam_nest) =
3581 crate::refscan::family_ref_segments(&pool.dexes, &cand_set);
3582 if std::env::var("DDC_STATS").is_ok() {
3583 eprintln!(
3584 "[renames] field-deshadow scan: cands={} scan={:?}",
3585 cand_set.len(),
3586 t0.elapsed()
3587 );
3588 }
3589 for (fam, fields) in cand {
3590 let own_root = fam.find('/').map(|i| fam[..i].to_string());
3591 let scanned = fam_segs.get(&fam);
3592 // NO nested-tail collision trigger here: a private field named
3593 // like a nested class does capture `Fam.b.member` in expression
3594 // position (lark LKEvent static-ctx family, ~1k lines), but
3595 // renaming it is corpus-toxic even gated private+body-
3596 // referenced — lark +32k (43,643 renames), weixin/weibo −200.
3597 // Eighth falsification of loose rename gates: the resolution
3598 // perturbation surface of mass field renames dwarfs the target
3599 // family. The fam_nest scan stays wired for a future
3600 // render-side fix (the capture is only unfixable INSIDE the
3601 // family file; foreign files could import the nested type).
3602 let _ = &fam_nest;
3603 let hits: Vec<(String, String, String)> = fields
3604 .into_iter()
3605 .filter(|(disp, _, _, _access)| {
3606 scanned.is_some_and(|s| s.contains(disp))
3607 || own_root.as_deref() == Some(disp.as_str())
3608 })
3609 .map(|(d, n, de, _)| (d, n, de))
3610 .collect();
3611 if hits.is_empty() {
3612 continue;
3613 }
3614 // Names already taken in the family's member scope: field and
3615 // method displays plus direct nested-class tails (member types
3616 // share the lexical scope of the rendered file). Built only for
3617 // hit families — the per-family setup must stay off the 175k-
3618 // candidate loop (an O(pool.order) nested scan there cost 60s on
3619 // weixin).
3620 let mut taken: jdc_core::FxHashSet<String> = jdc_core::FxHashSet::default();
3621 if let Some(pc) = pool.get_if_materialized(&fam) {
3622 for f in pc.static_fields.iter().chain(pc.instance_fields.iter()) {
3623 taken.insert(crate::classdec::java_ident(&f.name).into_owned());
3624 }
3625 for m in pc.direct_methods.iter().chain(pc.virtual_methods.iter()) {
3626 taken.insert(crate::classdec::java_ident(&m.name).into_owned());
3627 }
3628 }
3629 let mut nested_tails: jdc_core::FxHashSet<String> =
3630 jdc_core::FxHashSet::default();
3631 for child in pool.children_of(&fam) {
3632 if let Some(tail) = child.rsplit('$').next() {
3633 if !tail.is_empty() {
3634 taken.insert(tail.to_string());
3635 nested_tails.insert(tail.to_string());
3636 }
3637 }
3638 }
3639 for (disp, name, desc) in hits {
3640 let mut k = 0u32;
3641 let new_disp = loop {
3642 k += 1;
3643 let c = if k == 1 {
3644 format!("{disp}x")
3645 } else {
3646 format!("{disp}x{k}")
3647 };
3648 if !taken.contains(&c) && !root_segs.contains(&c) {
3649 break c;
3650 }
3651 };
3652 taken.insert(new_disp.clone());
3653 out.entry(std::sync::Arc::from(fam.as_str()))
3654 .or_default()
3655 .push(jdc_core::rename::FieldRename {
3656 name: std::sync::Arc::from(name.as_str()),
3657 desc: std::sync::Arc::from(desc.as_str()),
3658 display: std::sync::Arc::from(new_disp.as_str()),
3659 });
3660 }
3661 }
3662 out
3663}
3664pub use jdc_core::rename::apply_class_rename;
3665
3666// ---------------------------------------------------------------------------
3667// Default-package relocation.
3668// ---------------------------------------------------------------------------
3669
3670/// The synthetic package the default-package cohort currently relocates
3671/// to (Mutex, not OnceLock: `set_class_renames` replaces the registry per
3672/// pool, so a second pool in one process must be able to re-key this).
3673static ROOT_PKG: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
3674
3675/// The synthetic package display root-package classes were moved under
3676/// (`None` when no relocation ran). Consumers keying per-package caches
3677/// by the ORIGINAL package map this display back to `""`.
3678pub fn root_pkg_display() -> Option<String> {
3679 ROOT_PKG
3680 .lock()
3681 .unwrap_or_else(|e| e.into_inner())
3682 .clone()
3683}
3684
3685/// Default-package relocation: javac cannot resolve ANY reference from a
3686/// named package to an unnamed-package class (JLS 7.4.2 — `private it0 f;`
3687/// inside com.amap.X is 找不到符号 whatever the syntax; xingye ~198k +
3688/// Amap ~81k errors ≈ 73% of the whole-directory sweep total, and
3689/// kotlin.jvm.Function0 even EXTENDS a root class on xingye). No source
3690/// syntax escapes it — but the rename registry escapes the NAME: move the
3691/// whole root cohort under a synthetic package (`ddcroot/a.java`,
3692/// `package ddcroot;`) and every cross-package ref renders the resolvable
3693/// FQN `ddcroot.a`. Cohort-uniform: in-cohort refs keep resolving (one
3694/// new shared package), the case/lossy dedupes inside the cohort still
3695/// hold (a directory move preserves relative collisions), and the
3696/// synthetic segment is collision-bumped against every pool package and
3697/// class so it can never shadow or be shadowed. Runs LAST (prefixes the
3698/// settled displays). Fidelity note: declared package no longer matches
3699/// the binary name — the same trade every rename rule here makes, on a
3700/// cohort whose cross-package render is otherwise dead code.
3701fn root_pkg_relocation(pool: &DexPool, map: &mut HashMap<String, String>) {
3702 // Gate on NAMES only (identical verdict in lazy browse and full
3703 // decompile — the display must not depend on materialization):
3704 // relocation matters only when BOTH cohorts exist — the JLS-dead
3705 // direction is named-package → root-package, so an all-root app
3706 // (hello fixtures, pure-demo dexes) keeps the faithful layout.
3707 let has_root = pool.order.iter().any(|n| !n.contains('/'));
3708 let has_named = pool.order.iter().any(|n| n.contains('/'));
3709 if !has_root || !has_named {
3710 *ROOT_PKG.lock().unwrap_or_else(|e| e.into_inner()) = None;
3711 return;
3712 }
3713 let root_segs = pool.root_pkg_segs();
3714 let mut pkg = "ddcroot".to_string();
3715 while pool.has_name(&pkg) || root_segs.contains(&pkg) {
3716 pkg.push('_');
3717 }
3718 // A root class whose simple name IS a top-level package segment
3719 // (`com`, `org`, ...) cannot simply MOVE into the synthetic
3720 // package: a same-package type shadows the package name in every
3721 // qualified ref from every cohort file (JLS 6.4.1 — rimet's root
3722 // `com`/`org` hijacked 235k `com.alibaba...` refs as 类 alibaba
3723 // 位置: 类 com). Those get a bumped first segment (`com` →
3724 // ddcroot/com2) — a display rename the registry carries through
3725 // every ref path, like the obscuring renames.
3726 const FW_SEGS: [&str; 10] = [
3727 "java", "javax", "android", "org", "junit", "dalvik", "libcore", "androidx", "kotlin",
3728 "kotlinx",
3729 ];
3730 let mut taken: jdc_core::FxHashSet<String> = jdc_core::FxHashSet::default();
3731 for name in &pool.order {
3732 if name.contains('/') {
3733 continue;
3734 }
3735 let disp = map.get(name).cloned().unwrap_or_else(|| name.clone());
3736 taken.insert(format!("{pkg}/{disp}"));
3737 }
3738 let mut moved = 0usize;
3739 let mut bumped = 0usize;
3740 for name in &pool.order {
3741 if name.contains('/') {
3742 continue;
3743 }
3744 let disp = map.get(name).cloned().unwrap_or_else(|| name.clone());
3745 if disp.contains('/') {
3746 continue; // defensive: some rule already packaged it
3747 }
3748 if disp == *name && name.contains('$') && find_outer_name(pool, name).is_some() {
3749 // An UNRENAMED nested name with a pool outer must stay
3750 // entry-less so apply_class_rename's $-walk composes it
3751 // through the outer's relocated+renamed display — an exact
3752 // entry short-circuits the walk and freezes the outer's
3753 // pre-rename simple (xingye's case-collision quads:
3754 // `ue5$a` exact-mapped to ddcroot/ue5$a instead of
3755 // ddcroot/ue5_4$a — 程序包ddcroot.ue5不存在 ×61k).
3756 continue;
3757 }
3758 let head = disp.split('$').next().unwrap_or(&disp);
3759 let collide = root_segs.contains(head) || FW_SEGS.contains(&head);
3760 if !collide {
3761 map.insert(name.clone(), format!("{pkg}/{disp}"));
3762 moved += 1;
3763 continue;
3764 }
3765 let rest = &disp[head.len()..];
3766 let mut k = 1u32;
3767 loop {
3768 k += 1;
3769 let nh = format!("{head}{k}");
3770 if root_segs.contains(&nh) || FW_SEGS.contains(&nh.as_str()) {
3771 continue;
3772 }
3773 let cand = format!("{pkg}/{nh}{rest}");
3774 if taken.contains(&cand) {
3775 continue;
3776 }
3777 taken.insert(cand.clone());
3778 map.insert(name.clone(), cand);
3779 moved += 1;
3780 bumped += 1;
3781 break;
3782 }
3783 }
3784 *ROOT_PKG.lock().unwrap_or_else(|e| e.into_inner()) = Some(pkg.clone());
3785 if std::env::var("DDC_STATS").is_ok() {
3786 eprintln!("[renames] root-pkg relocation: {moved} classes -> {pkg}/ ({bumped} segment-bumped)");
3787 }
3788}