Skip to main content

ddc_dec/
ctx.rs

1//! The DEX front-end's implementation of `jdc_core::Ctx`.
2//!
3//! Every method here answers a *semantic* question about class metadata
4//! using the pooled DEX class table; generics are absent (erased), so all
5//! generic-aware queries answer "unknown" and the core degrades gracefully.
6
7use jdc_core::ir::expr::{Expr, TypeRef};
8use jdc_core::types::{
9    ClassAccessFlags, FieldAccessFlags, GenericType, JavaType, MethodAccessFlags, MethodDescriptor,
10};
11use jdc_core::{Ctx, Family, NestedClass, NestedKind};
12
13use crate::access::*;
14use crate::{desc_type, DexPool, PoolClass};
15
16/// Front-end context handed to the core's structurer and printer.
17pub struct DexCtx<'a> {
18    pub pool: &'a DexPool,
19    pub class: &'a PoolClass,
20    /// Field display names visible in this class's lexical scope by
21    /// INHERITANCE or ENCLOSURE (supers/interfaces of the class and of
22    /// every `$`-outer, transitively). `declares_field` only saw own
23    /// fields: an inherited int `h` captured the class ref `h.e`
24    /// (无法取消引用int, weixin v2/j family) because the shadow check
25    /// missed it and the simple render stayed unqualified.
26    inherited_fields: jdc_core::FxHashSet<String>,
27}
28
29impl<'a> DexCtx<'a> {
30    pub fn new(pool: &'a DexPool, class: &'a PoolClass) -> Self {
31        let inherited_fields = {
32            let mut set: jdc_core::FxHashSet<String> = jdc_core::FxHashSet::default();
33            let mut level = class.name.clone();
34            loop {
35                let mut queue = vec![level.clone()];
36                let mut seen: jdc_core::FxHashSet<String> =
37                    jdc_core::FxHashSet::default();
38                let mut hops = 0u32;
39                while let Some(c) = queue.pop() {
40                    if hops >= 64 || !seen.insert(c.clone()) {
41                        continue;
42                    }
43                    hops += 1;
44                    let Some(pc) = pool.get(&c) else { continue };
45                    if c != class.name {
46                        for f in pc.static_fields.iter().chain(pc.instance_fields.iter()) {
47                            set.insert(crate::classdec::java_ident(&f.name).into_owned());
48                        }
49                    }
50                    if let Some(sup) = &pc.super_name {
51                        queue.push(sup.clone());
52                    }
53                    queue.extend(pc.interfaces.iter().cloned());
54                }
55                let Some(i) = level.rfind('$') else { break };
56                level.truncate(i);
57            }
58            set
59        };
60        DexCtx { pool, class, inherited_fields }
61    }
62
63    fn find_class(&self, internal: &str) -> Option<&PoolClass> {
64        self.pool.get(internal)
65    }
66
67    /// The javac-convention enclosing field: named `this$0` AND typed
68    /// as the outer. The pure type match over-fires on STATIC nested
69    /// classes that legitimately hold an outer-typed field (wcdb
70    /// CancellationSignal$Transport's mCancellationSignal — rendered as
71    /// an inner class, `new Transport(null)` from a static method is
72    /// "需要包含...的封闭实例"). An obfuscated-renamed this$0 falls to
73    /// the static render, which stays compilable: the ctor keeps its
74    /// outer param and every call site passes it explicitly.
75    /// JLS inner-ctor shape: the synthetic outer instance rides as
76    /// formal-0 typed as the DIRECT enclosing class. Field evidence
77    /// alone misclassifies Kotlin lambda classes — kotlinc names the
78    /// captured `this` field this$0 too, but at an ARBITRARY param
79    /// position (lark SearchResultView$q: `(int $requestSeq,
80    /// SearchResultView this$0)`; the int capture was hijacked as the
81    /// qualified-new outer — `(this.w + 1).new q17(this)`, lark
82    /// 意外的类型 ×295). Mirrors the decl-side strip guard in classdec
83    /// (`d.args.first()` must BE the enclosing type).
84    fn outer_is_formal0(&self, internal: &str, pc: &PoolClass) -> bool {
85        let Some(outer) = self.find_outer(internal) else {
86            return false;
87        };
88        pc.all_methods().any(|m| {
89            &*m.name == "<init>"
90                && m.parsed_desc().is_some_and(|d| {
91                    d.args.first().is_some_and(|t| {
92                        matches!(t, JavaType::Object(n) if n.as_ref() == outer.as_str())
93                    })
94                })
95        })
96    }
97
98    fn holds_this0(&self, internal: &str, pc: &PoolClass) -> bool {
99        let Some(outer) = self.find_outer(internal) else {
100            return false;
101        };
102        pc.instance_fields.iter().any(|f| {
103            f.name == "this$0"
104                && f
105                    .desc
106                    .strip_prefix('L')
107                    .and_then(|d| d.strip_suffix(';'))
108                    .is_some_and(|ty| ty == outer)
109        })
110    }
111
112    /// Nesting evidence (see `find_outer_name`).
113    fn outer_of(&self, internal: &str) -> Option<String> {
114        crate::find_outer_name(self.pool, internal)
115    }
116
117    fn class_access_flags(&self, internal: &str) -> ClassAccessFlags {
118        let mut f = ClassAccessFlags::empty();
119        let Some(pc) = self.find_class(internal) else {
120            return f;
121        };
122        let a = pc.access;
123        if a & ACC_PUBLIC != 0 {
124            f |= ClassAccessFlags::PUBLIC;
125        }
126        if a & ACC_FINAL != 0 {
127            f |= ClassAccessFlags::FINAL;
128        }
129        if a & ACC_INTERFACE != 0 {
130            f |= ClassAccessFlags::INTERFACE;
131        }
132        if a & ACC_ABSTRACT != 0 {
133            f |= ClassAccessFlags::ABSTRACT;
134        }
135        if a & ACC_SYNTHETIC != 0 {
136            f |= ClassAccessFlags::SYNTHETIC;
137        }
138        if a & ACC_ANNOTATION != 0 {
139            f |= ClassAccessFlags::ANNOTATION;
140        }
141        if a & ACC_ENUM != 0 {
142            f |= ClassAccessFlags::ENUM;
143        }
144        f
145    }
146}
147
148impl<'a> Ctx for DexCtx<'a> {
149    fn pool_id(&self) -> u64 {
150        // Printer::shorten memo cache key: every DexCtx in a run shares
151        // one DexPool, and shorten's ctx queries (has_class/find_outer/
152        // class_bases) are pool-level — one cache entry set per pool.
153        self.pool as *const DexPool as u64
154    }
155
156    fn obscured_simple(&self, internal: &str) -> Option<String> {
157        crate::classdec::obscured_render_pub(internal)
158    }
159
160    fn class_name(&self) -> &str {
161        &self.class.name
162    }
163
164    fn source_level(&self) -> u16 {
165        52
166    }
167
168    fn find_outer(&self, internal: &str) -> Option<String> {
169        // ddcroot root-package relocation, SYMMETRIC with has_class's
170        // root_pkg clause: a relocated NESTED class (`ddcroot/agv$b`)
171        // must resolve its outer (`ddcroot/agv`) so nested_display dots
172        // the `$` into `ddcroot.agv.b`. has_class already un-prefixes
173        // `ddcroot/agv$b` to the pool key `agv$b` (→ true), but without
174        // this the outer walk fails (`ddcroot/agv` is not a pool key),
175        // so keep_dollar_pool saw (has_class, no-outer) and treated the
176        // genuine nestee as a flat `$` emission unit — rimet rendered
177        // `new ddcroot.agv$b(..)` / `ddcroot.agv$b[]`, unresolvable
178        // (找不到符号 类 agv$b/qse$b/bik$a ×1,100+). A relocated FLAT unit
179        // (R8 deleted the outer, lark UserCustomStatusExtraParams$*)
180        // still returns None here — the stripped outer is off-pool — so
181        // it correctly keeps its `$`.
182        if let Some(rp) = crate::root_pkg_display() {
183            if internal.len() > rp.len() + 1
184                && internal.starts_with(rp.as_str())
185                && internal.as_bytes()[rp.len()] == b'/'
186            {
187                let stripped = &internal[rp.len() + 1..];
188                return crate::find_outer_name(self.pool, stripped)
189                    .map(|o| format!("{rp}/{o}"));
190            }
191        }
192        self.outer_of(internal)
193    }
194
195    fn family(&self, root: &str) -> Family {
196        let mut fam = Family {
197            root: root.to_string(),
198            ..Default::default()
199        };
200        // Cached child index: BFS over the `$` chain from `root`.
201        let mut queue: std::collections::VecDeque<String> =
202            self.pool.children_of(root).iter().cloned().collect();
203        let mut seen: jdc_core::FxHashSet<String> = queue.iter().cloned().collect();
204        while let Some(name) = queue.pop_front() {
205            for c in self.pool.children_of(&name) {
206                if seen.insert(c.clone()) {
207                    queue.push_back(c.clone());
208                }
209            }
210            let Some(_) = self.find_class(&name) else {
211                continue;
212            };
213            let root_prefix = format!("{}$", root);
214            let rest: String = if name.starts_with(&root_prefix) {
215                name[root_prefix.len()..].to_string()
216            } else {
217                name.rsplit('$').next().unwrap_or(&name).to_string()
218            };
219            let simple = rest.rsplit('$').next().unwrap_or(&rest).to_string();
220            let kind = classify_nested(&rest);
221            let access = self.class_access_flags(&name);
222            fam.nested.insert(
223                name.clone(),
224                NestedClass {
225                    name: name.clone(),
226                    simple,
227                    kind,
228                    access,
229                    sig_header: None,
230                },
231            );
232            match kind {
233                NestedKind::Anonymous => {
234                    fam.anonymous.insert(name.clone());
235                }
236                NestedKind::Local => {
237                    fam.locals.insert(name.clone());
238                }
239                NestedKind::Lambda => {
240                    fam.lambdas.insert(name.clone());
241                }
242                NestedKind::Member => {}
243            }
244        }
245        fam
246    }
247
248    fn nested_is_static(&self, internal: &str) -> bool {
249        // ACC_STATIC (annotation evidence) OR the structural signal:
250        // no instance field typed as the outer class. javac ALWAYS
251        // gives a non-static inner class an enclosing-instance field
252        // (this$0), and the field TYPE survives obfuscation that
253        // renames the field itself. Plain d8 output carries no
254        // nesting annotations at all — without the structural
255        // fallback every static nested class rendered as an inner
256        // one (`str.new Report(...)` swallowing the first ctor arg).
257        // A this$0 field WITHOUT the formal-0 outer ctor param is a
258        // capture, not a JLS outer (Kotlin lambdas) — static too.
259        // Logic lives in the free `nested_is_static` below (shared
260        // with method.rs passes that run without a ctx).
261        match self.find_class(internal) {
262            Some(pc) => nested_is_static(self.pool, pc),
263            None => true,
264        }
265    }
266
267    fn class_has_this0(&self, internal: &str) -> bool {
268        // Inner classes without ACC_STATIC carry an enclosing instance.
269        match self.find_class(internal) {
270            Some(pc) => {
271                !pc.is_static_nested()
272                    && self.holds_this0(internal, pc)
273                    && self.outer_is_formal0(internal, pc)
274            }
275            None => false,
276        }
277    }
278
279    fn is_subtype_of(&self, sub: &JavaType, sup: &str) -> bool {
280        if let JavaType::Object(n) = sub {
281            self.pool.is_subtype(n, sup)
282        } else {
283            false
284        }
285    }
286
287    fn is_interface(&self, internal: &str) -> bool {
288        self.find_class(internal)
289            .map(|pc| pc.is_interface())
290            .unwrap_or(false)
291    }
292
293    fn is_sealed(&self, _internal: &str) -> bool {
294        false
295    }
296
297    fn super_name(&self, internal: &str) -> Option<String> {
298        self.find_class(internal)
299            .and_then(|pc| pc.super_name.clone())
300    }
301
302    fn has_class(&self, internal: &str) -> bool {
303        self.pool.get(internal).is_some()
304            || internal == self.class.name
305            // The ddcroot ROOT-PACKAGE RELOCATION only: the display
306            // prepends the synthetic package, the pool key lacks it.
307            // Deliberately NOT a general un-rename: collision-renamed
308            // nested families (weibo x0$a$b) render dotted against
309            // their renamed emission owners — a general un-rename
310            // flipped them to flat `$` renders (weibo 5,357 → 77,783
311            // cannot-find cascade). Flat `$` here is right ONLY for
312            // relocated root classes, which ARE their own emission
313            // unit (lark UserCustomStatusExtraParams$* "不可见" ×138).
314            || crate::root_pkg_display().is_some_and(|rp| {
315                internal.len() > rp.len() + 1
316                    && internal.starts_with(rp.as_str())
317                    && internal.as_bytes()[rp.len()] == b'/'
318                    && self.pool.get(&internal[rp.len() + 1..]).is_some()
319            })
320    }
321
322    fn class_supers_args(
323        &self,
324        internal: &str,
325        _args: &[GenericType],
326    ) -> Vec<(String, Vec<GenericType>)> {
327        let mut out = Vec::new();
328        let mut cur = self.find_class(internal).map(|pc| pc.name.clone());
329        let mut hops = 0;
330        while let Some(name) = cur {
331            hops += 1;
332            if hops > 64 {
333                break;
334            }
335            if name == "java/lang/Object" {
336                break;
337            }
338            out.push((name.clone(), Vec::new()));
339            cur = self.find_class(&name).and_then(|pc| pc.super_name.clone());
340        }
341        out
342    }
343
344    fn class_bases(&self, internal: &str) -> Option<(Vec<String>, Option<String>)> {
345        let pc = self.find_class(internal)?;
346        Some((pc.interfaces.clone(), pc.super_name.clone()))
347    }
348
349    fn field_flags(&self, internal: &str, name: &str) -> Option<FieldAccessFlags> {
350        let pc = self.find_class(internal)?;
351        let raw = pc
352            .static_fields
353            .iter()
354            .chain(pc.instance_fields.iter())
355            .find(|f| f.name == name)?
356            .access;
357        Some(raw_field_flags(raw))
358    }
359
360    fn method_flags(&self, internal: &str, name: &str, desc: &str) -> Option<MethodAccessFlags> {
361        let pc = self.find_class(internal)?;
362        let m = pc.find_method(name, desc)?;
363        Some(raw_method_flags(m.access))
364    }
365
366    fn declares_field(&self, internal: &str, name: &str) -> bool {
367        if internal == self.class.name {
368            return self.inherited_fields.contains(name)
369                || self.class.field_flags_of(name).is_some();
370        }
371        self.find_class(internal)
372            .map(|pc| pc.field_flags_of(name).is_some())
373            .unwrap_or(false)
374    }
375
376    fn declares_method_named(&self, internal: &str, name: &str) -> bool {
377        self.find_class(internal)
378            .map(|pc| pc.all_methods().any(|m| &*m.name == name))
379            .unwrap_or(false)
380    }
381
382    fn is_generic_call(&self, _e: &Expr) -> bool {
383        false
384    }
385
386    fn generic_call_formals(&self, _e: &Expr) -> Option<(Vec<GenericType>, Vec<String>)> {
387        None
388    }
389
390    fn polymorphic_ret_cast(
391        &self,
392        _cls: &str,
393        _name: &str,
394        _desc: &MethodDescriptor,
395    ) -> Option<JavaType> {
396        None
397    }
398
399    fn ctor_formals_by_arity(&self, internal: &str, arity: usize) -> Option<Vec<GenericType>> {
400        let pc = self.find_class(internal)?;
401        let ctors = pc.ctors_by_arity(arity);
402        let m = ctors.first()?;
403        let md = m.parsed_desc()?;
404        Some(md.args.iter().map(java_type_to_generic).collect())
405    }
406
407    fn ctor_param_types(
408        &self,
409        internal: &str,
410        skip: usize,
411        n: usize,
412        args: &[Expr],
413    ) -> Option<Vec<JavaType>> {
414        let _ = args;
415        let pc = self.find_class(internal)?;
416        let ctors = pc.ctors_by_arity(skip + n);
417        let m = ctors.first()?;
418        let md = m.parsed_desc()?;
419        Some(md.args.iter().skip(skip).cloned().collect())
420    }
421
422    fn outer_param_via_super(&self, _internal: &str) -> bool {
423        false
424    }
425
426    fn nested_method(
427        &self,
428        _l: &jdc_core::ir::expr::LambdaExpr,
429        _outer_vt: &jdc_core::var::VarTable,
430    ) -> Option<jdc_core::MethodBody> {
431        None
432    }
433}
434
435/// `$`-suffix classification (javac conventions d8 preserves).
436fn classify_nested(rest: &str) -> NestedKind {
437    // rest is the text after `Outer$`.
438    let tail = rest.rsplit('$').next().unwrap_or(rest);
439    if rest.starts_with("-$$Lambda$") || tail.starts_with("-$$Lambda$") {
440        return NestedKind::Lambda;
441    }
442    if !tail.is_empty() && tail.chars().all(|c| c.is_ascii_digit()) {
443        return NestedKind::Anonymous;
444    }
445    if tail.starts_with(|c: char| c.is_ascii_digit()) {
446        return NestedKind::Local;
447    }
448    NestedKind::Member
449}
450
451fn raw_field_flags(raw: u32) -> FieldAccessFlags {
452    let mut f = FieldAccessFlags::empty();
453    if raw & ACC_PUBLIC != 0 {
454        f |= FieldAccessFlags::PUBLIC;
455    }
456    if raw & ACC_PRIVATE != 0 {
457        f |= FieldAccessFlags::PRIVATE;
458    }
459    if raw & ACC_PROTECTED != 0 {
460        f |= FieldAccessFlags::PROTECTED;
461    }
462    if raw & ACC_STATIC != 0 {
463        f |= FieldAccessFlags::STATIC;
464    }
465    if raw & ACC_FINAL != 0 {
466        f |= FieldAccessFlags::FINAL;
467    }
468    if raw & ACC_SYNTHETIC != 0 {
469        f |= FieldAccessFlags::SYNTHETIC;
470    }
471    if raw & ACC_ENUM != 0 {
472        f |= FieldAccessFlags::ENUM;
473    }
474    f
475}
476
477fn raw_method_flags(raw: u32) -> MethodAccessFlags {
478    let mut f = MethodAccessFlags::empty();
479    if raw & ACC_PUBLIC != 0 {
480        f |= MethodAccessFlags::PUBLIC;
481    }
482    if raw & ACC_PRIVATE != 0 {
483        f |= MethodAccessFlags::PRIVATE;
484    }
485    if raw & ACC_PROTECTED != 0 {
486        f |= MethodAccessFlags::PROTECTED;
487    }
488    if raw & ACC_STATIC != 0 {
489        f |= MethodAccessFlags::STATIC;
490    }
491    if raw & ACC_FINAL != 0 {
492        f |= MethodAccessFlags::FINAL;
493    }
494    if raw & ACC_SYNCHRONIZED != 0 || raw & ACC_DECLARED_SYNCHRONIZED != 0 {
495        f |= MethodAccessFlags::SYNCHRONIZED;
496    }
497    if raw & ACC_BRIDGE != 0 {
498        f |= MethodAccessFlags::BRIDGE;
499    }
500    if raw & ACC_VARARGS != 0 {
501        f |= MethodAccessFlags::VARARGS;
502    }
503    if raw & ACC_NATIVE != 0 {
504        f |= MethodAccessFlags::NATIVE;
505    }
506    if raw & ACC_ABSTRACT != 0 {
507        f |= MethodAccessFlags::ABSTRACT;
508    }
509    if raw & ACC_STRICT != 0 {
510        f |= MethodAccessFlags::STRICT;
511    }
512    if raw & ACC_SYNTHETIC != 0 {
513        f |= MethodAccessFlags::SYNTHETIC;
514    }
515    f
516}
517
518/// Erased JavaType → generic type view (no signature data in DEX).
519pub fn java_type_to_generic(t: &JavaType) -> GenericType {
520    match t {
521        JavaType::Object(n) => GenericType::Class(class_sig_of(n)),
522        JavaType::Array(inner) => GenericType::Array(Box::new(java_type_to_generic(inner))),
523        other => GenericType::Primitive(other.primitive_char().unwrap_or('V')),
524    }
525}
526
527fn class_sig_of(internal: &str) -> jdc_core::types::ClassSig {
528    let (package, name) = match internal.rfind('/') {
529        Some(i) => (internal[..i].to_string(), internal[i + 1..].to_string()),
530        None => (String::new(), internal.to_string()),
531    };
532    jdc_core::types::ClassSig {
533        package,
534        parts: vec![jdc_core::types::ClassSigPart { name, args: vec![] }],
535    }
536}
537
538/// Render a type reference for signatures where the printer is not used.
539pub fn type_ref_of(desc: &str) -> TypeRef {
540    TypeRef::J(desc_type(desc))
541}
542
543/// Pool-level mirror of the `DexCtx::nested_is_static` render decision
544/// for passes that run without a ctx (method.rs). ACC_STATIC annotation
545/// evidence OR the structural signals — no outer-typed `this$0` field,
546/// or no formal-0 outer ctor param (a this$0 field without the formal-0
547/// param is a Kotlin lambda capture, not a JLS outer).
548pub fn nested_is_static(pool: &DexPool, pc: &PoolClass) -> bool {
549    if pc.is_static_nested() {
550        return true;
551    }
552    let Some(outer) = crate::find_outer_name(pool, &pc.name) else {
553        return true;
554    };
555    let holds = pc.instance_fields.iter().any(|f| {
556        f.name == "this$0"
557            && f
558                .desc
559                .strip_prefix('L')
560                .and_then(|d| d.strip_suffix(';'))
561                .is_some_and(|ty| ty == outer)
562    });
563    if !holds {
564        return true;
565    }
566    !pc.all_methods().any(|m| {
567        &*m.name == "<init>"
568            && m.parsed_desc().is_some_and(|d| {
569                d.args.first().is_some_and(|t| {
570                    matches!(t, JavaType::Object(n) if n.as_ref() == outer.as_str())
571                })
572            })
573    })
574}