Skip to main content

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;
10
11pub use classdec::ClassOptions;
12pub mod ctx;
13pub mod lift;
14pub mod method;
15pub mod passes;
16pub mod platform;
17
18use jdc_core::FxHashMap as HashMap;
19
20use ddc_dex::annotations::{self, EncodedValue};
21
22/// A resolved static-field initializer.
23#[derive(Debug, Clone)]
24pub enum StaticValue {
25    Int(i64),
26    Float(f32),
27    Double(f64),
28    Str(String),
29    Type(String),
30    Boolean(bool),
31    Null,
32    /// (declaring class, field name) — enum constants.
33    Field(String, String),
34    Other,
35}
36use ddc_dex::{ClassDef, DexFile};
37use jdc_core::types::{
38    parse_field_descriptor, parse_method_descriptor, JavaType, MethodDescriptor,
39};
40
41// ---------------------------------------------------------------------------
42// Access flags (Dalvik numbering, JVM-compatible subset).
43// ---------------------------------------------------------------------------
44pub mod access {
45    pub const ACC_PUBLIC: u32 = 0x1;
46    pub const ACC_PRIVATE: u32 = 0x2;
47    pub const ACC_PROTECTED: u32 = 0x4;
48    pub const ACC_STATIC: u32 = 0x8;
49    pub const ACC_FINAL: u32 = 0x10;
50    pub const ACC_SYNCHRONIZED: u32 = 0x20;
51    pub const ACC_BRIDGE: u32 = 0x40;
52    pub const ACC_VARARGS: u32 = 0x80;
53    pub const ACC_NATIVE: u32 = 0x100;
54    pub const ACC_INTERFACE: u32 = 0x200;
55    pub const ACC_ABSTRACT: u32 = 0x400;
56    pub const ACC_STRICT: u32 = 0x800;
57    pub const ACC_SYNTHETIC: u32 = 0x1000;
58    pub const ACC_ANNOTATION: u32 = 0x2000;
59    pub const ACC_ENUM: u32 = 0x4000;
60    pub const ACC_CONSTRUCTOR: u32 = 0x1_0000;
61    pub const ACC_DECLARED_SYNCHRONIZED: u32 = 0x2_0000;
62}
63
64/// One field of a pooled class.
65#[derive(Debug, Clone)]
66pub struct PoolField {
67    pub name: String,
68    /// Field descriptor (`I`, `Ljava/lang/String;`, ...).
69    pub desc: String,
70    pub access: u32,
71    pub is_static: bool,
72}
73
74/// One method of a pooled class.
75#[derive(Debug, Clone)]
76pub struct PoolMethod {
77    /// Shared with the dex string table (the idx IS the dedup key).
78    pub name: std::sync::Arc<str>,
79    /// Method descriptor, shared per proto (a dex's proto table is the
80    /// descriptor dedup layer — 1.9M methods on lark share ~1 proto
81    /// table's worth of unique descriptors).
82    pub desc: std::sync::Arc<str>,
83    pub access: u32,
84    pub code_off: u32,
85    pub debug_info_off: u32,
86    /// Which DEX image the body lives in.
87    pub dex_idx: usize,
88}
89
90impl PoolMethod {
91    pub fn parsed_desc(&self) -> Option<MethodDescriptor> {
92        parse_method_descriptor(&self.desc)
93    }
94    pub fn is_static(&self) -> bool {
95        self.access & access::ACC_STATIC != 0
96    }
97    pub fn is_abstract_or_native(&self) -> bool {
98        self.access & (access::ACC_ABSTRACT | access::ACC_NATIVE) != 0
99    }
100}
101
102/// One pool entry: either already built, or name-registered with its
103/// (dex index, class_def index) locator for on-demand construction.
104enum ClassEntry {
105    Eager(PoolClass),
106    Lazy {
107        at: (usize, usize),
108        pc: std::sync::OnceLock<PoolClass>,
109    },
110}
111
112/// A class materialized from one `class_def_item` (with ids resolved to
113/// names and the class data expanded).
114#[derive(Debug, Clone)]
115pub struct PoolClass {
116    pub name: String,
117    pub access: u32,
118    /// `None` for `java/lang/Object` roots.
119    pub super_name: Option<String>,
120    pub interfaces: Vec<String>,
121    pub source_file: Option<String>,
122    pub static_fields: Vec<PoolField>,
123    pub instance_fields: Vec<PoolField>,
124    pub direct_methods: Vec<PoolMethod>,
125    pub virtual_methods: Vec<PoolMethod>,
126    /// Static initial values aligned with the head of `static_fields`.
127    pub static_values: Vec<StaticValue>,
128    /// Nesting evidence with annotation ids resolved to names.
129    pub nesting: ResolvedNesting,
130    /// Which DEX image the class body lives in (provenance header).
131    pub dex_idx: usize,
132}
133
134/// Nesting evidence, names resolved at pooling time.
135#[derive(Debug, Clone, Default)]
136pub struct ResolvedNesting {
137    pub enclosing_class: Option<String>,
138    /// (class internal name, method name) of the enclosing method.
139    pub enclosing_method: Option<(String, String)>,
140    pub member_classes: Vec<String>,
141}
142
143impl PoolClass {
144    pub fn is_interface(&self) -> bool {
145        self.access & access::ACC_INTERFACE != 0
146    }
147
148    pub fn is_enum(&self) -> bool {
149        self.access & access::ACC_ENUM != 0
150    }
151
152    pub fn is_synthetic(&self) -> bool {
153        self.access & access::ACC_SYNTHETIC != 0
154    }
155
156    pub fn is_static_nested(&self) -> bool {
157        self.access & access::ACC_STATIC != 0
158    }
159
160    /// All methods in declaration order.
161    pub fn all_methods(&self) -> impl Iterator<Item = &PoolMethod> {
162        self.direct_methods
163            .iter()
164            .chain(self.virtual_methods.iter())
165    }
166
167    /// Find a method by name + descriptor.
168    pub fn find_method(&self, name: &str, desc: &str) -> Option<&PoolMethod> {
169        self.all_methods()
170            .find(|m| &*m.name == name && &*m.desc == desc)
171    }
172
173    /// Constructors `<init>` matching `arity` descriptor arguments.
174    pub fn ctors_by_arity(&self, arity: usize) -> Vec<&PoolMethod> {
175        self.all_methods()
176            .filter(|m| &*m.name == "<init>")
177            .filter(|m| {
178                m.parsed_desc()
179                    .map(|d| d.args.len() == arity)
180                    .unwrap_or(false)
181            })
182            .collect()
183    }
184
185    pub fn field_flags_of(&self, name: &str) -> Option<u32> {
186        self.static_fields
187            .iter()
188            .chain(self.instance_fields.iter())
189            .find(|f| f.name == name)
190            .map(|f| f.access)
191    }
192}
193
194/// Multi-DEX class pool: classes from all images, first definition wins.
195pub struct DexPool {
196    /// Images as Arcs: `dex()` hands out snapshots whose borrows stay
197    /// valid for the Arc's lifetime (decompile workers hold them), while
198    /// `release_images` empties the image data through exclusive access
199    /// when all of an image's classes are done (full-decompile driver
200    /// only — progressive callers keep images whole).
201    dexes: Vec<std::sync::Arc<DexFile>>,
202    /// Human label per image ("weibo!classes.dex") for the provenance
203    /// header; defaults to "dex N" until the CLI names the inputs.
204    pub dex_labels: Vec<String>,
205    /// Name → class entry. Eager pools materialize everything at add
206    /// time (full decompile, tests); lazy pools register names only and
207    /// materialize on first `get` (progressive `getclass` — one class's
208    /// PoolClass costs annotation reads, 145k of them cost ~0.2s).
209    classes: HashMap<String, ClassEntry>,
210    /// Class names in insertion order (stable for output).
211    pub order: Vec<String>,
212    /// Per-image remaining class count once `arm_retirement` fires.
213    retire_counts: std::sync::Mutex<Vec<u64>>,
214    retire_armed: std::sync::atomic::AtomicBool,
215    /// name → outer (computed once; `$` heuristic + dalvik annotations).
216    outers: std::sync::OnceLock<HashMap<String, Option<String>>>,
217    /// outer → direct children (computed once).
218    children: std::sync::OnceLock<HashMap<String, Vec<String>>>,
219    /// Per-image hot-reference interning (parallel to `dexes`).
220    ref_caches: Vec<DexRefCache>,
221}
222
223/// Lazily-filled, thread-shared reference interning for one image.
224///
225/// The lifter used to rebuild class names, field/method names and WHOLE
226/// method descriptors per INSTRUCTION (`method_ref` alone: N param
227/// Strings → `format!` descriptor → re-parse — 6-10 allocations per
228/// invoke). Every entry here is built at most once per (image, table
229/// index); lifts and the endless IR clones downstream are refcount
230/// bumps. Slots are `OnceLock` so worker threads fill them race-free
231/// without a lock on the hot path.
232pub(crate) struct DexRefCache {
233    proto_descs: Box<[std::sync::OnceLock<std::sync::Arc<jdc_core::types::MethodDescriptor>>]>,
234    type_names: Box<[std::sync::OnceLock<std::sync::Arc<str>>]>,
235    type_javas: Box<[std::sync::OnceLock<std::sync::Arc<jdc_core::types::JavaType>>]>,
236}
237
238impl DexRefCache {
239    fn new(protos: usize, types: usize) -> Self {
240        DexRefCache {
241            proto_descs: (0..protos).map(|_| std::sync::OnceLock::new()).collect(),
242            type_names: (0..types).map(|_| std::sync::OnceLock::new()).collect(),
243            type_javas: (0..types).map(|_| std::sync::OnceLock::new()).collect(),
244        }
245    }
246}
247
248impl DexPool {
249    pub fn new() -> Self {
250        DexPool {
251            dexes: Vec::new(),
252            retire_armed: std::sync::atomic::AtomicBool::new(false),
253            dex_labels: Vec::new(),
254            classes: HashMap::default(),
255            order: Vec::new(),
256            retire_counts: std::sync::Mutex::new(Vec::new()),
257            outers: std::sync::OnceLock::new(),
258            children: std::sync::OnceLock::new(),
259            ref_caches: Vec::new(),
260        }
261    }
262
263    /// Shared `MethodDescriptor` of a proto (one parse per image).
264    pub fn proto_desc_parsed(
265        &self,
266        di: usize,
267        proto_idx: u32,
268    ) -> std::sync::Arc<jdc_core::types::MethodDescriptor> {
269        let Some(dex) = self.dexes.get(di) else {
270            return std::sync::Arc::new(jdc_core::types::MethodDescriptor {
271                args: Vec::new(),
272                ret: jdc_core::types::JavaType::Void,
273            });
274        };
275        let build = || {
276            std::sync::Arc::new(parse_proto_desc(dex, proto_idx))
277        };
278        match self
279            .ref_caches
280            .get(di)
281            .and_then(|c| c.proto_descs.get(proto_idx as usize))
282        {
283            Some(slot) => slot.get_or_init(build).clone(),
284            None => build(),
285        }
286    }
287
288    /// Shared internal class name of a type id (one strip+alloc per image).
289    pub fn type_name_arc(&self, di: usize, type_idx: u32) -> std::sync::Arc<str> {
290        let Some(dex) = self.dexes.get(di) else {
291            return std::sync::Arc::from("");
292        };
293        let build = || std::sync::Arc::from(dex.class_name(type_idx).as_str());
294        match self
295            .ref_caches
296            .get(di)
297            .and_then(|c| c.type_names.get(type_idx as usize))
298        {
299            Some(slot) => slot.get_or_init(build).clone(),
300            None => build(),
301        }
302    }
303
304    /// Shared parsed type of a type id.
305    pub fn type_java(&self, di: usize, type_idx: u32) -> std::sync::Arc<jdc_core::types::JavaType> {
306        let Some(dex) = self.dexes.get(di) else {
307            return std::sync::Arc::new(jdc_core::types::JavaType::Object(
308                std::sync::Arc::from("java/lang/Object"),
309            ));
310        };
311        let build = || std::sync::Arc::new(desc_type(dex.type_name(type_idx)));
312        match self
313            .ref_caches
314            .get(di)
315            .and_then(|c| c.type_javas.get(type_idx as usize))
316        {
317            Some(slot) => slot.get_or_init(build).clone(),
318            None => build(),
319        }
320    }
321
322    /// name → outer map, computed lazily once.
323    fn outer_map(&self) -> &HashMap<String, Option<String>> {
324        self.outers.get_or_init(|| {
325            self.order
326                .iter()
327                .map(|n| (n.clone(), find_outer_name(self, n)))
328                .collect()
329        })
330    }
331
332    /// The outer class of `name`, from the cached map (borrowed).
333    pub fn outer_of(&self, name: &str) -> Option<&str> {
334        self.outer_map().get(name).and_then(|o| o.as_deref())
335    }
336
337    /// Direct nested children of `internal` (any `$` depth 1), cached.
338    /// (Perf: returns a borrowed slice — the owned-Vec clone ran once per
339    /// class on 98k-class runs.)
340    pub fn children_of(&self, internal: &str) -> &[String] {
341        if self.children.get().is_none() {
342            // Build FIRST, set ONCE: the previous shape set an empty map
343            // to claim the OnceLock and then silently failed to store the
344            // real index (`let _ = set(...)` on an initialized lock) —
345            // children_of returned [] forever, so member nested classes
346            // were neither inlined nor emitted as files (Guard$Report
347            // vanished whole; every corpus run since the borrow refactor
348            // dropped them, invisible to the syntax-only gate).
349            let mut idx: HashMap<String, Vec<String>> = HashMap::default();
350            for name in &self.order {
351                if let Some(outer) = self.outer_of(name).map(str::to_string) {
352                    idx.entry(outer).or_default().push(name.clone());
353                }
354            }
355            // A racing thread may have set an identical map first — the
356            // index is a pure function of `order`, so either copy is right.
357            let _ = self.children.set(idx);
358        }
359        self.children
360            .get()
361            .and_then(|m| m.get(internal))
362            .map(|v| v.as_slice())
363            .unwrap_or(&[])
364    }
365
366    /// Adds one image; duplicate class names keep their first definition.
367    /// Returns the image's index — call `set_dex_label` with it to give the
368    /// provenance header a real origin instead of the default "dex N".
369    pub fn add_dex(&mut self, dex: DexFile) -> usize {
370        let dex_idx = self.dexes.len();
371        // Pre-size the name map: 240k-entry growth rehashed repeatedly
372        // (reserve_rehash showed up in corpus profiles).
373        self.classes.reserve(dex.class_defs.len());
374        // The annotation reader borrows the image; pool classes are built
375        // before ownership moves into `self.dexes` (no full-image copy).
376        for cd in &dex.class_defs {
377            let name = dex.class_name(cd.class_idx);
378            if self.classes.contains_key(&name) {
379                continue;
380            }
381            let pc = pool_class_of(&dex, dex.raw(), cd, dex_idx);
382            self.classes.insert(name.clone(), ClassEntry::Eager(pc));
383            self.order.push(name);
384        }
385        self.ref_caches
386            .push(DexRefCache::new(dex.proto_count(), dex.type_count()));
387        self.dexes.push(std::sync::Arc::new(dex));
388        self.retire_counts.lock().unwrap().push(0);
389        self.dex_labels.push(format!("dex {}", dex_idx));
390        dex_idx
391    }
392
393    /// Registers class NAMES only; the PoolClass (annotation reads
394    /// included) is materialized on first `get`. Duplicate class names
395    /// keep their first definition, matching `add_dex`.
396    pub fn add_dex_lazy(&mut self, dex: DexFile) -> usize {
397        let dex_idx = self.dexes.len();
398        self.classes.reserve(dex.class_defs.len());
399        for (ci, cd) in dex.class_defs.iter().enumerate() {
400            let name = dex.class_name(cd.class_idx);
401            if self.classes.contains_key(&name) {
402                continue;
403            }
404            self.classes.insert(
405                name.clone(),
406                ClassEntry::Lazy {
407                    at: (dex_idx, ci),
408                    pc: std::sync::OnceLock::new(),
409                },
410            );
411            self.order.push(name);
412        }
413        self.ref_caches
414            .push(DexRefCache::new(dex.proto_count(), dex.type_count()));
415        self.dexes.push(std::sync::Arc::new(dex));
416        self.retire_counts.lock().unwrap().push(0);
417        self.dex_labels.push(format!("dex {}", dex_idx));
418        dex_idx
419    }
420
421    /// Label the image at `idx` (see `add_dex`).
422    pub fn set_dex_label(&mut self, idx: usize, label: impl Into<String>) {
423        if let Some(slot) = self.dex_labels.get_mut(idx) {
424            *slot = label.into();
425        }
426    }
427
428    pub fn len(&self) -> usize {
429        self.classes.len()
430    }
431
432    pub fn is_empty(&self) -> bool {
433        self.classes.is_empty()
434    }
435
436    pub fn get(&self, internal: &str) -> Option<&PoolClass> {
437        self.get_inner(internal, None)
438    }
439
440    /// `get` with optional pre-taken raw-image snapshots (one per
441    /// image). `materialize_all` hoists the `DexFile::raw()` lock out of
442    /// the per-class loop — the parallel materialize used to take the
443    /// same per-image lock once PER CLASS across all threads.
444    fn get_inner(&self, internal: &str, raws: Option<&[&[u8]]>) -> Option<&PoolClass> {
445        match self.classes.get(internal)? {
446            ClassEntry::Eager(pc) => Some(pc),
447            ClassEntry::Lazy { at, pc } => {
448                if let Some(built) = pc.get() {
449                    return Some(built);
450                }
451                let (di, ci) = *at;
452                let dex = self.dexes.get(di)?;
453                let cd = dex.class_defs.get(ci)?;
454                let raw = match raws {
455                    Some(r) => r.get(di).copied().unwrap_or(&[]),
456                    None => dex.raw(),
457                };
458                let built = pool_class_of(dex, raw, cd, di);
459                Some(pc.get_or_init(move || built))
460            }
461        }
462    }
463
464    /// Materialize every lazy entry (parallel across the given chunk
465    /// count). After this the pool is observationally identical to an
466    /// eagerly-built one — including the annotation-aware outer-map —
467    /// while the annotation reads ran on worker threads instead of the
468    /// serial pool build (~0.2s on weibo).
469    pub fn materialize_all(&self, threads: usize) {
470        let keys: Vec<String> = self
471            .classes
472            .iter()
473            .filter(|(_, e)| matches!(e, ClassEntry::Lazy { .. }))
474            .map(|(k, _)| k.clone())
475            .collect();
476        if keys.is_empty() {
477            return;
478        }
479        // One raw() snapshot per image for the whole sweep (see
480        // get_inner). Safe window: materialize_all completes before
481        // retirement is armed, so no image releases while these slices
482        // are alive.
483        let raws: Vec<&[u8]> = self.dexes.iter().map(|d| d.raw()).collect();
484        let threads = threads.max(1);
485        let next = std::sync::atomic::AtomicUsize::new(0);
486        std::thread::scope(|scope| {
487            for _ in 0..threads {
488                scope.spawn(|| loop {
489                    let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
490                    let Some(k) = keys.get(i) else { break };
491                    let _ = self.get_inner(k, Some(&raws));
492                });
493            }
494        });
495    }
496
497    /// `get` without materializing: None for not-yet-built lazy entries.
498    fn get_if_materialized(&self, internal: &str) -> Option<&PoolClass> {
499        match self.classes.get(internal)? {
500            ClassEntry::Eager(pc) => Some(pc),
501            ClassEntry::Lazy { pc, .. } => pc.get(),
502        }
503    }
504
505    /// Name registered (no materialization).
506    pub fn has_name(&self, internal: &str) -> bool {
507        self.classes.contains_key(internal)
508    }
509
510    /// One image as an Arc snapshot (borrows of the snapshot live as
511    /// long as the caller holds the Arc).
512    pub fn dex(&self, idx: usize) -> Option<std::sync::Arc<DexFile>> {
513        self.dexes.get(idx).cloned()
514    }
515
516    pub fn dex_count(&self) -> usize {
517        self.dexes.len()
518    }
519
520    pub fn class_names(&self) -> impl Iterator<Item = &str> {
521        self.order.iter().map(|s| s.as_str())
522    }
523
524    /// True when `sub` is assignable to `sup` (internal names), walking the
525    /// pool's hierarchy. Unknown classes are never assignable (conservative).
526    pub fn is_subtype(&self, sub: &str, sup: &str) -> bool {
527        if sub == sup {
528            return true;
529        }
530        // Arrays: covariance by element type when both are arrays.
531        if let (Some(sub_elem), Some(sup_elem)) = (array_elem(sub), array_elem(sup)) {
532            if sub_elem.starts_with('L')
533                && sup_elem.starts_with('L')
534                && sub_elem.ends_with(';')
535                && sup_elem.ends_with(';')
536            {
537                return self.is_subtype(
538                    &sub_elem[1..sub_elem.len() - 1],
539                    &sup_elem[1..sup_elem.len() - 1],
540                );
541            }
542            return sub_elem == sup_elem;
543        }
544        let mut cur = self.get(sub);
545        let mut hops = 0;
546        while let Some(c) = cur {
547            hops += 1;
548            if hops > 64 {
549                return false;
550            }
551            for i in &c.interfaces {
552                if i == sup || self.is_subtype(i, sup) {
553                    return true;
554                }
555            }
556            match &c.super_name {
557                Some(s) if s == sup => return true,
558                Some(s) if s != "java/lang/Object" => {
559                    cur = self.get(s);
560                }
561                _ => return false,
562            }
563        }
564        false
565    }
566}
567
568impl Default for DexPool {
569    fn default() -> Self {
570        Self::new()
571    }
572}
573
574fn array_elem(desc: &str) -> Option<&str> {
575    desc.strip_prefix('[')
576}
577
578fn resolve_static_value(v: &EncodedValue, dex: &DexFile) -> StaticValue {
579    match v {
580        EncodedValue::Byte(x) => StaticValue::Int(*x as i64),
581        EncodedValue::Short(x) => StaticValue::Int(*x as i64),
582        EncodedValue::Char(x) => StaticValue::Int(*x as i64),
583        EncodedValue::Int(x) => StaticValue::Int(*x as i64),
584        EncodedValue::Long(x) => StaticValue::Int(*x),
585        EncodedValue::Float(x) => StaticValue::Float(*x),
586        EncodedValue::Double(x) => StaticValue::Double(*x),
587        EncodedValue::String(i) => StaticValue::Str(dex.string(*i).to_string()),
588        EncodedValue::Type(i) => StaticValue::Type(dex.class_name(*i)),
589        EncodedValue::Boolean(b) => StaticValue::Boolean(*b),
590        EncodedValue::Null => StaticValue::Null,
591        EncodedValue::Enum(i) | EncodedValue::Field(i) => {
592            let f = dex.field(*i);
593            StaticValue::Field(
594                dex.class_name(f.class_idx),
595                dex.string(f.name_idx).to_string(),
596            )
597        }
598        _ => StaticValue::Other,
599    }
600}
601
602fn pool_class_of(dex: &DexFile, raw: &[u8], cd: &ClassDef, dex_idx: usize) -> PoolClass {
603    let name = dex.class_name(cd.class_idx);
604    let super_name = if cd.superclass_idx == ddc_dex::NO_INDEX {
605        None
606    } else {
607        let s = dex.class_name(cd.superclass_idx);
608        if s.is_empty() || s == "java/lang/Object" {
609            None
610        } else {
611            Some(s)
612        }
613    };
614    let interfaces = dex
615        .interfaces_of(cd)
616        .into_iter()
617        .map(|t| dex.class_name(t))
618        .collect();
619    let source_file = if cd.source_file_idx == ddc_dex::NO_INDEX {
620        None
621    } else {
622        Some(dex.string(cd.source_file_idx).to_string())
623    };
624
625    let data = dex.class_data(cd);
626    let mk_field = |ef: &ddc_dex::EncodedField, is_static: bool| {
627        let f = dex.field(ef.field_idx);
628        PoolField {
629            name: dex.string(f.name_idx).to_string(),
630            desc: dex.type_name(f.type_idx).to_string(),
631            access: ef.access_flags,
632            is_static,
633        }
634    };
635    let static_fields: Vec<PoolField> = data
636        .static_fields
637        .iter()
638        .map(|f| mk_field(f, true))
639        .collect();
640    let instance_fields: Vec<PoolField> = data
641        .instance_fields
642        .iter()
643        .map(|f| mk_field(f, false))
644        .collect();
645    let mk_method = |em: &ddc_dex::EncodedMethod| {
646        let m = dex.method(em.method_idx);
647        let (code_off, debug_info_off) = match dex.debug_info_off_at(em.code_off) {
648            Some(d) => (em.code_off, d),
649            None => (0, 0),
650        };
651        PoolMethod {
652            name: dex.string_arc(m.name_idx),
653            desc: dex.proto_desc(m.proto_idx),
654            access: em.access_flags,
655            code_off,
656            debug_info_off,
657            dex_idx,
658        }
659    };
660    let direct_methods: Vec<PoolMethod> = data.direct_methods.iter().map(&mk_method).collect();
661    let virtual_methods: Vec<PoolMethod> = data.virtual_methods.iter().map(&mk_method).collect();
662
663    let static_values: Vec<StaticValue> = dex
664        .static_values(cd.static_values_off)
665        .into_iter()
666        .map(|v| resolve_static_value(&v, dex))
667        .collect();
668    let anns = if cd.annotations_off != 0 {
669        annotations::read_class_annotations(raw, cd.annotations_off)
670    } else {
671        Vec::new()
672    };
673    let raw = annotations::nesting_from(&anns, &|t: u32| dex.type_name(t).to_string());
674    let nesting = ResolvedNesting {
675        enclosing_class: raw.enclosing_class.map(|t| dex.class_name(t)),
676        enclosing_method: raw.enclosing_method.map(|m| {
677            let mid = dex.method(m);
678            (
679                dex.class_name(mid.class_idx),
680                dex.string(mid.name_idx).to_string(),
681            )
682        }),
683        member_classes: raw
684            .member_classes
685            .into_iter()
686            .map(|t| dex.class_name(t))
687            .collect(),
688    };
689
690    PoolClass {
691        name,
692        access: cd.access_flags,
693        super_name,
694        interfaces,
695        source_file,
696        static_fields,
697        instance_fields,
698        direct_methods,
699        virtual_methods,
700        static_values,
701        nesting,
702        dex_idx,
703    }
704}
705
706/// JavaType for a field/method descriptor segment.
707/// Parse a proto's descriptor into a MethodDescriptor straight from the
708/// tables (no string round-trip).
709fn parse_proto_desc(
710    dex: &ddc_dex::DexFile,
711    proto_idx: u32,
712) -> jdc_core::types::MethodDescriptor {
713    let proto = dex.proto(proto_idx);
714    let args = dex
715        .proto_params(proto_idx)
716        .iter()
717        .map(|&t| desc_type(dex.type_name(t)))
718        .collect();
719    jdc_core::types::MethodDescriptor {
720        args,
721        ret: desc_type(dex.type_name(proto.return_type_idx)),
722    }
723}
724
725pub fn desc_type(desc: &str) -> JavaType {
726    parse_field_descriptor(desc).unwrap_or(JavaType::Object("java/lang/Object".into()))
727}
728
729/// Nesting evidence for `internal`: dalvik annotations first, then the
730/// `$`-name heuristic against the pool.
731pub fn find_outer_name(pool: &DexPool, internal: &str) -> Option<String> {
732    // Annotation refinement only for ALREADY-MATERIALIZED classes: eager
733    // pools (full decompile) behave exactly as before; lazy pools
734    // (progressive getclass) fall straight to the `$` chain without
735    // materializing the world.
736    if let Some(pc) = pool.get_if_materialized(internal) {
737        if let Some(enc) = &pc.nesting.enclosing_class {
738            return Some(enc.clone());
739        }
740    }
741    let mut rest = internal;
742    while let Some(d) = rest.rfind('$') {
743        let cand = &rest[..d];
744        if pool.has_name(cand) {
745            return Some(cand.to_string());
746        }
747        rest = cand;
748    }
749    None
750}
751
752/// True when the `$` tail names a plain member class (not anonymous/local/
753/// lambda), i.e. the class renders inside its outer's compilation unit.
754fn clean_member_tail(rest: &str) -> bool {
755    if rest.starts_with('-') {
756        return false;
757    }
758    let tail = rest.rsplit('$').next().unwrap_or(rest);
759    if tail.is_empty() || tail.starts_with(|c: char| c.is_ascii_digit()) {
760        return false;
761    }
762    true
763}
764
765/// Classes to emit as their own compilation units: top-level classes plus
766/// anonymous/local/lambda-shaped ones (clean members render inline).
767impl DexPool {
768    /// Arm image retirement (full-decompile driver only): count one
769    /// pending class per image by pool ownership.
770    pub fn arm_retirement(&self) {
771        self.retire_armed
772            .store(true, std::sync::atomic::Ordering::Release);
773        let mut counts = self.retire_counts.lock().unwrap();
774        for c in counts.iter_mut() {
775            *c = 0;
776        }
777        for entry in self.classes.values() {
778            let di = match entry {
779                ClassEntry::Eager(pc) => pc.dex_idx,
780                ClassEntry::Lazy { at, .. } => at.0,
781            };
782            if let Some(c) = counts.get_mut(di) {
783                *c += 1;
784            }
785        }
786    }
787
788    /// Report one class finished; Some(image) when it was the image's
789    /// last class (driver batches these into release_images).
790    pub fn report_class_done(&self, class_name: &str) -> Option<usize> {
791        if !self.retire_armed.load(std::sync::atomic::Ordering::Acquire) {
792            return None;
793        }
794        let entry = self.classes.get(class_name)?;
795        let di = match entry {
796            ClassEntry::Eager(pc) => pc.dex_idx,
797            ClassEntry::Lazy { at, .. } => at.0,
798        };
799        let mut counts = self.retire_counts.lock().unwrap();
800        match counts.get_mut(di) {
801            Some(c) => {
802                *c = c.saturating_sub(1);
803                if *c == 0 {
804                    Some(di)
805                } else {
806                    None
807                }
808            }
809            None => None,
810        }
811    }
812
813    /// Release the images' inflated bytes. Safe: the driver calls this
814    /// only when every class of each image is emitted or failed; new
815    /// `dex()` snapshots still work (tables valid, code accessors empty).
816    pub fn release_images(&self, indexes: &[usize]) {
817        let mut counts = self.retire_counts.lock().unwrap();
818        for &i in indexes {
819            if let Some(dex) = self.dexes.get(i) {
820                // Mark the shared image: code accessors go empty
821                // immediately; the bytes drop when the last snapshot
822                // drops (workers hold snapshots only mid-class).
823                dex.mark_released();
824            }
825            if let Some(c) = counts.get_mut(i) {
826                *c = u64::MAX; // released marker
827            }
828        }
829    }
830}
831
832pub fn top_level_classes(pool: &DexPool) -> Vec<String> {
833    pool.class_names()
834        .filter(|name| match pool.outer_of(name) {
835            None => true,
836            Some(outer) => {
837                if pool.get(outer).is_none() {
838                    return true;
839                }
840                // The outer can come from an ANNOTATION (EnclosingClass)
841                // with no naming relationship to this class — obfuscated
842                // apps pair a 1-char name with a long enclosing descriptor
843                // (weixin), which made the old blind slice panic. Only a
844                // real `outer$tail` prefix yields a member tail; anything
845                // else is a standalone unit.
846                let rest = name
847                    .strip_prefix(outer)
848                    .and_then(|t| t.strip_prefix('$'))
849                    .unwrap_or("");
850                !clean_member_tail(rest)
851            }
852        })
853        .map(|n| n.to_string())
854        .collect()
855}
856
857/// Deterministic case-collision renames over the FILE-emission set:
858/// classes whose internal names differ only in letter case cannot share
859/// one case-insensitive directory; the first (sorted) member of each
860/// group keeps its name, the others gain `_2`, `_3`, … on the simple
861/// segment. The map carries identity entries for unrenamed file-level
862/// classes (they anchor nested prefix walks in apply_class_rename).
863pub fn case_rename_map(pool: &DexPool) -> HashMap<String, String> {
864    use std::collections::HashMap;
865    let mut groups: HashMap<String, Vec<String>> = HashMap::default();
866    for t in top_level_classes(pool) {
867        groups.entry(t.to_lowercase()).or_default().push(t);
868    }
869    let folds: std::collections::HashSet<String> = groups.keys().cloned().collect();
870    let mut map = HashMap::default();
871    for (_, mut members) in groups {
872        members.sort();
873        for (i, m) in members.iter().enumerate() {
874            if i == 0 {
875                map.insert(m.clone(), m.clone());
876                continue;
877            }
878            // Suffix the simple segment; keep incrementing if the fold
879            // of the suffixed name is already taken by a real class.
880            let cut = m.rfind('/').map(|x| x + 1).unwrap_or(0);
881            let mut n = i + 1;
882            loop {
883                let cand = format!("{}{}_{}", &m[..cut], &m[cut..], n);
884                let fold = cand.to_lowercase();
885                if !folds.contains(&fold) {
886                    map.insert(m.clone(), cand);
887                    break;
888                }
889                n += 1;
890            }
891        }
892    }
893    map
894}
895
896/// Display-level renames for two nested-class shapes that render
897/// uncompilable or inconsistent output:
898///
899/// 1. A member class whose simple tail equals its rendered parent's
900///    tail (`x0$a$a` inside `x0$a`): javac rejects a member class with
901///    the same simple name as its immediately enclosing class ("已在类
902///    x0中定义了类 x0.a") — a shape Kotlin lambda families hit by the
903///    thousand (lark alone: 22k). Bump the tail: `a` → `a2`, `a3`, …
904/// 2. An orphaned intermediate (`x0$a$b` with `x0$a` absent from the
905///    pool): the member DECLARES as `b` inside `x0` but references
906///    printed `x0.a$b` — a type that exists nowhere. Flatten the
907///    display name to `x0$b` so every site agrees.
908///
909/// Both are pure display renames keyed by internal name; declarations,
910/// ctor names, file names and every type reference funnel through
911/// apply_class_rename, so one map keeps all sites consistent. Children
912/// Display-level renames for nested member classes that render
913/// uncompilable or inconsistent output:
914///
915/// 1. A member whose simple tail equals ANY enclosing class's simple
916///    name in its nesting chain. javac rejects more than the immediate
917///    parent (`class a { static class a2 { static class a {} } }` —
918///    member `a` two levels under `a` — is "已在类 X中定义了类 X.a");
919///    Kotlin lambda families (`x0$a$a` inside `x0$a`) hit it by the
920///    thousand (lark alone: 22k). Bump the tail until it clears every
921///    ancestor name: `a` → `a3`.
922/// 2. An orphaned intermediate (`x0$a$b` with `x0$a` absent): the
923///    member DECLARES as `b` inside `x0` but references printed
924///    `x0.a$b` — a type that exists nowhere. Flatten the display to
925///    `x0$b` so every site agrees.
926///
927/// Candidates build on the parent's DISPLAY name (ancestors are
928/// renamed first — ascending `$`-depth order), so declarations,
929/// constructor names, file names and every type reference stay
930/// consistent through apply_class_rename. All are pure display
931/// renames keyed by internal name.
932fn nested_collision_renames(pool: &DexPool, map: &mut HashMap<String, String>) {
933    // Ancestors before descendants: a parent's rename must be in the
934    // map when its children compute their display chain.
935    let mut names: Vec<&String> = pool.order.iter().collect();
936    names.sort_by_key(|n| n.matches('$').count());
937    let mut assigned: jdc_core::FxHashSet<String> = jdc_core::FxHashSet::default();
938    for name in names {
939        if !name.contains('$') || map.contains_key(name) {
940            continue;
941        }
942        let Some(parent) = find_outer_name(pool, name) else {
943            continue;
944        };
945        // Only a REAL `parent$rest` name renders as an inline member;
946        // anonymous/local/lambda tails keep their flat own-file names.
947        let Some(rest) = name
948            .strip_prefix(parent.as_str())
949            .and_then(|t| t.strip_prefix('$'))
950        else {
951            continue;
952        };
953        if !clean_member_tail(rest) {
954            continue;
955        }
956        // Display simple names of every enclosing level, bottom-up.
957        let mut chain: Vec<String> = Vec::new();
958        let mut cur = parent.clone();
959        loop {
960            let disp = map.get(&cur).cloned().unwrap_or_else(|| cur.clone());
961            let simple = disp.rsplit('/').next().unwrap_or(&disp);
962            chain.push(simple.rsplit('$').next().unwrap_or(simple).to_string());
963            match find_outer_name(pool, &cur) {
964                Some(o) if o != cur => cur = o,
965                _ => break,
966            }
967        }
968        let disp_parent = map
969            .get(&parent)
970            .cloned()
971            .unwrap_or_else(|| parent.clone());
972        let tail = rest.rsplit('$').next().unwrap_or(rest);
973        let orphan = rest.contains('$');
974        let clash = chain.iter().any(|c| c == tail);
975        if !orphan && !clash {
976            continue;
977        }
978        let mut k = 0u32;
979        loop {
980            k += 1;
981            let cand_tail = if k == 1 {
982                tail.to_string()
983            } else {
984                format!("{tail}{k}")
985            };
986            // The candidate must clear every ancestor display name,
987            // not just the immediate parent (javac checks the whole
988            // chain — see the shape list above).
989            if chain.contains(&cand_tail) {
990                continue;
991            }
992            let cand = format!("{disp_parent}${cand_tail}");
993            if pool.has_name(&cand) || assigned.contains(&cand) {
994                continue;
995            }
996            assigned.insert(cand.clone());
997            map.insert(name.clone(), cand);
998            break;
999        }
1000    }
1001}
1002
1003/// Compute and install the registry (call before worker threads spawn).
1004pub fn install_case_renames(pool: &DexPool) {
1005    let mut map = case_rename_map(pool);
1006    // Package-leaf shadows FIRST: the nested-collision renames compute
1007    // display chains off the (renamed) parent display names — running
1008    // them before the parent rename left both rules minting the same
1009    // display (`a2` twice in weibo's AIDL families).
1010    pkg_leaf_shadow_renames(pool, &mut map);
1011    nested_collision_renames(pool, &mut map);
1012    jdc_core::rename::set_class_renames(map);
1013    jdc_core::rename::set_field_renames(member_collision_renames(pool));
1014}
1015
1016/// Obfuscators can name a class after its own package leaf (`package k;`
1017/// `class k extends EditText`). Every SAME-PACKAGE reference to `k.Anything`
1018/// then resolves the first segment to the CLASS, not the package —
1019/// javac looks for `Anything` as a member of class k ("找不到符号 class p2,
1020/// location: class k"). Renaming the class (display-level, the registry
1021/// carries declarations and references) makes the package the only
1022/// thing the leaf name resolves to.
1023fn pkg_leaf_shadow_renames(pool: &DexPool, map: &mut HashMap<String, String>) {
1024    let taken: jdc_core::FxHashSet<String> = pool.order.iter().cloned().collect();
1025    for name in &pool.order {
1026        let Some((pkg, simple)) = name.rsplit_once('/') else {
1027            continue;
1028        };
1029        if simple.is_empty() || pkg.is_empty() {
1030            continue;
1031        }
1032        let leaf = pkg.rsplit('/').next().unwrap_or(pkg);
1033        // class name == package leaf, and the package really exists
1034        // (more classes than just this one live under it).
1035        if simple != leaf {
1036            continue;
1037        }
1038        let prefix = format!("{pkg}/");
1039        let siblings = pool
1040            .order
1041            .iter()
1042            .filter(|n| n.starts_with(&prefix) && **n != *name)
1043            .count();
1044        if siblings == 0 || map.get(name).is_some_and(|v| v != name) {
1045            continue; // already renamed by an earlier rule; identity anchors are fine to overwrite
1046        }
1047        let mut k = 1u32;
1048        loop {
1049            k += 1;
1050            let cand = format!("{pkg}/{simple}{k}");
1051            if !taken.contains(&cand) && !map.values().any(|v| *v == cand) {
1052                map.insert(name.clone(), cand);
1053                break;
1054            }
1055        }
1056    }
1057}
1058
1059/// Member-level collision renames (fields AND methods of one class).
1060/// Two sources collapse onto one display name: obfuscators renaming a
1061/// synthetic outer reference (`this$0`) onto a real field's name, and
1062/// the identifier sanitizer mapping non-ASCII to `_` (whole
1063/// `ERROR_中文` families render one `ERROR________`).
1064/// Both are legal in bytecode (members resolve by index) and both are
1065/// javac "already defined" errors in source. Policy per colliding group
1066/// (fields keep the first non-synthetic name; a synthetic outer
1067/// reference restores `this$0`; everything else gets `2`/`3` suffixes;
1068/// method keys include erased parameter types):
1069/// Keys stay ORIGINAL (name, descriptor) so references resolve exactly;
1070/// only the rendered identifier changes.
1071fn member_collision_renames(
1072    pool: &DexPool,
1073) -> HashMap<std::sync::Arc<str>, Vec<jdc_core::rename::FieldRename>> {
1074    let mut out: HashMap<std::sync::Arc<str>, Vec<jdc_core::rename::FieldRename>> =
1075        HashMap::default();
1076    for name in &pool.order {
1077        let Some(pc) = pool.get_if_materialized(name) else {
1078            continue;
1079        };
1080        let outer_ref_desc = find_outer_name(pool, name)
1081            .filter(|o| o != name)
1082            .map(|o| format!("L{o};"));
1083        // ---- fields: one shared namespace (static + instance) ----
1084        let fields: Vec<&PoolField> = pc
1085            .static_fields
1086            .iter()
1087            .chain(pc.instance_fields.iter())
1088            .collect();
1089        let fgroups: HashMap<String, Vec<&PoolField>> = HashMap::default();
1090        let mut fgroups = fgroups;
1091        for f in &fields {
1092            let disp = crate::classdec::java_ident(&f.name).into_owned();
1093            fgroups.entry(disp).or_default().push(f);
1094        }
1095        let f_taken: jdc_core::FxHashSet<String> = fields
1096            .iter()
1097            .map(|f| crate::classdec::java_ident(&f.name).into_owned())
1098            .collect();
1099        let mut f_taken = f_taken;
1100        for group in fgroups.values() {
1101            if group.len() < 2 {
1102                continue;
1103            }
1104            let keeper_pos = group
1105                .iter()
1106                .position(|f| f.access & crate::access::ACC_SYNTHETIC == 0)
1107                .unwrap_or(0);
1108            for (gi, f) in group.iter().enumerate() {
1109                if gi == keeper_pos {
1110                    continue;
1111                }
1112                let base = crate::classdec::java_ident(&f.name).into_owned();
1113                let display: String = match &outer_ref_desc {
1114                    Some(ord)
1115                        if f.access & crate::access::ACC_SYNTHETIC != 0
1116                            && !f.is_static
1117                            && *ord == f.desc =>
1118                    {
1119                        let mut k = 0u32;
1120                        loop {
1121                            let cand = if k == 0 {
1122                                "this$0".to_string()
1123                            } else {
1124                                format!("this$0{k}")
1125                            };
1126                            if f_taken.insert(cand.clone()) {
1127                                break cand;
1128                            }
1129                            k += 1;
1130                        }
1131                    }
1132                    _ => suffix_unique(&base, &mut f_taken),
1133                };
1134                out.entry(std::sync::Arc::from(name.as_str()))
1135                    .or_default()
1136                    .push(jdc_core::rename::FieldRename {
1137                        name: std::sync::Arc::from(f.name.as_str()),
1138                        desc: std::sync::Arc::from(f.desc.as_str()),
1139                        display: std::sync::Arc::from(display.as_str()),
1140                    });
1141            }
1142        }
1143        // ---- methods: display key = sanitized name + erased params ----
1144        let methods: Vec<&PoolMethod> = pc.all_methods().collect();
1145        let mut m_taken: jdc_core::FxHashSet<String> = methods
1146            .iter()
1147            .map(|m| crate::classdec::java_ident(&m.name).into_owned())
1148            .collect();
1149        let mut mgroups: HashMap<(String, String), Vec<&PoolMethod>> = HashMap::default();
1150        for m in &methods {
1151            let d: &str = &m.desc;
1152            let lo = d.find('(').map(|i| i + 1).unwrap_or(0);
1153            let hi = d.find(')').unwrap_or(d.len());
1154            let key = (
1155                crate::classdec::java_ident(&m.name).into_owned(),
1156                d[lo..hi].to_string(),
1157            );
1158            mgroups.entry(key).or_default().push(m);
1159        }
1160        for ((base, _), group) in &mgroups {
1161            if group.len() < 2 {
1162                continue;
1163            }
1164            // A COVARIANT override pair (same ORIGINAL name, different
1165            // descriptors — the compiler's bridge shape: the interface's
1166            // `deserialize(e)` plus the narrower implementation). Renaming
1167            // either side breaks @Override ("is not abstract and does not
1168            // override abstract method deserialize(e)", ~2.2k on reqable);
1169            // the emitter's claim logic already renders only the
1170            // non-bridge member of the pair.
1171            let covariant = group
1172                .iter()
1173                .any(|m| group.iter().any(|o| o.name == m.name && o.desc != m.desc));
1174            if covariant {
1175                continue;
1176            }
1177            // Real re-declarations (same original name AND descriptor —
1178            // R8 duplicates) are already deduped by the emitter's claim
1179            // logic; only SANITIZER collapses reach here and every one of
1180            // them is a distinct method.
1181            let mut base = base.clone();
1182            let mut seen_orig: jdc_core::FxHashSet<(&str, &str)> =
1183                jdc_core::FxHashSet::default();
1184            for m in group {
1185                if !seen_orig.insert((&m.name, &m.desc)) {
1186                    continue; // exact duplicate: emitter drops it
1187                }
1188                let display = suffix_unique(&base, &mut m_taken);
1189                out.entry(std::sync::Arc::from(name.as_str()))
1190                    .or_default()
1191                    .push(jdc_core::rename::FieldRename {
1192                        name: m.name.clone(),
1193                        desc: m.desc.clone(),
1194                        display: std::sync::Arc::from(display.as_str()),
1195                    });
1196                // The base stays the sanitized ORIGINAL so the first
1197                // occurrence keeps the plain name.
1198                let _ = &mut base;
1199            }
1200        }
1201    }
1202    out
1203}
1204
1205fn suffix_unique(base: &str, taken: &mut jdc_core::FxHashSet<String>) -> String {
1206    let mut k = 1u32;
1207    loop {
1208        k += 1;
1209        let cand = format!("{base}{k}");
1210        if taken.insert(cand.clone()) {
1211            return cand;
1212        }
1213    }
1214}
1215
1216/// Install member renames (call with the class rename install, before
1217/// workers spawn).
1218pub fn install_field_renames(pool: &DexPool) {
1219    jdc_core::rename::set_field_renames(member_collision_renames(pool));
1220}
1221pub use jdc_core::rename::apply_class_rename;