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

//! ActivityManager binder client.
//!
//! Focused-task queries (`getFocusedRootTaskInfo` / legacy `StackInfo`), the
//! `IProcessObserver` / `IForegroundProcessObserver` foreground sources, and
//! DEX-resolved transaction codes.

use super::sys::*;
use crate::CoreError;
use crate::android::dex;
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::os::raw::{c_char, c_void};
use std::sync::Mutex;
use std::sync::atomic::{AtomicI32, AtomicU32, AtomicU64, AtomicUsize, Ordering};

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

const AM_DESCRIPTOR: &[u8] = b"android.app.IActivityManager\0";
const OBS_DESCRIPTOR: &[u8] = b"android.app.IProcessObserver\0";
const FGPROC_DESCRIPTOR: &[u8] = b"android.app.IForegroundProcessObserver\0";
const UID_OBS_DESCRIPTOR: &[u8] = b"android.app.IUidObserver\0";
const ACTIVITY_SERVICE: &[u8] = b"activity\0";
// ── Tx code cache ─────────────────────────────────────────────────────────
// Format (watcher.c compatible): observer_code query_code api_mode fg_code
// api_mode: 1 = getFocusedRootTaskInfo, 2 = getFocusedStackInfo (API 29)

// ── Statics for observer callback (binder thread pool context) ────────────
// The core owns the eventfd for the observer lifetime; the consumer receives
// a dup and may close it freely. The callback only ever writes to the core's
// copy, so it can never touch a closed/recycled fd (C2). The mutex guards
// publication/revocation against a callback firing concurrently.

static OBS_FG_CODE: AtomicU32 = AtomicU32::new(0);
static OBS_EVENTFD: Mutex<Option<OwnedFd>> = Mutex::new(None);

fn obs_eventfd_guard() -> std::sync::MutexGuard<'static, Option<OwnedFd>> {
    OBS_EVENTFD.lock().unwrap_or_else(|p| p.into_inner())
}

// ── IForegroundProcessObserver statics ───────────────────────────────────
// Separate from the IProcessObserver pair; same C2 discipline (core owns
// the eventfd, consumer gets a dup). FGPROC_READ_I32 holds the vtable's
// AParcel_readInt32 fn pointer so the callback can decode the `int pid`
// argument without owning the Vtable; it is published (non-zero) before
// FGPROC_FG_CODE/eventfd, so the callback never races an unset reader.

static FGPROC_FG_CODE: AtomicU32 = AtomicU32::new(0);
static FGPROC_PID: AtomicI32 = AtomicI32::new(0);
static FGPROC_EVENTFD: Mutex<Option<OwnedFd>> = Mutex::new(None);
static FGPROC_READ_I32: AtomicUsize = AtomicUsize::new(0);
// Binder class mode: 0 = stock IForegroundProcessObserver (single int pid),
// 1 = custom IProcessObserver (pid, uid, fg triplets). Only one of the two
// is ever configured by open_with_fgproc_observer; the callback branches on
// this to decode the in-parcel layout it actually receives.
static FGPROC_IPROC_MODE: AtomicU32 = AtomicU32::new(0);

fn fgproc_eventfd_guard() -> std::sync::MutexGuard<'static, Option<OwnedFd>> {
    FGPROC_EVENTFD.lock().unwrap_or_else(|p| p.into_inner())
}

// ── IUidObserver statics ────────────────────────────────────────────────
// Same C2 discipline: core owns the eventfd, consumer gets a dup. All six
// callback tx codes are published so the callback can dispatch on code and
// decode the leading `int uid` from each parcel layout:
//   onUidGone(uid, disabled)          onUidActive(uid)
//   onUidIdle(uid, disabled)          onUidCachedChanged(uid, cached)
//   onUidStateChanged(uid, state, seq, cap)  onUidProcAdjChanged(uid, adj)
// UID_LAST_UID holds the most recent uid; UID_LAST_KIND is 0=gone, 1=active,
// 2=idle, 3=cached, 4=state, 5=adj. Only events for the daemon's pinned uid
// are actionable, so the consumer filters on `uid == pinned_uid`.
//
// Both are packed into one atomic so a consumer reading on the eventfd wake
// always observes a consistent `(uid, kind)` pair — two separate atomics could
// be read as a new-uid + old-kind mix and misclassify the event.

