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.as_ref() == "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.as_ref() == 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 is_fw_shadow(&self, internal: &str) -> bool {
377        crate::is_fw_shadow(internal)
378    }
379
380    fn declares_field_display(&self, internal: &str, display: &str) -> bool {
381        let pc = if internal == self.class.name {
382            self.class
383        } else {
384            match self.find_class(internal) {
385                Some(pc) => pc,
386                None => return false,
387            }
388        };
389        pc.static_fields
390            .iter()
391            .chain(pc.instance_fields.iter())
392            .any(|f| {
393                let disp = jdc_core::rename::field_display(internal, &f.name, &f.desc)
394                    .map(|d| d.to_string())
395                    .unwrap_or_else(|| crate::classdec::java_ident(&f.name).into_owned());
396                disp == display
397            })
398    }
399
400    fn declares_method_named(&self, internal: &str, name: &str) -> bool {
401        self.find_class(internal)
402            .map(|pc| pc.all_methods().any(|m| &*m.name == name))
403            .unwrap_or(false)
404    }
405
406    fn is_generic_call(&self, _e: &Expr) -> bool {
407        false
408    }
409
410    fn generic_call_formals(&self, _e: &Expr) -> Option<(Vec<GenericType>, Vec<String>)> {
411        None
412    }
413
414    fn polymorphic_ret_cast(
415        &self,
416        _cls: &str,
417        _name: &str,
418        _desc: &MethodDescriptor,
419    ) -> Option<JavaType> {
420        None
421    }
422
423    fn ctor_formals_by_arity(&self, internal: &str, arity: usize) -> Option<Vec<GenericType>> {
424        let pc = self.find_class(internal)?;
425        let ctors = pc.ctors_by_arity(arity);
426        let m = ctors.first()?;
427        let md = m.parsed_desc()?;
428        Some(md.args.iter().map(java_type_to_generic).collect())
429    }
430
431    fn ctor_param_types(
432        &self,
433        internal: &str,
434        skip: usize,
435        n: usize,
436        args: &[Expr],
437    ) -> Option<Vec<JavaType>> {
438        let _ = args;
439        let pc = self.find_class(internal)?;
440        let ctors = pc.ctors_by_arity(skip + n);
441        let m = ctors.first()?;
442        let md = m.parsed_desc()?;
443        Some(md.args.iter().skip(skip).cloned().collect())
444    }
445
446    fn outer_param_via_super(&self, _internal: &str) -> bool {
447        false
448    }
449
450    fn nested_method(
451        &self,
452        _l: &jdc_core::ir::expr::LambdaExpr,
453        _outer_vt: &jdc_core::var::VarTable,
454    ) -> Option<jdc_core::MethodBody> {
455        None
456    }
457}
458
459/// `$`-suffix classification (javac conventions d8 preserves).
460fn classify_nested(rest: &str) -> NestedKind {
461    // rest is the text after `Outer$`.
462    let tail = rest.rsplit('$').next().unwrap_or(rest);
463    if rest.starts_with("-$$Lambda$") || tail.starts_with("-$$Lambda$") {
464        return NestedKind::Lambda;
465    }
466    if !tail.is_empty() && tail.chars().all(|c| c.is_ascii_digit()) {
467        return NestedKind::Anonymous;
468    }
469    if tail.starts_with(|c: char| c.is_ascii_digit()) {
470        return NestedKind::Local;
471    }
472    NestedKind::Member
473}
474
475fn raw_field_flags(raw: u32) -> FieldAccessFlags {
476    let mut f = FieldAccessFlags::empty();
477    if raw & ACC_PUBLIC != 0 {
478        f |= FieldAccessFlags::PUBLIC;
479    }
480    if raw & ACC_PRIVATE != 0 {
481        f |= FieldAccessFlags::PRIVATE;
482    }
483    if raw & ACC_PROTECTED != 0 {
484        f |= FieldAccessFlags::PROTECTED;
485    }
486    if raw & ACC_STATIC != 0 {
487        f |= FieldAccessFlags::STATIC;
488    }
489    if raw & ACC_FINAL != 0 {
490        f |= FieldAccessFlags::FINAL;
491    }
492    if raw & ACC_SYNTHETIC != 0 {
493        f |= FieldAccessFlags::SYNTHETIC;
494    }
495    if raw & ACC_ENUM != 0 {
496        f |= FieldAccessFlags::ENUM;
497    }
498    f
499}
500
501fn raw_method_flags(raw: u32) -> MethodAccessFlags {
502    let mut f = MethodAccessFlags::empty();
503    if raw & ACC_PUBLIC != 0 {
504        f |= MethodAccessFlags::PUBLIC;
505    }
506    if raw & ACC_PRIVATE != 0 {
507        f |= MethodAccessFlags::PRIVATE;
508    }
509    if raw & ACC_PROTECTED != 0 {
510        f |= MethodAccessFlags::PROTECTED;
511    }
512    if raw & ACC_STATIC != 0 {
513        f |= MethodAccessFlags::STATIC;
514    }
515    if raw & ACC_FINAL != 0 {
516        f |= MethodAccessFlags::FINAL;
517    }
518    if raw & ACC_SYNCHRONIZED != 0 || raw & ACC_DECLARED_SYNCHRONIZED != 0 {
519        f |= MethodAccessFlags::SYNCHRONIZED;
520    }
521    if raw & ACC_BRIDGE != 0 {
522        f |= MethodAccessFlags::BRIDGE;
523    }
524    if raw & ACC_VARARGS != 0 {
525        f |= MethodAccessFlags::VARARGS;
526    }
527    if raw & ACC_NATIVE != 0 {
528        f |= MethodAccessFlags::NATIVE;
529    }
530    if raw & ACC_ABSTRACT != 0 {
531        f |= MethodAccessFlags::ABSTRACT;
532    }
533    if raw & ACC_STRICT != 0 {
534        f |= MethodAccessFlags::STRICT;
535    }
536    if raw & ACC_SYNTHETIC != 0 {
537        f |= MethodAccessFlags::SYNTHETIC;
538    }
539    f
540}
541
542/// Erased JavaType → generic type view (no signature data in DEX).
543pub fn java_type_to_generic(t: &JavaType) -> GenericType {
544    match t {
545        JavaType::Object(n) => GenericType::Class(class_sig_of(n)),
546        JavaType::Array(inner) => GenericType::Array(Box::new(java_type_to_generic(inner))),
547        other => GenericType::Primitive(other.primitive_char().unwrap_or('V')),
548    }
549}
550
551fn class_sig_of(internal: &str) -> jdc_core::types::ClassSig {
552    let (package, name) = match internal.rfind('/') {
553        Some(i) => (internal[..i].to_string(), internal[i + 1..].to_string()),
554        None => (String::new(), internal.to_string()),
555    };
556    jdc_core::types::ClassSig {
557        package,
558        parts: vec![jdc_core::types::ClassSigPart { name, args: vec![] }],
559    }
560}
561
562/// Render a type reference for signatures where the printer is not used.
563pub fn type_ref_of(desc: &str) -> TypeRef {
564    TypeRef::J(desc_type(desc))
565}
566
567/// Pool-level mirror of the `DexCtx::nested_is_static` render decision
568/// for passes that run without a ctx (method.rs). ACC_STATIC annotation
569/// evidence OR the structural signals — no outer-typed `this$0` field,
570/// or no formal-0 outer ctor param (a this$0 field without the formal-0
571/// param is a Kotlin lambda capture, not a JLS outer).
572pub fn nested_is_static(pool: &DexPool, pc: &PoolClass) -> bool {
573    if pc.is_static_nested() {
574        return true;
575    }
576    let Some(outer) = crate::find_outer_name(pool, &pc.name) else {
577        return true;
578    };
579    let holds = pc.instance_fields.iter().any(|f| {
580        f.name.as_ref() == "this$0"
581            && f
582                .desc
583                .strip_prefix('L')
584                .and_then(|d| d.strip_suffix(';'))
585                .is_some_and(|ty| ty == outer)
586    });
587    if !holds {
588        return true;
589    }
590    !pc.all_methods().any(|m| {
591        &*m.name == "<init>"
592            && m.parsed_desc().is_some_and(|d| {
593                d.args.first().is_some_and(|t| {
594                    matches!(t, JavaType::Object(n) if n.as_ref() == outer.as_str())
595                })
596            })
597    })
598}