cloudfox-coreshift-core 2.14.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
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
// 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/

//! ContentProvider handoff: resolve an app's exported provider through
//! `IActivityManager.getContentProviderExternal`, hand a service binder to it
//! via `IContentProvider.call("sendBinder", …)`, and release the provider.
//!
//! This is the mechanism that lets a shell-uid daemon push its serving binder
//! into a sandboxed app (the shaved Shizuku pattern, documented in
//! `docs/BINDER-EXEC-DILEMMA.md`). The caller pins the app's `uid` read out of
//! the provider's `ApplicationInfo` during the holder walk (no extra IPC) and
//! gates later transactions on it (decision 2B).
//!
//! Wire target is Android 14 / SDK 34 exclusively:
//!
//! - `getContentProviderExternal` tx code resolved fresh from
//!   `framework.jar` DEX (`TRANSACTION_getContentProviderExternal`).
//! - `removeContentProviderExternalAsUser` tx code resolved fresh from DEX —
//!   the live SDK 34 release method; the plain `removeContentProviderExternal`
//!   is deprecated there and takes an `IBinder` token, not a user id.
//! - `IContentProvider.call` is the stable compile-time constant 21
//!   (`CALL_TRANSACTION`).
//! - The request carries an `AttributionSource` (AIDL `start_size = 56` with
//!   all-null optionals) and a single-entry `Bundle` holding the service
//!   binder (`length = 56`, `VAL_IBINDER = 15`).
//!
//! Verified against AOSP generated `AttributionSourceState.java` (refs
//! `prebuilts/fullsdk/sources`): SDK 34 has **no** `deviceId` field and
//! serializes pid, uid, packageName, attributionTag, token,
//! renouncedPermissions, next — matching the layout below exactly. `deviceId`
//! (an `int`, not a `String`) only appears on SDK 35+, inserted between `uid`
//! and `packageName`; it is irrelevant for the SDK 34 target.

use super::sys::*;
use crate::CoreError;
use crate::android::dex;
use std::os::raw::{c_char, c_void};

// ── Interface constants ───────────────────────────────────────────────────

const AM_DESCRIPTOR: &[u8] = b"android.app.IActivityManager\0";
const ICP_DESCRIPTOR: &[u8] = b"android.content.IContentProvider\0";
const ACTIVITY_SERVICE: &[u8] = b"activity\0";
/// `IContentProvider.CALL_TRANSACTION` — `FIRST_CALL_TRANSACTION (1) + 20`.
const CALL_TRANSACTION: u32 = 21;
/// Android's `AID_APP_START`: the lowest uid assigned to installed apps.
/// A pinned app uid below this is never a real whitelisted manager.
const AID_APP_START: i32 = 10000;
/// `AttributionSourceState` AIDL `start_size` with pid/uid and all-null
/// optionals: size-int 4 + pid 4 + uid 4 + pkg-null 4 + tag-null 4 +
/// token-null 28 + renounced-null 4 + next-null 4 = 56. The reader lands
/// exactly on `authority` after `setDataPosition(start_pos + start_size)`.
///
/// The token-null is **28 bytes, not 24**: `Parcel::flattenBinder` writes
/// the 24-byte `flat_binder_object` (`writeObject`) and then a 4-byte
/// stability int32 (`finishFlattenBinder`). Both the writer (native
/// `writeStrongBinder`) and the reader (Java `readStrongBinder`) consume
/// the same 28 bytes — undercounting it shifts the whole request body by
/// 4 and the server then reads the bundle length from the wrong offset
/// (`IllegalStateException: Bundle length is not aligned by 4` →
/// `EX_ILLEGAL_STATE (-5)`).
const ATTRIBUTION_START_SIZE: i32 = 56;
/// `sendBinder` extras bundle — the `BaseBundle.writeToParcelInner` length
/// field for the single `{"binder": IBinder}` entry. `writeToParcelInner`
/// captures `startPos` after the magic, so `length = endPos - startPos`
/// excludes the magic (the reader consumes the length int, then the magic,
/// then advances by `length`): `N=1` 4 + String16 `"binder"` 20 (len-int 4
/// + 16 bytes: 14 UTF-16 bytes padded to 16) + `VAL_IBINDER` 4 + binder 28
/// (24-byte `flat_binder_object` + 4-byte stability int32, as above) = 56.
const BUNDLE_LENGTH: i32 = 56;
/// Bundle key under which the app reads the handed service binder.
const BUNDLE_KEY: &str = "binder";

