cloudfox-coreshift-core 2.13.1

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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
// 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/

//! Shared NDK binder primitives used by every service module.
//!
//! - `Vtable` / `load_vtable`: `dlopen`d symbol table for `libbinder_ndk.so`
//! - parcel readers/writers and the `transact_write` helper
//! - RAII wrappers (`DlHandle`, `OwnedParcel`, `OwnedBinder`)
//! - status codes, raw type aliases, the bounded string allocator, and the
//!   shared `GET_USER_DATA` callback helper

use crate::CoreError;
use std::os::raw::{c_char, c_void};

// ── NDK binder status codes ───────────────────────────────────────────────

pub(super) const STATUS_OK: i32 = 0;
pub(super) const STATUS_UNKNOWN_TRANSACTION: i32 = -2;
/// Binder's `BR_DEAD_REPLY`-adjacent transport failure status: the server was
/// asked for more concurrent work than it is willing to admit. Used as the
/// busy reply when a served binder's in-flight admission gate is saturated.
pub(super) const STATUS_OUT_OF_RESOURCES: i32 = -7;
pub(super) const EX_NONE: i32 = 0;
/// `BaseBundle.BUNDLE_MAGIC` — the int `Parcel.writeBundle` writes before the
/// array-map payload. The handoff walk validates it while skipping a bundle.
pub(super) const BUNDLE_MAGIC: i32 = 0x4C444E42;
/// `Parcel.writeValue` tag for an `IBinder` (`VAL_IBINDER`). 15, not 22.
pub(super) const VAL_IBINDER: i32 = 15;
#[cfg(target_pointer_width = "64")]
pub(super) const LIBBINDER_PATH: &[u8] = b"/system/lib64/libbinder_ndk.so\0";
#[cfg(target_pointer_width = "32")]
pub(super) const LIBBINDER_PATH: &[u8] = b"/system/lib/libbinder_ndk.so\0";
// ── Raw NDK type aliases ──────────────────────────────────────────────────

pub(super) type AIBinder = c_void;
#[allow(non_camel_case_types)]
pub(super) type AIBinder_Class = c_void;
#[allow(non_camel_case_types)]
pub(super) type AIBinder_DeathRecipient = c_void;
pub(super) type AParcel = c_void;
pub(super) type BinderStatus = i32;
pub(super) type StringAllocator = unsafe extern "C" fn(*mut c_void, i32, *mut *mut c_char) -> bool;
#[allow(non_camel_case_types)]
pub(super) type AIBinder_DeathRecipient_onDiedCallback = unsafe extern "C" fn(*mut c_void);

/// `AIBinder_transact` flag for a fire-and-forget transaction with no reply.
pub(super) const FLAG_ONEWAY: u32 = 0x01;
// ── String allocator ─────────────────────────────────────────────────────

/// Ceiling on a single parcel string regardless of the length the peer
/// advertises. Component names are at most a few hundred bytes; this bounds
/// the allocation so a malformed advertised length cannot drive a giant
/// `reserve_exact` (which would abort on OOM).
const MAX_BINDER_STRING_LEN: usize = 1024 * 1024;

/// Cap on a decoded String8 payload (`read_string8`). Package names are a
/// few hundred bytes; this bounds the reconstruction buffer so a malformed
/// advertised length cannot balloon the allocation.
const STRING8_CAP: usize = 1024 * 1024;

unsafe extern "C" fn string_alloc(
    cookie: *mut c_void,
    length: i32,
    buffer: *mut *mut c_char,
) -> bool {
    // length == -1 is the Java null-string marker: AParcel_readString
    // calls the allocator with -1 (and a null buffer) when the parcel
    // holds a null string, so returning true there decodes it to None
    // instead of a hard STATUS_UNEXPECTED_NULL failure. Any other
    // negative length is corruption and an allocation failure: returning
    // true with no usable buffer would hand the reader a dangling pointer,
    // and an oversized reserve_exact would abort on OOM.
    if length == -1 {
        return true;
    }
    if length < 0 {
        return false;
    }
    let len = length as usize;
    if len > MAX_BINDER_STRING_LEN {
        return false;
    }
    let s = unsafe { &mut *(cookie as *mut StringBuf) };
    s.0.reserve_exact(len + 1);
    unsafe { s.0.as_mut_vec().resize(len + 1, 0) };
    unsafe { *buffer = s.0.as_mut_ptr() as *mut c_char };
    true
}

struct StringBuf(String);
impl StringBuf {
    fn new() -> Self {
        Self(String::new())
    }
    fn finish(mut self) -> Option<String> {
        if let Some(pos) = self.0.as_bytes().iter().position(|&b| b == 0) {
            unsafe { self.0.as_mut_vec().truncate(pos) };
        }
        if self.0.is_empty() {
            None
        } else {
            Some(self.0)
        }
    }
}
// ── Vtable ────────────────────────────────────────────────────────────────

