cloudfox-coreshift-core 1.2.35

Low-level Linux and Android systems primitives for CoreShift (CloudFox)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! Minimal ZIP + DEX parser for reading TRANSACTION_* static int field values
//! from `framework.jar` without any subprocess or external tool.
//!
//! Only handles STORED (uncompressed) DEX entries. Android framework JARs
//! store DEX uncompressed so ART can mmap directly from the ZIP.

// ── Byte readers ──────────────────────────────────────────────────────────────

fn u16le(b: &[u8], off: usize) -> Option<u16> {
    let s = b.get(off..off + 2)?;
    Some(u16::from_le_bytes([s[0], s[1]]))
}

fn u32le(b: &[u8], off: usize) -> Option<u32> {
    let s = b.get(off..off + 4)?;
    Some(u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
}

fn uleb128(b: &[u8], off: &mut usize) -> Option<u32> {
    let mut result = 0u32;
    let mut shift = 0u32;
    loop {
        let byte = *b.get(*off)?;
        *off += 1;
        result |= ((byte & 0x7f) as u32) << shift;
        if byte & 0x80 == 0 { return Some(result); }
        shift += 7;
        if shift >= 35 { return None; }
    }
}

// ── ZIP ───────────────────────────────────────────────────────────────────────

const ZIP_EOCD_SIG:   [u8; 4] = [0x50, 0x4b, 0x05, 0x06];
const ZIP_CD_SIG:     [u8; 4] = [0x50, 0x4b, 0x01, 0x02];
const ZIP_LOCAL_SIG:  [u8; 4] = [0x50, 0x4b, 0x03, 0x04];
const ZIP_STORED: u16 = 0;

struct ZipEntry {
    local_off:  usize,
    comp_size:  usize,
    fname_hash: u64, // djb2 of filename
}

fn djb2(s: &[u8]) -> u64 {
    let mut h = 5381u64;
    for &b in s { h = h.wrapping_mul(33).wrapping_add(b as u64); }
    h
}

fn zip_find_dex_entries(data: &[u8]) -> Vec<ZipEntry> {
    // Scan backwards for EOCD (ignore ZIP comment — Android JARs have none).
    let scan_start = data.len().saturating_sub(65558);
    let eocd_pos = match data[scan_start..]
        .windows(4)
        .rposition(|w| w == ZIP_EOCD_SIG)
    {
        Some(p) => scan_start + p,
        None    => return Vec::new(),
    };

    let cd_size = match u32le(data, eocd_pos + 12) { Some(v) => v as usize, None => return Vec::new() };
    let cd_off  = match u32le(data, eocd_pos + 16) { Some(v) => v as usize, None => return Vec::new() };

    let mut pos = cd_off;
    let cd_end  = cd_off.saturating_add(cd_size);
    let mut entries = Vec::new();

    while pos + 46 <= cd_end && pos + 46 <= data.len() {
        if data.get(pos..pos + 4) != Some(&ZIP_CD_SIG) { break; }

        let compression = match u16le(data, pos + 10) { Some(v) => v, None => break };
        let comp_size   = match u32le(data, pos + 20) { Some(v) => v as usize, None => break };
        let local_off   = match u32le(data, pos + 42) { Some(v) => v as usize, None => break };
        let fname_len   = match u16le(data, pos + 28) { Some(v) => v as usize, None => break };
        let extra_len   = match u16le(data, pos + 30) { Some(v) => v as usize, None => break };
        let comment_len = match u16le(data, pos + 32) { Some(v) => v as usize, None => break };

        let fname_end = pos + 46 + fname_len;
        if fname_end > data.len() { break; }
        let fname = &data[pos + 46..fname_end];

        // Collect classes*.dex entries that are STORED.
        let is_dex = fname.starts_with(b"classes") && fname.ends_with(b".dex");
        if is_dex && compression == ZIP_STORED {
            entries.push(ZipEntry {
                local_off,
                comp_size,
                fname_hash: djb2(fname),
            });
        }

        pos = match pos.checked_add(46 + fname_len + extra_len + comment_len) {
            Some(v) => v,
            None    => break,
        };
    }

    // Sort classes.dex first (djb2 of b"classes.dex" < b"classes2.dex" etc. by content — just sort by hash to be deterministic; classes.dex is shortest so sort by fname_hash ascending mimics alphabetical).
    // Actually sort by comp_size descending: largest DEX is most likely to contain IActivityManager.
    entries.sort_by(|a, b| b.comp_size.cmp(&a.comp_size));
    entries
}

fn zip_entry_data<'a>(data: &'a [u8], entry: &ZipEntry) -> Option<&'a [u8]> {
    let lh = entry.local_off;
    if data.get(lh..lh + 4) != Some(&ZIP_LOCAL_SIG) { return None; }
    let fname_len = u16le(data, lh + 26)? as usize;
    let extra_len = u16le(data, lh + 28)? as usize;
    let data_start = lh + 30 + fname_len + extra_len;
    data.get(data_start..data_start + entry.comp_size)
}