// ── AIBinder_Class callbacks (client-only; no server side) ───────────────

unsafe extern "C" fn hf_on_create(_: *mut c_void) -> *mut c_void {
    std::ptr::null_mut()
}
unsafe extern "C" fn hf_on_destroy(_: *mut c_void) {}
unsafe extern "C" fn hf_on_transact(
    _: *mut AIBinder,
    _: u32,
    _: *const AParcel,
    _: *mut AParcel,
) -> BinderStatus {
    STATUS_UNKNOWN_TRANSACTION
}
// ── Holder-walk element skips ─────────────────────────────────────────────

/// `PatternMatcher`: `writeString(mPattern)` + `writeInt(mType)` +
/// `writeIntArray(mParsedPattern)`.
fn skip_pattern_matcher(r: &ParcelReader<'_>) -> Result<(), CoreError> {
    r.skip_string16()?;
    r.read_i32()?;
    r.skip_int_array()
}

/// `PathPermission`: `super` (PatternMatcher) + `writeString(readPermission)`
/// + `writeString(writePermission)`.
fn skip_path_permission(r: &ParcelReader<'_>) -> Result<(), CoreError> {
    skip_pattern_matcher(r)?;
    r.skip_string16()?;
    r.skip_string16().map(|_| ())
}

/// `SharedLibraryInfo`: `writeString8(mPath)`, `writeString8(mPackageName)`,
/// `writeInt(1)`+`writeString8Array(mCodePaths)` (or `writeInt(0)`),
/// `writeString8(mName)`, `writeLong(mVersion)`, `writeInt(mType)`,
/// `writeParcelable(mDeclaringPackage)` (VersionedPackage: String16 class
/// name + `writeString8` + `writeLong`), `writeList(mDependentPackages)`
/// (N×`writeValue`), `writeTypedList(mDependencies)` (VersionedPackage),
/// `writeBoolean(mIsNative)`.
fn skip_shared_library_info(r: &ParcelReader<'_>) -> Result<(), CoreError> {
    r.skip_string8()?;
    r.skip_string8()?;
    if r.read_i32()? == 1 {
        r.skip_string8_array()?;
    }
    r.skip_string8()?;
    r.read_int64()?;
    r.read_i32()?;
    // mDeclaringPackage (VersionedPackage) via writeParcelable.
    if r.skip_string16()? {
        r.skip_string8()?;
        r.read_int64()?;
    }
    // mDependentPackages via writeList: N × writeValue.
    let dep = r.read_i32()?;
    if dep >= 0 {
        for _ in 0..dep {
            r.skip_value()?;
        }
    }
    // mDependencies via writeTypedList: N × (marker + VersionedPackage).
    let deps = r.read_i32()?;
    if deps >= 0 {
        for _ in 0..deps {
            if r.read_i32()? == 1 {
                r.skip_string8()?;
                r.read_int64()?;
            }
        }
    }
    r.read_i32()?;
    Ok(())
}
// ── The ProviderInfo chain walk ───────────────────────────────────────────

/// Skip the `PackageItemInfo` block (`name`, `packageName`, `labelRes`,
/// `nonLocalizedLabel` CharSequence, `icon`, `logo`, `metaData` Bundle,
/// `banner`, `showUserIcon`) and return the holder's `packageName` — the
/// identity check that makes the authority→package trust chain auditable.
fn read_package_item_info(r: &ParcelReader<'_>) -> Result<String, CoreError> {
    r.skip_string8()?; // name
    let package_name = r.read_string8()?.unwrap_or_default(); // packageName
    r.read_i32()?;
    r.skip_char_sequence()?;
    r.read_i32()?;
    r.read_i32()?;
    r.skip_bundle()?;
    r.read_i32()?;
    r.read_i32()?;
    Ok(package_name)
}

/// Skip the `PackageItemInfo` block without capturing the package name.
fn skip_package_item_info(r: &ParcelReader<'_>) -> Result<(), CoreError> {
    let _ = read_package_item_info(r)?;
    Ok(())
}