/// Copyable snapshot of every `libbinder_ndk.so` symbol the crate binds.
/// All fields are fn pointers; a copy can be boxed alongside a serving
/// handler so its `on_transact` has the same symbol table as the client side.
#[derive(Clone, Copy)]
pub(super) struct Vtable {
    pub(super) get_service: unsafe extern "C" fn(*const c_char) -> *mut AIBinder,
    pub(super) class_define: unsafe extern "C" fn(
        *const c_char,
        unsafe extern "C" fn(*mut c_void) -> *mut c_void,
        unsafe extern "C" fn(*mut c_void),
        unsafe extern "C" fn(*mut AIBinder, u32, *const AParcel, *mut AParcel) -> BinderStatus,
    ) -> *mut AIBinder_Class,
    pub(super) associate_class: unsafe extern "C" fn(*mut AIBinder, *mut AIBinder_Class) -> bool,
    pub(super) new_binder:
        unsafe extern "C" fn(*const AIBinder_Class, *mut c_void) -> *mut AIBinder,
    pub(super) prepare_transaction:
        unsafe extern "C" fn(*mut AIBinder, *mut *mut AParcel) -> BinderStatus,
    pub(super) transact: unsafe extern "C" fn(
        *mut AIBinder,
        u32,
        *mut *mut AParcel,
        *mut *mut AParcel,
        u32,
    ) -> BinderStatus,
    pub(super) dec_strong: unsafe extern "C" fn(*mut AIBinder),
    pub(super) parcel_delete: unsafe extern "C" fn(*mut AParcel),
    pub(super) read_int32: unsafe extern "C" fn(*const AParcel, *mut i32) -> BinderStatus,
    pub(super) read_string:
        unsafe extern "C" fn(*const AParcel, *mut c_void, StringAllocator) -> BinderStatus,
    pub(super) write_strong_binder:
        unsafe extern "C" fn(*mut AParcel, *mut AIBinder) -> BinderStatus,
    pub(super) set_thread_pool_max: unsafe extern "C" fn(u32),
    pub(super) join_thread_pool: unsafe extern "C" fn(),
    pub(super) get_user_data: unsafe extern "C" fn(*const AIBinder) -> *mut c_void,
    pub(super) write_int32: unsafe extern "C" fn(*mut AParcel, i32) -> BinderStatus,
    pub(super) read_float: Option<unsafe extern "C" fn(*const AParcel, *mut f32) -> BinderStatus>,
    pub(super) read_int64: Option<unsafe extern "C" fn(*const AParcel, *mut i64) -> BinderStatus>,
    // Optional: only present on API 29+, but all modern Android has this
    pub(super) read_bool: Option<unsafe extern "C" fn(*const AParcel, *mut bool) -> BinderStatus>,
    // ── serving side (binder::serve) ─────────────────────────────────────
    pub(super) get_calling_uid: unsafe extern "C" fn() -> u32,
    pub(super) get_calling_pid: unsafe extern "C" fn() -> i32,
    pub(super) read_strong_binder:
        unsafe extern "C" fn(*const AParcel, *mut *mut AIBinder) -> BinderStatus,
    pub(super) write_string: unsafe extern "C" fn(*mut AParcel, *const c_char, i32) -> BinderStatus,
    pub(super) death_recipient_new: unsafe extern "C" fn(
        AIBinder_DeathRecipient_onDiedCallback,
    ) -> *mut AIBinder_DeathRecipient,
    pub(super) death_recipient_delete: unsafe extern "C" fn(*mut AIBinder_DeathRecipient),
    pub(super) link_to_death: unsafe extern "C" fn(
        *mut AIBinder,
        *mut AIBinder_DeathRecipient,
        *mut c_void,
    ) -> BinderStatus,
    pub(super) unlink_to_death: unsafe extern "C" fn(
        *mut AIBinder,
        *mut AIBinder_DeathRecipient,
        *mut c_void,
    ) -> BinderStatus,
}
// ── RAII wrappers ─────────────────────────────────────────────────────────

pub(super) struct DlHandle;
unsafe impl Send for DlHandle {}
impl Drop for DlHandle {
    fn drop(&mut self) {
        // Intentionally no dlclose: the binder thread pool spawned in
        // open_with_observer() keeps executing library code until process
        // exit. Unloading the library while that thread runs causes
        // use-after-free. libbinder_ndk.so is never unloaded during the
        // daemon lifetime; the OS reclaims it on exit.
    }
}

pub(super) struct OwnedParcel {
    pub(super) ptr: *mut AParcel,
    pub(super) delete: unsafe extern "C" fn(*mut AParcel),
}
impl Drop for OwnedParcel {
    fn drop(&mut self) {
        if !self.ptr.is_null() {
            unsafe { (self.delete)(self.ptr) };
        }
    }
}

pub struct OwnedBinder {
    pub(super) ptr: *mut AIBinder,
    pub(super) dec_strong: unsafe extern "C" fn(*mut AIBinder),
}
unsafe impl Send for OwnedBinder {}
impl OwnedBinder {
    /// The raw `AIBinder*`, e.g. to hand to `push_oneway`.
    pub fn as_raw(&self) -> *mut std::os::raw::c_void {
        self.ptr as *mut std::os::raw::c_void
    }
}
impl Drop for OwnedBinder {
    fn drop(&mut self) {
        if !self.ptr.is_null() {
            unsafe { (self.dec_strong)(self.ptr) };
        }
    }
}
// ── dlsym helper ─────────────────────────────────────────────────────────