static UID_GONE_CODE: AtomicU32 = AtomicU32::new(0);
static UID_ACTIVE_CODE: AtomicU32 = AtomicU32::new(0);
static UID_IDLE_CODE: AtomicU32 = AtomicU32::new(0);
static UID_CACHED_CODE: AtomicU32 = AtomicU32::new(0);
static UID_STATE_CODE: AtomicU32 = AtomicU32::new(0);
static UID_ADJ_CODE: AtomicU32 = AtomicU32::new(0);
/// Low 32 bits: the most recent callback uid (raw `i32` bit pattern; the `-1`
/// "none" sentinel is preserved). High 32 bits: the event kind (0=gone,
/// 1=active, 2=idle, 3=cached, 4=state, 5=adj). Packed so `last_uid_event`
/// reads one consistent value.
static UID_LAST_EVENT: AtomicU64 = AtomicU64::new(0x0000_0000_FFFF_FFFF); // uid=-1, kind=0
static UID_EVENTFD: Mutex<Option<OwnedFd>> = Mutex::new(None);
static UID_READ_I32: AtomicUsize = AtomicUsize::new(0);

fn uid_eventfd_guard() -> std::sync::MutexGuard<'static, Option<OwnedFd>> {
    UID_EVENTFD.lock().unwrap_or_else(|p| p.into_inner())
}
// ── AIBinder_Class callbacks ──────────────────────────────────────────────

// AM client — no-op server side (we're a client only)
unsafe extern "C" fn am_on_create(_: *mut c_void) -> *mut c_void {
    std::ptr::null_mut()
}
unsafe extern "C" fn am_on_destroy(_: *mut c_void) {}
unsafe extern "C" fn am_on_transact(
    _: *mut AIBinder,
    _: u32,
    _: *const AParcel,
    _: *mut AParcel,
) -> BinderStatus {
    STATUS_UNKNOWN_TRANSACTION
}

// IProcessObserver server callbacks
unsafe extern "C" fn obs_on_create(_: *mut c_void) -> *mut c_void {
    std::ptr::null_mut()
}
unsafe extern "C" fn obs_on_destroy(_: *mut c_void) {}
unsafe extern "C" fn obs_on_transact(
    _: *mut AIBinder,
    code: u32,
    _: *const AParcel,
    _: *mut AParcel,
) -> BinderStatus {
    if code == OBS_FG_CODE.load(Ordering::Relaxed) {
        // Write while holding the lock: the fd can only be closed while
        // we hold it, so a revoke can never race us into a stale number.
        if let Some(fd) = obs_eventfd_guard().as_ref() {
            let val: u64 = 1;
            unsafe { libc::write(fd.as_raw_fd(), &val as *const u64 as *const c_void, 8) };
        }
    }
    STATUS_OK
}

