Skip to main content

ddc_dex/
file.rs

1//! DEX container: header, id tables, class defs.
2
3use std::collections::HashMap;
4
5use crate::annotations::{self, EncodedValue};
6use crate::code::CodeItem;
7use crate::reader::Cursor;
8
9/// Index sentinel for "absent".
10pub const NO_INDEX: u32 = 0xffff_ffff;
11
12#[derive(Debug, Clone)]
13pub struct ProtoId {
14    /// Index into string ids: the shorty descriptor.
15    pub shorty_idx: u32,
16    /// Index into type ids: return type.
17    pub return_type_idx: u32,
18    /// Offset of the parameter type list, or 0.
19    pub parameters_off: u32,
20}
21
22#[derive(Debug, Clone)]
23pub struct FieldId {
24    pub class_idx: u32,
25    pub type_idx: u32,
26    pub name_idx: u32,
27}
28
29#[derive(Debug, Clone)]
30pub struct MethodId {
31    pub class_idx: u32,
32    pub proto_idx: u32,
33    pub name_idx: u32,
34}
35
36/// One `class_def_item`.
37#[derive(Debug, Clone)]
38pub struct ClassDef {
39    /// Index into type ids.
40    pub class_idx: u32,
41    pub access_flags: u32,
42    pub superclass_idx: u32,
43    pub interfaces_off: u32,
44    pub source_file_idx: u32,
45    pub annotations_off: u32,
46    pub class_data_off: u32,
47    pub static_values_off: u32,
48}
49
50/// One `encoded_field`.
51#[derive(Debug, Clone)]
52pub struct EncodedField {
53    pub field_idx: u32,
54    pub access_flags: u32,
55}
56
57/// One `encoded_method`.
58#[derive(Debug, Clone)]
59pub struct EncodedMethod {
60    pub method_idx: u32,
61    pub access_flags: u32,
62    pub code_off: u32,
63}
64
65/// One `class_data_item`, fully expanded (index diffs applied).
66#[derive(Debug, Clone, Default)]
67pub struct ClassData {
68    pub static_fields: Vec<EncodedField>,
69    pub instance_fields: Vec<EncodedField>,
70    pub direct_methods: Vec<EncodedMethod>,
71    pub virtual_methods: Vec<EncodedMethod>,
72}
73
74/// A parsed DEX image.
75///
76/// Id tables and class defs are parsed eagerly; code items, class data and
77/// annotations are materialized on demand. All accessors degrade to
78/// sentinels/`None` on out-of-range indices instead of panicking.
79pub struct DexFile {
80    /// The raw image. `None` after `release_data`/`mark_released` —
81    /// retired images drop their inflated bytes (the full-decompile
82    /// pipeline retires a dex once every class in it has been emitted;
83    /// on weibo/lark that is ~360MB of images that used to stay resident
84    /// for the whole run).
85    data: std::sync::Mutex<Option<Vec<u8>>>,
86    /// Set by `mark_released` from a shared (&) reference — the actual
87    /// bytes drop immediately through the mutex.
88    released: std::sync::atomic::AtomicBool,
89    /// MUTF-8 string table as shared `Arc<str>` slices: pool-side
90    /// structures (PoolMethod names, resolved names) clone the Arc
91    /// instead of copying heap bytes per method — a dex string idx is
92    /// already the dedup key.
93    strings: Vec<std::sync::Arc<str>>,
94    /// Type ids: descriptor string indices.
95    types: Vec<u32>,
96    protos: Vec<ProtoId>,
97    /// Parameter type-id lists per proto, resolved once at parse: the
98    /// invoke decode path used to re-read each `type_list` from the
99    /// image on EVERY call (`read_type_list` hit the `raw()` mutex per
100    /// u16 — a full lock cycle per parameter, per invoke, per method).
101    proto_tys: Vec<Box<[u32]>>,
102    /// Method-descriptor string per proto (`(ILjava/lang/String;)V`),
103    /// formatted once at parse: pool-side PoolMethod descs clone the Arc
104    /// instead of re-joining per method (a dex's proto table is the
105    /// descriptor dedup layer — methods share protos heavily).
106    proto_descs: Vec<std::sync::Arc<str>>,
107    fields: Vec<FieldId>,
108    methods: Vec<MethodId>,
109    pub class_defs: Vec<ClassDef>,
110    pub version: String,
111    /// class_idx → index into class_defs.
112    by_type: HashMap<u32, usize>,
113    /// `method_handle_item`s (DEX 037+): (kind, field/method id).
114    method_handles: Vec<MethodHandleItem>,
115    /// `call_site_id_item`s (DEX 037+), resolved.
116    call_sites: Vec<CallSiteInfo>,
117}
118
119/// One `method_handle_item`.
120#[derive(Debug, Clone)]
121pub struct MethodHandleItem {
122    /// 0-3: field static-put/static-get/instance-put/instance-get;
123    /// 4: invoke-static; 5: invoke-instance; 6: invoke-constructor;
124    /// 7: invoke-direct; 8: invoke-interface.
125    pub kind: u16,
126    /// Field or method id (widened from u2).
127    pub target_id: u32,
128    pub is_field: bool,
129}
130
131/// A resolved `call_site_id_item`: the `call_site_off` encoded array.
132#[derive(Debug, Clone)]
133pub struct CallSiteInfo {
134    /// Bootstrap method handle index.
135    pub bootstrap_handle: u32,
136    /// Call-site method name (string index).
137    pub name_idx: u32,
138    /// Call-site method type (proto index).
139    pub proto_idx: u32,
140    /// Linker arguments (raw encoded values).
141    pub linker_args: Vec<crate::annotations::EncodedValue>,
142}
143
144impl Drop for DexFile {
145    fn drop(&mut self) {
146        *self.data.lock().unwrap() = None;
147    }
148}
149
150impl DexFile {
151    pub fn parse(data: Vec<u8>) -> Result<DexFile, String> {
152        if data.len() < crate::DEX_HEADER_SIZE {
153            return Err("file too small for DEX header".into());
154        }
155        let magic = &data[..8];
156        if &magic[..4] != b"dex\n" || magic[7] != 0 {
157            return Err(format!("not a DEX file: magic {:02x?}", magic));
158        }
159        let version = String::from_utf8_lossy(&magic[4..7]).into_owned();
160        // 036 was an unofficial odex-era marker; ART accepts 035, 037-041.
161        if !matches!(
162            version.as_str(),
163            "035" | "037" | "038" | "039" | "040" | "041"
164        ) {
165            return Err(format!("unsupported DEX version {}", version));
166        }
167        let endian = u32::from_le_bytes(data[40..44].try_into().unwrap());
168        if endian != 0x1234_5678 {
169            return Err(format!("unexpected endian tag {endian:#x}"));
170        }
171
172        let u32at = |off: usize| -> u32 {
173            if off + 4 > data.len() {
174                return 0;
175            }
176            u32::from_le_bytes(data[off..off + 4].try_into().unwrap())
177        };
178        let string_ids_size = u32at(0x38) as usize;
179        let string_ids_off = u32at(0x3c) as usize;
180        let type_ids_size = u32at(0x40) as usize;
181        let type_ids_off = u32at(0x44) as usize;
182        let proto_ids_size = u32at(0x48) as usize;
183        let proto_ids_off = u32at(0x4c) as usize;
184        let field_ids_size = u32at(0x50) as usize;
185        let field_ids_off = u32at(0x54) as usize;
186        let method_ids_size = u32at(0x58) as usize;
187        let method_ids_off = u32at(0x5c) as usize;
188        let class_defs_size = u32at(0x60) as usize;
189        let class_defs_off = u32at(0x64) as usize;
190
191        // Strings: MUTF-8 with uleb length.
192        let mut strings = Vec::with_capacity(string_ids_size);
193        if string_ids_off + 4 * string_ids_size <= data.len() {
194            for i in 0..string_ids_size {
195                let so = u32at(string_ids_off + 4 * i) as usize;
196                let mut c = Cursor::at(&data, so);
197                let s = c
198                    .read_uleb128()
199                    .and_then(|len| c.read_mutf8(c.pos, len))
200                    .unwrap_or_default();
201                strings.push(std::sync::Arc::from(s));
202            }
203        }
204
205        // Type ids: u4 descriptor string indices.
206        let mut types = Vec::with_capacity(type_ids_size);
207        if type_ids_off + 4 * type_ids_size <= data.len() {
208            for i in 0..type_ids_size {
209                types.push(u32at(type_ids_off + 4 * i));
210            }
211        }
212
213        // Proto ids: 12 bytes each.
214        let mut protos = Vec::with_capacity(proto_ids_size);
215        if proto_ids_off + 12 * proto_ids_size <= data.len() {
216            for i in 0..proto_ids_size {
217                let base = proto_ids_off + 12 * i;
218                protos.push(ProtoId {
219                    shorty_idx: u32at(base),
220                    return_type_idx: {
221                        let v = u16::from_le_bytes(data[base + 4..base + 6].try_into().unwrap());
222                        v as u32
223                    },
224                    parameters_off: u32at(base + 8),
225                });
226            }
227        }
228        // Resolve every proto's parameter list once, straight off the
229        // local image slice (no `raw()` mutex on this path at all).
230        let proto_tys: Vec<Box<[u32]>> = protos
231            .iter()
232            .map(|p| read_type_list_at(&data, p.parameters_off as usize))
233            .collect();
234        // Descriptor per proto, straight off the local tables.
235        let ty_name = |t: u32| -> &str {
236            match types.get(t as usize) {
237                Some(&si) => strings.get(si as usize).map(|s| &**s).unwrap_or(""),
238                None => "",
239            }
240        };
241        let proto_descs: Vec<std::sync::Arc<str>> = protos
242            .iter()
243            .zip(&proto_tys)
244            .map(|(p, tys)| {
245                let ret = ty_name(p.return_type_idx);
246                let mut d = String::with_capacity(2 + ret.len() + tys.len() * 12);
247                d.push('(');
248                for &t in tys.iter() {
249                    d.push_str(ty_name(t));
250                }
251                d.push(')');
252                d.push_str(ret);
253                std::sync::Arc::from(d)
254            })
255            .collect();
256
257        // Field ids: 8 bytes each.
258        let mut fields = Vec::with_capacity(field_ids_size);
259        if field_ids_off + 8 * field_ids_size <= data.len() {
260            for i in 0..field_ids_size {
261                let base = field_ids_off + 8 * i;
262                fields.push(FieldId {
263                    class_idx: u16::from_le_bytes(data[base..base + 2].try_into().unwrap()) as u32,
264                    type_idx: u16::from_le_bytes(data[base + 2..base + 4].try_into().unwrap())
265                        as u32,
266                    name_idx: u32at(base + 4),
267                });
268            }
269        }
270
271        // Method ids: 8 bytes each.
272        let mut methods = Vec::with_capacity(method_ids_size);
273        if method_ids_off + 8 * method_ids_size <= data.len() {
274            for i in 0..method_ids_size {
275                let base = method_ids_off + 8 * i;
276                methods.push(MethodId {
277                    class_idx: u16::from_le_bytes(data[base..base + 2].try_into().unwrap()) as u32,
278                    proto_idx: u16::from_le_bytes(data[base + 2..base + 4].try_into().unwrap())
279                        as u32,
280                    name_idx: u32at(base + 4),
281                });
282            }
283        }
284
285        // Class defs: 32 bytes each.
286        let mut class_defs = Vec::with_capacity(class_defs_size);
287        if class_defs_off + 32 * class_defs_size <= data.len() {
288            for i in 0..class_defs_size {
289                let base = class_defs_off + 32 * i;
290                class_defs.push(ClassDef {
291                    class_idx: u32at(base),
292                    access_flags: u32at(base + 4),
293                    superclass_idx: u32at(base + 8),
294                    interfaces_off: u32at(base + 12),
295                    source_file_idx: u32at(base + 16),
296                    annotations_off: u32at(base + 20),
297                    class_data_off: u32at(base + 24),
298                    static_values_off: u32at(base + 28),
299                });
300            }
301        }
302
303        let mut by_type = HashMap::with_capacity(class_defs.len());
304        for (i, cd) in class_defs.iter().enumerate() {
305            by_type.insert(cd.class_idx, i);
306        }
307
308        // DEX 037+ tables (call sites / method handles) live ONLY in the
309        // map list — the header carries no offsets for them.
310        let (method_handles, call_sites) = parse_map_tables(&data);
311
312        Ok(DexFile {
313            data: std::sync::Mutex::new(Some(data)),
314            released: std::sync::atomic::AtomicBool::new(false),
315            strings,
316            types,
317            protos,
318            proto_tys,
319            proto_descs,
320            fields,
321            methods,
322            class_defs,
323            version,
324            by_type,
325            method_handles,
326            call_sites,
327        })
328    }
329
330    /// The raw image, or empty once retired.
331    ///
332    /// SAFETY of the lifetime: the bytes live in an `Arc<Vec<u8>>` whose
333    /// clone is moved into a self-owned stash (`raw_keep`) that outlives
334    /// every later call — each call swaps the stash, keeping the previous
335    /// slice alive only for the previous caller, which is unsound in
336    /// general. The callers here hold the slice only inside one method
337    /// (`code_at` / parse-time table walks) and never across calls, and
338    /// single-call scope is the documented contract; the alternative
339    /// (returning a guard) would infect every parser signature.
340    pub fn raw(&self) -> &[u8] {
341        let guard = self.data.lock().unwrap();
342        match guard.as_ref() {
343            Some(bytes) => unsafe { std::mem::transmute::<&[u8], &[u8]>(bytes.as_slice()) },
344            None => &[],
345        }
346    }
347
348    /// Drop the inflated image (tables stay usable; code accessors return
349    /// empty). Call only when no further code decoding will happen.
350    pub fn release_data(&mut self) {
351        *self.data.lock().unwrap() = None;
352        self.released
353            .store(true, std::sync::atomic::Ordering::Release);
354    }
355
356    /// Mark the image retired through a shared reference: code accessors
357    /// go empty immediately; the bytes themselves drop when the last Arc
358    /// snapshot drops (workers hold snapshots only mid-class, so the
359    /// memory is reclaimed as chunks complete).
360    pub fn mark_released(&self) {
361        self.released
362            .store(true, std::sync::atomic::Ordering::Release);
363        // Free the bytes NOW (through the mutex, &self-safe).
364        *self.data.lock().unwrap() = None;
365    }
366
367    #[inline]
368    #[allow(dead_code)] // debug hook for retirement postmortems
369    fn is_released(&self) -> bool {
370        self.released.load(std::sync::atomic::Ordering::Acquire)
371    }
372
373    pub fn string(&self, idx: u32) -> &str {
374        self.strings
375            .get(idx as usize)
376            .map(|s| &**s)
377            .unwrap_or("")
378    }
379
380    pub fn string_count(&self) -> usize {
381        self.strings.len()
382    }
383
384    /// Type id → CLASS internal name (`java/lang/String`), descriptor
385    /// stripped; array descriptors pass through unchanged.
386    pub fn class_name(&self, idx: u32) -> String {
387        let d = self.type_name(idx);
388        if d.len() > 2 && d.starts_with('L') && d.ends_with(';') {
389            d[1..d.len() - 1].to_string()
390        } else {
391            d.to_string()
392        }
393    }
394
395    /// Type id → descriptor string (`Ljava/lang/String;`, `[I`, ...).
396    pub fn type_name(&self, idx: u32) -> &str {
397        match self.types.get(idx as usize) {
398            Some(&si) => self.string(si),
399            None => "",
400        }
401    }
402
403    pub fn type_count(&self) -> usize {
404        self.types.len()
405    }
406
407    pub fn proto(&self, idx: u32) -> &ProtoId {
408        static EMPTY: std::sync::OnceLock<ProtoId> = std::sync::OnceLock::new();
409        self.protos.get(idx as usize).unwrap_or_else(|| {
410            EMPTY.get_or_init(|| ProtoId {
411                shorty_idx: 0,
412                return_type_idx: 0,
413                parameters_off: 0,
414            })
415        })
416    }
417
418    /// Parameter type ids of a proto (empty for `(V)`).
419    /// Shared clone of a table string (the pool's method names).
420    pub fn string_arc(&self, idx: u32) -> std::sync::Arc<str> {
421        self.strings
422            .get(idx as usize)
423            .cloned()
424            .unwrap_or_else(|| std::sync::Arc::from(""))
425    }
426
427    /// Method descriptor of a proto as a shared clone.
428    pub fn proto_desc(&self, idx: u32) -> std::sync::Arc<str> {
429        self.proto_descs
430            .get(idx as usize)
431            .cloned()
432            .unwrap_or_else(|| std::sync::Arc::from("()V"))
433    }
434
435    /// Parameter type ids of a proto, resolved once at parse (shared
436    /// slice; the old per-call `type_list` re-read is gone).
437    pub fn proto_params(&self, idx: u32) -> &[u32] {
438        self.proto_tys
439            .get(idx as usize)
440            .map(|b| &**b)
441            .unwrap_or(&[])
442    }
443
444    /// `type_list` at `off` (interface lists): one `raw()` snapshot for
445    /// the whole walk — the shape below used to lock per u16 read.
446    fn read_type_list(&self, off: u32) -> Option<Vec<u32>> {
447        let raw = self.raw();
448        Some(read_type_list_at(raw, off as usize).into())
449    }
450
451    pub fn field(&self, idx: u32) -> &FieldId {
452        static EMPTY: std::sync::OnceLock<FieldId> = std::sync::OnceLock::new();
453        self.fields.get(idx as usize).unwrap_or_else(|| {
454            EMPTY.get_or_init(|| FieldId {
455                class_idx: 0,
456                type_idx: 0,
457                name_idx: 0,
458            })
459        })
460    }
461
462    pub fn field_count(&self) -> usize {
463        self.fields.len()
464    }
465
466    pub fn method(&self, idx: u32) -> &MethodId {
467        static EMPTY: std::sync::OnceLock<MethodId> = std::sync::OnceLock::new();
468        self.methods.get(idx as usize).unwrap_or_else(|| {
469            EMPTY.get_or_init(|| MethodId {
470                class_idx: 0,
471                proto_idx: 0,
472                name_idx: 0,
473            })
474        })
475    }
476
477    pub fn method_count(&self) -> usize {
478        self.methods.len()
479    }
480
481    /// Class def index for a type descriptor, when this DEX defines it.
482    pub fn class_def_of(&self, type_idx: u32) -> Option<usize> {
483        self.by_type.get(&type_idx).copied()
484    }
485
486    /// Interfaces of a class def as type ids.
487    pub fn interfaces_of(&self, cd: &ClassDef) -> Vec<u32> {
488        if cd.interfaces_off == 0 {
489            return Vec::new();
490        }
491        self.read_type_list(cd.interfaces_off).unwrap_or_default()
492    }
493
494    pub fn class_data(&self, cd: &ClassDef) -> ClassData {
495        if cd.class_data_off == 0 {
496            return ClassData::default();
497        }
498        self.read_class_data(cd.class_data_off).unwrap_or_default()
499    }
500
501    fn read_class_data(&self, off: u32) -> Option<ClassData> {
502        let mut c = Cursor::at(self.raw(), off as usize);
503        let sf = c.read_uleb128()? as usize;
504        let inf = c.read_uleb128()? as usize;
505        let dm = c.read_uleb128()? as usize;
506        let vm = c.read_uleb128()? as usize;
507
508        let read_fields = |n: usize, cur: &mut Cursor| -> Option<Vec<EncodedField>> {
509            let mut out = Vec::with_capacity(n);
510            let mut idx: u64 = 0;
511            for _ in 0..n {
512                idx += cur.read_uleb128()?;
513                out.push(EncodedField {
514                    field_idx: idx as u32,
515                    access_flags: cur.read_uleb128()? as u32,
516                });
517            }
518            Some(out)
519        };
520        let static_fields = read_fields(sf, &mut c)?;
521        let instance_fields = read_fields(inf, &mut c)?;
522
523        let read_methods = |n: usize, cur: &mut Cursor| -> Option<Vec<EncodedMethod>> {
524            let mut out = Vec::with_capacity(n);
525            let mut idx: u64 = 0;
526            for _ in 0..n {
527                idx += cur.read_uleb128()?;
528                out.push(EncodedMethod {
529                    method_idx: idx as u32,
530                    access_flags: cur.read_uleb128()? as u32,
531                    code_off: cur.read_uleb128()? as u32,
532                });
533            }
534            Some(out)
535        };
536        let direct_methods = read_methods(dm, &mut c)?;
537        let virtual_methods = read_methods(vm, &mut c)?;
538
539        Some(ClassData {
540            static_fields,
541            instance_fields,
542            direct_methods,
543            virtual_methods,
544        })
545    }
546
547    /// (registers_size, insns_size) read straight from the code_item header
548    /// — no instruction decoding. Hot path for risk checks.
549    pub fn code_stats(&self, off: u32) -> Option<(u16, u32)> {
550        if off == 0 {
551            return None;
552        }
553        let o = off as usize;
554        if o + 16 > self.raw().len() {
555            return None;
556        }
557        let regs = u16::from_le_bytes([self.raw()[o], self.raw()[o + 1]]);
558        let insns = u32::from_le_bytes([
559            self.raw()[o + 12],
560            self.raw()[o + 13],
561            self.raw()[o + 14],
562            self.raw()[o + 15],
563        ]);
564        Some((regs, insns))
565    }
566
567    /// debug_info_off straight from the code_item header (pool building).
568    pub fn debug_info_off_at(&self, off: u32) -> Option<u32> {
569        if off == 0 {
570            return None;
571        }
572        let o = off as usize;
573        if o + 12 > self.raw().len() {
574            return None;
575        }
576        Some(u32::from_le_bytes([
577            self.raw()[o + 8],
578            self.raw()[o + 9],
579            self.raw()[o + 10],
580            self.raw()[o + 11],
581        ]))
582    }
583
584    pub fn code_at(&self, off: u32) -> Option<CodeItem> {
585        if off == 0 {
586            return None;
587        }
588        CodeItem::parse(self.raw(), off as usize)
589    }
590
591    /// Class descriptors straight from an inflated image, WITHOUT a full
592    /// `DexFile::parse` (which decodes the whole string table — the class
593    /// names are a small slice of it). Class listing pays for exactly what
594    /// it prints.
595    pub fn class_names_from_image(image: &[u8]) -> Vec<String> {
596        if image.len() < 0x70 || &image[..4] != b"dex\n" {
597            return Vec::new();
598        }
599        let u4 = |o: usize| -> u32 {
600            u32::from_le_bytes([image[o], image[o + 1], image[o + 2], image[o + 3]])
601        };
602        let strings_size = u4(0x38) as usize;
603        let strings_off = u4(0x3c) as usize;
604        let types_size = u4(0x40) as usize;
605        let types_off = u4(0x44) as usize;
606        let classes_size = u4(0x60) as usize;
607        let classes_off = u4(0x64) as usize;
608        if strings_off + 4 * strings_size > image.len()
609            || types_off + 4 * types_size > image.len()
610            || classes_off + 32 * classes_size > image.len()
611        {
612            return Vec::new();
613        }
614        let u4at = |o: usize| -> u32 {
615            u32::from_le_bytes([image[o], image[o + 1], image[o + 2], image[o + 3]])
616        };
617        let string_at = |idx: u32| -> Option<String> {
618            let so = u4at(strings_off + 4 * idx as usize) as usize;
619            if so >= image.len() {
620                return None;
621            }
622            // mutf8 string_data_item: uleb len (utf16 units), bytes, NUL.
623            let mut p = so;
624            // uleb128
625            let mut len = 0u64;
626            let mut shift = 0;
627            loop {
628                if p >= image.len() {
629                    return None;
630                }
631                let b = image[p];
632                p += 1;
633                len |= ((b & 0x7f) as u64) << shift;
634                shift += 7;
635                if b & 0x80 == 0 {
636                    break;
637                }
638            }
639            let end = image[p..].iter().position(|&b| b == 0)? + p;
640            crate::reader::mutf8_decode(&image[p..end], len)
641        };
642        let mut out = Vec::with_capacity(classes_size);
643        for i in 0..classes_size {
644            let cd = classes_off + 32 * i;
645            let class_idx = u4at(cd) as usize;
646            if class_idx >= types_size {
647                continue;
648            }
649            let string_idx = u4at(types_off + 4 * class_idx);
650            if let Some(name) = string_at(string_idx) {
651                // type strings are descriptors (Lcom/foo/Bar;): strip the
652                // L; shell to match DexFile::class_name's plain form.
653                let plain = name
654                    .strip_prefix('L')
655                    .and_then(|s| s.strip_suffix(';'))
656                    .map(str::to_string)
657                    .unwrap_or(name);
658                out.push(plain);
659            }
660        }
661        out
662    }
663
664    /// The raw insns byte section of one code item (zero-copy) for the
665    /// boundary-walking scan path — skips try tables and full decode.
666    pub fn code_insns_bytes_at(&self, off: u32) -> Option<&[u8]> {
667        if off == 0 {
668            return None;
669        }
670        let off = off as usize;
671        let d = self.raw();
672        if off + 16 > d.len() {
673            return None;
674        }
675        // code_item: 4×u2 header, u4 debug_info_off, u4 insns_size(units).
676        let insns_size =
677            u32::from_le_bytes([d[off + 12], d[off + 13], d[off + 14], d[off + 15]]) as usize;
678        let start = off + 16;
679        let end = start + 2 * insns_size;
680        if end > d.len() {
681            return None;
682        }
683        Some(&d[start..end])
684    }
685
686    /// Static field initial values (aligned with `static_fields` order).
687    pub fn static_values(&self, off: u32) -> Vec<EncodedValue> {
688        if off == 0 {
689            return Vec::new();
690        }
691        annotations::read_encoded_array(self.raw(), off as usize).unwrap_or_default()
692    }
693
694    /// `method_handle_item` by index.
695    pub fn method_handle(&self, idx: u32) -> Option<&MethodHandleItem> {
696        self.method_handles.get(idx as usize)
697    }
698
699    pub fn method_handle_count(&self) -> usize {
700        self.method_handles.len()
701    }
702
703    /// Resolved call site by index.
704    pub fn call_site(&self, idx: u32) -> Option<&CallSiteInfo> {
705        self.call_sites.get(idx as usize)
706    }
707
708    pub fn call_site_count(&self) -> usize {
709        self.call_sites.len()
710    }
711
712    /// Parameter names from debug info (NO_INDEX → absent). `debug_info_off`
713    /// comes from a code item; the entry layout is `line_start` uleb,
714    /// `parameters_size` uleb, then `uleb128p1` names.
715    pub fn parameter_names(&self, debug_info_off: u32) -> Vec<Option<String>> {
716        if debug_info_off == 0 {
717            return Vec::new();
718        }
719        let mut c = Cursor::at(self.raw(), debug_info_off as usize);
720        let _line_start = match c.read_uleb128() {
721            Some(v) => v,
722            None => return Vec::new(),
723        };
724        let n = match c.read_uleb128() {
725            Some(v) => v as usize,
726            None => return Vec::new(),
727        };
728        let mut out = Vec::with_capacity(n);
729        for _ in 0..n {
730            let idx = c.read_uleb128p1().unwrap_or(-1);
731            if idx < 0 {
732                out.push(None);
733            } else {
734                out.push(Some(self.string(idx as u32).to_string()));
735            }
736        }
737        out
738    }
739}
740
741impl std::fmt::Debug for DexFile {
742    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
743        f.debug_struct("DexFile")
744            .field("version", &self.version)
745            .field("strings", &self.strings.len())
746            .field("types", &self.types.len())
747            .field("protos", &self.protos.len())
748            .field("fields", &self.fields.len())
749            .field("methods", &self.methods.len())
750            .field("class_defs", &self.class_defs.len())
751            .finish()
752    }
753}
754
755/// `type_list` at `off` straight off a byte slice: parse-time proto
756/// resolution and the interfaces read both go through here — one
757/// snapshot of the slice, no per-element locking. Reads past the end
758/// are truncated (the tolerant-sentinel rule for corrupt images).
759fn read_type_list_at(data: &[u8], off: usize) -> Box<[u32]> {
760    if off == 0 || off + 4 > data.len() {
761        return Vec::new().into_boxed_slice();
762    }
763    let size = u32::from_le_bytes(data[off..off + 4].try_into().unwrap()) as usize;
764    let mut p = off + 4;
765    let mut out = Vec::with_capacity(size);
766    for _ in 0..size {
767        if p + 2 > data.len() {
768            break;
769        }
770        out.push(u16::from_le_bytes(data[p..p + 2].try_into().unwrap()) as u32);
771        p += 2;
772    }
773    out.into_boxed_slice()
774}
775
776/// Sections 0x0007 (call_site_id) and 0x0008 (method_handle_id) from the
777/// map list. Layouts (dx `ItemType`/`MethodHandleItem`):
778/// * `call_site_id_item`: u4 offset → `call_site_off` encoded array
779///   [bootstrap METHOD_HANDLE, name STRING, type METHOD_TYPE, linker args…].
780/// * `method_handle_item`: u2 kind, u2 reserved, u2 target id, u2 reserved.
781fn parse_map_tables(data: &[u8]) -> (Vec<MethodHandleItem>, Vec<CallSiteInfo>) {
782    let mut handles = Vec::new();
783    let mut sites = Vec::new();
784    if data.len() < 0x70 {
785        return (handles, sites);
786    }
787    let map_off = u32le(data, 0x34) as usize;
788    if map_off + 4 > data.len() {
789        return (handles, sites);
790    }
791    let n = u32le(data, map_off) as usize;
792    let mut p = map_off + 4;
793    for _ in 0..n {
794        if p + 12 > data.len() {
795            break;
796        }
797        let t = u16le(data, p);
798        let size = u32le(data, p + 4) as usize;
799        let off = u32le(data, p + 8) as usize;
800        p += 12;
801        match t {
802            0x0007 => {
803                // call_site_id_item: u4 call_site_off each.
804                for i in 0..size {
805                    let q = off + 4 * i;
806                    if q + 4 > data.len() {
807                        break;
808                    }
809                    let cs_off = u32le(data, q) as usize;
810                    if let Some(info) = parse_call_site(data, cs_off) {
811                        sites.push(info);
812                    }
813                }
814            }
815            0x0008 => {
816                // method_handle_item: (u2 kind, u2 res, u2 id, u2 res).
817                for i in 0..size {
818                    let q = off + 8 * i;
819                    if q + 8 > data.len() {
820                        break;
821                    }
822                    let kind = u16le(data, q);
823                    let id = u16le(data, q + 4);
824                    handles.push(MethodHandleItem {
825                        kind,
826                        target_id: id as u32,
827                        is_field: kind <= 3,
828                    });
829                }
830            }
831            _ => {}
832        }
833    }
834    (handles, sites)
835}
836
837fn parse_call_site(data: &[u8], off: usize) -> Option<CallSiteInfo> {
838    let vals = crate::annotations::read_encoded_array(data, off)?;
839    if vals.len() < 3 {
840        return None;
841    }
842    let bootstrap_handle = match &vals[0] {
843        crate::annotations::EncodedValue::MethodHandle(h) => *h,
844        _ => return None,
845    };
846    let name_idx = match &vals[1] {
847        crate::annotations::EncodedValue::String(s) => *s,
848        _ => return None,
849    };
850    let proto_idx = match &vals[2] {
851        crate::annotations::EncodedValue::MethodType(p) => *p,
852        _ => return None,
853    };
854    Some(CallSiteInfo {
855        bootstrap_handle,
856        name_idx,
857        proto_idx,
858        linker_args: vals[3..].to_vec(),
859    })
860}
861
862fn u16le(data: &[u8], off: usize) -> u16 {
863    if off + 2 > data.len() {
864        return 0;
865    }
866    u16::from_le_bytes([data[off], data[off + 1]])
867}
868
869fn u32le(data: &[u8], off: usize) -> u32 {
870    if off + 4 > data.len() {
871        return 0;
872    }
873    u32::from_le_bytes([data[off], data[off + 1], data[off + 2], data[off + 3]])
874}
875
876#[cfg(test)]
877mod tests {
878    use super::*;
879
880    #[test]
881    fn rejects_non_dex() {
882        assert!(DexFile::parse(vec![0u8; 128]).is_err());
883    }
884}