macro_rules! dlsym_fn {
    ($handle:expr, $name:literal, $ty:ty) => {{
        let sym = unsafe { libc::dlsym($handle, concat!($name, "\0").as_ptr() as *const c_char) };
        if sym.is_null() {
            return Err(CoreError::binder(-1, concat!("dlsym:", $name)));
        }
        unsafe { std::mem::transmute::<*mut c_void, $ty>(sym) }
    }};
}

macro_rules! dlsym_opt {
    ($handle:expr, $name:literal, $ty:ty) => {{
        let sym = unsafe { libc::dlsym($handle, concat!($name, "\0").as_ptr() as *const c_char) };
        if sym.is_null() {
            None
        } else {
            Some(unsafe { std::mem::transmute::<*mut c_void, $ty>(sym) })
        }
    }};
}
pub(super) fn load_vtable(handle: *mut c_void) -> Result<Vtable, CoreError> {
    Ok(Vtable {
        get_service: dlsym_fn!(
            handle,
            "AServiceManager_getService",
            unsafe extern "C" fn(*const c_char) -> *mut AIBinder
        ),
        class_define: dlsym_fn!(
            handle,
            "AIBinder_Class_define",
            unsafe extern "C" fn(
                *const c_char,
                unsafe extern "C" fn(*mut c_void) -> *mut c_void,
                unsafe extern "C" fn(*mut c_void),
                unsafe extern "C" fn(
                    *mut AIBinder,
                    u32,
                    *const AParcel,
                    *mut AParcel,
                ) -> BinderStatus,
            ) -> *mut AIBinder_Class
        ),
        associate_class: dlsym_fn!(
            handle,
            "AIBinder_associateClass",
            unsafe extern "C" fn(*mut AIBinder, *mut AIBinder_Class) -> bool
        ),
        new_binder: dlsym_fn!(
            handle,
            "AIBinder_new",
            unsafe extern "C" fn(*const AIBinder_Class, *mut c_void) -> *mut AIBinder
        ),
        prepare_transaction: dlsym_fn!(
            handle,
            "AIBinder_prepareTransaction",
            unsafe extern "C" fn(*mut AIBinder, *mut *mut AParcel) -> BinderStatus
        ),
        transact: dlsym_fn!(
            handle,
            "AIBinder_transact",
            unsafe extern "C" fn(
                *mut AIBinder,
                u32,
                *mut *mut AParcel,
                *mut *mut AParcel,
                u32,
            ) -> BinderStatus
        ),
        dec_strong: dlsym_fn!(
            handle,
            "AIBinder_decStrong",
            unsafe extern "C" fn(*mut AIBinder)
        ),
        parcel_delete: dlsym_fn!(handle, "AParcel_delete", unsafe extern "C" fn(*mut AParcel)),
        read_int32: dlsym_fn!(
            handle,
            "AParcel_readInt32",
            unsafe extern "C" fn(*const AParcel, *mut i32) -> BinderStatus
        ),
        read_string: dlsym_fn!(
            handle,
            "AParcel_readString",
            unsafe extern "C" fn(*const AParcel, *mut c_void, StringAllocator) -> BinderStatus
        ),
        write_strong_binder: dlsym_fn!(
            handle,
            "AParcel_writeStrongBinder",
            unsafe extern "C" fn(*mut AParcel, *mut AIBinder) -> BinderStatus
        ),
        set_thread_pool_max: dlsym_fn!(
            handle,
            "ABinderProcess_setThreadPoolMaxThreadCount",
            unsafe extern "C" fn(u32)
        ),
        join_thread_pool: dlsym_fn!(
            handle,
            "ABinderProcess_joinThreadPool",
            unsafe extern "C" fn()
        ),
        get_user_data: dlsym_fn!(
            handle,
            "AIBinder_getUserData",
            unsafe extern "C" fn(*const AIBinder) -> *mut c_void
        ),
        write_int32: dlsym_fn!(
            handle,
            "AParcel_writeInt32",
            unsafe extern "C" fn(*mut AParcel, i32) -> BinderStatus
        ),
        read_bool: dlsym_opt!(
            handle,
            "AParcel_readBool",
            unsafe extern "C" fn(*const AParcel, *mut bool) -> BinderStatus
        ),
        read_float: dlsym_opt!(
            handle,
            "AParcel_readFloat",
            unsafe extern "C" fn(*const AParcel, *mut f32) -> BinderStatus
        ),
        read_int64: dlsym_opt!(
            handle,
            "AParcel_readInt64",
            unsafe extern "C" fn(*const AParcel, *mut i64) -> BinderStatus
        ),
        get_calling_uid: dlsym_fn!(
            handle,
            "AIBinder_getCallingUid",
            unsafe extern "C" fn() -> u32
        ),
        get_calling_pid: dlsym_fn!(
            handle,
            "AIBinder_getCallingPid",
            unsafe extern "C" fn() -> i32
        ),
        read_strong_binder: dlsym_fn!(
            handle,
            "AParcel_readStrongBinder",
            unsafe extern "C" fn(*const AParcel, *mut *mut AIBinder) -> BinderStatus
        ),
        write_string: dlsym_fn!(
            handle,
            "AParcel_writeString",
            unsafe extern "C" fn(*mut AParcel, *const c_char, i32) -> BinderStatus
        ),
        death_recipient_new: dlsym_fn!(
            handle,
            "AIBinder_DeathRecipient_new",
            unsafe extern "C" fn(
                AIBinder_DeathRecipient_onDiedCallback,
            ) -> *mut AIBinder_DeathRecipient
        ),
        death_recipient_delete: dlsym_fn!(
            handle,
            "AIBinder_DeathRecipient_delete",
            unsafe extern "C" fn(*mut AIBinder_DeathRecipient)
        ),
        link_to_death: dlsym_fn!(
            handle,
            "AIBinder_linkToDeath",
            unsafe extern "C" fn(
                *mut AIBinder,
                *mut AIBinder_DeathRecipient,
                *mut c_void,
            ) -> BinderStatus
        ),
        unlink_to_death: dlsym_fn!(
            handle,
            "AIBinder_unlinkToDeath",
            unsafe extern "C" fn(
                *mut AIBinder,
                *mut AIBinder_DeathRecipient,
                *mut c_void,
            ) -> BinderStatus
        ),
    })
}
// ── ParcelReader ──────────────────────────────────────────────────────────