// ── DEX ───────────────────────────────────────────────────────────────────────

const DEX_MAGIC: &[u8] = b"dex\n";

fn dex_string<'a>(dex: &'a [u8], string_ids_off: usize, idx: usize) -> Option<&'a [u8]> {
    let str_data_off = u32le(dex, string_ids_off + idx * 4)? as usize;
    // Skip ULEB128 UTF-16 length
    let mut off = str_data_off;
    loop {
        let b = *dex.get(off)?;
        off += 1;
        if b & 0x80 == 0 { break; }
    }
    // Null-terminated MUTF-8 bytes
    let start = off;
    while *dex.get(off)? != 0 { off += 1; }
    dex.get(start..off)
}

fn skip_encoded_value(dex: &[u8], off: &mut usize) -> Option<()> {
    let vbyte = *dex.get(*off)?;
    *off += 1;
    let vtype = vbyte & 0x1f;
    let varg  = (vbyte >> 5) as usize;
    match vtype {
        // value_arg+1 bytes follow
        0x00 | 0x02 | 0x03 | 0x04 | 0x06 |
        0x10 | 0x11 | 0x15 | 0x16 | 0x17 |
        0x18 | 0x19 | 0x1a | 0x1b => {
            *off = off.checked_add(varg + 1)?;
        }
        0x1c => { // VALUE_ARRAY
            let size = uleb128(dex, off)?;
            for _ in 0..size { skip_encoded_value(dex, off)?; }
        }
        0x1d => { // VALUE_ANNOTATION
            uleb128(dex, off)?; // type_idx
            let size = uleb128(dex, off)?;
            for _ in 0..size {
                uleb128(dex, off)?; // name_idx
                skip_encoded_value(dex, off)?;
            }
        }
        0x1e | 0x1f => {} // VALUE_NULL / VALUE_BOOLEAN — no extra bytes
        _ => return None,
    }
    Some(())
}

fn read_int_encoded_value(dex: &[u8], off: &mut usize) -> Option<u32> {
    let vbyte = *dex.get(*off)?;
    *off += 1;
    let vtype = vbyte & 0x1f;
    let varg  = (vbyte >> 5) as usize;
    // VALUE_INT = 0x04, value_arg+1 bytes, little-endian
    if vtype != 0x04 { return None; }
    let size = varg + 1;
    if size > 4 { return None; }
    let mut val = 0u32;
    for i in 0..size {
        val |= (*dex.get(*off + i)? as u32) << (i * 8);
    }
    *off += size;
    Some(val)
}