// IForegroundProcessObserver server callbacks. Two parcel layouts, selected
// by FGPROC_IPROC_MODE:
//  - mode 0 (stock): `onForegroundProcessChanged(int pid)` — single int32.
//  - mode 1 (custom ROMs without IForegroundProcessObserver): the ROM
//    repurposes `IProcessObserver.onForegroundActivitiesChanged` to deliver
//    `(int pid, int uid, int fg)`. The callback stores the pid and only
//    signals the eventfd when fg != 0 (a foreground transition), so
//    background transitions never cause the daemon to react.
unsafe extern "C" fn fgproc_on_create(_: *mut c_void) -> *mut c_void {
    std::ptr::null_mut()
}
unsafe extern "C" fn fgproc_on_destroy(_: *mut c_void) {}
unsafe extern "C" fn fgproc_on_transact(
    _: *mut AIBinder,
    code: u32,
    in_parcel: *const AParcel,
    _: *mut AParcel,
) -> BinderStatus {
    if code != FGPROC_FG_CODE.load(Ordering::Relaxed) {
        return STATUS_UNKNOWN_TRANSACTION;
    }
    // Read fn is published non-zero before the code/eventfd, so a matching
    // code is never paired with an unset reader.
    let read_addr = FGPROC_READ_I32.load(Ordering::Relaxed);
    if read_addr != 0 {
        let read_fn: unsafe extern "C" fn(*const AParcel, *mut i32) -> BinderStatus =
            unsafe { std::mem::transmute(read_addr) };
        if FGPROC_IPROC_MODE.load(Ordering::Relaxed) == 1 {
            // IProcessObserver.onForegroundActivitiesChanged(pid, uid, fg)
            let mut pid: i32 = 0;
            let mut _uid: i32 = 0;
            let mut fg: i32 = 0;
            let mut ok = unsafe { read_fn(in_parcel, &mut pid) } == STATUS_OK;
            ok &= unsafe { read_fn(in_parcel, &mut _uid) } == STATUS_OK;
            ok &= unsafe { read_fn(in_parcel, &mut fg) } == STATUS_OK;
            if ok {
                FGPROC_PID.store(pid, Ordering::Relaxed);
                // Only foreground transitions are actionable; suppress the
                // background transition entirely (fg == 0).
                if fg == 0 {
                    return STATUS_OK;
                }
            } else {
                return STATUS_OK;
            }
        } else {
            let mut pid: i32 = 0;
            if unsafe { read_fn(in_parcel, &mut pid) } == STATUS_OK {
                FGPROC_PID.store(pid, Ordering::Relaxed);
            }
        }
    }
    // Write while holding the lock: the fd can only be closed while we
    // hold it, so a revoke can never race us into a stale number.
    if let Some(fd) = fgproc_eventfd_guard().as_ref() {
        let val: u64 = 1;
        unsafe { libc::write(fd.as_raw_fd(), &val as *const u64 as *const c_void, 8) };
    }
    STATUS_OK
}

// IUidObserver server callbacks. Every callback's leading parcel field is the
// `int uid`; UID_READ_I32 is published (non-zero) before the callback codes
// and eventfd, so a matching code is never paired with an unset reader.
unsafe extern "C" fn uid_obs_on_create(_: *mut c_void) -> *mut c_void {
    std::ptr::null_mut()
}
unsafe extern "C" fn uid_obs_on_destroy(_: *mut c_void) {}
unsafe extern "C" fn uid_obs_on_transact(
    _: *mut AIBinder,
    code: u32,
    in_parcel: *const AParcel,
    _: *mut AParcel,
) -> BinderStatus {
    let kind = if code == UID_GONE_CODE.load(Ordering::Relaxed) {
        Some(0u32)
    } else if code == UID_ACTIVE_CODE.load(Ordering::Relaxed) {
        Some(1u32)
    } else if code == UID_IDLE_CODE.load(Ordering::Relaxed) {
        Some(2u32)
    } else if code == UID_CACHED_CODE.load(Ordering::Relaxed) {
        Some(3u32)
    } else if code == UID_STATE_CODE.load(Ordering::Relaxed) {
        Some(4u32)
    } else if code == UID_ADJ_CODE.load(Ordering::Relaxed) {
        Some(5u32)
    } else {
        None
    };
    let kind = match kind {
        Some(k) => k,
        None => return STATUS_UNKNOWN_TRANSACTION,
    };

    let read_addr = UID_READ_I32.load(Ordering::Relaxed);
    if read_addr != 0 {
        let read_fn: unsafe extern "C" fn(*const AParcel, *mut i32) -> BinderStatus =
            unsafe { std::mem::transmute(read_addr) };
        let mut uid: i32 = 0;
        if unsafe { read_fn(in_parcel, &mut uid) } == STATUS_OK {
            // Pack uid + kind into one atomic so a consumer never reads a
            // torn pair (new uid with an old kind from a previous event).
            let packed = (u64::from(kind) << 32) | u64::from(uid as u32);
            UID_LAST_EVENT.store(packed, Ordering::Release);
        }
    }

    // Write while holding the lock: the fd can only be closed while we
    // hold it, so a revoke can never race us into a stale number.
    if let Some(fd) = uid_eventfd_guard().as_ref() {
        let val: u64 = 1;
        unsafe { libc::write(fd.as_raw_fd(), &val as *const u64 as *const c_void, 8) };
    }
    STATUS_OK
}