/// Read cursor over a parcel (owned client reply, or a framework-owned
/// serving input). Binds the vtable snapshot for the read window.
pub struct ParcelReader<'a> {
    pub(super) vt: &'a Vtable,
    pub(super) parcel: *const AParcel,
}

impl<'a> ParcelReader<'a> {
    /// Wrap an owned reply parcel (client side). `OwnedParcel` keeps it
    /// alive for the read window; the reader never deletes.
    pub(super) fn owned(vt: &'a Vtable, parcel: &'a OwnedParcel) -> Self {
        Self {
            vt,
            parcel: parcel.ptr,
        }
    }

    /// Wrap a framework-owned input parcel (serving side, `on_transact`'s
    /// `in` parcel). Borrowed: the framework owns and deletes it; the reader
    /// never touches lifetime.
    pub(super) fn borrowed(vt: &'a Vtable, parcel: *const AParcel) -> Self {
        Self { vt, parcel }
    }

    pub fn read_i32(&self) -> Result<i32, CoreError> {
        let mut v = 0i32;
        let s = unsafe { (self.vt.read_int32)(self.parcel, &mut v) };
        if s != STATUS_OK {
            return Err(CoreError::binder(s, "AParcel_readInt32"));
        }
        Ok(v)
    }
    /// Read a String16 (Java `writeString`) as an owned `String`. Returns
    /// `None` for a null string (`-1` marker); `string_alloc` accepts the
    /// `-1` length so `AParcel_readString` returns `STATUS_OK` instead of
    /// `STATUS_UNEXPECTED_NULL`. Strings are bound-capped (1 MiB) by
    /// `string_alloc`.
    pub fn read_string(&self) -> Result<Option<String>, CoreError> {
        let mut buf = StringBuf::new();
        let s = unsafe {
            (self.vt.read_string)(
                self.parcel,
                &mut buf as *mut StringBuf as *mut c_void,
                string_alloc,
            )
        };
        if s != STATUS_OK {
            return Err(CoreError::binder(s, "AParcel_readString"));
        }
        Ok(buf.finish())
    }
    /// Read a strong binder from the parcel. Returns `None` for a null
    /// binder marker. The returned binder holds a strong reference the
    /// caller owns (`OwnedBinder` drops it via `AIBinder_decStrong`).
    pub fn read_strong_binder(&self) -> Result<Option<OwnedBinder>, CoreError> {
        let mut raw: *mut AIBinder = std::ptr::null_mut();
        let s = unsafe { (self.vt.read_strong_binder)(self.parcel, &mut raw) };
        if s != STATUS_OK {
            return Err(CoreError::binder(s, "AParcel_readStrongBinder"));
        }
        if raw.is_null() {
            return Ok(None);
        }
        Ok(Some(OwnedBinder {
            ptr: raw,
            dec_strong: self.vt.dec_strong,
        }))
    }
    pub fn read_float(&self) -> Result<f32, CoreError> {
        let r = self
            .vt
            .read_float
            .ok_or_else(|| CoreError::binder(-1, "AParcel_readFloat:unavailable"))?;
        let mut v = 0f32;
        let s = unsafe { r(self.parcel, &mut v) };
        if s != STATUS_OK {
            return Err(CoreError::binder(s, "AParcel_readFloat"));
        }
        Ok(v)
    }
    pub fn read_int64(&self) -> Result<i64, CoreError> {
        let r = self
            .vt
            .read_int64
            .ok_or_else(|| CoreError::binder(-1, "AParcel_readInt64:unavailable"))?;
        let mut v = 0i64;
        let s = unsafe { r(self.parcel, &mut v) };
        if s != STATUS_OK {
            return Err(CoreError::binder(s, "AParcel_readInt64"));
        }
        Ok(v)
    }
    pub fn read_bool(&self) -> Result<bool, CoreError> {
        if let Some(rb) = self.vt.read_bool {
            let mut v = false;
            let s = unsafe { rb(self.parcel, &mut v) };
            if s != STATUS_OK {
                return Err(CoreError::binder(s, "AParcel_readBool"));
            }
            Ok(v)
        } else {
            Ok(self.read_i32()? != 0)
        }
    }
    pub(super) fn skip_i32s(&self, n: usize) -> Result<(), CoreError> {
        for _ in 0..n {
            self.read_i32()?;
        }
        Ok(())
    }
    pub(super) fn skip_int_array(&self) -> Result<(), CoreError> {
        let count = self.read_i32()?.max(0) as usize;
        self.skip_i32s(count)
    }
    /// Skip `n` bytes, consuming 4-byte words. Parcel payloads are always
    /// 4-byte aligned (Parcel::pad_size), so `n` is a multiple of 4 for
    /// every skip we perform; the ceiling rounding is defensive.
    pub(super) fn skip_bytes(&self, n: usize) -> Result<(), CoreError> {
        self.skip_i32s(n.div_ceil(4))
    }
    /// Skip a String16 (Java `writeString`) payload — `writeInt32(len)`
    /// then `(len+1)*2` UTF-16 bytes padded to 4. Returns `Ok(true)` if a
    /// non-null string was consumed, `Ok(false)` for the null marker
    /// (`-1`). This never touches the decoded value, so it is immune to
    /// the UTF-16→UTF-8 allocation path.
    pub(super) fn skip_string16(&self) -> Result<bool, CoreError> {
        let len = self.read_i32()?;
        if len < 0 {
            return Ok(false);
        }
        // saturating: a hostile `len` could otherwise wrap the byte math
        // on 32-bit targets and silently desync the walk.
        let bytes = ((len as usize).saturating_add(1)).saturating_mul(2);
        self.skip_bytes(bytes)?;
        Ok(true)
    }
    /// Skip a String8 (Java `writeString8`) payload — `writeInt32(len)`
    /// then `len+1` UTF-8 bytes padded to 4. Used for
    /// `DisplayInfo.{name,ownerPackageName,uniqueId}` which the framework
    /// writes with `writeString8`; `AParcel_readString` only decodes
    /// String16 and would desync the walk.
    pub(super) fn skip_string8(&self) -> Result<bool, CoreError> {
        let len = self.read_i32()?;
        if len < 0 {
            return Ok(false);
        }
        let bytes = (len as usize).saturating_add(1);
        self.skip_bytes(bytes)?;
        Ok(true)
    }
    /// Read a String8 (Java `writeString8`) payload and decode it. Same wire
    /// as `skip_string8` (`writeInt32(len)` then `len+1` UTF-8 bytes padded
    /// to 4) but captures the value — used to verify the provider's
    /// `packageName` during the handoff walk. The trailing NUL is excluded
    /// from the returned string; `len` is a byte count, decoded lossily (a
    /// hostile/malformed value is never allowed to desync the walk).
    pub(super) fn read_string8(&self) -> Result<Option<String>, CoreError> {
        let len = self.read_i32()?;
        if len < 0 {
            return Ok(None);
        }
        if len as usize > STRING8_CAP {
            return Err(CoreError::binder(-1, "read_string8:too_long"));
        }
        // The parcel has no raw-byte reader; reconstruct the payload from
        // the 4-byte words `skip_string8` would consume. Little-endian: word
        // byte 0 is the next payload byte.
        let words = (len as usize + 1).div_ceil(4);
        let mut buf = Vec::with_capacity(words * 4);
        for _ in 0..words {
            buf.extend_from_slice(&(self.read_i32()? as u32).to_le_bytes());
        }
        buf.truncate(len as usize);
        let s = String::from_utf8_lossy(&buf).into_owned();
        Ok(Some(s))
    }
    /// Skip a `Parcel.readValue()` encoded value (Java `writeValue`).
    /// Wire: an i32 type tag, optionally followed by a length prefix and a
    /// payload per tag. Covers the tags present in the device-info walks
    /// (String/Integer/Parcelable/null) and the content-provider handoff
    /// walks (int[], long[], boolean[], String[]/String16, byte[],
    /// CharSequence, IBinder, and the length-prefixed containers); every
    /// other tag is defensively rejected so a layout drift surfaces as an
    /// error instead of a misaligned parse.
    pub(super) fn skip_value(&self) -> Result<(), CoreError> {
        let tag = self.read_i32()?;
        match tag {
            // VAL_NULL (-1): no payload.
            -1 => Ok(()),
            // VAL_STRING (0): writeString → String16.
            0 => self.skip_string16().map(|_| ()),
            // VAL_INTEGER (1), VAL_SHORT (5), VAL_BOOLEAN (9), VAL_BYTE (20),
            // VAL_CHAR (29): 4-byte scalar.
            1 | 5 | 9 | 20 | 29 => self.read_i32().map(|_| ()),
            // VAL_LONG (6): 8-byte scalar.
            6 => self.read_int64().map(|_| ()),
            // VAL_FLOAT (7): 4-byte scalar.
            7 => self.read_float().map(|_| ()),
            // VAL_DOUBLE (8): 8-byte scalar.
            8 => {
                self.read_i32()?;
                self.read_i32()?;
                Ok(())
            }
            // VAL_CHARSEQUENCE (10): TextUtils.writeToParcel — marker + body.
            10 => self.skip_char_sequence(),
            // VAL_IBINDER (15): writeStrongBinder → flat_binder_object.
            15 => self.read_strong_binder().map(|_| ()),
            // VAL_INTARRAY (18): int[] — writeIntArray, not length-prefixed.
            18 => self.skip_int_array(),
            // VAL_LONGARRAY (19): long[] — writeInt(N) + N×writeLong.
            19 => {
                let n = self.read_i32()?.max(0) as usize;
                for _ in 0..n {
                    self.read_int64()?;
                }
                Ok(())
            }
            // VAL_BYTEARRAY (13): writeInt(N) + N raw bytes padded to 4.
            13 => {
                let n = self.read_i32()?.max(0) as usize;
                self.skip_bytes(n)
            }
            // VAL_BOOLEANARRAY (23): writeInt(N) + N×writeInt.
            23 => {
                let n = self.read_i32()?.max(0) as usize;
                self.skip_i32s(n)
            }
            // VAL_STRINGARRAY (14): writeInt(N) + N×writeString (String16).
            14 => {
                let n = self.read_i32()?.max(0) as usize;
                for _ in 0..n {
                    self.skip_string16()?;
                }
                Ok(())
            }
            // VAL_SIZE (26): 2×i32.
            26 => self.skip_i32s(2),
            // VAL_SIZEF (27): 2×f32.
            27 => {
                self.read_float()?;
                self.read_float()?;
                Ok(())
            }
            // Length-prefixed containers: VAL_MAP (2), VAL_PARCELABLE (4),
            // VAL_LIST (11), VAL_SPARSEARRAY (12), VAL_PARCELABLEARRAY (16),
            // VAL_OBJECTARRAY (17), VAL_SERIALIZABLE (21). An i32 body
            // length follows the tag; skip that many bytes. Lengths are
            // 4-byte aligned in practice; the ceiling is defensive.
            2 | 4 | 11 | 12 | 16 | 17 | 21 => {
                let len = self.read_i32()?;
                if len < 0 {
                    return Ok(());
                }
                self.skip_bytes(len as usize)
            }
            // VAL_BUNDLE (3) / VAL_PERSISTABLEBUNDLE (25): NOT byte-length
            // prefixed like the containers above — the body is the raw
            // `writeBundle` shape `[i32 length][BUNDLE_MAGIC][length bytes]`,
            // which skip_bundle validates and consumes exactly.
            3 | 25 => self.skip_bundle(),
            _ => Err(CoreError::binder(tag, "parcel:unsupported readValue tag")),
        }
    }
    /// Skip a `String[]` written with `writeString8Array` (count prefix,
    /// `-1` = null, then N×String8).
    pub(super) fn skip_string8_array(&self) -> Result<(), CoreError> {
        let n = self.read_i32()?;
        if n < 0 {
            return Ok(());
        }
        for _ in 0..n {
            self.skip_string8()?;
        }
        Ok(())
    }
    /// Skip a `Parcel.writeBundle` payload (Java `Bundle`/`BaseBundle`).
    /// Wire: `writeInt(byteLength)` where 0 = empty/null, otherwise
    /// `writeInt(BUNDLE_MAGIC)` + `byteLength` bytes of the array-map
    /// payload. The reader validates the magic and 4-alignment; we
    /// validate the magic and skip exactly the advertised length.
    pub(super) fn skip_bundle(&self) -> Result<(), CoreError> {
        let length = self.read_i32()?;
        if length <= 0 {
            return Ok(());
        }
        let magic = self.read_i32()?;
        if magic != BUNDLE_MAGIC {
            return Err(CoreError::binder(magic, "parcel:bad bundle magic"));
        }
        self.skip_bytes(length as usize)
    }
    /// Skip a `TextUtils.writeToParcel(CharSequence)` payload. Wire: marker
    /// `writeInt(1)` for a plain/null string (then a String8), or marker
    /// `writeInt(0)` for a `Spanned` (then String8 + a span list + a
    /// `writeInt(0)` terminator). The spanned shape carries type-dependent
    /// span bodies that cannot be skipped generically, so it is defensively
    /// rejected — every label the handoff targets is a plain (unspanned)
    /// string or null.
    pub(super) fn skip_char_sequence(&self) -> Result<(), CoreError> {
        match self.read_i32()? {
            1 => self.skip_string8().map(|_| ()),
            0 => Err(CoreError::binder(
                0,
                "parcel:spanned CharSequence unsupported",
            )),
            m => Err(CoreError::binder(m, "parcel:bad CharSequence marker")),
        }
    }
    /// Skip a `Parcel.writeSparseArray` payload (SparseArray of `writeValue`
    /// objects): `writeInt(-1)` for null, else `writeInt(N)` + N×
    /// (`writeInt(key)` + `writeValue(value)`).
    pub(super) fn skip_sparsearray(&self) -> Result<(), CoreError> {
        let n = self.read_i32()?;
        if n < 0 {
            return Ok(());
        }
        for _ in 0..n {
            self.read_i32()?;
            self.skip_value()?;
        }
        Ok(())
    }
    /// Skip a `Parcel.writeTypedArray` / `writeTypedList` payload of one
    /// parcelable type: `writeInt(-1)` for null, else `writeInt(N)` + N×
    /// (`writeInt(1)` marker + `skip` the element body, or `writeInt(0)`
    /// for a null element).
    pub(super) fn skip_typed_object_array(
        &self,
        skip_elem: impl Fn(&ParcelReader<'_>) -> Result<(), CoreError>,
    ) -> Result<(), CoreError> {
        let n = self.read_i32()?;
        if n < 0 {
            return Ok(());
        }
        for _ in 0..n {
            match self.read_i32()? {
                1 => skip_elem(self)?,
                0 => {}
                m => return Err(CoreError::binder(m, "parcel:bad typed-object marker")),
            }
        }
        Ok(())
    }
    /// Skip a `Parcel.writeTypedObject` Rect: an i32 marker (0 = null,
    /// 1 = non-null) followed by 4×i32 bounds when non-null. Anything else
    /// is a layout drift and rejected.
    pub(super) fn skip_typed_rect(&self) -> Result<(), CoreError> {
        match self.read_i32()? {
            0 => Ok(()),
            1 => self.skip_i32s(4),
            m => Err(CoreError::binder(m, "display_info:bad typed Rect marker")),
        }
    }
    pub(super) fn read_first_package_from_names(&self) -> Result<Option<String>, CoreError> {
        let count = self.read_i32()?.max(0) as usize;
        let mut first: Option<String> = None;
        for _ in 0..count {
            let s = self.read_string()?;
            if first.is_none() {
                first = s.and_then(|c| c.split('/').next().map(str::to_owned));
            }
        }
        Ok(first)
    }
}
// ── ParcelWriter / transact helper ────────────────────────────────────────

/// Write cursor over a parcel (owned client request, or a framework-owned
/// serving reply). Binds the vtable snapshot for the write window.
pub struct ParcelWriter<'a> {
    pub(super) vt: &'a Vtable,
    pub(super) parcel: *mut AParcel,
}