fn find_in_dex(dex: &[u8], class_desc: &[u8], field_name: &[u8]) -> Option<u32> {
    if !dex.starts_with(DEX_MAGIC) || dex.len() < 112 { return None; }

    let string_ids_size = u32le(dex, 56)? as usize;
    let string_ids_off  = u32le(dex, 60)? as usize;
    let type_ids_size   = u32le(dex, 64)? as usize;
    let type_ids_off    = u32le(dex, 68)? as usize;
    let field_ids_size  = u32le(dex, 80)? as usize;
    let field_ids_off   = u32le(dex, 84)? as usize;
    let class_defs_size = u32le(dex, 96)? as usize;
    let class_defs_off  = u32le(dex, 100)? as usize;

    // Find string index for class descriptor
    let mut class_str_idx: Option<usize> = None;
    for i in 0..string_ids_size {
        if dex_string(dex, string_ids_off, i) == Some(class_desc) {
            class_str_idx = Some(i);
            break;
        }
    }
    let class_str_idx = class_str_idx?;

    // Find type index
    let mut class_type_idx: Option<usize> = None;
    for i in 0..type_ids_size {
        if u32le(dex, type_ids_off + i * 4)? as usize == class_str_idx {
            class_type_idx = Some(i);
            break;
        }
    }
    let class_type_idx = class_type_idx?;

    // Find string index for field name
    let mut field_str_idx: Option<u32> = None;
    for i in 0..string_ids_size {
        if dex_string(dex, string_ids_off, i) == Some(field_name) {
            field_str_idx = Some(i as u32);
            break;
        }
    }
    let field_str_idx = field_str_idx?;

    // Find global field_idx in field_ids
    let mut target_field_idx: Option<u32> = None;
    for i in 0..field_ids_size {
        let foff = field_ids_off + i * 8;
        let fclass = u16le(dex, foff)? as usize;
        let fname  = u32le(dex, foff + 4)?;
        if fclass == class_type_idx && fname == field_str_idx {
            target_field_idx = Some(i as u32);
            break;
        }
    }
    let target_field_idx = target_field_idx?;

    // Find class def
    let mut class_data_off  = None;
    let mut static_vals_off = None;
    for i in 0..class_defs_size {
        let coff = class_defs_off + i * 32;
        if u32le(dex, coff)? as usize == class_type_idx {
            class_data_off  = Some(u32le(dex, coff + 24)? as usize);
            static_vals_off = Some(u32le(dex, coff + 28)? as usize);
            break;
        }
    }
    let class_data_off  = class_data_off?;
    let static_vals_off = static_vals_off?;
    if class_data_off == 0 || static_vals_off == 0 { return None; }

    // Walk class_data_item static fields to find position of target_field_idx
    let mut off = class_data_off;
    let static_fields_size  = uleb128(dex, &mut off)?;
    let _instance_fields    = uleb128(dex, &mut off)?;
    let _direct_methods     = uleb128(dex, &mut off)?;
    let _virtual_methods    = uleb128(dex, &mut off)?;

    let mut field_pos: Option<usize> = None;
    let mut cur_field_idx = 0u32;
    for i in 0..static_fields_size as usize {
        let diff         = uleb128(dex, &mut off)?;
        let _access_flags = uleb128(dex, &mut off)?;
        cur_field_idx += diff;
        if cur_field_idx == target_field_idx {
            field_pos = Some(i);
            break;
        }
    }
    let field_pos = field_pos?;

    // Read encoded_array at static_vals_off, skip to field_pos, read int
    let mut sv = static_vals_off;
    let sv_size = uleb128(dex, &mut sv)? as usize;
    if field_pos >= sv_size { return None; }

    for i in 0..=field_pos {
        if i == field_pos {
            return read_int_encoded_value(dex, &mut sv);
        }
        skip_encoded_value(dex, &mut sv)?;
    }
    None
}