/// The `(uid, kind)` captured by the most recent `IUidObserver` callback
/// (requires `open_with_uid_observer`). `kind`: 0=gone, 1=active, 2=idle,
/// 3=cached, 4=state, 5=adj. Consumers filter on their pinned uid.
pub fn last_uid_event() -> (i32, u32) {
    let packed = UID_LAST_EVENT.load(Ordering::Acquire);
    (packed as u32 as i32, (packed >> 32) as u32)
}

/// The PID captured by the most recent `onForegroundProcessChanged`
/// callback (requires `open_with_fgproc_observer`).
pub fn last_foreground_pid() -> i32 {
    FGPROC_PID.load(Ordering::Relaxed)
}
// ── Response parsers ──────────────────────────────────────────────────────

fn parse_stack_info_body(r: &ParcelReader<'_>) -> Result<Option<String>, CoreError> {
    r.skip_i32s(5)?;
    r.skip_int_array()?;
    r.read_first_package_from_names()
}

// RootTaskInfo → (taskId, first childTaskName package). Walks the parcel
// once: prefix (bounds, childTaskIds), captures the first package from
// childTaskNames, then skips childTaskBounds / childTaskUserIds / visible /
// position / TaskInfo.userId to reach taskId — never touching the
// Intent/TaskInfo tail. taskId and pkg come from the same transaction, so
// callers pair them without a second (racy) round-trip.
fn parse_root_task_info_task(r: &ParcelReader<'_>) -> Result<(i32, Option<String>), CoreError> {
    let scratch = r.read_i32()?;
    if scratch != 0 {
        r.skip_i32s(4)?;
    }
    r.skip_int_array()?; // childTaskIds
    let pkg = r.read_first_package_from_names()?; // childTaskNames → pkg
    // childTaskBounds: typed Rect array (nullable) — read count, skip 4 per entry
    let bounds_count = r.read_i32()?;
    let n = if bounds_count < 0 {
        0
    } else {
        bounds_count as usize
    };
    for _ in 0..n {
        let entry = r.read_i32()?;
        if entry != 0 {
            r.skip_i32s(4)?;
        }
    }
    r.skip_int_array()?; // childTaskUserIds
    r.skip_i32s(2)?; // visible, position
    r.skip_i32s(1)?; // TaskInfo.userId
    let task_id = r.read_i32()?;
    Ok((task_id, pkg))
}
// ── Tx code resolution ────────────────────────────────────────────────────

pub struct TxCodes {
    pub observer_code: u32,
    pub query_code: u32,
    pub api_mode: u8, // 1 = RootTaskInfo, 2 = StackInfo
    pub fg_code: u32,
}

pub fn resolve_tx_codes() -> Result<TxCodes, CoreError> {
    let (obs, query, api, fg) = dex::resolve_tx_codes_from_dex()
        .ok_or_else(|| CoreError::binder(-1, "tx_code_resolution:dex_parse_failed"))?;
    Ok(TxCodes {
        observer_code: obs,
        query_code: query,
        api_mode: api,
        fg_code: fg,
    })
}
// ── ActivityManager ─────────────────────────────────────────────────

pub struct ActivityManager {
    _lib: DlHandle,
    vt: Vtable,
    _class: *mut AIBinder_Class,
    service: OwnedBinder,
    tx_code: u32,
    legacy: bool,
}
unsafe impl Send for ActivityManager {}