impl<'a> ParcelWriter<'a> {
    /// Wrap an owned request parcel (client side). `OwnedParcel` keeps it
    /// alive for the write window; the writer never deletes.
    pub(super) fn owned(vt: &'a Vtable, parcel: &'a OwnedParcel) -> Self {
        Self {
            vt,
            parcel: parcel.ptr,
        }
    }

    /// Wrap a framework-owned reply parcel (serving side, `on_transact`'s
    /// `out` parcel). Borrowed: the framework owns the reply; the writer
    /// only fills it.
    pub(super) fn borrowed(vt: &'a Vtable, parcel: *mut AParcel) -> Self {
        Self { vt, parcel }
    }

    pub fn write_i32(&self, v: i32) -> Result<(), CoreError> {
        let s = unsafe { (self.vt.write_int32)(self.parcel, v) };
        if s != STATUS_OK {
            return Err(CoreError::binder(s, "AParcel_writeInt32"));
        }
        Ok(())
    }
    pub fn write_strong_binder(&self, b: *mut c_void) -> Result<(), CoreError> {
        let s = unsafe { (self.vt.write_strong_binder)(self.parcel, b as *mut AIBinder) };
        if s != STATUS_OK {
            return Err(CoreError::binder(s, "AParcel_writeStrongBinder"));
        }
        Ok(())
    }
    /// Write a String16 (Java `writeString`). `None` writes the null-string
    /// marker (`-1` length). Capped so a hostile length cannot write past a
    /// huge advertised size; 1 MiB matches the reader ceiling.
    pub fn write_string(&self, s: Option<&str>) -> Result<(), CoreError> {
        const MAX: usize = 1024 * 1024;
        match s {
            None => {
                let s = unsafe { (self.vt.write_string)(self.parcel, std::ptr::null(), -1) };
                if s != STATUS_OK {
                    return Err(CoreError::binder(s, "AParcel_writeString"));
                }
            }
            Some(s) => {
                let bytes = s.as_bytes();
                if bytes.len() > MAX {
                    return Err(CoreError::binder(-1, "AParcel_writeString:too_long"));
                }
                // Nul-terminated copy owned for the call; AParcel_writeString
                // copies the payload into the parcel, so this buffer may drop
                // immediately after.
                let mut c = Vec::with_capacity(bytes.len() + 1);
                c.extend_from_slice(bytes);
                c.push(0);
                let s = unsafe {
                    (self.vt.write_string)(
                        self.parcel,
                        c.as_ptr() as *const c_char,
                        bytes.len() as i32,
                    )
                };
                if s != STATUS_OK {
                    return Err(CoreError::binder(s, "AParcel_writeString"));
                }
            }
        }
        Ok(())
    }
}