/// Return the declared parameter types of a DEX method's proto.
///
/// Looks up `class_desc.method_name` in the method_ids table and returns the
/// type descriptor list from the referenced proto's type_list. Returns `None`
/// when any section is unreadable, the class is absent, or the method does
/// not exist (so callers can distinguish "method present" from "not found").
///
/// Needed DEX sections: string_ids (56/60), type_ids (64/68), proto_ids
/// (72/76), method_ids (88/92).
fn method_param_types<'a>(dex: &'a [u8], class_desc: &[u8], method_name: &[u8]) -> Option<Vec<&'a [u8]>> {
    if !dex.starts_with(DEX_MAGIC) || dex.len() < 112 { return None; }

    let string_ids_size = u32le(dex, 56)? as usize;
    let string_ids_off  = u32le(dex, 60)? as usize;
    let type_ids_size   = u32le(dex, 64)? as usize;
    let type_ids_off    = u32le(dex, 68)? as usize;
    let proto_ids_size  = u32le(dex, 72)? as usize;
    let proto_ids_off   = u32le(dex, 76)? as usize;
    let method_ids_size = u32le(dex, 88)? as usize;
    let method_ids_off  = u32le(dex, 92)? as usize;

    // String idx for the class descriptor
    let mut class_str_idx: Option<usize> = None;
    for i in 0..string_ids_size {
        if dex_string(dex, string_ids_off, i) == Some(class_desc) {
            class_str_idx = Some(i);
            break;
        }
    }
    let class_str_idx = class_str_idx?;

    // Type idx for the class descriptor
    let mut class_type_idx: Option<usize> = None;
    for i in 0..type_ids_size {
        if u32le(dex, type_ids_off + i * 4)? as usize == class_str_idx {
            class_type_idx = Some(i);
            break;
        }
    }
    let class_type_idx = class_type_idx?;

    // String idx for the method name
    let mut method_str_idx: Option<u32> = None;
    for i in 0..string_ids_size {
        if dex_string(dex, string_ids_off, i) == Some(method_name) {
            method_str_idx = Some(i as u32);
            break;
        }
    }
    let method_str_idx = method_str_idx?;

    // Method idx → proto_idx, matching class and name
    let mut proto_idx: Option<usize> = None;
    for i in 0..method_ids_size {
        let moff = method_ids_off + i * 8;
        let fclass = u16le(dex, moff)? as usize;
        let fproto = u16le(dex, moff + 2)? as usize;
        let fname  = u32le(dex, moff + 4)?;
        if fclass == class_type_idx && fname == method_str_idx {
            proto_idx = Some(fproto);
            break;
        }
    }
    let proto_idx = proto_idx?;
    if proto_idx >= proto_ids_size { return None; }

    // proto_id_item: shorty_idx, return_type_idx, parameters_off
    let poff = proto_ids_off + proto_idx * 12;
    let params_off = u32le(dex, poff + 8)? as usize;
    if params_off == 0 { return Some(Vec::new()); }

    // type_list: size u32, then u16 type indices
    let param_count = u32le(dex, params_off)? as usize;
    let mut params = Vec::with_capacity(param_count);
    for i in 0..param_count {
        let tidx = u16le(dex, params_off + 4 + i * 2)? as usize;
        let desc_str_idx = u32le(dex, type_ids_off + tidx * 4)? as usize;
        let desc = dex_string(dex, string_ids_off, desc_str_idx)?;
        params.push(desc);
    }
    Some(params)
}

// ── Public API ────────────────────────────────────────────────────────────────

/// Search `framework.jar` for the value of a static int field.
///
/// `class_desc` uses DEX descriptor syntax, e.g.
/// `"Landroid/app/IActivityManager$Stub;"`.
///
/// Returns `None` if the JAR is unreadable, the class/field is absent, or
/// the entry is compressed (DEFLATE — not expected for framework DEX).
pub fn find_transaction_code(jar_path: &str, class_desc: &str, field_name: &str) -> Option<u32> {
    let data = std::fs::read(jar_path).ok()?;
    let entries = zip_find_dex_entries(&data);
    for entry in &entries {
        if let Some(dex) = zip_entry_data(&data, entry) {
            if let Some(code) = find_in_dex(dex, class_desc.as_bytes(), field_name.as_bytes()) {
                return Some(code);
            }
        }
    }
    None
}