/// Walk `ApplicationInfo.writeToParcel` field-by-field and return `uid`
/// (step 13). Follows docs/BINDER-EXEC-DILEMMA.md §3.6.1 exactly: every field
/// is a verified primitive, including the two Parcelling builtins (steps 16,
/// 20) and the hand-written `mAppClassNamesByProcess` SparseArray (step 18).
fn walk_application_info(r: &ParcelReader<'_>) -> Result<i32, CoreError> {
    // 1. maybeWriteSquashed — the reply parcel is never squash-rewound, so
    //    the marker must be 0; anything else means "skip to earlier position"
    //    and cannot be honored.
    if r.read_i32()? != 0 {
        return Err(CoreError::binder(-1, "handoff:squashed_application_info"));
    }
    // 2. super — PackageItemInfo block.
    skip_package_item_info(r)?;
    // 3. taskAffinity, permission, processName, className.
    r.skip_string8()?;
    r.skip_string8()?;
    r.skip_string8()?;
    r.skip_string8()?;
    // 4. theme, flags, privateFlags, privateFlagsExt,
    //    requiresSmallestWidthDp, compatibleWidthLimitDp, largestWidthLimitDp.
    r.skip_i32s(7)?;
    // 5. storageUuid: writeInt(0) or writeInt(1) + 2×writeLong.
    if r.read_i32()? == 1 {
        r.read_int64()?;
        r.read_int64()?;
    }
    // 6. scanSourceDir, scanPublicSourceDir, sourceDir, publicSourceDir.
    r.skip_string8()?;
    r.skip_string8()?;
    r.skip_string8()?;
    r.skip_string8()?;
    // 7. splitNames, splitSourceDirs, splitPublicSourceDirs.
    r.skip_string8_array()?;
    r.skip_string8_array()?;
    r.skip_string8_array()?;
    // 8. splitDependencies — SparseArray<int[]>.
    r.skip_sparsearray()?;
    // 9. nativeLibraryDir, secondaryNativeLibraryDir, nativeLibraryRootDir,
    //    nativeLibraryRootRequiresIsa, primaryCpuAbi, secondaryCpuAbi.
    r.skip_string8()?;
    r.skip_string8()?;
    r.skip_string8()?;
    r.read_i32()?;
    r.skip_string8()?;
    r.skip_string8()?;
    // 10. resourceDirs, overlayPaths, seInfo, seInfoUser, sharedLibraryFiles.
    r.skip_string8_array()?;
    r.skip_string8_array()?;
    r.skip_string8()?;
    r.skip_string8()?;
    r.skip_string8_array()?;
    // 11. sharedLibraryInfos — List<SharedLibraryInfo>.
    r.skip_typed_object_array(skip_shared_library_info)?;
    // 12. dataDir, deviceProtectedDataDir, credentialProtectedDataDir.
    r.skip_string8()?;
    r.skip_string8()?;
    r.skip_string8()?;
    // 13. uid — the pinned-uid source. This is a security gate: a walk that
    // drifted off the real field layout would otherwise yield a plausible-wrong
    // uid and the caller would pin the wrong app. Sanity-check the value
    // against the installed-app range: Android assigns app uids ≥ 10000
    // (AID_APP_START); a value below that (or negative) can only come from a
    // desynced walk, never from a real whitelisted manager app.
    let uid = r.read_i32()?;
    if uid < AID_APP_START {
        return Err(CoreError::binder(-1, "handoff:uid_out_of_range"));
    }
    // 14. minSdkVersion, targetSdkVersion, longVersionCode, enabled,
    //     enabledSetting, installLocation, manageSpaceActivityName,
    //     backupAgentName, descriptionRes, uiOptions, fullBackupContent,
    //     dataExtractionRulesRes.
    r.read_i32()?;
    r.read_i32()?;
    r.read_int64()?;
    r.read_i32()?;
    r.read_i32()?;
    r.read_i32()?;
    r.skip_string8()?;
    r.skip_string8()?;
    r.read_i32()?;
    r.read_i32()?;
    r.read_i32()?;
    r.read_i32()?;
    // 15. crossProfile, networkSecurityConfigRes, category,
    //     targetSandboxVersion, classLoaderName, splitClassLoaderNames,
    //     compileSdkVersion, compileSdkVersionCodename, appComponentFactory,
    //     iconRes, roundIconRes, mHiddenApiPolicy, hiddenUntilInstalled,
    //     zygotePreloadName, gwpAsanMode, memtagMode,
    //     nativeHeapZeroInitialized.
    r.read_i32()?;
    r.read_i32()?;
    r.read_i32()?;
    r.read_i32()?;
    r.skip_string8()?;
    r.skip_string8_array()?;
    r.read_i32()?;
    r.skip_string8()?;
    r.skip_string8()?;
    r.read_i32()?;
    r.read_i32()?;
    r.read_i32()?;
    r.read_i32()?;
    r.skip_string8()?;
    r.read_i32()?;
    r.read_i32()?;
    r.read_i32()?;
    // 16. sForBoolean.parcel(requestRawExternalStorageAccess) — one int
    //     (1 = null, 0 = false, -1 = true); a single read consumes it.
    r.read_i32()?;
    // 17. writeLong(createTimestamp).
    r.read_int64()?;
    // 18. mAppClassNamesByProcess — writeInt(0) null, else N ×
    //     (writeString + writeString); both are String16.
    let names = r.read_i32()?;
    if names > 0 {
        for _ in 0..names {
            r.skip_string16()?;
            r.skip_string16()?;
        }
    }
    // 19. writeInt(localeConfigRes).
    r.read_i32()?;
    // 20. sForStringSet.parcel(mKnownActivityEmbeddingCerts) — writeInt(-1)
    //     null, else N × writeString (String16).
    let certs = r.read_i32()?;
    if certs >= 0 {
        for _ in 0..certs {
            r.skip_string16()?;
        }
    }
    Ok(uid)
}