/// Prepare an input parcel, run `writes`, then transact. RAII on both
/// ends: a write error drops the input parcel (previously it leaked on the
/// write-error path, never reaching transact), and the reply parcel is
/// returned owned. The input parcel is transferred to `AIBinder_transact`
/// (the framework deletes it even on failure), so the wrapper records that
/// by nulling its pointer — never a double-delete.
pub(super) fn transact_write(
    vt: &Vtable,
    binder: *mut AIBinder,
    code: u32,
    writes: impl FnOnce(&ParcelWriter<'_>) -> Result<(), CoreError>,
) -> Result<OwnedParcel, CoreError> {
    let mut in_ptr: *mut AParcel = std::ptr::null_mut();
    let s = unsafe { (vt.prepare_transaction)(binder, &mut in_ptr) };
    if s != STATUS_OK {
        return Err(CoreError::binder(s, "AIBinder_prepareTransaction"));
    }
    let mut inp = OwnedParcel {
        ptr: in_ptr,
        delete: vt.parcel_delete,
    };
    {
        let writer = ParcelWriter::owned(vt, &inp);
        writes(&writer)?;
    }
    let mut out_ptr: *mut AParcel = std::ptr::null_mut();
    let s = unsafe { (vt.transact)(binder, code, &mut inp.ptr, &mut out_ptr, 0) };
    // The framework owns (and deletes) the input parcel from here.
    inp.ptr = std::ptr::null_mut();
    let out = OwnedParcel {
        ptr: out_ptr,
        delete: vt.parcel_delete,
    };
    if s != STATUS_OK {
        return Err(CoreError::binder(s, "AIBinder_transact"));
    }
    Ok(out)
}

/// Prepare an input parcel, run `writes`, then fire a fire-and-forget
/// transaction (`FLAG_ONEWAY`). The framework takes ownership of the input
/// parcel (deletes it), so the wrapper nulls its pointer — never a
/// double-delete. No reply parcel is produced or read.
pub(super) fn transact_oneway(
    vt: &Vtable,
    binder: *mut AIBinder,
    code: u32,
    writes: impl FnOnce(&ParcelWriter<'_>) -> Result<(), CoreError>,
) -> Result<(), CoreError> {
    let mut in_ptr: *mut AParcel = std::ptr::null_mut();
    let s = unsafe { (vt.prepare_transaction)(binder, &mut in_ptr) };
    if s != STATUS_OK {
        return Err(CoreError::binder(s, "AIBinder_prepareTransaction"));
    }
    let mut inp = OwnedParcel {
        ptr: in_ptr,
        delete: vt.parcel_delete,
    };
    {
        let writer = ParcelWriter::owned(vt, &inp);
        writes(&writer)?;
    }
    // `AIBinder_transact` requires a non-null `out` even for one-way calls —
    // it always allocates `*out = new AParcel(binder)`. The caller owns that
    // reply parcel and must delete it (it is only auto-deleted on error).
    let mut out_ptr: *mut AParcel = std::ptr::null_mut();
    let s = unsafe { (vt.transact)(binder, code, &mut inp.ptr, &mut out_ptr, FLAG_ONEWAY) };
    // The framework owns (and deletes) the input parcel from here.
    inp.ptr = std::ptr::null_mut();
    if !out_ptr.is_null() {
        unsafe { (vt.parcel_delete)(out_ptr) };
    }
    if s != STATUS_OK {
        return Err(CoreError::binder(s, "AIBinder_transact"));
    }
    Ok(())
}
// The callback resolves the per-binder eventfd through AIBinder_getUserData.
// The symbol address is process-wide, so it is cached once in a static.
pub(super) static GET_USER_DATA: std::sync::Mutex<
    Option<unsafe extern "C" fn(*const AIBinder) -> *mut c_void>,
> = std::sync::Mutex::new(None);

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

    fn alloc(length: i32) -> bool {
        let mut buf = StringBuf::new();
        let mut out: *mut c_char = std::ptr::null_mut();
        unsafe { string_alloc(&mut buf as *mut StringBuf as *mut c_void, length, &mut out) }
    }

    #[test]
    fn string_alloc_rejects_oversized() {
        assert!(!alloc(MAX_BINDER_STRING_LEN as i32 + 1));
    }

    #[test]
    fn string_alloc_accepts_null_marker_rejects_other_negative() {
        assert!(alloc(-1));
        assert!(!alloc(-2));
    }

    #[test]
    fn string_alloc_accepts_valid_len_and_nul_terminates() {
        let mut buf = StringBuf::new();
        let mut out: *mut c_char = std::ptr::null_mut();
        let ok = unsafe { string_alloc(&mut buf as *mut StringBuf as *mut c_void, 4, &mut out) };
        assert!(ok);
        assert!(!out.is_null());
        {
            let vec = unsafe { buf.0.as_mut_vec() };
            b"ABCD".iter().enumerate().for_each(|(i, &b)| vec[i] = b);
            vec[4] = 0;
        }
        assert_eq!(buf.finish().as_deref(), Some("ABCD"));
    }
}