/// Resolve all four tx codes needed for binder observer mode.
///
/// Returns `(observer_code, query_code, api_mode, fg_code)` where:
/// - `observer_code` = `TRANSACTION_registerProcessObserver`
/// - `query_code`    = `TRANSACTION_getFocusedRootTaskInfo` (or StackInfo on API 29)
/// - `api_mode`      = 1 (RootTaskInfo) or 2 (StackInfo)
/// - `fg_code`       = `TRANSACTION_onForegroundActivitiesChanged`
pub fn resolve_tx_codes_from_dex() -> Option<(u32, u32, u8, u32)> {
    const JAR: &str = "/system/framework/framework.jar";
    const AM_STUB:  &str = "Landroid/app/IActivityManager$Stub;";
    const OBS_STUB: &str = "Landroid/app/IProcessObserver$Stub;";

    let observer_code = find_transaction_code(JAR, AM_STUB, "TRANSACTION_registerProcessObserver")?;
    let fg_code = find_transaction_code(JAR, OBS_STUB, "TRANSACTION_onForegroundActivitiesChanged")?;

    if let Some(query_code) = find_transaction_code(JAR, AM_STUB, "TRANSACTION_getFocusedRootTaskInfo") {
        return Some((observer_code, query_code, 1, fg_code));
    }
    // API 29 fallback
    let query_code = find_transaction_code(JAR, AM_STUB, "TRANSACTION_getFocusedStackInfo")?;
    Some((observer_code, query_code, 2, fg_code))
}

/// Resolve `IPowerManager.isInteractive()` transaction code from DEX.
pub fn resolve_is_interactive_tx() -> Option<u32> {
    const JAR: &str = "/system/framework/framework.jar";
    find_transaction_code(JAR, "Landroid/os/IPowerManager$Stub;", "TRANSACTION_isInteractive")
}

/// Resolve the `IForegroundProcessObserver` registration tx codes from DEX.
///
/// Returns `(register_code, on_change_code)` where:
/// - `register_code` = `TRANSACTION_registerForegroundProcessObserver`
/// - `on_change_code` = `TRANSACTION_onForegroundProcessChanged`
pub fn resolve_fgproc_codes() -> Option<(u32, u32)> {
    const JAR: &str = "/system/framework/framework.jar";
    const AM_STUB: &str = "Landroid/app/IActivityManager$Stub;";
    const FGPROC_STUB: &str = "Landroid/app/IForegroundProcessObserver$Stub;";

    let register_code =
        find_transaction_code(JAR, AM_STUB, "TRANSACTION_registerForegroundProcessObserver")?;
    let on_change_code =
        find_transaction_code(JAR, FGPROC_STUB, "TRANSACTION_onForegroundProcessChanged")?;
    Some((register_code, on_change_code))
}

/// Resolve the fallback `IProcessObserver` foreground observer tx codes used
/// by ROMs that removed `IForegroundProcessObserver`.
///
/// Custom ROMs drop the stock `IForegroundProcessObserver` (no
/// `registerForegroundProcessObserver` / `onForegroundProcessChanged`) but
/// repurpose `IProcessObserver.onForegroundActivitiesChanged` to deliver the
/// foreground **pid** (`(I,I,Z)V` — pid, uid, fg) instead of the stock
/// package string (`(String,I,Z)V`). For those ROMs the daemon can register
/// via the classic `registerProcessObserver` and read the pid straight out of
/// the callback parcel.
///
/// Returns `None` when the stock [`resolve_fgproc_codes`] path succeeds
/// (callers must prefer it), when `onForegroundActivitiesChanged` does not
/// lead with an `int` parameter, or when either tx code cannot be resolved.
pub fn resolve_fgproc_codes_fallback() -> Option<(u32, u32)> {
    const JAR: &str = "/system/framework/framework.jar";
    const AM_STUB:   &str = "Landroid/app/IActivityManager$Stub;";
    const OBS_STUB:  &str = "Landroid/app/IProcessObserver$Stub;";
    const OBS_IFACE: &str = "Landroid/app/IProcessObserver;";

    // Stock IForegroundProcessObserver present → stock path is fine.
    if resolve_fgproc_codes().is_some() {
        return None;
    }

    let data = std::fs::read(JAR).ok()?;
    let entries = zip_find_dex_entries(&data);

    // onForegroundActivitiesChanged must declare an int first param (pid);
    // stock String-first (pkg) form cannot serve this daemon.
    let mut pid_first = false;
    for entry in &entries {
        if let Some(dex) = zip_entry_data(&data, entry) {
            if let Some(params) = method_param_types(dex, OBS_IFACE.as_bytes(), b"onForegroundActivitiesChanged") {
                pid_first = params.first().map(|t| *t == b"I").unwrap_or(false);
                break;
            }
        }
    }
    if !pid_first { return None; }

    let register_code = find_transaction_code(JAR, AM_STUB, "TRANSACTION_registerProcessObserver")?;
    let on_change_code =
        find_transaction_code(JAR, OBS_STUB, "TRANSACTION_onForegroundActivitiesChanged")?;
    Some((register_code, on_change_code))
}