/// Walk the full `ProviderInfo` chain (`PackageItemInfo` →
/// `ApplicationInfo` → `ComponentInfo` tail → `ProviderInfo` tail), then read
/// the `ContentProviderHolder` tail. Returns `(provider, connection, uid,
/// noReleaseNeeded, mLocal)`.
#[allow(clippy::type_complexity)]
fn walk_holder(
    r: &ParcelReader<'_>,
) -> Result<
    (
        Option<OwnedBinder>,
        Option<OwnedBinder>,
        i32,
        bool,
        bool,
        String,
    ),
    CoreError,
> {
    // ComponentInfo → super (PackageItemInfo), then applicationInfo
    // (ApplicationInfo, direct writeToParcel — no class-name prefix). The
    // holder's `packageName` is the identity used to verify the resolved
    // provider really belongs to the whitelisted package.
    let package_name = read_package_item_info(r)?;
    let uid = walk_application_info(r)?;
    r.skip_string8()?; // processName
    r.skip_string8()?; // splitName
    r.skip_string8_array()?; // attributionTags
    r.read_i32()?; // descriptionRes
    r.read_i32()?; // enabled
    r.read_i32()?; // exported
    r.read_i32()?; // directBootAware
    // ProviderInfo tail.
    r.skip_string8()?; // authority
    r.skip_string8()?; // readPermission
    r.skip_string8()?; // writePermission
    r.read_i32()?; // grantUriPermissions
    r.read_i32()?; // forceUriPermissions
    r.skip_typed_object_array(skip_pattern_matcher)?; // uriPermissionPatterns
    r.skip_typed_object_array(skip_path_permission)?; // pathPermissions
    r.read_i32()?; // multiprocess
    r.read_i32()?; // initOrder
    r.read_i32()?; // flags
    r.read_i32()?; // isSyncable
    // ContentProviderHolder tail.
    let provider = r.read_strong_binder()?;
    let connection = r.read_strong_binder()?;
    let no_release_needed = r.read_i32()? != 0;
    let m_local = r.read_i32()? != 0;
    Ok((
        provider,
        connection,
        uid,
        no_release_needed,
        m_local,
        package_name,
    ))
}
// ── Handoff ───────────────────────────────────────────────────────────────

/// The resolved content-provider holder: the `IContentProvider` binder to
/// call, the connection binder to release, and the app's pinned uid read from
/// `ApplicationInfo.uid` during the walk (no extra IPC).
pub struct ProviderHandle {
    /// The `IContentProvider` proxy (class associated). Dropping releases the
    /// strong ref.
    pub provider: OwnedBinder,
    /// The holder's connection binder, held for release accounting.
    pub connection: OwnedBinder,
    /// The app's `ApplicationInfo.uid` — the per-transaction pin (2B).
    pub uid: i32,
    /// `ContentProviderHolder.noReleaseNeeded`: when true the caller must NOT
    /// call `removeContentProviderExternalAsUser`.
    pub no_release_needed: bool,
    /// The holder's `PackageItemInfo.packageName`, read during the walk. The
    /// identity that binds the resolved provider to the whitelisted package —
    /// handoff verifies this against the expected package rather than trusting
    /// the authority string alone.
    pub package_name: String,
}

