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        match self.find_class(internal) {
230            // ACC_STATIC (annotation evidence) OR the structural signal:
231            // no instance field typed as the outer class. javac ALWAYS
232            // gives a non-static inner class an enclosing-instance field
233            // (this$0), and the field TYPE survives obfuscation that
234            // renames the field itself. Plain d8 output carries no
235            // nesting annotations at all — without the structural
236            // fallback every static nested class rendered as an inner
237            // one (`str.new Report(...)` swallowing the first ctor arg).
238            // A this$0 field WITHOUT the formal-0 outer ctor param is a
239            // capture, not a JLS outer (Kotlin lambdas) — static too.
240            Some(pc) => {
241                pc.is_static_nested()
242                    || !self.holds_this0(internal, pc)
243                    || !self.outer_is_formal0(internal, pc)
244            }
245            None => true,
246        }
247    }
248
249    fn class_has_this0(&self, internal: &str) -> bool {
250        // Inner classes without ACC_STATIC carry an enclosing instance.
251        match self.find_class(internal) {
252            Some(pc) => {
253                !pc.is_static_nested()
254                    && self.holds_this0(internal, pc)
255                    && self.outer_is_formal0(internal, pc)
256            }
257            None => false,
258        }
259    }
260
261    fn is_subtype_of(&self, sub: &JavaType, sup: &str) -> bool {
262        if let JavaType::Object(n) = sub {
263            self.pool.is_subtype(n, sup)
264        } else {
265            false
266        }
267    }
268
269    fn is_interface(&self, internal: &str) -> bool {
270        self.find_class(internal)
271            .map(|pc| pc.is_interface())
272            .unwrap_or(false)
273    }
274
275    fn is_sealed(&self, _internal: &str) -> bool {
276        false
277    }
278
279    fn super_name(&self, internal: &str) -> Option<String> {
280        self.find_class(internal)
281            .and_then(|pc| pc.super_name.clone())
282    }
283
284    fn has_class(&self, internal: &str) -> bool {
285        self.pool.get(internal).is_some() || internal == self.class.name
286    }
287
288    fn class_supers_args(
289        &self,
290        internal: &str,
291        _args: &[GenericType],
292    ) -> Vec<(String, Vec<GenericType>)> {
293        let mut out = Vec::new();
294        let mut cur = self.find_class(internal).map(|pc| pc.name.clone());
295        let mut hops = 0;
296        while let Some(name) = cur {
297            hops += 1;
298            if hops > 64 {
299                break;
300            }
301            if name == "java/lang/Object" {
302                break;
303            }
304            out.push((name.clone(), Vec::new()));
305            cur = self.find_class(&name).and_then(|pc| pc.super_name.clone());
306        }
307        out
308    }
309
310    fn class_bases(&self, internal: &str) -> Option<(Vec<String>, Option<String>)> {
311        let pc = self.find_class(internal)?;
312        Some((pc.interfaces.clone(), pc.super_name.clone()))
313    }
314
315    fn field_flags(&self, internal: &str, name: &str) -> Option<FieldAccessFlags> {
316        let pc = self.find_class(internal)?;
317        let raw = pc
318            .static_fields
319            .iter()
320            .chain(pc.instance_fields.iter())
321            .find(|f| f.name == name)?
322            .access;
323        Some(raw_field_flags(raw))
324    }
325
326    fn method_flags(&self, internal: &str, name: &str, desc: &str) -> Option<MethodAccessFlags> {
327        let pc = self.find_class(internal)?;
328        let m = pc.find_method(name, desc)?;
329        Some(raw_method_flags(m.access))
330    }
331
332    fn declares_field(&self, internal: &str, name: &str) -> bool {
333        if internal == self.class.name {
334            return self.inherited_fields.contains(name)
335                || self.class.field_flags_of(name).is_some();
336        }
337        self.find_class(internal)
338            .map(|pc| pc.field_flags_of(name).is_some())
339            .unwrap_or(false)
340    }
341
342    fn declares_method_named(&self, internal: &str, name: &str) -> bool {
343        self.find_class(internal)
344            .map(|pc| pc.all_methods().any(|m| &*m.name == name))
345            .unwrap_or(false)
346    }
347
348    fn is_generic_call(&self, _e: &Expr) -> bool {
349        false
350    }
351
352    fn generic_call_formals(&self, _e: &Expr) -> Option<(Vec<GenericType>, Vec<String>)> {
353        None
354    }
355
356    fn polymorphic_ret_cast(
357        &self,
358        _cls: &str,
359        _name: &str,
360        _desc: &MethodDescriptor,
361    ) -> Option<JavaType> {
362        None
363    }
364
365    fn ctor_formals_by_arity(&self, internal: &str, arity: usize) -> Option<Vec<GenericType>> {
366        let pc = self.find_class(internal)?;
367        let ctors = pc.ctors_by_arity(arity);
368        let m = ctors.first()?;
369        let md = m.parsed_desc()?;
370        Some(md.args.iter().map(java_type_to_generic).collect())
371    }
372
373    fn ctor_param_types(
374        &self,
375        internal: &str,
376        skip: usize,
377        n: usize,
378        args: &[Expr],
379    ) -> Option<Vec<JavaType>> {
380        let _ = args;
381        let pc = self.find_class(internal)?;
382        let ctors = pc.ctors_by_arity(skip + n);
383        let m = ctors.first()?;
384        let md = m.parsed_desc()?;
385        Some(md.args.iter().skip(skip).cloned().collect())
386    }
387
388    fn outer_param_via_super(&self, _internal: &str) -> bool {
389        false
390    }
391
392    fn nested_method(
393        &self,
394        _l: &jdc_core::ir::expr::LambdaExpr,
395        _outer_vt: &jdc_core::var::VarTable,
396    ) -> Option<jdc_core::MethodBody> {
397        None
398    }
399}
400
401/// `$`-suffix classification (javac conventions d8 preserves).
402fn classify_nested(rest: &str) -> NestedKind {
403    // rest is the text after `Outer$`.
404    let tail = rest.rsplit('$').next().unwrap_or(rest);
405    if rest.starts_with("-$$Lambda$") || tail.starts_with("-$$Lambda$") {
406        return NestedKind::Lambda;
407    }
408    if !tail.is_empty() && tail.chars().all(|c| c.is_ascii_digit()) {
409        return NestedKind::Anonymous;
410    }
411    if tail.starts_with(|c: char| c.is_ascii_digit()) {
412        return NestedKind::Local;
413    }
414    NestedKind::Member
415}
416
417fn raw_field_flags(raw: u32) -> FieldAccessFlags {
418    let mut f = FieldAccessFlags::empty();
419    if raw & ACC_PUBLIC != 0 {
420        f |= FieldAccessFlags::PUBLIC;
421    }
422    if raw & ACC_PRIVATE != 0 {
423        f |= FieldAccessFlags::PRIVATE;
424    }
425    if raw & ACC_PROTECTED != 0 {
426        f |= FieldAccessFlags::PROTECTED;
427    }
428    if raw & ACC_STATIC != 0 {
429        f |= FieldAccessFlags::STATIC;
430    }
431    if raw & ACC_FINAL != 0 {
432        f |= FieldAccessFlags::FINAL;
433    }
434    if raw & ACC_SYNTHETIC != 0 {
435        f |= FieldAccessFlags::SYNTHETIC;
436    }
437    if raw & ACC_ENUM != 0 {
438        f |= FieldAccessFlags::ENUM;
439    }
440    f
441}
442
443fn raw_method_flags(raw: u32) -> MethodAccessFlags {
444    let mut f = MethodAccessFlags::empty();
445    if raw & ACC_PUBLIC != 0 {
446        f |= MethodAccessFlags::PUBLIC;
447    }
448    if raw & ACC_PRIVATE != 0 {
449        f |= MethodAccessFlags::PRIVATE;
450    }
451    if raw & ACC_PROTECTED != 0 {
452        f |= MethodAccessFlags::PROTECTED;
453    }
454    if raw & ACC_STATIC != 0 {
455        f |= MethodAccessFlags::STATIC;
456    }
457    if raw & ACC_FINAL != 0 {
458        f |= MethodAccessFlags::FINAL;
459    }
460    if raw & ACC_SYNCHRONIZED != 0 || raw & ACC_DECLARED_SYNCHRONIZED != 0 {
461        f |= MethodAccessFlags::SYNCHRONIZED;
462    }
463    if raw & ACC_BRIDGE != 0 {
464        f |= MethodAccessFlags::BRIDGE;
465    }
466    if raw & ACC_VARARGS != 0 {
467        f |= MethodAccessFlags::VARARGS;
468    }
469    if raw & ACC_NATIVE != 0 {
470        f |= MethodAccessFlags::NATIVE;
471    }
472    if raw & ACC_ABSTRACT != 0 {
473        f |= MethodAccessFlags::ABSTRACT;
474    }
475    if raw & ACC_STRICT != 0 {
476        f |= MethodAccessFlags::STRICT;
477    }
478    if raw & ACC_SYNTHETIC != 0 {
479        f |= MethodAccessFlags::SYNTHETIC;
480    }
481    f
482}
483
484/// Erased JavaType → generic type view (no signature data in DEX).
485pub fn java_type_to_generic(t: &JavaType) -> GenericType {
486    match t {
487        JavaType::Object(n) => GenericType::Class(class_sig_of(n)),
488        JavaType::Array(inner) => GenericType::Array(Box::new(java_type_to_generic(inner))),
489        other => GenericType::Primitive(other.primitive_char().unwrap_or('V')),
490    }
491}
492
493fn class_sig_of(internal: &str) -> jdc_core::types::ClassSig {
494    let (package, name) = match internal.rfind('/') {
495        Some(i) => (internal[..i].to_string(), internal[i + 1..].to_string()),
496        None => (String::new(), internal.to_string()),
497    };
498    jdc_core::types::ClassSig {
499        package,
500        parts: vec![jdc_core::types::ClassSigPart { name, args: vec![] }],
501    }
502}
503
504/// Render a type reference for signatures where the printer is not used.
505pub fn type_ref_of(desc: &str) -> TypeRef {
506    TypeRef::J(desc_type(desc))
507}