/// Resolve the `IWindowManager` task-FPS callback tx codes from DEX.
///
/// Returns `(register_code, unregister_code, on_fps_code)` where:
/// - `register_code`   = `TRANSACTION_registerTaskFpsCallback`
/// - `unregister_code` = `TRANSACTION_unregisterTaskFpsCallback`
/// - `on_fps_code`     = `TRANSACTION_onFpsReported` on `ITaskFpsCallback`
pub fn resolve_fps_codes() -> Option<(u32, u32, u32)> {
    const JAR: &str = "/system/framework/framework.jar";
    const IWM_STUB: &str = "Landroid/view/IWindowManager$Stub;";
    const FPS_STUB: &str = "Landroid/window/ITaskFpsCallback$Stub;";

    let register_code = find_transaction_code(JAR, IWM_STUB, "TRANSACTION_registerTaskFpsCallback")?;
    let unregister_code =
        find_transaction_code(JAR, IWM_STUB, "TRANSACTION_unregisterTaskFpsCallback")?;
    let on_fps_code = find_transaction_code(JAR, FPS_STUB, "TRANSACTION_onFpsReported")?;
    Some((register_code, unregister_code, on_fps_code))
}

/// Resolve the `IActivityTaskManager` task-stack listener tx codes from DEX.
///
/// Returns `(register_code, unregister_code)`:
/// - `register_code`   = `TRANSACTION_registerTaskStackListener`
/// - `unregister_code` = `TRANSACTION_unregisterTaskStackListener`
///
/// This target's ROM exposes the legacy `ITaskStackListener` /
/// `registerTaskStackListener` pair on `IActivityTaskManager`; the newer
/// `ITaskChangeListener` / `registerTaskChangeListener` interface is absent
/// and must not be relied on.
pub fn resolve_task_stack_codes() -> Option<(u32, u32)> {
    const JAR: &str = "/system/framework/framework.jar";
    const ATM_STUB: &str = "Landroid/app/IActivityTaskManager$Stub;";

    let register_code =
        find_transaction_code(JAR, ATM_STUB, "TRANSACTION_registerTaskStackListener")?;
    let unregister_code =
        find_transaction_code(JAR, ATM_STUB, "TRANSACTION_unregisterTaskStackListener")?;
    Some((register_code, unregister_code))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn u32put(b: &mut Vec<u8>, off: usize, v: u32) {
        b[off..off + 4].copy_from_slice(&v.to_le_bytes());
    }

    // Build a minimal DEX header + string/type/proto/method id tables for a
    // single class with a single method whose proto has the given param type
    // descriptors. Only the sections method_param_types() reads are populated.
    fn build_dex(class_desc: &[u8], method_name: &[u8], params: &[&[u8]]) -> Vec<u8> {
        let mut out = vec![0u8; 112];
        out[0..4].copy_from_slice(DEX_MAGIC);
        out[4..8].copy_from_slice(b"035\0");

        let mut strings: Vec<Vec<u8>> = vec![class_desc.to_vec(), method_name.to_vec()];
        for p in params {
            if !strings.iter().any(|s| s == p) {
                strings.push(p.to_vec());
            }
        }
        let n_string = strings.len();
        let mut types: Vec<Vec<u8>> = vec![class_desc.to_vec()];
        for p in params {
            if !types.iter().any(|t| t == p) {
                types.push(p.to_vec());
            }
        }
        let n_type = types.len();

        let off_string_ids = 112;
        let off_type_ids = off_string_ids + n_string * 4;
        let off_proto_ids = off_type_ids + n_type * 4;
        let off_method_ids = off_proto_ids + 12; // one proto

        // Reserve id table space.
        out.resize(off_method_ids + 8, 0); // one method

        // string_data items (in file order, referenced by string_ids)
        let mut string_offs = Vec::with_capacity(n_string);
        for s in &strings {
            string_offs.push(out.len());
            let n = s.len() as u8;
            out.push(n); // short ULEB128 length (ASCII only)
            out.extend_from_slice(s);
            out.push(0);
        }

        // type_list for the single proto's parameters.
        let params_off = out.len();
        out.extend_from_slice(&(params.len() as u32).to_le_bytes());
        for p in params {
            let ti = types.iter().position(|t| t == p).unwrap();
            out.extend_from_slice(&(ti as u16).to_le_bytes());
        }

        // Header: counts + offsets (offsets 56..=100).
        u32put(&mut out, 56, n_string as u32);
        u32put(&mut out, 60, off_string_ids as u32);
        u32put(&mut out, 64, n_type as u32);
        u32put(&mut out, 68, off_type_ids as u32);
        u32put(&mut out, 72, 1); // proto count
        u32put(&mut out, 76, off_proto_ids as u32);
        u32put(&mut out, 80, 0); // field_ids count
        u32put(&mut out, 84, 0);
        u32put(&mut out, 88, 1); // method count
        u32put(&mut out, 92, off_method_ids as u32);
        u32put(&mut out, 96, 0); // class_defs count
        u32put(&mut out, 100, 0);

        // string_ids
        for (i, &so) in string_offs.iter().enumerate() {
            u32put(&mut out, off_string_ids + i * 4, so as u32);
        }
        // type_ids → descriptor string index
        for (i, t) in types.iter().enumerate() {
            let si = strings.iter().position(|s| s == t).unwrap();
            u32put(&mut out, off_type_ids + i * 4, si as u32);
        }
        // proto_ids: shorty, return, params_off
        u32put(&mut out, off_proto_ids + 0, 0);
        u32put(&mut out, off_proto_ids + 4, 0);
        u32put(&mut out, off_proto_ids + 8, params_off as u32);
        // method_ids: class_idx, proto_idx, name_idx
        let m = off_method_ids;
        out[m..m + 2].copy_from_slice(&0u16.to_le_bytes());
        out[m + 2..m + 4].copy_from_slice(&0u16.to_le_bytes());
        u32put(&mut out, m + 4, 1);

        out
    }

    #[test]
    fn parses_int_first_proto() {
        let dex = build_dex(b"Landroid/app/IProcessObserver;", b"onForegroundActivitiesChanged", &[b"I", b"I", b"Z"]);
        let params = method_param_types(&dex, b"Landroid/app/IProcessObserver;", b"onForegroundActivitiesChanged")
            .expect("method present");
        assert_eq!(params, [&b"I"[..], &b"I"[..], &b"Z"[..]]);
    }

    #[test]
    fn rejects_string_first_proto() {
        // Stock signature onForegroundActivitiesChanged(String, int, boolean)
        let dex = build_dex(b"Landroid/app/IProcessObserver;", b"onForegroundActivitiesChanged", &[b"Ljava/lang/String;", b"I", b"Z"]);
        let params = method_param_types(&dex, b"Landroid/app/IProcessObserver;", b"onForegroundActivitiesChanged")
            .expect("method present");
        assert_eq!(params.first().map(|t| *t == b"I"), Some(false));
    }

    #[test]
    fn absent_method_returns_none() {
        let dex = build_dex(b"Landroid/app/IProcessObserver;", b"onForegroundActivitiesChanged", &[b"I"]);
        assert!(method_param_types(&dex, b"Landroid/app/IProcessObserver;", b"onProcessDied").is_none());
    }
}