cloudfox-coreshift-core 2.5.0

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
// 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;
pub(super) const EX_NONE: i32 = 0;
#[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;
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;
// ── 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;

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 ────────────────────────────────────────────────────────────────

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>,
}
// ── 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(super) struct OwnedBinder {
    pub(super) ptr: *mut AIBinder,
    pub(super) dec_strong: unsafe extern "C" fn(*mut AIBinder),
}
unsafe impl Send for OwnedBinder {}
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
        ),
    })
}
// ── ParcelReader ──────────────────────────────────────────────────────────

pub(super) struct ParcelReader<'a> {
    pub(super) vt: &'a Vtable,
    pub(super) parcel: &'a OwnedParcel,
}

impl<'a> ParcelReader<'a> {
    pub(super) fn read_i32(&self) -> Result<i32, CoreError> {
        let mut v = 0i32;
        let s = unsafe { (self.vt.read_int32)(self.parcel.ptr, &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(super) fn read_string(&self) -> Result<Option<String>, CoreError> {
        let mut buf = StringBuf::new();
        let s = unsafe {
            (self.vt.read_string)(
                self.parcel.ptr,
                &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())
    }
    pub(super) 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.ptr, &mut v) };
        if s != STATUS_OK {
            return Err(CoreError::binder(s, "AParcel_readFloat"));
        }
        Ok(v)
    }
    pub(super) 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.ptr, &mut v) };
        if s != STATUS_OK {
            return Err(CoreError::binder(s, "AParcel_readInt64"));
        }
        Ok(v)
    }
    pub(super) 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.ptr, &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)
    }
    /// Skip a `Parcel.readValue()` encoded value (Java `writeValue`).
    /// Wire: an i32 type tag, optionally followed by a length prefix and a
    /// payload per tag. Only the tags present in `DeviceProductInfo`
    /// (String/Integer/Parcelable/null) and its nested `ManufactureDate`
    /// must be handled; everything else is defensively rejected so a
    /// layout drift surfaces as a `display_info` 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_SIZE (26): 2×i32.
            26 => self.skip_i32s(2),
            // VAL_SIZEF (27): 2×f32.
            27 => {
                self.read_float()?;
                self.read_float()?;
                Ok(())
            }
            // VAL_PARCELABLE (4): length-prefixed — i32 tag, i32 body
            // length, then the parcelable (class name + fields). Lengths
            // are 4-byte aligned in practice; the ceiling is defensive.
            4 => {
                let len = self.read_i32()?;
                if len < 0 {
                    return Ok(());
                }
                self.skip_bytes(len as usize)
            }
            _ => Err(CoreError::binder(
                tag,
                "display_info:unsupported readValue tag",
            )),
        }
    }
    /// 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 ────────────────────────────────────────

pub(super) struct ParcelWriter<'a> {
    pub(super) vt: &'a Vtable,
    pub(super) parcel: &'a OwnedParcel,
}

impl<'a> ParcelWriter<'a> {
    pub(super) fn write_i32(&self, v: i32) -> Result<(), CoreError> {
        let s = unsafe { (self.vt.write_int32)(self.parcel.ptr, v) };
        if s != STATUS_OK {
            return Err(CoreError::binder(s, "AParcel_writeInt32"));
        }
        Ok(())
    }
    pub(super) fn write_strong_binder(&self, b: *mut AIBinder) -> Result<(), CoreError> {
        let s = unsafe { (self.vt.write_strong_binder)(self.parcel.ptr, b) };
        if s != STATUS_OK {
            return Err(CoreError::binder(s, "AParcel_writeStrongBinder"));
        }
        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 { vt, parcel: &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)
}
// 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"));
    }
}