/// ContentProvider handoff client.
///
/// Owns the `dlopen`ed `libbinder_ndk.so`, the `IActivityManager` and
/// `IContentProvider` class definitions, the `"activity"` service proxy, and
/// the DEX-resolved tx codes for the handoff lifecycle.
pub struct Handoff {
    _lib: DlHandle,
    vt: Vtable,
    _am_class: *mut AIBinder_Class,
    _icp_class: *mut AIBinder_Class,
    service: OwnedBinder,
    get_code: u32,
    remove_code: u32,
}
unsafe impl Send for Handoff {}

impl Handoff {
    /// Open the handoff client: resolve `getContentProviderExternal` and
    /// `removeContentProviderExternalAsUser` tx codes from the installed
    /// `framework.jar` and bind the `"activity"` service.
    pub fn open() -> Result<Self, CoreError> {
        let handle = unsafe {
            libc::dlopen(
                LIBBINDER_PATH.as_ptr() as *const c_char,
                libc::RTLD_NOW | libc::RTLD_LOCAL,
            )
        };
        if handle.is_null() {
            return Err(CoreError::binder(-1, "dlopen:libbinder_ndk.so"));
        }
        let lib = DlHandle;
        let vt = load_vtable(handle)?;

        let am_class = unsafe {
            (vt.class_define)(
                AM_DESCRIPTOR.as_ptr() as *const c_char,
                hf_on_create,
                hf_on_destroy,
                hf_on_transact,
            )
        };
        if am_class.is_null() {
            return Err(CoreError::binder(-1, "AIBinder_Class_define:AM"));
        }
        let icp_class = unsafe {
            (vt.class_define)(
                ICP_DESCRIPTOR.as_ptr() as *const c_char,
                hf_on_create,
                hf_on_destroy,
                hf_on_transact,
            )
        };
        if icp_class.is_null() {
            return Err(CoreError::binder(
                -1,
                "AIBinder_Class_define:IContentProvider",
            ));
        }

        let raw = unsafe { (vt.get_service)(ACTIVITY_SERVICE.as_ptr() as *const c_char) };
        if raw.is_null() {
            return Err(CoreError::binder(-1, "AServiceManager_getService:activity"));
        }
        unsafe { (vt.associate_class)(raw, am_class) };
        let service = OwnedBinder {
            ptr: raw,
            dec_strong: vt.dec_strong,
        };

        let (get_code, remove_code) = dex::resolve_handoff_codes()
            .ok_or_else(|| CoreError::binder(-1, "handoff:tx_code_resolution:dex_parse_failed"))?;

        Ok(Self {
            _lib: lib,
            vt,
            _am_class: am_class,
            _icp_class: icp_class,
            service,
            get_code,
            remove_code,
        })
    }

    /// Resolve `authority` for `user_id` and walk the holder reply. The
    /// returned [`ProviderHandle`] carries the app's pinned `uid` and the
    /// `IContentProvider` proxy with the class already associated so
    /// [`Handoff::send_binder`] can transact it directly.
    pub fn acquire_provider(
        &self,
        authority: &str,
        user_id: i32,
    ) -> Result<ProviderHandle, CoreError> {
        let out = transact_write(&self.vt, self.service.ptr, self.get_code, |w| {
            w.write_string(Some(authority))?;
            w.write_i32(user_id)?;
            w.write_strong_binder(std::ptr::null_mut())?;
            w.write_string(Some(authority))
        })?;
        let r = ParcelReader::owned(&self.vt, &out);
        let ex = r.read_i32()?;
        if ex != EX_NONE {
            return Err(CoreError::binder(
                ex,
                "getContentProviderExternal:exception",
            ));
        }
        // writeTypedObject marker: 1 = holder present, 0 = null.
        if r.read_i32()? != 1 {
            return Err(CoreError::binder(
                -1,
                "getContentProviderExternal:no_holder",
            ));
        }
        let (provider, connection, uid, no_release_needed, _m_local, package_name) =
            walk_holder(&r)?;
        let provider = provider
            .ok_or_else(|| CoreError::binder(-1, "getContentProviderExternal:null_provider"))?;
        // Associate the IContentProvider class so AIBinder_prepareTransaction
        // writes the interface token on the call transaction.
        unsafe { (self.vt.associate_class)(provider.ptr, self._icp_class) };
        let connection = connection.unwrap_or_else(|| OwnedBinder {
            ptr: std::ptr::null_mut(),
            dec_strong: self.vt.dec_strong,
        });
        Ok(ProviderHandle {
            provider,
            connection,
            uid,
            no_release_needed,
            package_name,
        })
    }