impl ActivityManager {
    fn open_inner(
        handle: *mut c_void,
    ) -> Result<(DlHandle, Vtable, *mut AIBinder_Class, OwnedBinder), CoreError> {
        let lib = DlHandle;
        let vt = load_vtable(handle)?;

        let am_class = unsafe {
            (vt.class_define)(
                AM_DESCRIPTOR.as_ptr() as *const c_char,
                am_on_create,
                am_on_destroy,
                am_on_transact,
            )
        };
        if am_class.is_null() {
            return Err(CoreError::binder(-1, "AIBinder_Class_define:AM"));
        }

        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,
        };
        Ok((lib, vt, am_class, service))
    }

    fn dlopen_libbinder() -> Result<*mut c_void, CoreError> {
        use std::os::raw::c_char;
        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"));
        }
        Ok(handle)
    }

    /// Open ActivityManager binder (polling mode — no observer).
    /// Resolves the query tx code from cache or DEX.
    pub fn open() -> Result<Self, CoreError> {
        let handle = Self::dlopen_libbinder()?;
        let (lib, vt, class, service) = Self::open_inner(handle)?;
        let codes = resolve_tx_codes()?;
        let legacy = codes.api_mode == 2;
        Ok(Self {
            _lib: lib,
            vt,
            _class: class,
            service,
            tx_code: codes.query_code,
            legacy,
        })
    }

    /// Open ActivityManager binder and register as IProcessObserver.
    ///
    /// Returns `(Self, OwnedFd)` where the eventfd is a dup of the core's
    /// callback fd. It becomes readable whenever `onForegroundActivitiesChanged`
    /// fires. Caller must add it to epoll and may close it at any time — the
    /// callback keeps writing to the core's copy, so closing the returned
    /// fd never invalidates the notification path (C2). After the event
    /// fires, call `get_focused_package`.
    pub fn open_with_observer() -> Result<(Self, OwnedFd), CoreError> {
        let handle = Self::dlopen_libbinder()?;
        let (lib, vt, am_class, service) = Self::open_inner(handle)?;
        let codes = resolve_tx_codes()?;
        let legacy = codes.api_mode == 2;

        // Create eventfd for callback → epoll bridge. Ownership stays in the
        // core for the observer lifetime; the consumer receives a dup below.
        let owned = unsafe {
            let raw = libc::eventfd(0, libc::EFD_NONBLOCK | libc::EFD_CLOEXEC);
            if raw < 0 {
                return Err(CoreError::sys(*libc::__errno(), "eventfd"));
            }
            OwnedFd::from_raw_fd(raw)
        };

        // Define IProcessObserver class (we're the server)
        let obs_class = unsafe {
            (vt.class_define)(
                OBS_DESCRIPTOR.as_ptr() as *const c_char,
                obs_on_create,
                obs_on_destroy,
                obs_on_transact,
            )
        };
        if obs_class.is_null() {
            return Err(CoreError::binder(-1, "AIBinder_Class_define:Observer"));
        }

        // Instantiate our observer binder object
        let obs_binder = unsafe { (vt.new_binder)(obs_class, std::ptr::null_mut()) };
        if obs_binder.is_null() {
            return Err(CoreError::binder(-1, "AIBinder_new:Observer"));
        }
        unsafe { (vt.associate_class)(obs_binder, obs_class) };

        // Call registerProcessObserver(observer)
        let _ = transact_write(&vt, service.ptr, codes.observer_code, |w| {
            w.write_strong_binder(obs_binder)
        })?;

        // Consumer dup — made before publishing, so an error path drops the
        // owned fd without ever leaving a stale handle for the callback.
        let consumer = owned
            .try_clone()
            .map_err(|e| CoreError::sys(e.raw_os_error().unwrap_or(-1), "dup:observer"))?;

        // Publish fg_code and the core-owned eventfd for the callback
        OBS_FG_CODE.store(codes.fg_code, Ordering::Relaxed);
        *obs_eventfd_guard() = Some(owned);

        // Start binder thread pool — blocks forever in background thread
        unsafe { (vt.set_thread_pool_max)(0) };
        let join_fn = vt.join_thread_pool;
        std::thread::spawn(move || unsafe { join_fn() });

        let binder = Self {
            _lib: lib,
            vt,
            _class: am_class,
            service,
            tx_code: codes.query_code,
            legacy,
        };
        Ok((binder, consumer))
    }

    /// Open ActivityManager binder and register as the foreground process
    /// observer.
    ///
    /// The authoritative foreground PID is delivered in the callback; this
    /// is the low-noise foreground source. Two ROM variants are supported
    /// and selected automatically:
    ///
    /// - Stock: `IForegroundProcessObserver.onForegroundProcessChanged`
    ///   delivers a single `int pid`.
    /// - Custom ROMs that dropped that interface instead deliver `(int pid,
    ///   int uid, int fg)` through the repurposed
    ///   `IProcessObserver.onForegroundActivitiesChanged`; this registers
    ///   via `registerProcessObserver` and only signals on `fg != 0`.
    ///
    /// The callback stores the PID (readable via [`last_foreground_pid`])
    /// and signals the returned eventfd.
    ///
    /// Returns `(Self, OwnedFd)` where the eventfd is a dup of the core's
    /// callback fd. It becomes readable whenever a foreground process
    /// change fires. Same lifetime contract as
    /// [`ActivityManager::open_with_observer`] (C2): the core owns
    /// the eventfd and the callback only ever writes to that copy, so
    /// closing the returned dup never invalidates the notification path.
    pub fn open_with_fgproc_observer() -> Result<(Self, OwnedFd), CoreError> {
        let handle = Self::dlopen_libbinder()?;
        let (lib, vt, am_class, service) = Self::open_inner(handle)?;

        // Resolve the foreground-observer tx codes. Prefer the stock
        // IForegroundProcessObserver path; fall back to the custom
        // IProcessObserver pid-carrying form on ROMs that dropped it.
        // mode 0 = stock single-int callback, mode 1 = (pid, uid, fg).
        let (register_code, fgproc_code, mode, descriptor): (u32, u32, u32, &[u8]) =
            match crate::android::dex::resolve_fgproc_codes() {
                Some((r, c)) => (r, c, 0, FGPROC_DESCRIPTOR),
                None => match crate::android::dex::resolve_fgproc_codes_fallback() {
                    Some((r, c)) => (r, c, 1, OBS_DESCRIPTOR),
                    None => {
                        return Err(CoreError::binder(
                            -1,
                            "tx_code_resolution:fgproc_dex_parse_failed",
                        ));
                    }
                },
            };

        // Create eventfd for callback → epoll bridge. Ownership stays in the
        // core for the observer lifetime; the consumer receives a dup below.
        let owned = unsafe {
            let raw = libc::eventfd(0, libc::EFD_NONBLOCK | libc::EFD_CLOEXEC);
            if raw < 0 {
                return Err(CoreError::sys(*libc::__errno(), "eventfd"));
            }
            OwnedFd::from_raw_fd(raw)
        };

        // Define our observer class (we're the server). The descriptor must
        // match whichever interface we actually register as.
        let obs_class = unsafe {
            (vt.class_define)(
                descriptor.as_ptr() as *const c_char,
                fgproc_on_create,
                fgproc_on_destroy,
                fgproc_on_transact,
            )
        };
        if obs_class.is_null() {
            return Err(CoreError::binder(
                -1,
                "AIBinder_Class_define:FGProcessObserver",
            ));
        }

        // Instantiate our observer binder object
        let obs_binder = unsafe { (vt.new_binder)(obs_class, std::ptr::null_mut()) };
        if obs_binder.is_null() {
            return Err(CoreError::binder(-1, "AIBinder_new:FGProcessObserver"));
        }
        unsafe { (vt.associate_class)(obs_binder, obs_class) };

        // Call registerForegroundProcessObserver(observer) or the fallback
        // registerProcessObserver(observer) depending on resolved mode.
        let _ = transact_write(&vt, service.ptr, register_code, |w| {
            w.write_strong_binder(obs_binder)
        })?;

        // Consumer dup — made before publishing, so an error path drops the
        // owned fd without ever leaving a stale handle for the callback.
        let consumer = owned
            .try_clone()
            .map_err(|e| CoreError::sys(e.raw_os_error().unwrap_or(-1), "dup:fgproc_observer"))?;

        // Publish reader fn, mode, fg code, pid base, and the core-owned
        // eventfd for the callback. Reader and mode are published first so
        // the callback never sees a matching code with an unset reader or
        // mode (C2-adjacent init order).
        FGPROC_READ_I32.store(vt.read_int32 as usize, Ordering::Relaxed);
        FGPROC_IPROC_MODE.store(mode, Ordering::Relaxed);
        FGPROC_FG_CODE.store(fgproc_code, Ordering::Relaxed);
        FGPROC_PID.store(0, Ordering::Relaxed);
        *fgproc_eventfd_guard() = Some(owned);

        // Start binder thread pool — blocks forever in background thread
        unsafe { (vt.set_thread_pool_max)(0) };
        let join_fn = vt.join_thread_pool;
        std::thread::spawn(move || unsafe { join_fn() });

        let binder = Self {
            _lib: lib,
            vt,
            _class: am_class,
            service,
            tx_code: 0,
            legacy: false,
        };
        Ok((binder, consumer))
    }

    /// Open ActivityManager binder and register as `IUidObserver`.
    ///
    /// Returns `(Self, OwnedFd)` where the eventfd is a dup of the core's
    /// callback fd. It becomes readable whenever a registered uid-lifecycle
    /// callback fires (`onUidGone`/`onUidActive`/`onUidIdle`/
    /// `onUidCachedChanged`/`onUidStateChanged`/`onUidProcAdjChanged`).
    /// Caller adds it to epoll, reads `last_uid_event()` on wake, and
    /// filters on its pinned uid. Caller may close the returned fd at any
    /// time — the callback keeps writing to the core's copy (C2).
    ///
    /// Requests `which = UID_OBSERVER_GONE|ACTIVE|IDLE|CACHED` and cutpoint
    /// `PROCESS_STATE_UNKNOWN` (the `STATE`/`ADJ` codes are resolved for the
    /// dispatcher but not requested unless the caller extends `which`).
    pub fn open_with_uid_observer() -> Result<(Self, OwnedFd), CoreError> {
        const UID_OBSERVER_GONE: i32 = 1 << 1;
        const UID_OBSERVER_IDLE: i32 = 1 << 2;
        const UID_OBSERVER_ACTIVE: i32 = 1 << 3;
        const UID_OBSERVER_CACHED: i32 = 1 << 4;
        const PROCESS_STATE_UNKNOWN: i32 = -1;

        let handle = Self::dlopen_libbinder()?;
        let (lib, vt, am_class, service) = Self::open_inner(handle)?;
        let codes = dex::resolve_uid_observer_codes().ok_or_else(|| {
            CoreError::binder(-1, "tx_code_resolution:uid_observer_dex_parse_failed")
        })?;

        // Create eventfd for callback → epoll bridge. Ownership stays in the
        // core for the observer lifetime; the consumer receives a dup below.
        let owned = unsafe {
            let raw = libc::eventfd(0, libc::EFD_NONBLOCK | libc::EFD_CLOEXEC);
            if raw < 0 {
                return Err(CoreError::sys(*libc::__errno(), "eventfd"));
            }
            OwnedFd::from_raw_fd(raw)
        };

        // Define IUidObserver class (we're the server)
        let uid_class = unsafe {
            (vt.class_define)(
                UID_OBS_DESCRIPTOR.as_ptr() as *const c_char,
                uid_obs_on_create,
                uid_obs_on_destroy,
                uid_obs_on_transact,
            )
        };
        if uid_class.is_null() {
            return Err(CoreError::binder(-1, "AIBinder_Class_define:UidObserver"));
        }

        // Instantiate our observer binder object
        let uid_binder = unsafe { (vt.new_binder)(uid_class, std::ptr::null_mut()) };
        if uid_binder.is_null() {
            return Err(CoreError::binder(-1, "AIBinder_new:UidObserver"));
        }
        unsafe { (vt.associate_class)(uid_binder, uid_class) };

        // Call registerUidObserver(observer, which, cutpoint, callingPackage)
        let _ = transact_write(&vt, service.ptr, codes.register_code, |w| {
            w.write_strong_binder(uid_binder)?;
            w.write_i32(UID_OBSERVER_GONE | UID_OBSERVER_IDLE | UID_OBSERVER_ACTIVE | UID_OBSERVER_CACHED)?;
            w.write_i32(PROCESS_STATE_UNKNOWN)?;
            w.write_string(None)
        })?;

        // Consumer dup — made before publishing, so an error path drops the
        // owned fd without ever leaving a stale handle for the callback.
        let consumer = owned
            .try_clone()
            .map_err(|e| CoreError::sys(e.raw_os_error().unwrap_or(-1), "dup:uid_observer"))?;

        // Publish reader fn, callback codes, and the core-owned eventfd.
        // Reader is published first so a matching code never pairs with an
        // unset reader (C2-adjacent init order).
        UID_READ_I32.store(vt.read_int32 as usize, Ordering::Relaxed);
        UID_GONE_CODE.store(codes.on_gone_code, Ordering::Relaxed);
        UID_ACTIVE_CODE.store(codes.on_active_code, Ordering::Relaxed);
        UID_IDLE_CODE.store(codes.on_idle_code, Ordering::Relaxed);
        UID_CACHED_CODE.store(codes.on_cached_code, Ordering::Relaxed);
        UID_STATE_CODE.store(codes.on_state_code, Ordering::Relaxed);
        UID_ADJ_CODE.store(codes.on_adj_code, Ordering::Relaxed);
        UID_LAST_EVENT.store(u64::from(u32::MAX), Ordering::Release); // uid=-1, kind=0
        *uid_eventfd_guard() = Some(owned);

        // Start binder thread pool — blocks forever in background thread
        unsafe { (vt.set_thread_pool_max)(0) };
        let join_fn = vt.join_thread_pool;
        std::thread::spawn(move || unsafe { join_fn() });

        let binder = Self {
            _lib: lib,
            vt,
            _class: am_class,
            service,
            tx_code: 0,
            legacy: false,
        };
        Ok((binder, consumer))
    }

    fn do_transact(&self) -> Result<OwnedParcel, CoreError> {
        transact_write(&self.vt, self.service.ptr, self.tx_code, |_| Ok(()))
    }

    /// The focused root task's `(taskId, topActivity package)` from a single
    /// txn-31 transaction. Outer `None` = no focused root task (or legacy
    /// API 29, where the reply is `StackInfo` and carries no taskId); inner
    /// `None` = task known but no package in `childTaskNames`. Both values
    /// come from the same parcel, so the registration key and the report
    /// tag can never diverge.
    pub fn get_focused_task(&self) -> Result<Option<(i32, Option<String>)>, CoreError> {
        if self.legacy {
            // StackInfo has no taskId — report None rather than a wrong id.
            return Ok(None);
        }
        let out = self.do_transact()?;
        let r = ParcelReader::owned(&self.vt, &out);
        let ex = r.read_i32()?;
        if ex != EX_NONE {
            return Err(CoreError::binder(ex, "getFocusedTask:exception"));
        }
        let present = r.read_i32()?;
        if present == 0 {
            return Ok(None);
        }
        Ok(Some(parse_root_task_info_task(&r)?))
    }

    /// The `topActivity` package of the focused root task (legacy API 29
    /// builds use `StackInfo` and still resolve the package). Thin wrapper
    /// over [`ActivityManager::get_focused_task`].
    pub fn get_focused_package(&self) -> Result<Option<String>, CoreError> {
        if self.legacy {
            let out = self.do_transact()?;
            let r = ParcelReader::owned(&self.vt, &out);
            let ex = r.read_i32()?;
            if ex != EX_NONE {
                return Err(CoreError::binder(ex, "getFocusedTask:exception"));
            }
            let present = r.read_i32()?;
            if present == 0 {
                return Ok(None);
            }
            return parse_stack_info_body(&r);
        }
        Ok(self.get_focused_task()?.and_then(|(_, pkg)| pkg))
    }

    /// The `taskId` of the currently focused root task. Thin wrapper over
    /// [`ActivityManager::get_focused_task`]; returns `None` when there
    /// is no focused root task or on legacy API 29 builds.
    pub fn get_focused_task_id(&self) -> Result<Option<i32>, CoreError> {
        Ok(self.get_focused_task()?.map(|(task_id, _)| task_id))
    }
}