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()
284            || internal == self.class.name
285            // The ddcroot ROOT-PACKAGE RELOCATION only: the display
286            // prepends the synthetic package, the pool key lacks it.
287            // Deliberately NOT a general un-rename: collision-renamed
288            // nested families (weibo x0$a$b) render dotted against
289            // their renamed emission owners — a general un-rename
290            // flipped them to flat `$` renders (weibo 5,357 → 77,783
291            // cannot-find cascade). Flat `$` here is right ONLY for
292            // relocated root classes, which ARE their own emission
293            // unit (lark UserCustomStatusExtraParams$* "不可见" ×138).
294            || crate::root_pkg_display().is_some_and(|rp| {
295                internal.len() > rp.len() + 1
296                    && internal.starts_with(rp.as_str())
297                    && internal.as_bytes()[rp.len()] == b'/'
298                    && self.pool.get(&internal[rp.len() + 1..]).is_some()
299            })
300    }
301
302    fn class_supers_args(
303        &self,
304        internal: &str,
305        _args: &[GenericType],
306    ) -> Vec<(String, Vec<GenericType>)> {
307        let mut out = Vec::new();
308        let mut cur = self.find_class(internal).map(|pc| pc.name.clone());
309        let mut hops = 0;
310        while let Some(name) = cur {
311            hops += 1;
312            if hops > 64 {
313                break;
314            }
315            if name == "java/lang/Object" {
316                break;
317            }
318            out.push((name.clone(), Vec::new()));
319            cur = self.find_class(&name).and_then(|pc| pc.super_name.clone());
320        }
321        out
322    }
323
324    fn class_bases(&self, internal: &str) -> Option<(Vec<String>, Option<String>)> {
325        let pc = self.find_class(internal)?;
326        Some((pc.interfaces.clone(), pc.super_name.clone()))
327    }
328
329    fn field_flags(&self, internal: &str, name: &str) -> Option<FieldAccessFlags> {
330        let pc = self.find_class(internal)?;
331        let raw = pc
332            .static_fields
333            .iter()
334            .chain(pc.instance_fields.iter())
335            .find(|f| f.name == name)?
336            .access;
337        Some(raw_field_flags(raw))
338    }
339
340    fn method_flags(&self, internal: &str, name: &str, desc: &str) -> Option<MethodAccessFlags> {
341        let pc = self.find_class(internal)?;
342        let m = pc.find_method(name, desc)?;
343        Some(raw_method_flags(m.access))
344    }
345
346    fn declares_field(&self, internal: &str, name: &str) -> bool {
347        if internal == self.class.name {
348            return self.inherited_fields.contains(name)
349                || self.class.field_flags_of(name).is_some();
350        }
351        self.find_class(internal)
352            .map(|pc| pc.field_flags_of(name).is_some())
353            .unwrap_or(false)
354    }
355
356    fn declares_method_named(&self, internal: &str, name: &str) -> bool {
357        self.find_class(internal)
358            .map(|pc| pc.all_methods().any(|m| &*m.name == name))
359            .unwrap_or(false)
360    }
361
362    fn is_generic_call(&self, _e: &Expr) -> bool {
363        false
364    }
365
366    fn generic_call_formals(&self, _e: &Expr) -> Option<(Vec<GenericType>, Vec<String>)> {
367        None
368    }
369
370    fn polymorphic_ret_cast(
371        &self,
372        _cls: &str,
373        _name: &str,
374        _desc: &MethodDescriptor,
375    ) -> Option<JavaType> {
376        None
377    }
378
379    fn ctor_formals_by_arity(&self, internal: &str, arity: usize) -> Option<Vec<GenericType>> {
380        let pc = self.find_class(internal)?;
381        let ctors = pc.ctors_by_arity(arity);
382        let m = ctors.first()?;
383        let md = m.parsed_desc()?;
384        Some(md.args.iter().map(java_type_to_generic).collect())
385    }
386
387    fn ctor_param_types(
388        &self,
389        internal: &str,
390        skip: usize,
391        n: usize,
392        args: &[Expr],
393    ) -> Option<Vec<JavaType>> {
394        let _ = args;
395        let pc = self.find_class(internal)?;
396        let ctors = pc.ctors_by_arity(skip + n);
397        let m = ctors.first()?;
398        let md = m.parsed_desc()?;
399        Some(md.args.iter().skip(skip).cloned().collect())
400    }
401
402    fn outer_param_via_super(&self, _internal: &str) -> bool {
403        false
404    }
405
406    fn nested_method(
407        &self,
408        _l: &jdc_core::ir::expr::LambdaExpr,
409        _outer_vt: &jdc_core::var::VarTable,
410    ) -> Option<jdc_core::MethodBody> {
411        None
412    }
413}
414
415/// `$`-suffix classification (javac conventions d8 preserves).
416fn classify_nested(rest: &str) -> NestedKind {
417    // rest is the text after `Outer$`.
418    let tail = rest.rsplit('$').next().unwrap_or(rest);
419    if rest.starts_with("-$$Lambda$") || tail.starts_with("-$$Lambda$") {
420        return NestedKind::Lambda;
421    }
422    if !tail.is_empty() && tail.chars().all(|c| c.is_ascii_digit()) {
423        return NestedKind::Anonymous;
424    }
425    if tail.starts_with(|c: char| c.is_ascii_digit()) {
426        return NestedKind::Local;
427    }
428    NestedKind::Member
429}
430
431fn raw_field_flags(raw: u32) -> FieldAccessFlags {
432    let mut f = FieldAccessFlags::empty();
433    if raw & ACC_PUBLIC != 0 {
434        f |= FieldAccessFlags::PUBLIC;
435    }
436    if raw & ACC_PRIVATE != 0 {
437        f |= FieldAccessFlags::PRIVATE;
438    }
439    if raw & ACC_PROTECTED != 0 {
440        f |= FieldAccessFlags::PROTECTED;
441    }
442    if raw & ACC_STATIC != 0 {
443        f |= FieldAccessFlags::STATIC;
444    }
445    if raw & ACC_FINAL != 0 {
446        f |= FieldAccessFlags::FINAL;
447    }
448    if raw & ACC_SYNTHETIC != 0 {
449        f |= FieldAccessFlags::SYNTHETIC;
450    }
451    if raw & ACC_ENUM != 0 {
452        f |= FieldAccessFlags::ENUM;
453    }
454    f
455}
456
457fn raw_method_flags(raw: u32) -> MethodAccessFlags {
458    let mut f = MethodAccessFlags::empty();
459    if raw & ACC_PUBLIC != 0 {
460        f |= MethodAccessFlags::PUBLIC;
461    }
462    if raw & ACC_PRIVATE != 0 {
463        f |= MethodAccessFlags::PRIVATE;
464    }
465    if raw & ACC_PROTECTED != 0 {
466        f |= MethodAccessFlags::PROTECTED;
467    }
468    if raw & ACC_STATIC != 0 {
469        f |= MethodAccessFlags::STATIC;
470    }
471    if raw & ACC_FINAL != 0 {
472        f |= MethodAccessFlags::FINAL;
473    }
474    if raw & ACC_SYNCHRONIZED != 0 || raw & ACC_DECLARED_SYNCHRONIZED != 0 {
475        f |= MethodAccessFlags::SYNCHRONIZED;
476    }
477    if raw & ACC_BRIDGE != 0 {
478        f |= MethodAccessFlags::BRIDGE;
479    }
480    if raw & ACC_VARARGS != 0 {
481        f |= MethodAccessFlags::VARARGS;
482    }
483    if raw & ACC_NATIVE != 0 {
484        f |= MethodAccessFlags::NATIVE;
485    }
486    if raw & ACC_ABSTRACT != 0 {
487        f |= MethodAccessFlags::ABSTRACT;
488    }
489    if raw & ACC_STRICT != 0 {
490        f |= MethodAccessFlags::STRICT;
491    }
492    if raw & ACC_SYNTHETIC != 0 {
493        f |= MethodAccessFlags::SYNTHETIC;
494    }
495    f
496}
497
498/// Erased JavaType → generic type view (no signature data in DEX).
499pub fn java_type_to_generic(t: &JavaType) -> GenericType {
500    match t {
501        JavaType::Object(n) => GenericType::Class(class_sig_of(n)),
502        JavaType::Array(inner) => GenericType::Array(Box::new(java_type_to_generic(inner))),
503        other => GenericType::Primitive(other.primitive_char().unwrap_or('V')),
504    }
505}
506
507fn class_sig_of(internal: &str) -> jdc_core::types::ClassSig {
508    let (package, name) = match internal.rfind('/') {
509        Some(i) => (internal[..i].to_string(), internal[i + 1..].to_string()),
510        None => (String::new(), internal.to_string()),
511    };
512    jdc_core::types::ClassSig {
513        package,
514        parts: vec![jdc_core::types::ClassSigPart { name, args: vec![] }],
515    }
516}
517
518/// Render a type reference for signatures where the printer is not used.
519pub fn type_ref_of(desc: &str) -> TypeRef {
520    TypeRef::J(desc_type(desc))
521}
522
523/// Pool-level mirror of the `DexCtx::nested_is_static` render decision
524/// for passes that run without a ctx (method.rs). ACC_STATIC annotation
525/// evidence OR the structural signals — no outer-typed `this$0` field,
526/// or no formal-0 outer ctor param (a this$0 field without the formal-0
527/// param is a Kotlin lambda capture, not a JLS outer).
528pub fn nested_is_static(pool: &DexPool, pc: &PoolClass) -> bool {
529    if pc.is_static_nested() {
530        return true;
531    }
532    let Some(outer) = crate::find_outer_name(pool, &pc.name) else {
533        return true;
534    };
535    let holds = pc.instance_fields.iter().any(|f| {
536        f.name == "this$0"
537            && f
538                .desc
539                .strip_prefix('L')
540                .and_then(|d| d.strip_suffix(';'))
541                .is_some_and(|ty| ty == outer)
542    });
543    if !holds {
544        return true;
545    }
546    !pc.all_methods().any(|m| {
547        &*m.name == "<init>"
548            && m.parsed_desc().is_some_and(|d| {
549                d.args.first().is_some_and(|t| {
550                    matches!(t, JavaType::Object(n) if n.as_ref() == outer.as_str())
551                })
552            })
553    })
554}