    /// Send one `IContentProvider.call(method, arg, extras{binder})` on an
    /// acquired provider. `service_binder` is the raw `AIBinder*` to hand off
    /// (e.g. [`crate::binder::ServingBinder::as_raw`]). The request carries an
    /// `AttributionSource` (`start_size = 56`) and a single-entry `Bundle`
    /// (`length = 56`, key `"binder"`, `VAL_IBINDER = 15`).
    pub fn send_binder(
        &self,
        handle: &ProviderHandle,
        authority: &str,
        method: &str,
        arg: &str,
        service_binder: *mut c_void,
    ) -> Result<(), CoreError> {
        // The server-side `AttributionSource` constructor runs
        // `enforceCallingUid()`, comparing the written uid against
        // `Binder.getCallingUid()` (the daemon's effective uid on the current
        // transaction). Use the live euid — never a hardcoded constant — so
        // the handoff works regardless of whether the daemon runs as root,
        // shell, or a dedicated uid.
        let euid = unsafe { libc::geteuid() } as i32;
        let out = transact_write(&self.vt, handle.provider.ptr, CALL_TRANSACTION, |w| {
            // AttributionSource (pid, uid, all-null optionals).
            w.write_i32(ATTRIBUTION_START_SIZE)?;
            w.write_i32(-1)?; // pid
            w.write_i32(euid)?; // uid
            w.write_string(None)?; // packageName
            w.write_string(None)?; // attributionTag
            w.write_strong_binder(std::ptr::null_mut())?; // token
            w.write_i32(-1)?; // renouncedPermissions null
            w.write_i32(-1)?; // next null
            // call(authority, method, arg, extras).
            w.write_string(Some(authority))?;
            w.write_string(Some(method))?;
            w.write_string(Some(arg))?;
            // extras bundle: single entry { "binder": IBinder }.
            w.write_i32(BUNDLE_LENGTH)?;
            w.write_i32(BUNDLE_MAGIC)?;
            w.write_i32(1)?;
            w.write_string(Some(BUNDLE_KEY))?;
            w.write_i32(VAL_IBINDER)?;
            w.write_strong_binder(service_binder)
        })?;
        let r = ParcelReader::owned(&self.vt, &out);
        let ex = r.read_i32()?;
        if ex != EX_NONE {
            return Err(CoreError::binder(ex, "call:exception"));
        }
        Ok(())
    }

    /// Release a previously acquired provider: `removeContentProviderExternal
    /// AsUser(name, token, userId)`. Must be paired with each successful
    /// acquire unless the holder set `noReleaseNeeded`.
    pub fn remove_provider(&self, authority: &str, user_id: i32) -> Result<(), CoreError> {
        let out = transact_write(&self.vt, self.service.ptr, self.remove_code, |w| {
            w.write_string(Some(authority))?;
            w.write_strong_binder(std::ptr::null_mut())?;
            w.write_i32(user_id)
        })?;
        let r = ParcelReader::owned(&self.vt, &out);
        let ex = r.read_i32()?;
        if ex != EX_NONE {
            return Err(CoreError::binder(
                ex,
                "removeContentProviderExternalAsUser:exception",
            ));
        }
        Ok(())
    }

    /// Full handoff in one call: acquire the provider for `authority`, verify
    /// the resolved holder's `packageName` is `expected_package` (rejecting a
    /// squatted authority that resolves to a different app), send
    /// `service_binder` via `call(method, arg, extras{binder})`, then release
    /// (unless `noReleaseNeeded`). Returns the app's pinned `uid`.
    pub fn handoff(
        &self,
        expected_package: &str,
        authority: &str,
        user_id: i32,
        method: &str,
        arg: &str,
        service_binder: *mut c_void,
    ) -> Result<i32, CoreError> {
        let handle = self.acquire_provider(authority, user_id)?;
        // Identity check before any binder is handed over: the authority
        // string is caller-supplied and could be squatted by another package;
        // only a provider whose PackageItemInfo.packageName matches the
        // whitelisted package receives the daemon's serving binder.
        if handle.package_name != expected_package {
            return Err(CoreError::binder(-1, "handoff:package_mismatch"));
        }
        let result = self.send_binder(&handle, authority, method, arg, service_binder);
        // Release duty is unconditional on a successful acquire (even if the
        // call itself failed), mirroring the Shizuku try/finally.
        if !handle.no_release_needed {
            let _ = self.remove_provider(authority, user_id);
        }
        result?;
        Ok(handle.uid)
    }
}