Skip to main content

webbluetooth_android/
dex.rs

1//! A DEX writer, for classes that do not exist until we make them.
2//!
3//! Android's BLE APIs are callback-driven, and every callback type —
4//! `BluetoothGattCallback`, `ScanCallback`, `BluetoothGattServerCallback`,
5//! `AdvertiseCallback` — is an **abstract class**, not an interface. So
6//! `java.lang.reflect.Proxy` cannot help: it only proxies interfaces. Something
7//! has to subclass them, and on a device there is no compiler to do it.
8//!
9//! This is the same problem CoreBluetooth poses, and it gets the same answer:
10//! build the class at run time. Where Apple has `objc_allocateClassPair`,
11//! Android has a class *file format* — so the class is emitted as a DEX,
12//! loaded with `InMemoryDexClassLoader`, and its methods bound to Rust
13//! functions with `RegisterNatives`.
14//!
15//! # Why this is far less work than it sounds
16//!
17//! A method declared `native` has **no bytecode** — no `code_item` at all, just
18//! a metadata entry. Since every override we need is native, this writer emits
19//! constant tables and nothing else. The single exception is the constructor,
20//! which must call `super()`, and that is four code units written by hand:
21//!
22//! ```text
23//!     invoke-direct {v0}, Lsuper;-><init>()V
24//!     return-void
25//! ```
26//!
27//! So there is no compiler here, and no optimiser — a layout problem and a
28//! handful of sorted tables.
29//!
30//! # The parts that must be exactly right
31//!
32//! * **Tables are sorted**, and the verifier rejects the file if they are not:
33//!   strings by UTF-16 code point, types by descriptor, protos by return type
34//!   then parameters, methods by `(class, name, proto)`.
35//! * **`encoded_method` stores index *deltas***, not indices, so the order of
36//!   the method list and the order of `method_ids` are coupled.
37//! * **The header carries an Adler-32 and a SHA-1** over everything that
38//!   follows them, written last.
39//! * **The `map_list` must describe every section**, in offset order.
40
41use std::collections::BTreeMap;
42
43const HEADER_SIZE: usize = 0x70;
44const ENDIAN_TAG: u32 = 0x1234_5678;
45/// `dex\n035\0` — the oldest format every `InMemoryDexClassLoader` accepts.
46const MAGIC: [u8; 8] = [0x64, 0x65, 0x78, 0x0A, 0x30, 0x33, 0x35, 0x00];
47
48const ACC_PUBLIC: u32 = 0x1;
49const ACC_NATIVE: u32 = 0x100;
50const ACC_CONSTRUCTOR: u32 = 0x1_0000;
51
52mod map_type {
53    pub const HEADER: u16 = 0x0000;
54    pub const STRING_ID: u16 = 0x0001;
55    pub const TYPE_ID: u16 = 0x0002;
56    pub const PROTO_ID: u16 = 0x0003;
57    pub const METHOD_ID: u16 = 0x0005;
58    pub const CLASS_DEF: u16 = 0x0006;
59    pub const MAP_LIST: u16 = 0x1000;
60    pub const TYPE_LIST: u16 = 0x1001;
61    pub const CLASS_DATA: u16 = 0x2000;
62    pub const CODE: u16 = 0x2001;
63    pub const STRING_DATA: u16 = 0x2002;
64}
65
66/// One method to declare `native` on the generated class.
67#[derive(Debug, Clone)]
68pub struct NativeMethod {
69    /// The Java name, e.g. `onConnectionStateChange`.
70    pub name: String,
71    /// A JNI type descriptor, e.g. `(Landroid/bluetooth/BluetoothGatt;II)V`.
72    pub descriptor: String,
73}
74
75impl NativeMethod {
76    pub fn new(name: &str, descriptor: &str) -> Self {
77        Self {
78            name: name.into(),
79            descriptor: descriptor.into(),
80        }
81    }
82}
83
84/// Builds a DEX containing one class: a subclass with native overrides.
85#[derive(Debug, Clone)]
86pub struct DexBuilder {
87    class: String,
88    superclass: String,
89    methods: Vec<NativeMethod>,
90}
91
92impl DexBuilder {
93    /// `class` and `superclass` are internal names, e.g.
94    /// `dev/webbluetooth/GattCallback` and
95    /// `android/bluetooth/BluetoothGattCallback`.
96    pub fn new(class: &str, superclass: &str) -> Self {
97        Self {
98            class: class.into(),
99            superclass: superclass.into(),
100            methods: Vec::new(),
101        }
102    }
103
104    pub fn native_method(mut self, name: &str, descriptor: &str) -> Self {
105        self.methods.push(NativeMethod::new(name, descriptor));
106        self
107    }
108
109    /// Emit the DEX.
110    pub fn build(&self) -> Vec<u8> {
111        let class_descriptor = format!("L{};", self.class);
112        let super_descriptor = format!("L{};", self.superclass);
113
114        // ── Collect every string the file mentions ──────────────────────────
115        let mut strings: Vec<String> = vec![
116            class_descriptor.clone(),
117            super_descriptor.clone(),
118            "<init>".into(),
119            "V".into(),
120        ];
121        let mut types: Vec<String> = vec![
122            class_descriptor.clone(),
123            super_descriptor.clone(),
124            "V".into(),
125        ];
126
127        // The constructor, plus every native override.
128        let mut protos: Vec<Proto> = vec![Proto::parse("()V")];
129        for m in &self.methods {
130            strings.push(m.name.clone());
131            let proto = Proto::parse(&m.descriptor);
132            types.push(proto.return_type.clone());
133            types.extend(proto.parameters.iter().cloned());
134            protos.push(proto);
135        }
136        for p in &protos {
137            strings.push(p.shorty.clone());
138            strings.push(p.return_type.clone());
139            strings.extend(p.parameters.iter().cloned());
140        }
141        strings.extend(types.iter().cloned());
142
143        strings.sort_by(|a, b| compare_mutf8(a, b));
144        strings.dedup();
145        let string_index: BTreeMap<&str, u32> = strings
146            .iter()
147            .enumerate()
148            .map(|(i, s)| (s.as_str(), i as u32))
149            .collect();
150
151        // Types are sorted by their descriptor's string index.
152        types.sort_by(|a, b| compare_mutf8(a, b));
153        types.dedup();
154        let type_index: BTreeMap<&str, u32> = types
155            .iter()
156            .enumerate()
157            .map(|(i, t)| (t.as_str(), i as u32))
158            .collect();
159
160        // Protos sort by return type, then by parameter list.
161        protos.sort_by(|a, b| {
162            let by_return =
163                type_index[a.return_type.as_str()].cmp(&type_index[b.return_type.as_str()]);
164            by_return.then_with(|| {
165                let a_params: Vec<u32> = a
166                    .parameters
167                    .iter()
168                    .map(|p| type_index[p.as_str()])
169                    .collect();
170                let b_params: Vec<u32> = b
171                    .parameters
172                    .iter()
173                    .map(|p| type_index[p.as_str()])
174                    .collect();
175                a_params.cmp(&b_params)
176            })
177        });
178        protos.dedup_by(|a, b| a.descriptor == b.descriptor);
179        let proto_index: BTreeMap<&str, u32> = protos
180            .iter()
181            .enumerate()
182            .map(|(i, p)| (p.descriptor.as_str(), i as u32))
183            .collect();
184
185        // ── Method ids ──────────────────────────────────────────────────────
186        // `super.<init>()V` is referenced by the constructor's bytecode, so it
187        // needs an id even though we do not define it.
188        let mut method_ids: Vec<MethodId> = vec![
189            MethodId {
190                class: class_descriptor.clone(),
191                name: "<init>".into(),
192                proto: "()V".into(),
193            },
194            MethodId {
195                class: super_descriptor.clone(),
196                name: "<init>".into(),
197                proto: "()V".into(),
198            },
199        ];
200        for m in &self.methods {
201            method_ids.push(MethodId {
202                class: class_descriptor.clone(),
203                name: m.name.clone(),
204                proto: m.descriptor.clone(),
205            });
206        }
207        method_ids.sort_by_key(|m| {
208            (
209                type_index[m.class.as_str()],
210                string_index[m.name.as_str()],
211                proto_index[m.proto.as_str()],
212            )
213        });
214        let method_index: BTreeMap<(&str, &str, &str), u32> = method_ids
215            .iter()
216            .enumerate()
217            .map(|(i, m)| {
218                (
219                    (m.class.as_str(), m.name.as_str(), m.proto.as_str()),
220                    i as u32,
221                )
222            })
223            .collect();
224
225        // ── Lay the file out ────────────────────────────────────────────────
226        let string_ids_off = HEADER_SIZE;
227        let type_ids_off = string_ids_off + strings.len() * 4;
228        let proto_ids_off = type_ids_off + types.len() * 4;
229        let method_ids_off = proto_ids_off + protos.len() * 12;
230        let class_defs_off = method_ids_off + method_ids.len() * 8;
231        let data_off = class_defs_off + 32;
232
233        let mut data = Section::new(data_off);
234
235        // Parameter type lists, one per proto that takes arguments.
236        let mut type_list_offsets: BTreeMap<String, usize> = BTreeMap::new();
237        for p in &protos {
238            if p.parameters.is_empty() {
239                continue;
240            }
241            data.align(4);
242            type_list_offsets.insert(p.descriptor.clone(), data.position());
243            data.u32(p.parameters.len() as u32);
244            for param in &p.parameters {
245                data.u16(type_index[param.as_str()] as u16);
246            }
247        }
248
249        // String data.
250        let mut string_data_offsets: Vec<usize> = Vec::with_capacity(strings.len());
251        for s in &strings {
252            string_data_offsets.push(data.position());
253            // The length is in UTF-16 code units, the bytes are MUTF-8.
254            data.uleb128(s.chars().map(|c| c.len_utf16()).sum::<usize>() as u32);
255            data.bytes(&mutf8(s));
256            data.u8(0);
257        }
258
259        // The constructor's code: call super, return.
260        data.align(4);
261        let code_off = data.position();
262        let super_init = method_index[&(super_descriptor.as_str(), "<init>", "()V")];
263        data.u16(1); // registers_size — just `this`
264        data.u16(1); // ins_size
265        data.u16(1); // outs_size
266        data.u16(0); // tries_size
267        data.u32(0); // debug_info_off
268        data.u32(4); // insns_size, in 16-bit units
269                     // invoke-direct {v0}, super.<init>()V   (format 35c: A=1 arg, G=0)
270        data.u16(0x1070);
271        data.u16(super_init as u16);
272        data.u16(0x0000); // registers C..F, all zero: v0
273        data.u16(0x000E); // return-void
274
275        // class_data_item: no fields, one direct method (the constructor),
276        // and every native override as a virtual method.
277        let class_data_off = data.position();
278        data.uleb128(0); // static_fields_size
279        data.uleb128(0); // instance_fields_size
280        data.uleb128(1); // direct_methods_size
281        data.uleb128(self.methods.len() as u32); // virtual_methods_size
282
283        let ctor = method_index[&(class_descriptor.as_str(), "<init>", "()V")];
284        data.uleb128(ctor); // first entry's index is absolute
285        data.uleb128(ACC_PUBLIC | ACC_CONSTRUCTOR);
286        data.uleb128(code_off as u32);
287
288        // Virtual methods are stored as deltas, so they must be emitted in
289        // method_ids order.
290        let mut virtuals: Vec<u32> = self
291            .methods
292            .iter()
293            .map(|m| {
294                method_index[&(
295                    class_descriptor.as_str(),
296                    m.name.as_str(),
297                    m.descriptor.as_str(),
298                )]
299            })
300            .collect();
301        virtuals.sort_unstable();
302        let mut previous = 0u32;
303        for (i, index) in virtuals.iter().enumerate() {
304            data.uleb128(if i == 0 { *index } else { index - previous });
305            data.uleb128(ACC_PUBLIC | ACC_NATIVE);
306            data.uleb128(0); // native methods have no code
307            previous = *index;
308        }
309
310        // ── map_list, last, describing everything ───────────────────────────
311        data.align(4);
312        let map_off = data.position();
313        let mut map: Vec<(u16, u32, u32)> = vec![
314            (map_type::HEADER, 1, 0),
315            (
316                map_type::STRING_ID,
317                strings.len() as u32,
318                string_ids_off as u32,
319            ),
320            (map_type::TYPE_ID, types.len() as u32, type_ids_off as u32),
321            (
322                map_type::PROTO_ID,
323                protos.len() as u32,
324                proto_ids_off as u32,
325            ),
326            (
327                map_type::METHOD_ID,
328                method_ids.len() as u32,
329                method_ids_off as u32,
330            ),
331            (map_type::CLASS_DEF, 1, class_defs_off as u32),
332        ];
333        if !type_list_offsets.is_empty() {
334            let first = *type_list_offsets.values().min().expect("non-empty");
335            map.push((
336                map_type::TYPE_LIST,
337                type_list_offsets.len() as u32,
338                first as u32,
339            ));
340        }
341        map.push((
342            map_type::STRING_DATA,
343            strings.len() as u32,
344            string_data_offsets[0] as u32,
345        ));
346        map.push((map_type::CODE, 1, code_off as u32));
347        map.push((map_type::CLASS_DATA, 1, class_data_off as u32));
348        map.push((map_type::MAP_LIST, 1, map_off as u32));
349        map.sort_by_key(|(_, _, offset)| *offset);
350
351        data.u32(map.len() as u32);
352        for (kind, size, offset) in &map {
353            data.u16(*kind);
354            data.u16(0);
355            data.u32(*size);
356            data.u32(*offset);
357        }
358
359        let data_bytes = data.finish();
360        let data_size = data_bytes.len();
361        let file_size = data_off + data_size;
362
363        // ── Assemble ────────────────────────────────────────────────────────
364        let mut out = vec![0u8; file_size];
365        out[..8].copy_from_slice(&MAGIC);
366
367        let mut header = Cursor::new(&mut out, 32);
368        header.u32(file_size as u32);
369        header.u32(HEADER_SIZE as u32);
370        header.u32(ENDIAN_TAG);
371        header.u32(0); // link_size
372        header.u32(0); // link_off
373        header.u32(map_off as u32);
374        header.u32(strings.len() as u32);
375        header.u32(string_ids_off as u32);
376        header.u32(types.len() as u32);
377        header.u32(type_ids_off as u32);
378        header.u32(protos.len() as u32);
379        header.u32(proto_ids_off as u32);
380        header.u32(0); // field_ids_size
381        header.u32(0); // field_ids_off — zero when empty
382        header.u32(method_ids.len() as u32);
383        header.u32(method_ids_off as u32);
384        header.u32(1); // class_defs_size
385        header.u32(class_defs_off as u32);
386        header.u32(data_size as u32);
387        header.u32(data_off as u32);
388
389        let mut strings_cursor = Cursor::new(&mut out, string_ids_off);
390        for offset in &string_data_offsets {
391            strings_cursor.u32(*offset as u32);
392        }
393
394        let mut types_cursor = Cursor::new(&mut out, type_ids_off);
395        for t in &types {
396            types_cursor.u32(string_index[t.as_str()]);
397        }
398
399        let mut protos_cursor = Cursor::new(&mut out, proto_ids_off);
400        for p in &protos {
401            protos_cursor.u32(string_index[p.shorty.as_str()]);
402            protos_cursor.u32(type_index[p.return_type.as_str()]);
403            protos_cursor.u32(type_list_offsets.get(&p.descriptor).copied().unwrap_or(0) as u32);
404        }
405
406        let mut methods_cursor = Cursor::new(&mut out, method_ids_off);
407        for m in &method_ids {
408            methods_cursor.u16(type_index[m.class.as_str()] as u16);
409            methods_cursor.u16(proto_index[m.proto.as_str()] as u16);
410            methods_cursor.u32(string_index[m.name.as_str()]);
411        }
412
413        let mut class_cursor = Cursor::new(&mut out, class_defs_off);
414        class_cursor.u32(type_index[class_descriptor.as_str()]);
415        class_cursor.u32(ACC_PUBLIC);
416        class_cursor.u32(type_index[super_descriptor.as_str()]);
417        class_cursor.u32(0); // interfaces_off
418        class_cursor.u32(0xFFFF_FFFF); // source_file_idx — NO_INDEX
419        class_cursor.u32(0); // annotations_off
420        class_cursor.u32(class_data_off as u32);
421        class_cursor.u32(0); // static_values_off
422
423        out[data_off..].copy_from_slice(&data_bytes);
424
425        // The signature covers everything after it; the checksum covers
426        // everything after *it*, signature included. Order matters.
427        let signature = sha1(&out[32..]);
428        out[12..32].copy_from_slice(&signature);
429        let checksum = adler32(&out[12..]);
430        out[8..12].copy_from_slice(&checksum.to_le_bytes());
431
432        out
433    }
434}
435
436struct MethodId {
437    class: String,
438    name: String,
439    proto: String,
440}
441
442/// A parsed method descriptor.
443#[derive(Debug, Clone)]
444struct Proto {
445    descriptor: String,
446    shorty: String,
447    return_type: String,
448    parameters: Vec<String>,
449}
450
451impl Proto {
452    /// Split `(Landroid/bluetooth/BluetoothGatt;II)V` into its parts.
453    fn parse(descriptor: &str) -> Self {
454        let bytes = descriptor.as_bytes();
455        assert_eq!(
456            bytes.first(),
457            Some(&b'('),
458            "not a method descriptor: {descriptor}"
459        );
460        let close = descriptor
461            .find(')')
462            .expect("unterminated method descriptor");
463
464        let mut parameters = Vec::new();
465        let mut i = 1;
466        while i < close {
467            let len = type_length(&bytes[i..close]).expect("malformed parameter type");
468            parameters.push(descriptor[i..i + len].to_string());
469            i += len;
470        }
471        let return_type = descriptor[close + 1..].to_string();
472
473        // The shorty collapses every reference type to `L`.
474        let mut shorty = String::new();
475        shorty.push(shorty_char(&return_type));
476        for p in &parameters {
477            shorty.push(shorty_char(p));
478        }
479
480        Self {
481            descriptor: descriptor.to_string(),
482            shorty,
483            return_type,
484            parameters,
485        }
486    }
487}
488
489/// How many bytes the first type descriptor occupies.
490fn type_length(bytes: &[u8]) -> Option<usize> {
491    match bytes.first()? {
492        b'[' => Some(1 + type_length(&bytes[1..])?),
493        b'L' => bytes.iter().position(|b| *b == b';').map(|i| i + 1),
494        b'V' | b'Z' | b'B' | b'S' | b'C' | b'I' | b'J' | b'F' | b'D' => Some(1),
495        _ => None,
496    }
497}
498
499fn shorty_char(descriptor: &str) -> char {
500    match descriptor.as_bytes().first() {
501        Some(b'L') | Some(b'[') => 'L',
502        Some(c) => *c as char,
503        None => 'V',
504    }
505}
506
507/// Compare two strings the way the DEX spec orders them: by UTF-16 code point.
508fn compare_mutf8(a: &str, b: &str) -> std::cmp::Ordering {
509    a.chars().cmp(b.chars())
510}
511
512/// Modified UTF-8: like UTF-8, except NUL is two bytes and astral characters
513/// are written as a surrogate pair. Class and method names are ASCII in
514/// practice, so this only has to be correct, not fast.
515fn mutf8(s: &str) -> Vec<u8> {
516    let mut out = Vec::with_capacity(s.len());
517    for c in s.chars() {
518        let code = c as u32;
519        match code {
520            0 => out.extend_from_slice(&[0xC0, 0x80]),
521            0x01..=0x7F => out.push(code as u8),
522            0x80..=0x7FF => {
523                out.push(0xC0 | (code >> 6) as u8);
524                out.push(0x80 | (code & 0x3F) as u8);
525            }
526            0x800..=0xFFFF => {
527                out.push(0xE0 | (code >> 12) as u8);
528                out.push(0x80 | ((code >> 6) & 0x3F) as u8);
529                out.push(0x80 | (code & 0x3F) as u8);
530            }
531            _ => {
532                // Astral: encode the UTF-16 surrogate pair, three bytes each.
533                let mut buf = [0u16; 2];
534                for unit in c.encode_utf16(&mut buf) {
535                    let unit = *unit as u32;
536                    out.push(0xE0 | (unit >> 12) as u8);
537                    out.push(0x80 | ((unit >> 6) & 0x3F) as u8);
538                    out.push(0x80 | (unit & 0x3F) as u8);
539                }
540            }
541        }
542    }
543    out
544}
545
546// ── Little helpers for writing ──────────────────────────────────────────────
547
548/// An append-only buffer that knows its absolute offset in the file.
549struct Section {
550    base: usize,
551    buf: Vec<u8>,
552}
553
554impl Section {
555    fn new(base: usize) -> Self {
556        Self {
557            base,
558            buf: Vec::new(),
559        }
560    }
561    fn position(&self) -> usize {
562        self.base + self.buf.len()
563    }
564    fn align(&mut self, n: usize) {
565        while !self.position().is_multiple_of(n) {
566            self.buf.push(0);
567        }
568    }
569    fn u8(&mut self, v: u8) {
570        self.buf.push(v);
571    }
572    fn u16(&mut self, v: u16) {
573        self.buf.extend_from_slice(&v.to_le_bytes());
574    }
575    fn u32(&mut self, v: u32) {
576        self.buf.extend_from_slice(&v.to_le_bytes());
577    }
578    fn bytes(&mut self, v: &[u8]) {
579        self.buf.extend_from_slice(v);
580    }
581    /// Unsigned LEB128, as every size and index in a `class_data_item` is.
582    fn uleb128(&mut self, mut v: u32) {
583        loop {
584            let mut byte = (v & 0x7F) as u8;
585            v >>= 7;
586            if v != 0 {
587                byte |= 0x80;
588            }
589            self.buf.push(byte);
590            if v == 0 {
591                break;
592            }
593        }
594    }
595    fn finish(self) -> Vec<u8> {
596        self.buf
597    }
598}
599
600/// Writes into an already-sized buffer at a fixed offset.
601struct Cursor<'a> {
602    buf: &'a mut [u8],
603    at: usize,
604}
605
606impl<'a> Cursor<'a> {
607    fn new(buf: &'a mut [u8], at: usize) -> Self {
608        Self { buf, at }
609    }
610    fn u16(&mut self, v: u16) {
611        self.buf[self.at..self.at + 2].copy_from_slice(&v.to_le_bytes());
612        self.at += 2;
613    }
614    fn u32(&mut self, v: u32) {
615        self.buf[self.at..self.at + 4].copy_from_slice(&v.to_le_bytes());
616        self.at += 4;
617    }
618}
619
620/// Adler-32, as the DEX header's checksum.
621fn adler32(data: &[u8]) -> u32 {
622    let (mut a, mut b) = (1u32, 0u32);
623    for byte in data {
624        a = (a + *byte as u32) % 65521;
625        b = (b + a) % 65521;
626    }
627    (b << 16) | a
628}
629
630/// SHA-1, as the DEX header's signature.
631fn sha1(data: &[u8]) -> [u8; 20] {
632    let mut h: [u32; 5] = [
633        0x6745_2301,
634        0xEFCD_AB89,
635        0x98BA_DCFE,
636        0x1032_5476,
637        0xC3D2_E1F0,
638    ];
639
640    let mut message = data.to_vec();
641    let bit_length = (data.len() as u64) * 8;
642    message.push(0x80);
643    while !(message.len() % 64).is_multiple_of(64) && message.len() % 64 != 56 {
644        message.push(0);
645    }
646    message.extend_from_slice(&bit_length.to_be_bytes());
647
648    for chunk in message.chunks_exact(64) {
649        let mut w = [0u32; 80];
650        for (i, word) in chunk.chunks_exact(4).enumerate() {
651            w[i] = u32::from_be_bytes([word[0], word[1], word[2], word[3]]);
652        }
653        for i in 16..80 {
654            w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1);
655        }
656
657        let (mut a, mut b, mut c, mut d, mut e) = (h[0], h[1], h[2], h[3], h[4]);
658        for (i, word) in w.iter().enumerate() {
659            let (f, k) = match i {
660                0..=19 => ((b & c) | (!b & d), 0x5A82_7999),
661                20..=39 => (b ^ c ^ d, 0x6ED9_EBA1),
662                40..=59 => ((b & c) | (b & d) | (c & d), 0x8F1B_BCDC),
663                _ => (b ^ c ^ d, 0xCA62_C1D6),
664            };
665            let temp = a
666                .rotate_left(5)
667                .wrapping_add(f)
668                .wrapping_add(e)
669                .wrapping_add(k)
670                .wrapping_add(*word);
671            e = d;
672            d = c;
673            c = b.rotate_left(30);
674            b = a;
675            a = temp;
676        }
677        h[0] = h[0].wrapping_add(a);
678        h[1] = h[1].wrapping_add(b);
679        h[2] = h[2].wrapping_add(c);
680        h[3] = h[3].wrapping_add(d);
681        h[4] = h[4].wrapping_add(e);
682    }
683
684    let mut out = [0u8; 20];
685    for (i, word) in h.iter().enumerate() {
686        out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
687    }
688    out
689}
690
691#[cfg(test)]
692mod tests {
693    use super::*;
694
695    fn sample() -> Vec<u8> {
696        DexBuilder::new(
697            "dev/webbluetooth/GattCallback",
698            "android/bluetooth/BluetoothGattCallback",
699        )
700        .native_method(
701            "onConnectionStateChange",
702            "(Landroid/bluetooth/BluetoothGatt;II)V",
703        )
704        .native_method(
705            "onServicesDiscovered",
706            "(Landroid/bluetooth/BluetoothGatt;I)V",
707        )
708        .native_method(
709            "onCharacteristicChanged",
710            "(Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattCharacteristic;[B)V",
711        )
712        .build()
713    }
714
715    fn read_u32(dex: &[u8], at: usize) -> u32 {
716        u32::from_le_bytes([dex[at], dex[at + 1], dex[at + 2], dex[at + 3]])
717    }
718
719    #[test]
720    fn the_header_is_well_formed() {
721        let dex = sample();
722        assert_eq!(&dex[..8], &MAGIC, "wrong magic");
723        assert_eq!(
724            read_u32(&dex, 32),
725            dex.len() as u32,
726            "file_size disagrees with the file"
727        );
728        assert_eq!(read_u32(&dex, 36), HEADER_SIZE as u32);
729        assert_eq!(read_u32(&dex, 40), ENDIAN_TAG);
730        assert_eq!(read_u32(&dex, 96), 1, "expected exactly one class_def");
731    }
732
733    #[test]
734    fn the_checksum_and_signature_cover_the_right_ranges() {
735        let dex = sample();
736        // SHA-1 covers everything after the signature field.
737        assert_eq!(&dex[12..32], &sha1(&dex[32..]), "signature mismatch");
738        // Adler-32 covers everything after the checksum field — signature too.
739        assert_eq!(read_u32(&dex, 8), adler32(&dex[12..]), "checksum mismatch");
740    }
741
742    #[test]
743    fn a_changed_class_changes_the_signature() {
744        let a = sample();
745        let b = DexBuilder::new(
746            "dev/webbluetooth/Other",
747            "android/bluetooth/BluetoothGattCallback",
748        )
749        .native_method(
750            "onServicesDiscovered",
751            "(Landroid/bluetooth/BluetoothGatt;I)V",
752        )
753        .build();
754        assert_ne!(&a[12..32], &b[12..32]);
755    }
756
757    #[test]
758    fn sha1_matches_known_vectors() {
759        // Hand-checking a DEX signature is impractical, so pin the primitive.
760        assert_eq!(
761            sha1(b"abc"),
762            [
763                0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A, 0xBA, 0x3E, 0x25, 0x71, 0x78, 0x50,
764                0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D
765            ]
766        );
767        assert_eq!(
768            sha1(b""),
769            [
770                0xDA, 0x39, 0xA3, 0xEE, 0x5E, 0x6B, 0x4B, 0x0D, 0x32, 0x55, 0xBF, 0xEF, 0x95, 0x60,
771                0x18, 0x90, 0xAF, 0xD8, 0x07, 0x09
772            ]
773        );
774    }
775
776    #[test]
777    fn adler32_matches_known_vectors() {
778        assert_eq!(adler32(b""), 1);
779        assert_eq!(adler32(b"abc"), 0x024D_0127);
780        assert_eq!(adler32(b"Wikipedia"), 0x11E6_0398);
781    }
782
783    #[test]
784    fn method_descriptors_parse() {
785        let p = Proto::parse("(Landroid/bluetooth/BluetoothGatt;II)V");
786        assert_eq!(p.return_type, "V");
787        assert_eq!(
788            p.parameters,
789            ["Landroid/bluetooth/BluetoothGatt;", "I", "I"]
790        );
791        assert_eq!(p.shorty, "VLII", "the shorty collapses references to L");
792
793        let arrays = Proto::parse("([BLjava/lang/String;)[I");
794        assert_eq!(arrays.parameters, ["[B", "Ljava/lang/String;"]);
795        assert_eq!(arrays.return_type, "[I");
796        assert_eq!(arrays.shorty, "LLL");
797
798        let empty = Proto::parse("()V");
799        assert!(empty.parameters.is_empty());
800        assert_eq!(empty.shorty, "V");
801    }
802
803    #[test]
804    fn uleb128_matches_the_spec() {
805        let encode = |v: u32| {
806            let mut s = Section::new(0);
807            s.uleb128(v);
808            s.finish()
809        };
810        assert_eq!(encode(0), vec![0x00]);
811        assert_eq!(encode(1), vec![0x01]);
812        assert_eq!(encode(127), vec![0x7F]);
813        assert_eq!(encode(128), vec![0x80, 0x01]);
814        assert_eq!(encode(16256), vec![0x80, 0x7F]);
815    }
816
817    #[test]
818    fn strings_are_sorted_by_code_point() {
819        // The verifier rejects an unsorted string table outright.
820        let dex = sample();
821        let count = read_u32(&dex, 56) as usize;
822        let ids_off = read_u32(&dex, 60) as usize;
823
824        let mut previous: Option<String> = None;
825        for i in 0..count {
826            let data_off = read_u32(&dex, ids_off + i * 4) as usize;
827            // Skip the uleb128 length, then read to the NUL.
828            let mut at = data_off;
829            while dex[at] & 0x80 != 0 {
830                at += 1;
831            }
832            at += 1;
833            let end = dex[at..].iter().position(|b| *b == 0).unwrap() + at;
834            let s = String::from_utf8_lossy(&dex[at..end]).into_owned();
835            if let Some(prev) = &previous {
836                assert!(
837                    prev.chars().lt(s.chars()),
838                    "string table out of order: {prev:?} then {s:?}"
839                );
840            }
841            previous = Some(s);
842        }
843    }
844
845    #[test]
846    fn mutf8_encodes_nul_as_two_bytes() {
847        // The one place MUTF-8 differs from UTF-8 for text we might emit.
848        assert_eq!(mutf8("a\0b"), vec![b'a', 0xC0, 0x80, b'b']);
849        assert_eq!(mutf8("onScanResult"), b"onScanResult".to_vec());
850    }
851
852    #[test]
853    fn the_map_list_is_in_offset_order_and_ends_the_file() {
854        let dex = sample();
855        let map_off = read_u32(&dex, 52) as usize;
856        let count = read_u32(&dex, map_off) as usize;
857        assert!(count >= 8, "expected every section in the map, got {count}");
858
859        let mut last = 0;
860        for i in 0..count {
861            let entry = map_off + 4 + i * 12;
862            let offset = read_u32(&dex, entry + 8);
863            assert!(offset >= last, "map_list is not in offset order");
864            last = offset;
865        }
866        // The map is the last thing written.
867        assert_eq!(last as usize, map_off);
868    }
869
870    #[test]
871    fn a_class_with_no_overrides_still_builds() {
872        // Degenerate but legal: the constructor alone.
873        let dex = DexBuilder::new("dev/webbluetooth/Empty", "java/lang/Object").build();
874        assert_eq!(&dex[..8], &MAGIC);
875        assert_eq!(read_u32(&dex, 32), dex.len() as u32);
876        assert_eq!(&dex[12..32], &sha1(&dex[32..]));
877    }
878}