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        if internal == self.class.name {
170            return self.outer_of(internal);
171        }
172        self.outer_of(internal)
173    }
174
175    fn family(&self, root: &str) -> Family {
176        let mut fam = Family {
177            root: root.to_string(),
178            ..Default::default()
179        };
180        // Cached child index: BFS over the `$` chain from `root`.
181        let mut queue: std::collections::VecDeque<String> =
182            self.pool.children_of(root).iter().cloned().collect();
183        let mut seen: jdc_core::FxHashSet<String> = queue.iter().cloned().collect();
184        while let Some(name) = queue.pop_front() {
185            for c in self.pool.children_of(&name) {
186                if seen.insert(c.clone()) {
187                    queue.push_back(c.clone());
188                }
189            }
190            let Some(_) = self.find_class(&name) else {
191                continue;
192            };
193            let root_prefix = format!("{}$", root);
194            let rest: String = if name.starts_with(&root_prefix) {
195                name[root_prefix.len()..].to_string()
196            } else {
197                name.rsplit('$').next().unwrap_or(&name).to_string()
198            };
199            let simple = rest.rsplit('$').next().unwrap_or(&rest).to_string();
200            let kind = classify_nested(&rest);
201            let access = self.class_access_flags(&name);
202            fam.nested.insert(
203                name.clone(),
204                NestedClass {
205                    name: name.clone(),
206                    simple,
207                    kind,
208                    access,
209                    sig_header: None,
210                },
211            );
212            match kind {
213                NestedKind::Anonymous => {
214                    fam.anonymous.insert(name.clone());
215                }
216                NestedKind::Local => {
217                    fam.locals.insert(name.clone());
218                }
219                NestedKind::Lambda => {
220                    fam.lambdas.insert(name.clone());
221                }
222                NestedKind::Member => {}
223            }
224        }
225        fam
226    }
227
228    fn nested_is_static(&self, internal: &str) -> bool {
229        // ACC_STATIC (annotation evidence) OR the structural signal:
230        // no instance field typed as the outer class. javac ALWAYS
231        // gives a non-static inner class an enclosing-instance field
232        // (this$0), and the field TYPE survives obfuscation that
233        // renames the field itself. Plain d8 output carries no
234        // nesting annotations at all — without the structural
235        // fallback every static nested class rendered as an inner
236        // one (`str.new Report(...)` swallowing the first ctor arg).
237        // A this$0 field WITHOUT the formal-0 outer ctor param is a
238        // capture, not a JLS outer (Kotlin lambdas) — static too.
239        // Logic lives in the free `nested_is_static` below (shared
240        // with method.rs passes that run without a ctx).
241        match self.find_class(internal) {
242            Some(pc) => nested_is_static(self.pool, pc),
243            None => true,
244        }
245    }
246
247    fn class_has_this0(&self, internal: &str) -> bool {
248        // Inner classes without ACC_STATIC carry an enclosing instance.
249        match self.find_class(internal) {
250            Some(pc) => {
251                !pc.is_static_nested()
252                    && self.holds_this0(internal, pc)
253                    && self.outer_is_formal0(internal, pc)
254            }
255            None => false,
256        }
257    }
258
259    fn is_subtype_of(&self, sub: &JavaType, sup: &str) -> bool {
260        if let JavaType::Object(n) = sub {
261            self.pool.is_subtype(n, sup)
262        } else {
263            false
264        }
265    }
266
267    fn is_interface(&self, internal: &str) -> bool {
268        self.find_class(internal)
269            .map(|pc| pc.is_interface())
270            .unwrap_or(false)
271    }
272
273    fn is_sealed(&self, _internal: &str) -> bool {
274        false
275    }
276
277    fn super_name(&self, internal: &str) -> Option<String> {
278        self.find_class(internal)
279            .and_then(|pc| pc.super_name.clone())
280    }
281
282    fn has_class(&self, internal: &str) -> bool {
283        self.pool.get(internal).is_some() || internal == self.class.name
284    }
285
286    fn class_supers_args(
287        &self,
288        internal: &str,
289        _args: &[GenericType],
290    ) -> Vec<(String, Vec<GenericType>)> {
291        let mut out = Vec::new();
292        let mut cur = self.find_class(internal).map(|pc| pc.name.clone());
293        let mut hops = 0;
294        while let Some(name) = cur {
295            hops += 1;
296            if hops > 64 {
297                break;
298            }
299            if name == "java/lang/Object" {
300                break;
301            }
302            out.push((name.clone(), Vec::new()));
303            cur = self.find_class(&name).and_then(|pc| pc.super_name.clone());
304        }
305        out
306    }
307
308    fn class_bases(&self, internal: &str) -> Option<(Vec<String>, Option<String>)> {
309        let pc = self.find_class(internal)?;
310        Some((pc.interfaces.clone(), pc.super_name.clone()))
311    }
312
313    fn field_flags(&self, internal: &str, name: &str) -> Option<FieldAccessFlags> {
314        let pc = self.find_class(internal)?;
315        let raw = pc
316            .static_fields
317            .iter()
318            .chain(pc.instance_fields.iter())
319            .find(|f| f.name == name)?
320            .access;
321        Some(raw_field_flags(raw))
322    }
323
324    fn method_flags(&self, internal: &str, name: &str, desc: &str) -> Option<MethodAccessFlags> {
325        let pc = self.find_class(internal)?;
326        let m = pc.find_method(name, desc)?;
327        Some(raw_method_flags(m.access))
328    }
329
330    fn declares_field(&self, internal: &str, name: &str) -> bool {
331        if internal == self.class.name {
332            return self.inherited_fields.contains(name)
333                || self.class.field_flags_of(name).is_some();
334        }
335        self.find_class(internal)
336            .map(|pc| pc.field_flags_of(name).is_some())
337            .unwrap_or(false)
338    }
339
340    fn declares_method_named(&self, internal: &str, name: &str) -> bool {
341        self.find_class(internal)
342            .map(|pc| pc.all_methods().any(|m| &*m.name == name))
343            .unwrap_or(false)
344    }
345
346    fn is_generic_call(&self, _e: &Expr) -> bool {
347        false
348    }
349
350    fn generic_call_formals(&self, _e: &Expr) -> Option<(Vec<GenericType>, Vec<String>)> {
351        None
352    }
353
354    fn polymorphic_ret_cast(
355        &self,
356        _cls: &str,
357        _name: &str,
358        _desc: &MethodDescriptor,
359    ) -> Option<JavaType> {
360        None
361    }
362
363    fn ctor_formals_by_arity(&self, internal: &str, arity: usize) -> Option<Vec<GenericType>> {
364        let pc = self.find_class(internal)?;
365        let ctors = pc.ctors_by_arity(arity);
366        let m = ctors.first()?;
367        let md = m.parsed_desc()?;
368        Some(md.args.iter().map(java_type_to_generic).collect())
369    }
370
371    fn ctor_param_types(
372        &self,
373        internal: &str,
374        skip: usize,
375        n: usize,
376        args: &[Expr],
377    ) -> Option<Vec<JavaType>> {
378        let _ = args;
379        let pc = self.find_class(internal)?;
380        let ctors = pc.ctors_by_arity(skip + n);
381        let m = ctors.first()?;
382        let md = m.parsed_desc()?;
383        Some(md.args.iter().skip(skip).cloned().collect())
384    }
385
386    fn outer_param_via_super(&self, _internal: &str) -> bool {
387        false
388    }
389
390    fn nested_method(
391        &self,
392        _l: &jdc_core::ir::expr::LambdaExpr,
393        _outer_vt: &jdc_core::var::VarTable,
394    ) -> Option<jdc_core::MethodBody> {
395        None
396    }
397}
398
399/// `$`-suffix classification (javac conventions d8 preserves).
400fn classify_nested(rest: &str) -> NestedKind {
401    // rest is the text after `Outer$`.
402    let tail = rest.rsplit('$').next().unwrap_or(rest);
403    if rest.starts_with("-$$Lambda$") || tail.starts_with("-$$Lambda$") {
404        return NestedKind::Lambda;
405    }
406    if !tail.is_empty() && tail.chars().all(|c| c.is_ascii_digit()) {
407        return NestedKind::Anonymous;
408    }
409    if tail.starts_with(|c: char| c.is_ascii_digit()) {
410        return NestedKind::Local;
411    }
412    NestedKind::Member
413}
414
415fn raw_field_flags(raw: u32) -> FieldAccessFlags {
416    let mut f = FieldAccessFlags::empty();
417    if raw & ACC_PUBLIC != 0 {
418        f |= FieldAccessFlags::PUBLIC;
419    }
420    if raw & ACC_PRIVATE != 0 {
421        f |= FieldAccessFlags::PRIVATE;
422    }
423    if raw & ACC_PROTECTED != 0 {
424        f |= FieldAccessFlags::PROTECTED;
425    }
426    if raw & ACC_STATIC != 0 {
427        f |= FieldAccessFlags::STATIC;
428    }
429    if raw & ACC_FINAL != 0 {
430        f |= FieldAccessFlags::FINAL;
431    }
432    if raw & ACC_SYNTHETIC != 0 {
433        f |= FieldAccessFlags::SYNTHETIC;
434    }
435    if raw & ACC_ENUM != 0 {
436        f |= FieldAccessFlags::ENUM;
437    }
438    f
439}
440
441fn raw_method_flags(raw: u32) -> MethodAccessFlags {
442    let mut f = MethodAccessFlags::empty();
443    if raw & ACC_PUBLIC != 0 {
444        f |= MethodAccessFlags::PUBLIC;
445    }
446    if raw & ACC_PRIVATE != 0 {
447        f |= MethodAccessFlags::PRIVATE;
448    }
449    if raw & ACC_PROTECTED != 0 {
450        f |= MethodAccessFlags::PROTECTED;
451    }
452    if raw & ACC_STATIC != 0 {
453        f |= MethodAccessFlags::STATIC;
454    }
455    if raw & ACC_FINAL != 0 {
456        f |= MethodAccessFlags::FINAL;
457    }
458    if raw & ACC_SYNCHRONIZED != 0 || raw & ACC_DECLARED_SYNCHRONIZED != 0 {
459        f |= MethodAccessFlags::SYNCHRONIZED;
460    }
461    if raw & ACC_BRIDGE != 0 {
462        f |= MethodAccessFlags::BRIDGE;
463    }
464    if raw & ACC_VARARGS != 0 {
465        f |= MethodAccessFlags::VARARGS;
466    }
467    if raw & ACC_NATIVE != 0 {
468        f |= MethodAccessFlags::NATIVE;
469    }
470    if raw & ACC_ABSTRACT != 0 {
471        f |= MethodAccessFlags::ABSTRACT;
472    }
473    if raw & ACC_STRICT != 0 {
474        f |= MethodAccessFlags::STRICT;
475    }
476    if raw & ACC_SYNTHETIC != 0 {
477        f |= MethodAccessFlags::SYNTHETIC;
478    }
479    f
480}
481
482/// Erased JavaType → generic type view (no signature data in DEX).
483pub fn java_type_to_generic(t: &JavaType) -> GenericType {
484    match t {
485        JavaType::Object(n) => GenericType::Class(class_sig_of(n)),
486        JavaType::Array(inner) => GenericType::Array(Box::new(java_type_to_generic(inner))),
487        other => GenericType::Primitive(other.primitive_char().unwrap_or('V')),
488    }
489}
490
491fn class_sig_of(internal: &str) -> jdc_core::types::ClassSig {
492    let (package, name) = match internal.rfind('/') {
493        Some(i) => (internal[..i].to_string(), internal[i + 1..].to_string()),
494        None => (String::new(), internal.to_string()),
495    };
496    jdc_core::types::ClassSig {
497        package,
498        parts: vec![jdc_core::types::ClassSigPart { name, args: vec![] }],
499    }
500}
501
502/// Render a type reference for signatures where the printer is not used.
503pub fn type_ref_of(desc: &str) -> TypeRef {
504    TypeRef::J(desc_type(desc))
505}
506
507/// Pool-level mirror of the `DexCtx::nested_is_static` render decision
508/// for passes that run without a ctx (method.rs). ACC_STATIC annotation
509/// evidence OR the structural signals — no outer-typed `this$0` field,
510/// or no formal-0 outer ctor param (a this$0 field without the formal-0
511/// param is a Kotlin lambda capture, not a JLS outer).
512pub fn nested_is_static(pool: &DexPool, pc: &PoolClass) -> bool {
513    if pc.is_static_nested() {
514        return true;
515    }
516    let Some(outer) = crate::find_outer_name(pool, &pc.name) else {
517        return true;
518    };
519    let holds = pc.instance_fields.iter().any(|f| {
520        f.name == "this$0"
521            && f
522                .desc
523                .strip_prefix('L')
524                .and_then(|d| d.strip_suffix(';'))
525                .is_some_and(|ty| ty == outer)
526    });
527    if !holds {
528        return true;
529    }
530    !pc.all_methods().any(|m| {
531        &*m.name == "<init>"
532            && m.parsed_desc().is_some_and(|d| {
533                d.args.first().is_some_and(|t| {
534                    matches!(t, JavaType::Object(n) if n.as_ref() == outer.as_str())
535                })
536            })
537    })
538}