Skip to main content

coreshift_core/binder/
mod.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/
4
5//! NDK binder primitives for querying Android system services.
6//!
7//! Uses `dlopen` on `libbinder_ndk.so` to avoid hard-linking against a library
8//! absent from older NDK toolchains or non-Android targets.
9//!
10//! ## Transaction code resolution
11//!
12//! Transaction codes are resolved fresh from `framework.jar` DEX on each
13//! startup; no persistent cache.
14//!
15//! ## Observer mode
16//!
17//! `ActivityManagerBinder::open_with_observer` registers this process as an
18//! `IProcessObserver` with ActivityManager. Callbacks fire when foreground
19//! activities change and signal an `eventfd` that callers can poll via epoll.
20//! After the eventfd fires, call `get_focused_package` to read the new value.
21
22// ─────────────────────────────────────────────────────────────────────────────
23// Android-only implementation
24// ─────────────────────────────────────────────────────────────────────────────
25
26#[cfg(target_os = "android")]
27mod imp {
28    use crate::CoreError;
29    use crate::dex;
30    use std::os::fd::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd};
31    use std::os::raw::{c_char, c_void};
32    use std::sync::atomic::{AtomicI32, AtomicU32, AtomicUsize, Ordering};
33    use std::sync::Mutex;
34
35    // ── NDK binder status codes ───────────────────────────────────────────────
36
37    const STATUS_OK: i32 = 0;
38    const STATUS_UNKNOWN_TRANSACTION: i32 = -2;
39    const EX_NONE: i32 = 0;
40
41    // ── Interface constants ───────────────────────────────────────────────────
42
43    const AM_DESCRIPTOR:    &[u8] = b"android.app.IActivityManager\0";
44    const OBS_DESCRIPTOR:   &[u8] = b"android.app.IProcessObserver\0";
45    const FGPROC_DESCRIPTOR: &[u8] = b"android.app.IForegroundProcessObserver\0";
46    const ACTIVITY_SERVICE: &[u8] = b"activity\0";
47    #[cfg(target_pointer_width = "64")]
48    const LIBBINDER_PATH: &[u8] = b"/system/lib64/libbinder_ndk.so\0";
49    #[cfg(target_pointer_width = "32")]
50    const LIBBINDER_PATH: &[u8] = b"/system/lib/libbinder_ndk.so\0";
51
52    // ── Tx code cache ─────────────────────────────────────────────────────────
53    // Format (watcher.c compatible): observer_code query_code api_mode fg_code
54    // api_mode: 1 = getFocusedRootTaskInfo, 2 = getFocusedStackInfo (API 29)
55
56    // ── Statics for observer callback (binder thread pool context) ────────────
57    // The core owns the eventfd for the observer lifetime; the consumer receives
58    // a dup and may close it freely. The callback only ever writes to the core's
59    // copy, so it can never touch a closed/recycled fd (C2). The mutex guards
60    // publication/revocation against a callback firing concurrently.
61
62    static OBS_FG_CODE: AtomicU32 = AtomicU32::new(0);
63    static OBS_EVENTFD:  Mutex<Option<OwnedFd>> = Mutex::new(None);
64
65    fn obs_eventfd_guard() -> std::sync::MutexGuard<'static, Option<OwnedFd>> {
66        OBS_EVENTFD.lock().unwrap_or_else(|p| p.into_inner())
67    }
68
69    // ── IForegroundProcessObserver statics ───────────────────────────────────
70    // Separate from the IProcessObserver pair; same C2 discipline (core owns
71    // the eventfd, consumer gets a dup). FGPROC_READ_I32 holds the vtable's
72    // AParcel_readInt32 fn pointer so the callback can decode the `int pid`
73    // argument without owning the Vtable; it is published (non-zero) before
74    // FGPROC_FG_CODE/eventfd, so the callback never races an unset reader.
75
76    static FGPROC_FG_CODE: AtomicU32 = AtomicU32::new(0);
77    static FGPROC_PID: AtomicI32 = AtomicI32::new(0);
78    static FGPROC_EVENTFD: Mutex<Option<OwnedFd>> = Mutex::new(None);
79    static FGPROC_READ_I32: AtomicUsize = AtomicUsize::new(0);
80    // Binder class mode: 0 = stock IForegroundProcessObserver (single int pid),
81    // 1 = custom IProcessObserver (pid, uid, fg triplets). Only one of the two
82    // is ever configured by open_with_fgproc_observer; the callback branches on
83    // this to decode the in-parcel layout it actually receives.
84    static FGPROC_IPROC_MODE: AtomicU32 = AtomicU32::new(0);
85
86    fn fgproc_eventfd_guard() -> std::sync::MutexGuard<'static, Option<OwnedFd>> {
87        FGPROC_EVENTFD.lock().unwrap_or_else(|p| p.into_inner())
88    }
89
90    // ── Raw NDK type aliases ──────────────────────────────────────────────────
91
92    type AIBinder = c_void;
93    #[allow(non_camel_case_types)]
94    type AIBinder_Class = c_void;
95    type AParcel = c_void;
96    type BinderStatus = i32;
97    type StringAllocator = unsafe extern "C" fn(*mut c_void, i32, *mut *mut c_char) -> bool;
98
99    // ── AIBinder_Class callbacks ──────────────────────────────────────────────
100
101    // AM client — no-op server side (we're a client only)
102    unsafe extern "C" fn am_on_create(_: *mut c_void) -> *mut c_void { std::ptr::null_mut() }
103    unsafe extern "C" fn am_on_destroy(_: *mut c_void) {}
104    unsafe extern "C" fn am_on_transact(
105        _: *mut AIBinder, _: u32, _: *const AParcel, _: *mut AParcel,
106    ) -> BinderStatus { STATUS_UNKNOWN_TRANSACTION }
107
108    // IProcessObserver server callbacks
109    unsafe extern "C" fn obs_on_create(_: *mut c_void) -> *mut c_void { std::ptr::null_mut() }
110    unsafe extern "C" fn obs_on_destroy(_: *mut c_void) {}
111    unsafe extern "C" fn obs_on_transact(
112        _: *mut AIBinder, code: u32, _: *const AParcel, _: *mut AParcel,
113    ) -> BinderStatus {
114        if code == OBS_FG_CODE.load(Ordering::Relaxed) {
115            // Write while holding the lock: the fd can only be closed while
116            // we hold it, so a revoke can never race us into a stale number.
117            if let Some(fd) = obs_eventfd_guard().as_ref() {
118                let val: u64 = 1;
119                unsafe { libc::write(fd.as_raw_fd(), &val as *const u64 as *const c_void, 8) };
120            }
121        }
122        STATUS_OK
123    }
124
125    // IForegroundProcessObserver server callbacks. Two parcel layouts, selected
126    // by FGPROC_IPROC_MODE:
127    //  - mode 0 (stock): `onForegroundProcessChanged(int pid)` — single int32.
128    //  - mode 1 (custom ROMs without IForegroundProcessObserver): the ROM
129    //    repurposes `IProcessObserver.onForegroundActivitiesChanged` to deliver
130    //    `(int pid, int uid, int fg)`. The callback stores the pid and only
131    //    signals the eventfd when fg != 0 (a foreground transition), so
132    //    background transitions never cause the daemon to react.
133    unsafe extern "C" fn fgproc_on_create(_: *mut c_void) -> *mut c_void { std::ptr::null_mut() }
134    unsafe extern "C" fn fgproc_on_destroy(_: *mut c_void) {}
135    unsafe extern "C" fn fgproc_on_transact(
136        _: *mut AIBinder, code: u32, in_parcel: *const AParcel, _: *mut AParcel,
137    ) -> BinderStatus {
138        if code != FGPROC_FG_CODE.load(Ordering::Relaxed) {
139            return STATUS_UNKNOWN_TRANSACTION;
140        }
141        // Read fn is published non-zero before the code/eventfd, so a matching
142        // code is never paired with an unset reader.
143        let read_addr = FGPROC_READ_I32.load(Ordering::Relaxed);
144        if read_addr != 0 {
145            let read_fn: unsafe extern "C" fn(*const AParcel, *mut i32) -> BinderStatus =
146                unsafe { std::mem::transmute(read_addr) };
147            if FGPROC_IPROC_MODE.load(Ordering::Relaxed) == 1 {
148                // IProcessObserver.onForegroundActivitiesChanged(pid, uid, fg)
149                let mut pid: i32 = 0;
150                let mut _uid: i32 = 0;
151                let mut fg: i32 = 0;
152                let mut ok = unsafe { read_fn(in_parcel, &mut pid) } == STATUS_OK;
153                ok &= unsafe { read_fn(in_parcel, &mut _uid) } == STATUS_OK;
154                ok &= unsafe { read_fn(in_parcel, &mut fg) } == STATUS_OK;
155                if ok {
156                    FGPROC_PID.store(pid, Ordering::Relaxed);
157                    // Only foreground transitions are actionable; suppress the
158                    // background transition entirely (fg == 0).
159                    if fg == 0 {
160                        return STATUS_OK;
161                    }
162                } else {
163                    return STATUS_OK;
164                }
165            } else {
166                let mut pid: i32 = 0;
167                if unsafe { read_fn(in_parcel, &mut pid) } == STATUS_OK {
168                    FGPROC_PID.store(pid, Ordering::Relaxed);
169                }
170            }
171        }
172        // Write while holding the lock: the fd can only be closed while we
173        // hold it, so a revoke can never race us into a stale number.
174        if let Some(fd) = fgproc_eventfd_guard().as_ref() {
175            let val: u64 = 1;
176            unsafe { libc::write(fd.as_raw_fd(), &val as *const u64 as *const c_void, 8) };
177        }
178        STATUS_OK
179    }
180
181    /// The PID captured by the most recent `onForegroundProcessChanged`
182    /// callback (requires `open_with_fgproc_observer`).
183    pub fn last_foreground_pid() -> i32 {
184        FGPROC_PID.load(Ordering::Relaxed)
185    }
186
187    // ── String allocator ─────────────────────────────────────────────────────
188
189    /// Ceiling on a single parcel string regardless of the length the peer
190    /// advertises. Component names are at most a few hundred bytes; this bounds
191    /// the allocation so a malformed advertised length cannot drive a giant
192    /// `reserve_exact` (which would abort on OOM).
193    const MAX_BINDER_STRING_LEN: usize = 1024 * 1024;
194
195    unsafe extern "C" fn string_alloc(
196        cookie: *mut c_void, length: i32, buffer: *mut *mut c_char,
197    ) -> bool {
198        // Negative or oversized lengths are allocation failures: returning
199        // true with no usable buffer would hand the reader a dangling pointer,
200        // and an oversized reserve_exact would abort on OOM.
201        if length < 0 { return false; }
202        let len = length as usize;
203        if len > MAX_BINDER_STRING_LEN { return false; }
204        let s = unsafe { &mut *(cookie as *mut StringBuf) };
205        s.0.reserve_exact(len + 1);
206        unsafe { s.0.as_mut_vec().resize(len + 1, 0) };
207        unsafe { *buffer = s.0.as_mut_ptr() as *mut c_char };
208        true
209    }
210
211    struct StringBuf(String);
212    impl StringBuf {
213        fn new() -> Self { Self(String::new()) }
214        fn finish(mut self) -> Option<String> {
215            if let Some(pos) = self.0.as_bytes().iter().position(|&b| b == 0) {
216                unsafe { self.0.as_mut_vec().truncate(pos) };
217            }
218            if self.0.is_empty() { None } else { Some(self.0) }
219        }
220    }
221
222    // ── Vtable ────────────────────────────────────────────────────────────────
223
224    struct Vtable {
225        get_service:         unsafe extern "C" fn(*const c_char) -> *mut AIBinder,
226        class_define:        unsafe extern "C" fn(
227                                 *const c_char,
228                                 unsafe extern "C" fn(*mut c_void) -> *mut c_void,
229                                 unsafe extern "C" fn(*mut c_void),
230                                 unsafe extern "C" fn(*mut AIBinder, u32, *const AParcel, *mut AParcel) -> BinderStatus,
231                             ) -> *mut AIBinder_Class,
232        associate_class:     unsafe extern "C" fn(*mut AIBinder, *mut AIBinder_Class) -> bool,
233        new_binder:          unsafe extern "C" fn(*const AIBinder_Class, *mut c_void) -> *mut AIBinder,
234        prepare_transaction: unsafe extern "C" fn(*mut AIBinder, *mut *mut AParcel) -> BinderStatus,
235        transact:            unsafe extern "C" fn(*mut AIBinder, u32, *mut *mut AParcel, *mut *mut AParcel, u32) -> BinderStatus,
236        dec_strong:          unsafe extern "C" fn(*mut AIBinder),
237        parcel_delete:       unsafe extern "C" fn(*mut AParcel),
238        read_int32:          unsafe extern "C" fn(*const AParcel, *mut i32) -> BinderStatus,
239        read_string:         unsafe extern "C" fn(*const AParcel, *mut c_void, StringAllocator) -> BinderStatus,
240        write_strong_binder: unsafe extern "C" fn(*mut AParcel, *mut AIBinder) -> BinderStatus,
241        set_thread_pool_max: unsafe extern "C" fn(u32),
242        join_thread_pool:    unsafe extern "C" fn(),
243        get_user_data:       unsafe extern "C" fn(*const AIBinder) -> *mut c_void,
244        write_int32:         unsafe extern "C" fn(*mut AParcel, i32) -> BinderStatus,
245        // Optional: only present on API 29+, but all modern Android has this
246        read_bool:           Option<unsafe extern "C" fn(*const AParcel, *mut bool) -> BinderStatus>,
247    }
248
249    // ── RAII wrappers ─────────────────────────────────────────────────────────
250
251    struct DlHandle(*mut c_void);
252    unsafe impl Send for DlHandle {}
253    impl Drop for DlHandle {
254        fn drop(&mut self) {
255            // Intentionally no dlclose: the binder thread pool spawned in
256            // open_with_observer() keeps executing library code until process
257            // exit. Unloading the library while that thread runs causes
258            // use-after-free. libbinder_ndk.so is never unloaded during the
259            // daemon lifetime; the OS reclaims it on exit.
260        }
261    }
262
263    struct OwnedParcel { ptr: *mut AParcel, delete: unsafe extern "C" fn(*mut AParcel) }
264    impl Drop for OwnedParcel {
265        fn drop(&mut self) { if !self.ptr.is_null() { unsafe { (self.delete)(self.ptr) }; } }
266    }
267
268    struct OwnedBinder { ptr: *mut AIBinder, dec_strong: unsafe extern "C" fn(*mut AIBinder) }
269    unsafe impl Send for OwnedBinder {}
270    impl Drop for OwnedBinder {
271        fn drop(&mut self) { if !self.ptr.is_null() { unsafe { (self.dec_strong)(self.ptr) }; } }
272    }
273
274    // ── dlsym helper ─────────────────────────────────────────────────────────
275
276    macro_rules! dlsym_fn {
277        ($handle:expr, $name:literal, $ty:ty) => {{
278            let sym = unsafe {
279                libc::dlsym($handle, concat!($name, "\0").as_ptr() as *const c_char)
280            };
281            if sym.is_null() {
282                return Err(CoreError::binder(-1, concat!("dlsym:", $name)));
283            }
284            unsafe { std::mem::transmute::<*mut c_void, $ty>(sym) }
285        }};
286    }
287
288    macro_rules! dlsym_opt {
289        ($handle:expr, $name:literal, $ty:ty) => {{
290            let sym = unsafe {
291                libc::dlsym($handle, concat!($name, "\0").as_ptr() as *const c_char)
292            };
293            if sym.is_null() { None }
294            else { Some(unsafe { std::mem::transmute::<*mut c_void, $ty>(sym) }) }
295        }};
296    }
297
298    fn load_vtable(handle: *mut c_void) -> Result<Vtable, CoreError> {
299        Ok(Vtable {
300            get_service: dlsym_fn!(handle, "AServiceManager_getService",
301                unsafe extern "C" fn(*const c_char) -> *mut AIBinder),
302            class_define: dlsym_fn!(handle, "AIBinder_Class_define",
303                unsafe extern "C" fn(
304                    *const c_char,
305                    unsafe extern "C" fn(*mut c_void) -> *mut c_void,
306                    unsafe extern "C" fn(*mut c_void),
307                    unsafe extern "C" fn(*mut AIBinder, u32, *const AParcel, *mut AParcel) -> BinderStatus,
308                ) -> *mut AIBinder_Class),
309            associate_class: dlsym_fn!(handle, "AIBinder_associateClass",
310                unsafe extern "C" fn(*mut AIBinder, *mut AIBinder_Class) -> bool),
311            new_binder: dlsym_fn!(handle, "AIBinder_new",
312                unsafe extern "C" fn(*const AIBinder_Class, *mut c_void) -> *mut AIBinder),
313            prepare_transaction: dlsym_fn!(handle, "AIBinder_prepareTransaction",
314                unsafe extern "C" fn(*mut AIBinder, *mut *mut AParcel) -> BinderStatus),
315            transact: dlsym_fn!(handle, "AIBinder_transact",
316                unsafe extern "C" fn(*mut AIBinder, u32, *mut *mut AParcel, *mut *mut AParcel, u32) -> BinderStatus),
317            dec_strong: dlsym_fn!(handle, "AIBinder_decStrong",
318                unsafe extern "C" fn(*mut AIBinder)),
319            parcel_delete: dlsym_fn!(handle, "AParcel_delete",
320                unsafe extern "C" fn(*mut AParcel)),
321            read_int32: dlsym_fn!(handle, "AParcel_readInt32",
322                unsafe extern "C" fn(*const AParcel, *mut i32) -> BinderStatus),
323            read_string: dlsym_fn!(handle, "AParcel_readString",
324                unsafe extern "C" fn(*const AParcel, *mut c_void, StringAllocator) -> BinderStatus),
325            write_strong_binder: dlsym_fn!(handle, "AParcel_writeStrongBinder",
326                unsafe extern "C" fn(*mut AParcel, *mut AIBinder) -> BinderStatus),
327            set_thread_pool_max: dlsym_fn!(handle, "ABinderProcess_setThreadPoolMaxThreadCount",
328                unsafe extern "C" fn(u32)),
329            join_thread_pool: dlsym_fn!(handle, "ABinderProcess_joinThreadPool",
330                unsafe extern "C" fn()),
331            get_user_data: dlsym_fn!(handle, "AIBinder_getUserData",
332                unsafe extern "C" fn(*const AIBinder) -> *mut c_void),
333            write_int32: dlsym_fn!(handle, "AParcel_writeInt32",
334                unsafe extern "C" fn(*mut AParcel, i32) -> BinderStatus),
335            read_bool: dlsym_opt!(handle, "AParcel_readBool",
336                unsafe extern "C" fn(*const AParcel, *mut bool) -> BinderStatus),
337        })
338    }
339
340    // ── ParcelReader ──────────────────────────────────────────────────────────
341
342    struct ParcelReader<'a> { vt: &'a Vtable, parcel: &'a OwnedParcel }
343
344    impl<'a> ParcelReader<'a> {
345        fn read_i32(&self) -> Result<i32, CoreError> {
346            let mut v = 0i32;
347            let s = unsafe { (self.vt.read_int32)(self.parcel.ptr, &mut v) };
348            if s != STATUS_OK { return Err(CoreError::binder(s, "AParcel_readInt32")); }
349            Ok(v)
350        }
351        fn read_string(&self) -> Result<Option<String>, CoreError> {
352            let mut buf = StringBuf::new();
353            let s = unsafe {
354                (self.vt.read_string)(self.parcel.ptr, &mut buf as *mut StringBuf as *mut c_void, string_alloc)
355            };
356            if s != STATUS_OK { return Err(CoreError::binder(s, "AParcel_readString")); }
357            Ok(buf.finish())
358        }
359        fn skip_i32s(&self, n: usize) -> Result<(), CoreError> {
360            for _ in 0..n { self.read_i32()?; }
361            Ok(())
362        }
363        fn skip_int_array(&self) -> Result<(), CoreError> {
364            let count = self.read_i32()?.max(0) as usize;
365            self.skip_i32s(count)
366        }
367        fn read_first_package_from_names(&self) -> Result<Option<String>, CoreError> {
368            let count = self.read_i32()?.max(0) as usize;
369            let mut first: Option<String> = None;
370            for _ in 0..count {
371                let s = self.read_string()?;
372                if first.is_none() {
373                    first = s.and_then(|c| c.split('/').next().map(str::to_owned));
374                }
375            }
376            Ok(first)
377        }
378    }
379
380    // ── ParcelWriter / transact helper ────────────────────────────────────────
381
382    struct ParcelWriter<'a> { vt: &'a Vtable, parcel: &'a OwnedParcel }
383
384    impl<'a> ParcelWriter<'a> {
385        fn write_i32(&self, v: i32) -> Result<(), CoreError> {
386            let s = unsafe { (self.vt.write_int32)(self.parcel.ptr, v) };
387            if s != STATUS_OK { return Err(CoreError::binder(s, "AParcel_writeInt32")); }
388            Ok(())
389        }
390        fn write_strong_binder(&self, b: *mut AIBinder) -> Result<(), CoreError> {
391            let s = unsafe { (self.vt.write_strong_binder)(self.parcel.ptr, b) };
392            if s != STATUS_OK { return Err(CoreError::binder(s, "AParcel_writeStrongBinder")); }
393            Ok(())
394        }
395    }
396
397    /// Prepare an input parcel, run `writes`, then transact. RAII on both
398    /// ends: a write error drops the input parcel (previously it leaked on the
399    /// write-error path, never reaching transact), and the reply parcel is
400    /// returned owned. The input parcel is transferred to `AIBinder_transact`
401    /// (the framework deletes it even on failure), so the wrapper records that
402    /// by nulling its pointer — never a double-delete.
403    fn transact_write(
404        vt: &Vtable,
405        binder: *mut AIBinder,
406        code: u32,
407        writes: impl FnOnce(&ParcelWriter<'_>) -> Result<(), CoreError>,
408    ) -> Result<OwnedParcel, CoreError> {
409        let mut in_ptr: *mut AParcel = std::ptr::null_mut();
410        let s = unsafe { (vt.prepare_transaction)(binder, &mut in_ptr) };
411        if s != STATUS_OK {
412            return Err(CoreError::binder(s, "AIBinder_prepareTransaction"));
413        }
414        let mut inp = OwnedParcel { ptr: in_ptr, delete: vt.parcel_delete };
415        {
416            let writer = ParcelWriter { vt, parcel: &inp };
417            writes(&writer)?;
418        }
419        let mut out_ptr: *mut AParcel = std::ptr::null_mut();
420        let s = unsafe { (vt.transact)(binder, code, &mut inp.ptr, &mut out_ptr, 0) };
421        // The framework owns (and deletes) the input parcel from here.
422        inp.ptr = std::ptr::null_mut();
423        let out = OwnedParcel { ptr: out_ptr, delete: vt.parcel_delete };
424        if s != STATUS_OK {
425            return Err(CoreError::binder(s, "AIBinder_transact"));
426        }
427        Ok(out)
428    }
429
430    // ── Response parsers ──────────────────────────────────────────────────────
431
432    fn parse_stack_info_body(r: &ParcelReader<'_>) -> Result<Option<String>, CoreError> {
433        r.skip_i32s(5)?;
434        r.skip_int_array()?;
435        r.read_first_package_from_names()
436    }
437
438    // RootTaskInfo → (taskId, first childTaskName package). Walks the parcel
439    // once: prefix (bounds, childTaskIds), captures the first package from
440    // childTaskNames, then skips childTaskBounds / childTaskUserIds / visible /
441    // position / TaskInfo.userId to reach taskId — never touching the
442    // Intent/TaskInfo tail. taskId and pkg come from the same transaction, so
443    // callers pair them without a second (racy) round-trip.
444    fn parse_root_task_info_task(r: &ParcelReader<'_>) -> Result<(i32, Option<String>), CoreError> {
445        let scratch = r.read_i32()?;
446        if scratch != 0 { r.skip_i32s(4)?; }
447        r.skip_int_array()?; // childTaskIds
448        let pkg = r.read_first_package_from_names()?; // childTaskNames → pkg
449        // childTaskBounds: typed Rect array (nullable) — read count, skip 4 per entry
450        let bounds_count = r.read_i32()?;
451        let n = if bounds_count < 0 { 0 } else { bounds_count as usize };
452        for _ in 0..n {
453            let entry = r.read_i32()?;
454            if entry != 0 { r.skip_i32s(4)?; }
455        }
456        r.skip_int_array()?; // childTaskUserIds
457        r.skip_i32s(2)?;     // visible, position
458        r.skip_i32s(1)?;     // TaskInfo.userId
459        let task_id = r.read_i32()?;
460        Ok((task_id, pkg))
461    }
462
463    // ── Tx code resolution ────────────────────────────────────────────────────
464
465    pub struct TxCodes {
466        pub observer_code: u32,
467        pub query_code:    u32,
468        pub api_mode:      u8,  // 1 = RootTaskInfo, 2 = StackInfo
469        pub fg_code:       u32,
470    }
471
472    pub fn resolve_tx_codes() -> Result<TxCodes, CoreError> {
473        let (obs, query, api, fg) = dex::resolve_tx_codes_from_dex()
474            .ok_or_else(|| CoreError::binder(-1, "tx_code_resolution:dex_parse_failed"))?;
475        Ok(TxCodes { observer_code: obs, query_code: query, api_mode: api, fg_code: fg })
476    }
477
478    // ── ActivityManagerBinder ─────────────────────────────────────────────────
479
480    pub struct ActivityManagerBinder {
481        _lib:    DlHandle,
482        vt:      Vtable,
483        _class:  *mut AIBinder_Class,
484        service: OwnedBinder,
485        tx_code: u32,
486        legacy:  bool,
487    }
488    unsafe impl Send for ActivityManagerBinder {}
489
490    impl ActivityManagerBinder {
491        fn open_inner(handle: *mut c_void) -> Result<(DlHandle, Vtable, *mut AIBinder_Class, OwnedBinder), CoreError> {
492            let lib = DlHandle(handle);
493            let vt = load_vtable(handle)?;
494
495            let am_class = unsafe {
496                (vt.class_define)(
497                    AM_DESCRIPTOR.as_ptr() as *const c_char,
498                    am_on_create, am_on_destroy, am_on_transact,
499                )
500            };
501            if am_class.is_null() { return Err(CoreError::binder(-1, "AIBinder_Class_define:AM")); }
502
503            let raw = unsafe { (vt.get_service)(ACTIVITY_SERVICE.as_ptr() as *const c_char) };
504            if raw.is_null() { return Err(CoreError::binder(-1, "AServiceManager_getService:activity")); }
505            unsafe { (vt.associate_class)(raw, am_class) };
506
507            let service = OwnedBinder { ptr: raw, dec_strong: vt.dec_strong };
508            Ok((lib, vt, am_class, service))
509        }
510
511        fn dlopen_libbinder() -> Result<*mut c_void, CoreError> {
512            use std::os::raw::c_char;
513            let handle = unsafe {
514                libc::dlopen(LIBBINDER_PATH.as_ptr() as *const c_char, libc::RTLD_NOW | libc::RTLD_LOCAL)
515            };
516            if handle.is_null() { return Err(CoreError::binder(-1, "dlopen:libbinder_ndk.so")); }
517            Ok(handle)
518        }
519
520        /// Open ActivityManager binder (polling mode — no observer).
521        /// Resolves the query tx code from cache or DEX.
522        pub fn open() -> Result<Self, CoreError> {
523            let handle = Self::dlopen_libbinder()?;
524            let (lib, vt, class, service) = Self::open_inner(handle)?;
525            let codes = resolve_tx_codes()?;
526            let legacy = codes.api_mode == 2;
527            Ok(Self { _lib: lib, vt, _class: class, service, tx_code: codes.query_code, legacy })
528        }
529
530        /// Open ActivityManager binder and register as IProcessObserver.
531        ///
532        /// Returns `(Self, OwnedFd)` where the eventfd is a dup of the core's
533        /// callback fd. It becomes readable whenever `onForegroundActivitiesChanged`
534        /// fires. Caller must add it to epoll and may close it at any time — the
535        /// callback keeps writing to the core's copy, so closing the returned
536        /// fd never invalidates the notification path (C2). After the event
537        /// fires, call `get_focused_package`.
538        pub fn open_with_observer() -> Result<(Self, OwnedFd), CoreError> {
539            let handle = Self::dlopen_libbinder()?;
540            let (lib, vt, am_class, service) = Self::open_inner(handle)?;
541            let codes = resolve_tx_codes()?;
542            let legacy = codes.api_mode == 2;
543
544            // Create eventfd for callback → epoll bridge. Ownership stays in the
545            // core for the observer lifetime; the consumer receives a dup below.
546            let owned = unsafe {
547                let raw = libc::eventfd(0, libc::EFD_NONBLOCK | libc::EFD_CLOEXEC);
548                if raw < 0 { return Err(CoreError::sys(*libc::__errno(), "eventfd")); }
549                OwnedFd::from_raw_fd(raw)
550            };
551
552            // Define IProcessObserver class (we're the server)
553            let obs_class = unsafe {
554                (vt.class_define)(
555                    OBS_DESCRIPTOR.as_ptr() as *const c_char,
556                    obs_on_create, obs_on_destroy, obs_on_transact,
557                )
558            };
559            if obs_class.is_null() {
560                return Err(CoreError::binder(-1, "AIBinder_Class_define:Observer"));
561            }
562
563            // Instantiate our observer binder object
564            let obs_binder = unsafe { (vt.new_binder)(obs_class, std::ptr::null_mut()) };
565            if obs_binder.is_null() {
566                return Err(CoreError::binder(-1, "AIBinder_new:Observer"));
567            }
568            unsafe { (vt.associate_class)(obs_binder, obs_class) };
569
570            // Call registerProcessObserver(observer)
571            let _ = transact_write(&vt, service.ptr, codes.observer_code, |w| {
572                w.write_strong_binder(obs_binder)
573            })?;
574
575            // Consumer dup — made before publishing, so an error path drops the
576            // owned fd without ever leaving a stale handle for the callback.
577            let consumer = owned.try_clone()
578                .map_err(|e| CoreError::sys(e.raw_os_error().unwrap_or(-1), "dup:observer"))?;
579
580            // Publish fg_code and the core-owned eventfd for the callback
581            OBS_FG_CODE.store(codes.fg_code, Ordering::Relaxed);
582            *obs_eventfd_guard() = Some(owned);
583
584            // Start binder thread pool — blocks forever in background thread
585            unsafe { (vt.set_thread_pool_max)(0) };
586            let join_fn = vt.join_thread_pool;
587            std::thread::spawn(move || unsafe { join_fn() });
588
589            let binder = Self { _lib: lib, vt, _class: am_class, service, tx_code: codes.query_code, legacy };
590            Ok((binder, consumer))
591        }
592
593        /// Open ActivityManager binder and register as the foreground process
594        /// observer.
595        ///
596        /// The authoritative foreground PID is delivered in the callback; this
597        /// is the low-noise foreground source. Two ROM variants are supported
598        /// and selected automatically:
599        ///
600        /// - Stock: `IForegroundProcessObserver.onForegroundProcessChanged`
601        ///   delivers a single `int pid`.
602        /// - Custom ROMs that dropped that interface instead deliver `(int pid,
603        ///   int uid, int fg)` through the repurposed
604        ///   `IProcessObserver.onForegroundActivitiesChanged`; this registers
605        ///   via `registerProcessObserver` and only signals on `fg != 0`.
606        ///
607        /// The callback stores the PID (readable via [`last_foreground_pid`])
608        /// and signals the returned eventfd.
609        ///
610        /// Returns `(Self, OwnedFd)` where the eventfd is a dup of the core's
611        /// callback fd. It becomes readable whenever a foreground process
612        /// change fires. Same lifetime contract as
613        /// [`ActivityManagerBinder::open_with_observer`] (C2): the core owns
614        /// the eventfd and the callback only ever writes to that copy, so
615        /// closing the returned dup never invalidates the notification path.
616        pub fn open_with_fgproc_observer() -> Result<(Self, OwnedFd), CoreError> {
617            let handle = Self::dlopen_libbinder()?;
618            let (lib, vt, am_class, service) = Self::open_inner(handle)?;
619
620            // Resolve the foreground-observer tx codes. Prefer the stock
621            // IForegroundProcessObserver path; fall back to the custom
622            // IProcessObserver pid-carrying form on ROMs that dropped it.
623            // mode 0 = stock single-int callback, mode 1 = (pid, uid, fg).
624            let (register_code, fgproc_code, mode, descriptor): (u32, u32, u32, &[u8]) =
625                match crate::dex::resolve_fgproc_codes() {
626                    Some((r, c)) => (r, c, 0, FGPROC_DESCRIPTOR),
627                    None => match crate::dex::resolve_fgproc_codes_fallback() {
628                        Some((r, c)) => (r, c, 1, OBS_DESCRIPTOR),
629                        None => {
630                            return Err(CoreError::binder(-1, "tx_code_resolution:fgproc_dex_parse_failed"));
631                        }
632                    },
633                };
634
635            // Create eventfd for callback → epoll bridge. Ownership stays in the
636            // core for the observer lifetime; the consumer receives a dup below.
637            let owned = unsafe {
638                let raw = libc::eventfd(0, libc::EFD_NONBLOCK | libc::EFD_CLOEXEC);
639                if raw < 0 { return Err(CoreError::sys(*libc::__errno(), "eventfd")); }
640                OwnedFd::from_raw_fd(raw)
641            };
642
643            // Define our observer class (we're the server). The descriptor must
644            // match whichever interface we actually register as.
645            let obs_class = unsafe {
646                (vt.class_define)(
647                    descriptor.as_ptr() as *const c_char,
648                    fgproc_on_create, fgproc_on_destroy, fgproc_on_transact,
649                )
650            };
651            if obs_class.is_null() {
652                return Err(CoreError::binder(-1, "AIBinder_Class_define:FGProcessObserver"));
653            }
654
655            // Instantiate our observer binder object
656            let obs_binder = unsafe { (vt.new_binder)(obs_class, std::ptr::null_mut()) };
657            if obs_binder.is_null() {
658                return Err(CoreError::binder(-1, "AIBinder_new:FGProcessObserver"));
659            }
660            unsafe { (vt.associate_class)(obs_binder, obs_class) };
661
662            // Call registerForegroundProcessObserver(observer) or the fallback
663            // registerProcessObserver(observer) depending on resolved mode.
664            let _ = transact_write(&vt, service.ptr, register_code, |w| {
665                w.write_strong_binder(obs_binder)
666            })?;
667
668            // Consumer dup — made before publishing, so an error path drops the
669            // owned fd without ever leaving a stale handle for the callback.
670            let consumer = owned.try_clone()
671                .map_err(|e| CoreError::sys(e.raw_os_error().unwrap_or(-1), "dup:fgproc_observer"))?;
672
673            // Publish reader fn, mode, fg code, pid base, and the core-owned
674            // eventfd for the callback. Reader and mode are published first so
675            // the callback never sees a matching code with an unset reader or
676            // mode (C2-adjacent init order).
677            FGPROC_READ_I32.store(vt.read_int32 as usize, Ordering::Relaxed);
678            FGPROC_IPROC_MODE.store(mode, Ordering::Relaxed);
679            FGPROC_FG_CODE.store(fgproc_code, Ordering::Relaxed);
680            FGPROC_PID.store(0, Ordering::Relaxed);
681            *fgproc_eventfd_guard() = Some(owned);
682
683            // Start binder thread pool — blocks forever in background thread
684            unsafe { (vt.set_thread_pool_max)(0) };
685            let join_fn = vt.join_thread_pool;
686            std::thread::spawn(move || unsafe { join_fn() });
687
688            let binder = Self { _lib: lib, vt, _class: am_class, service, tx_code: 0, legacy: false };
689            Ok((binder, consumer))
690        }
691
692        fn do_transact(&self) -> Result<OwnedParcel, CoreError> {
693            transact_write(&self.vt, self.service.ptr, self.tx_code, |_| Ok(()))
694        }
695
696        /// The focused root task's `(taskId, topActivity package)` from a single
697        /// txn-31 transaction. Outer `None` = no focused root task (or legacy
698        /// API 29, where the reply is `StackInfo` and carries no taskId); inner
699        /// `None` = task known but no package in `childTaskNames`. Both values
700        /// come from the same parcel, so the registration key and the report
701        /// tag can never diverge.
702        pub fn get_focused_task(&self) -> Result<Option<(i32, Option<String>)>, CoreError> {
703            if self.legacy {
704                // StackInfo has no taskId — report None rather than a wrong id.
705                return Ok(None);
706            }
707            let out = self.do_transact()?;
708            let r = ParcelReader { vt: &self.vt, parcel: &out };
709            let ex = r.read_i32()?;
710            if ex != EX_NONE { return Err(CoreError::binder(ex, "getFocusedTask:exception")); }
711            let present = r.read_i32()?;
712            if present == 0 { return Ok(None); }
713            Ok(Some(parse_root_task_info_task(&r)?))
714        }
715
716        /// The `topActivity` package of the focused root task (legacy API 29
717        /// builds use `StackInfo` and still resolve the package). Thin wrapper
718        /// over [`ActivityManagerBinder::get_focused_task`].
719        pub fn get_focused_package(&self) -> Result<Option<String>, CoreError> {
720            if self.legacy {
721                let out = self.do_transact()?;
722                let r = ParcelReader { vt: &self.vt, parcel: &out };
723                let ex = r.read_i32()?;
724                if ex != EX_NONE { return Err(CoreError::binder(ex, "getFocusedTask:exception")); }
725                let present = r.read_i32()?;
726                if present == 0 { return Ok(None); }
727                return parse_stack_info_body(&r);
728            }
729            Ok(self.get_focused_task()?.map(|(_, pkg)| pkg).flatten())
730        }
731
732        /// The `taskId` of the currently focused root task. Thin wrapper over
733        /// [`ActivityManagerBinder::get_focused_task`]; returns `None` when there
734        /// is no focused root task or on legacy API 29 builds.
735        pub fn get_focused_task_id(&self) -> Result<Option<i32>, CoreError> {
736            Ok(self.get_focused_task()?.map(|(task_id, _)| task_id))
737        }
738    }
739
740    // ── DisplayManagerBinder ─────────────────────────────────────────────────
741
742    const DISPLAY_SERVICE:    &[u8] = b"display\0";
743    const DISPLAY_DESCRIPTOR: &[u8] = b"android.hardware.display.IDisplayManager\0";
744    const CALLBACK_DESCRIPTOR: &[u8] = b"android.hardware.display.IDisplayManagerCallback\0";
745    const POWER_SERVICE:      &[u8] = b"power\0";
746
747    const TX_DISPLAY_REGISTER_CALLBACK: u32 = 4;
748
749    // Core owns the callback eventfd; the consumer gets a dup and may close it
750    // freely. Same lifetime discipline as the ActivityManager observer (C2).
751    static DISP_EVENTFD: Mutex<Option<OwnedFd>> = Mutex::new(None);
752
753    fn disp_eventfd_guard() -> std::sync::MutexGuard<'static, Option<OwnedFd>> {
754        DISP_EVENTFD.lock().unwrap_or_else(|p| p.into_inner())
755    }
756
757    unsafe extern "C" fn disp_cb_on_create(_: *mut c_void) -> *mut c_void { std::ptr::null_mut() }
758    unsafe extern "C" fn disp_cb_on_destroy(_: *mut c_void) {}
759    unsafe extern "C" fn disp_cb_on_transact(
760        _: *mut AIBinder, code: u32, _: *const AParcel, _: *mut AParcel,
761    ) -> BinderStatus {
762        if code == 1 {
763            if let Some(fd) = disp_eventfd_guard().as_ref() {
764                let val: u64 = 1;
765                unsafe { libc::write(fd.as_raw_fd(), &val as *const u64 as *const c_void, 8) };
766            }
767        }
768        STATUS_OK
769    }
770
771    pub struct DisplayManagerBinder {
772        _lib:           DlHandle,
773        vt:             Vtable,
774        display:        OwnedBinder,
775        power:          Option<OwnedBinder>,
776        is_interactive_tx: u32,
777    }
778    unsafe impl Send for DisplayManagerBinder {}
779
780    impl DisplayManagerBinder {
781        pub fn open_with_callback() -> Result<(Self, crate::reactor::Fd), CoreError> {
782            let handle = unsafe {
783                libc::dlopen(LIBBINDER_PATH.as_ptr() as *const c_char, libc::RTLD_NOW | libc::RTLD_LOCAL)
784            };
785            if handle.is_null() { return Err(CoreError::binder(-1, "dlopen:libbinder_ndk.so")); }
786            let lib = DlHandle(handle);
787            let vt = load_vtable(handle)?;
788
789            // Blocking eventfd (no EFD_NONBLOCK) — callback writes, caller's
790            // read_u64_blocking() waits. The core owns it for the callback's
791            // lifetime; the consumer receives a dup below (C2).
792            let owned = unsafe {
793                let raw = libc::eventfd(0, libc::EFD_CLOEXEC);
794                if raw < 0 { return Err(CoreError::sys(*libc::__errno(), "eventfd")); }
795                OwnedFd::from_raw_fd(raw)
796            };
797
798            // Get display service (no class_define needed for client-only)
799            let raw_display = unsafe { (vt.get_service)(DISPLAY_SERVICE.as_ptr() as *const c_char) };
800            if raw_display.is_null() {
801                return Err(CoreError::binder(-1, "AServiceManager_getService:display"));
802            }
803            let display = OwnedBinder { ptr: raw_display, dec_strong: vt.dec_strong };
804
805            // Define IDisplayManagerCallback (we're the server receiving callbacks)
806            let cb_class = unsafe {
807                (vt.class_define)(
808                    CALLBACK_DESCRIPTOR.as_ptr() as *const c_char,
809                    disp_cb_on_create, disp_cb_on_destroy, disp_cb_on_transact,
810                )
811            };
812            if cb_class.is_null() {
813                return Err(CoreError::binder(-1, "AIBinder_Class_define:DisplayCallback"));
814            }
815
816            let cb_binder = unsafe { (vt.new_binder)(cb_class, std::ptr::null_mut()) };
817            if cb_binder.is_null() {
818                return Err(CoreError::binder(-1, "AIBinder_new:DisplayCallback"));
819            }
820
821            // registerCallback(callback) — tx 4
822            let _ = transact_write(
823                &vt,
824                display.ptr,
825                TX_DISPLAY_REGISTER_CALLBACK,
826                |w| w.write_strong_binder(cb_binder),
827            )?;
828
829            // Optional: grab power service for is_interactive()
830            let power = {
831                let raw = unsafe { (vt.get_service)(POWER_SERVICE.as_ptr() as *const c_char) };
832                if raw.is_null() { None } else { Some(OwnedBinder { ptr: raw, dec_strong: vt.dec_strong }) }
833            };
834
835            // Resolve isInteractive tx code from DEX at open time
836            let is_interactive_tx = crate::dex::resolve_is_interactive_tx()
837                .ok_or_else(|| CoreError::binder(-1, "dex:TRANSACTION_isInteractive not found"))?;
838
839            // Consumer dup — made before publishing, so an error path drops the
840            // owned fd without ever leaving a stale handle for the callback.
841            let efd_owned = owned.try_clone()
842                .map_err(|e| CoreError::sys(e.raw_os_error().unwrap_or(-1), "dup:display"))
843                .and_then(|dup| unsafe {
844                    crate::reactor::Fd::from_owned_raw_fd(dup.into_raw_fd(), "display.efd")
845                        .map_err(|_| CoreError::binder(-1, "Fd::from_owned_raw_fd:display.efd"))
846                })?;
847
848            // Publish the core-owned eventfd for the callback
849            *disp_eventfd_guard() = Some(owned);
850
851            // Join binder thread pool so callbacks can fire
852            unsafe { (vt.set_thread_pool_max)(0) };
853            let join_fn = vt.join_thread_pool;
854            std::thread::spawn(move || unsafe { join_fn() });
855
856            Ok((Self { _lib: lib, vt, display, power, is_interactive_tx }, efd_owned))
857        }
858
859        pub fn is_interactive(&self) -> Result<bool, CoreError> {
860            let power = self.power.as_ref()
861                .ok_or_else(|| CoreError::binder(-1, "power:unavailable"))?;
862            let out = transact_write(&self.vt, power.ptr, self.is_interactive_tx, |_| Ok(()))?;
863            let r = ParcelReader { vt: &self.vt, parcel: &out };
864            let ex = r.read_i32()?;
865            if ex != EX_NONE { return Err(CoreError::binder(ex, "isInteractive:exception")); }
866            if let Some(rb) = self.vt.read_bool {
867                let mut v = false;
868                let s = unsafe { rb(out.ptr as *const AParcel, &mut v) };
869                if s != STATUS_OK { return Err(CoreError::binder(s, "readBool:isInteractive")); }
870                Ok(v)
871            } else {
872                Ok(r.read_i32()? != 0)
873            }
874        }
875    }
876
877    // ── FpsListener (task FPS callback) ───────────────────────────────────────
878
879    const WINDOW_SERVICE:    &[u8] = b"window\0";
880    const WM_DESCRIPTOR:     &[u8] = b"android.view.IWindowManager\0";
881    const FPS_DESCRIPTOR:    &[u8] = b"android.window.ITaskFpsCallback\0";
882    // The last reported FPS (bit pattern of the f32) is published before the
883    // eventfd is signalled, so the consumer never reads a stale value. The wake
884    // eventfd is per-instance (same pattern as TaskStackListener): it is handed
885    // to AIBinder_new as the callback binder's userdata, so a second
886    // FpsListener can never rewire an earlier registration's wake into its own
887    // fd (the callback resolves its own binder's fd via AIBinder_getUserData).
888    static FPS_VALUE: AtomicU32 = AtomicU32::new(0);
889    static FPS_CODE: AtomicU32 = AtomicU32::new(0);
890    static FPS_READ_I32: AtomicUsize = AtomicUsize::new(0);
891
892    // No-op callbacks for the client-only IWindowManager class (we never serve
893    // transactions on the `window` binder — the class exists only to satisfy
894    // AIBinder_prepareTransaction's remote-transaction contract).
895    unsafe extern "C" fn wm_on_create(_: *mut c_void) -> *mut c_void { std::ptr::null_mut() }
896    unsafe extern "C" fn wm_on_destroy(_: *mut c_void) {}
897    unsafe extern "C" fn wm_on_transact(
898        _: *mut AIBinder, _: u32, _: *const AParcel, _: *mut AParcel,
899    ) -> BinderStatus { STATUS_OK }
900
901    // The per-instance wake eventfd is this callback binder's userdata, so
902    // onCreate must return the args passed to AIBinder_new — AIBinder_getUserData
903    // returns exactly that value — and onDestroy must reclaim the box (same
904    // pattern as TaskStackListener). Returning null here would make
905    // AIBinder_getUserData return null, silently breaking the FPS wake.
906    unsafe extern "C" fn fps_on_create(userdata: *mut c_void) -> *mut c_void { userdata }
907    unsafe extern "C" fn fps_on_destroy(userdata: *mut c_void) {
908        if !userdata.is_null() {
909            unsafe { drop(Box::from_raw(userdata as *mut OwnedFd)) };
910        }
911    }
912    unsafe extern "C" fn fps_on_transact(
913        binder: *mut AIBinder, code: u32, in_parcel: *const AParcel, _: *mut AParcel,
914    ) -> BinderStatus {
915        if code != FPS_CODE.load(Ordering::Relaxed) {
916            return STATUS_UNKNOWN_TRANSACTION;
917        }
918        // Reader is published non-zero before the code, so a matching code is
919        // never paired with an unset reader.
920        let read_addr = FPS_READ_I32.load(Ordering::Relaxed);
921        if read_addr != 0 {
922            let read_fn: unsafe extern "C" fn(*const AParcel, *mut i32) -> BinderStatus =
923                unsafe { std::mem::transmute(read_addr) };
924            let mut bits: i32 = 0;
925            if unsafe { read_fn(in_parcel, &mut bits) } == STATUS_OK {
926                // Publish the value before signalling so the consumer always
927                // sees the value that triggered the wakeup.
928                FPS_VALUE.store(bits as u32, Ordering::Relaxed);
929                // Per-instance wake: the eventfd is this callback binder's
930                // userdata (see FpsListener::open), so two FpsListeners never
931                // cross-wire their wakes. A missing slot means the process-wide
932                // AIBinder_getUserData symbol has not been cached — drop the
933                // signal rather than risk a stale fd.
934                let get_user_data = GET_USER_DATA
935                    .lock()
936                    .unwrap_or_else(|p| p.into_inner());
937                if let Some(get_user_data) = *get_user_data {
938                    let userdata = unsafe { get_user_data(binder) };
939                    if !userdata.is_null() {
940                        let efd = userdata as *mut OwnedFd;
941                        let val: u64 = 1;
942                        unsafe {
943                            libc::write((*efd).as_raw_fd(), &val as *const u64 as *const c_void, 8)
944                        };
945                    }
946                }
947            }
948        }
949        STATUS_OK
950    }
951
952    /// Push-based per-task FPS listener registered with `WindowManager`.
953    ///
954    /// Uses `IWindowManager.registerTaskFpsCallback(taskId, callback)`; the
955    /// daemon hosts the `ITaskFpsCallback` server object and receives
956    /// `onFpsReported(float)` one-way transactions from the `FpsReporter` at
957    /// most every ~500 ms.
958    ///
959    /// The registering UID must hold `ACCESS_FPS_COUNTER` (signature|privileged)
960    /// — this process typically runs as shell (uid 2000) via `su`.
961    ///
962    /// Returns `(Self, OwnedFd)` where the eventfd is a dup of the core's
963    /// callback fd. It becomes readable whenever `onFpsReported` fires; call
964    /// [`FpsListener::last_fps`] after the event to read the value.
965    pub struct FpsListener {
966        _lib:       DlHandle,
967        vt:         Vtable,
968        window:     OwnedBinder,
969        cb_binder:  *mut AIBinder,
970        _wm_class:  *mut AIBinder_Class,
971        register_code: u32,
972        unregister_code: u32,
973        task_id:    i32,
974    }
975    unsafe impl Send for FpsListener {}
976
977    impl FpsListener {
978        /// Open WindowManager and define the `ITaskFpsCallback` server object.
979        ///
980        /// Resolves the three tx codes from DEX. Does **not** register a task
981        /// yet — call [`FpsListener::register`] once a taskId is known. Starts
982        /// the binder thread pool so `onFpsReported` can fire.
983        pub fn open() -> Result<(Self, OwnedFd), CoreError> {
984            let handle = unsafe {
985                libc::dlopen(LIBBINDER_PATH.as_ptr() as *const c_char, libc::RTLD_NOW | libc::RTLD_LOCAL)
986            };
987            if handle.is_null() { return Err(CoreError::binder(-1, "dlopen:libbinder_ndk.so")); }
988            let lib = DlHandle(handle);
989            let vt = load_vtable(handle)?;
990
991            let (register_code, unregister_code, on_fps_code) =
992                crate::dex::resolve_fps_codes()
993                    .ok_or_else(|| CoreError::binder(-1, "dex:TRANSACTION_registerTaskFpsCallback not found"))?;
994
995            let window = {
996                let raw = unsafe { (vt.get_service)(WINDOW_SERVICE.as_ptr() as *const c_char) };
997                if raw.is_null() { return Err(CoreError::binder(-1, "AServiceManager_getService:window")); }
998                OwnedBinder { ptr: raw, dec_strong: vt.dec_strong }
999            };
1000
1001            // Remote transactions require a class on the binder (same
1002            // AIBinder_prepareTransaction contract as the AM service above).
1003            let wm_class = unsafe {
1004                (vt.class_define)(
1005                    WM_DESCRIPTOR.as_ptr() as *const c_char,
1006                    wm_on_create, wm_on_destroy, wm_on_transact,
1007                )
1008            };
1009            if wm_class.is_null() {
1010                return Err(CoreError::binder(-1, "AIBinder_Class_define:IWindowManager"));
1011            }
1012            unsafe { (vt.associate_class)(window.ptr, wm_class) };
1013
1014            let cb_class = unsafe {
1015                (vt.class_define)(
1016                    FPS_DESCRIPTOR.as_ptr() as *const c_char,
1017                    fps_on_create, fps_on_destroy, fps_on_transact,
1018                )
1019            };
1020            if cb_class.is_null() {
1021                return Err(CoreError::binder(-1, "AIBinder_Class_define:ITaskFpsCallback"));
1022            }
1023
1024            // Blocking eventfd — callback writes, consumer waits/reads. Each
1025            // instance owns its own fd; it is handed to the callback binder as
1026            // userdata (per-instance routing, no process-wide static) and the
1027            // consumer receives a dup below (C2).
1028            let owned = unsafe {
1029                let raw = libc::eventfd(0, libc::EFD_CLOEXEC);
1030                if raw < 0 { return Err(CoreError::sys(*libc::__errno(), "eventfd")); }
1031                OwnedFd::from_raw_fd(raw)
1032            };
1033
1034            let consumer = owned.try_clone()
1035                .map_err(|e| CoreError::sys(e.raw_os_error().unwrap_or(-1), "dup:fps"))?;
1036
1037            let userdata = Box::into_raw(Box::new(owned)) as *mut c_void;
1038            let cb_binder = unsafe { (vt.new_binder)(cb_class, userdata) };
1039            if cb_binder.is_null() {
1040                // Reclaim the userdata box handed to AIBinder_new before bailing.
1041                unsafe { drop(Box::from_raw(userdata as *mut OwnedFd)) };
1042                return Err(CoreError::binder(-1, "AIBinder_new:ITaskFpsCallback"));
1043            }
1044            unsafe { (vt.associate_class)(cb_binder, cb_class) };
1045
1046            // Publish the reader and code before the eventfd registration; a
1047            // matching code is never paired with an unset reader (C2-adjacent).
1048            FPS_READ_I32.store(vt.read_int32 as usize, Ordering::Relaxed);
1049            FPS_CODE.store(on_fps_code, Ordering::Relaxed);
1050            FPS_VALUE.store(0, Ordering::Relaxed);
1051            // The callback resolves AIBinder_getUserData from this vtable; the
1052            // symbol address is process-wide, so a cached static is safe.
1053            *GET_USER_DATA.lock().unwrap_or_else(|p| p.into_inner()) = Some(vt.get_user_data);
1054
1055            unsafe { (vt.set_thread_pool_max)(0) };
1056            let join_fn = vt.join_thread_pool;
1057            std::thread::spawn(move || unsafe { join_fn() });
1058
1059            Ok((Self {
1060                _lib: lib, vt, window, cb_binder, _wm_class: wm_class,
1061                register_code, unregister_code, task_id: -1,
1062            }, consumer))
1063        }
1064
1065        /// Register the callback for `task_id`. If a task was already
1066        /// registered, it is unregistered first (WindowManager tracks one task
1067        /// per callback binder).
1068        pub fn register(&mut self, task_id: i32) -> Result<(), CoreError> {
1069            if self.task_id == task_id {
1070                return Ok(());
1071            }
1072            if self.task_id >= 0 {
1073                let _ = self.unregister();
1074            }
1075
1076            let _ = transact_write(&self.vt, self.window.ptr, self.register_code, |w| {
1077                w.write_i32(task_id)?;
1078                w.write_strong_binder(self.cb_binder)
1079            })?;
1080            self.task_id = task_id;
1081            Ok(())
1082        }
1083
1084        /// Unregister the callback from WindowManager. No-op if nothing is
1085        /// registered.
1086        pub fn unregister(&mut self) -> Result<(), CoreError> {
1087            if self.task_id < 0 {
1088                return Ok(());
1089            }
1090            let _ = transact_write(&self.vt, self.window.ptr, self.unregister_code, |w| {
1091                w.write_strong_binder(self.cb_binder)
1092            })?;
1093            self.task_id = -1;
1094            Ok(())
1095        }
1096
1097        /// The most recent `onFpsReported` value (f32), or `None` if no report
1098        /// has arrived yet. Safe to call at any time; the bit pattern is
1099        /// published atomically.
1100        pub fn last_fps(&self) -> Option<f32> {
1101            let bits = FPS_VALUE.load(Ordering::Relaxed);
1102            if bits == 0 { None } else { Some(f32::from_bits(bits)) }
1103        }
1104
1105        /// The taskId currently registered, or `None` if none.
1106        pub fn task_id(&self) -> Option<i32> {
1107            (self.task_id >= 0).then_some(self.task_id)
1108        }
1109    }
1110
1111    impl Drop for FpsListener {
1112        /// Best-effort deregistration from WindowManager so a dropped listener
1113        /// does not leave the framework delivering `onFpsReported` forever. The
1114        /// callback binder's local strong ref is intentionally NOT released:
1115        /// keeping it alive guarantees the per-binder userdata (the OwnedFd)
1116        /// can never be reclaimed by `on_destroy` while a callback is in
1117        /// flight, and the framework-side registration has been dropped by the
1118        /// unregister, so no stale transaction targets this instance.
1119        fn drop(&mut self) {
1120            let _ = self.unregister();
1121        }
1122    }
1123
1124    // ── TaskStackListener (task-stack change wake-up) ────────────────────────
1125
1126    const TASK_SERVICE:     &[u8] = b"activity_task\0";
1127    const ATM_DESCRIPTOR:   &[u8] = b"android.app.IActivityTaskManager\0";
1128    const TASK_STACK_DESCRIPTOR: &[u8] = b"android.app.ITaskStackListener\0";
1129
1130    // No-op callbacks for the client-only IActivityTaskManager class (we never
1131    // serve transactions on the `activity_task` binder — the class exists only
1132    // to satisfy AIBinder_prepareTransaction's remote-transaction contract).
1133    unsafe extern "C" fn atm_on_create(_: *mut c_void) -> *mut c_void { std::ptr::null_mut() }
1134    unsafe extern "C" fn atm_on_destroy(_: *mut c_void) {}
1135    unsafe extern "C" fn atm_on_transact(
1136        _: *mut AIBinder, _: u32, _: *const AParcel, _: *mut AParcel,
1137    ) -> BinderStatus { STATUS_OK }
1138
1139    // Pure wake-up handler: any ITaskStackListener callback
1140    // (onTaskStackChanged, onTaskMovedToFront, …) just signals the eventfd.
1141    // The callback arguments are deliberately NOT parsed — the authoritative
1142    // (taskId, pkg) comes from re-querying getFocusedRootTaskInfo (txn 31) on
1143    // the event, so we never depend on a parcel layout (RunningTaskInfo places
1144    // taskId near the parcel tail).
1145    //
1146    // The wake eventfd is per-instance: the daemon hosts two listeners (the fg
1147    // task source and the fps channel), each with its own eventfd. It is handed
1148    // to AIBinder_new as the binder's userdata, so on_destroy must reclaim it.
1149    // No process-wide static — a shared fd would deliver every instance's
1150    // wake to whichever listener opened last.
1151    //
1152    // The callback resolves the per-binder eventfd through AIBinder_getUserData.
1153    // The symbol address is process-wide, so it is cached once in a static.
1154    static GET_USER_DATA: std::sync::Mutex<Option<unsafe extern "C" fn(*const AIBinder) -> *mut c_void>> =
1155        std::sync::Mutex::new(None);
1156
1157    unsafe extern "C" fn task_stack_on_create(userdata: *mut c_void) -> *mut c_void { userdata }
1158    unsafe extern "C" fn task_stack_on_destroy(userdata: *mut c_void) {
1159        if !userdata.is_null() {
1160            unsafe { drop(Box::from_raw(userdata as *mut OwnedFd)) };
1161        }
1162    }
1163    unsafe extern "C" fn task_stack_on_transact(
1164        binder: *mut AIBinder, _code: u32, _in_parcel: *const AParcel, _reply: *mut AParcel,
1165    ) -> BinderStatus {
1166        let get_user_data = GET_USER_DATA
1167            .lock()
1168            .unwrap_or_else(|p| p.into_inner());
1169        if let Some(get_user_data) = *get_user_data {
1170            let userdata = unsafe { get_user_data(binder) };
1171            if !userdata.is_null() {
1172                let efd = userdata as *mut OwnedFd;
1173                let val: u64 = 1;
1174                unsafe { libc::write((*efd).as_raw_fd(), &val as *const u64 as *const c_void, 8) };
1175            }
1176        }
1177        STATUS_OK
1178    }
1179
1180    /// Push-based task-stack change listener registered with
1181    /// `IActivityTaskManager`.
1182    ///
1183    /// Uses `IActivityTaskManager.registerTaskStackListener(listener)`; the
1184    /// daemon hosts the `ITaskStackListener` server object. The callback is a
1185    /// pure wake-up: on any task-stack change it signals the eventfd and
1186    /// parses nothing. Consumers re-query `getFocusedRootTaskInfo` (txn 31) on
1187    /// the event for the authoritative `(taskId, pkg)`.
1188    ///
1189    /// This target's ROM exposes the legacy `ITaskStackListener` /
1190    /// `registerTaskStackListener` pair; the newer `ITaskChangeListener` /
1191    /// `registerTaskChangeListener` interface is absent.
1192    ///
1193    /// The registering UID must hold `MANAGE_ACTIVITY_TASKS` /
1194    /// `MANAGE_ACTIVITY_STACKS` — the same gate as txn 31, which root passes
1195    /// empirically on the target ROM.
1196    ///
1197    /// Returns `(Self, OwnedFd)` where the eventfd is a dup of the core's
1198    /// callback fd. It becomes readable on any task-stack change.
1199    pub struct TaskStackListener {
1200        _lib:       DlHandle,
1201        vt:         Vtable,
1202        service:    OwnedBinder,
1203        cb_binder:  *mut AIBinder,
1204        _atm_class: *mut AIBinder_Class,
1205        register_code: u32,
1206        unregister_code: u32,
1207    }
1208    unsafe impl Send for TaskStackListener {}
1209
1210    impl TaskStackListener {
1211        /// Open `activity_task`, define the `ITaskStackListener` server object,
1212        /// and start the binder thread pool. Does **not** register yet — call
1213        /// [`TaskStackListener::register`] once consumers are active.
1214        pub fn open() -> Result<(Self, OwnedFd), CoreError> {
1215            let handle = unsafe {
1216                libc::dlopen(LIBBINDER_PATH.as_ptr() as *const c_char, libc::RTLD_NOW | libc::RTLD_LOCAL)
1217            };
1218            if handle.is_null() { return Err(CoreError::binder(-1, "dlopen:libbinder_ndk.so")); }
1219            let lib = DlHandle(handle);
1220            let vt = load_vtable(handle)?;
1221
1222            let (register_code, unregister_code) =
1223                crate::dex::resolve_task_stack_codes()
1224                    .ok_or_else(|| CoreError::binder(-1, "dex:TRANSACTION_registerTaskStackListener not found"))?;
1225
1226            let service = {
1227                let raw = unsafe { (vt.get_service)(TASK_SERVICE.as_ptr() as *const c_char) };
1228                if raw.is_null() { return Err(CoreError::binder(-1, "AServiceManager_getService:activity_task")); }
1229                OwnedBinder { ptr: raw, dec_strong: vt.dec_strong }
1230            };
1231
1232            // Remote transactions require a class on the binder (same
1233            // AIBinder_prepareTransaction contract as the other services).
1234            let atm_class = unsafe {
1235                (vt.class_define)(
1236                    ATM_DESCRIPTOR.as_ptr() as *const c_char,
1237                    atm_on_create, atm_on_destroy, atm_on_transact,
1238                )
1239            };
1240            if atm_class.is_null() {
1241                return Err(CoreError::binder(-1, "AIBinder_Class_define:IActivityTaskManager"));
1242            }
1243            unsafe { (vt.associate_class)(service.ptr, atm_class) };
1244
1245            let cb_class = unsafe {
1246                (vt.class_define)(
1247                    TASK_STACK_DESCRIPTOR.as_ptr() as *const c_char,
1248                    task_stack_on_create, task_stack_on_destroy, task_stack_on_transact,
1249                )
1250            };
1251            if cb_class.is_null() {
1252                return Err(CoreError::binder(-1, "AIBinder_Class_define:ITaskStackListener"));
1253            }
1254
1255            // Blocking eventfd — callback writes, consumer waits/reads. Each
1256            // instance owns its own fd; it is handed to the callback binder as
1257            // userdata (per-instance routing, no process-wide static) and the
1258            // consumer receives a dup below (C2).
1259            let owned = unsafe {
1260                let raw = libc::eventfd(0, libc::EFD_CLOEXEC);
1261                if raw < 0 { return Err(CoreError::sys(*libc::__errno(), "eventfd")); }
1262                OwnedFd::from_raw_fd(raw)
1263            };
1264
1265            let consumer = owned.try_clone()
1266                .map_err(|e| CoreError::sys(e.raw_os_error().unwrap_or(-1), "dup:task_stack"))?;
1267
1268            let userdata = Box::into_raw(Box::new(owned)) as *mut c_void;
1269            let cb_binder = unsafe { (vt.new_binder)(cb_class, userdata) };
1270            if cb_binder.is_null() {
1271                // Reclaim the userdata box handed to AIBinder_new before bailing.
1272                unsafe { drop(Box::from_raw(userdata as *mut OwnedFd)) };
1273                return Err(CoreError::binder(-1, "AIBinder_new:ITaskStackListener"));
1274            }
1275            unsafe { (vt.associate_class)(cb_binder, cb_class) };
1276
1277            // The callback resolves AIBinder_getUserData from this vtable; the
1278            // symbol address is process-wide, so a cached static is safe.
1279            *GET_USER_DATA.lock().unwrap_or_else(|p| p.into_inner()) = Some(vt.get_user_data);
1280
1281            unsafe { (vt.set_thread_pool_max)(0) };
1282            let join_fn = vt.join_thread_pool;
1283            std::thread::spawn(move || unsafe { join_fn() });
1284
1285            Ok((Self {
1286                _lib: lib, vt, service, cb_binder, _atm_class: atm_class,
1287                register_code, unregister_code,
1288            }, consumer))
1289        }
1290
1291        /// Register the task-stack listener with `activity_task` (one listener
1292        /// receives all task-stack events). Idempotent at the framework level;
1293        /// callers should register once and keep the object alive.
1294        pub fn register(&self) -> Result<(), CoreError> {
1295            let _ = transact_write(&self.vt, self.service.ptr, self.register_code, |w| {
1296                w.write_strong_binder(self.cb_binder)
1297            })?;
1298            Ok(())
1299        }
1300
1301        /// Unregister the task-stack listener from `activity_task`. No-op at
1302        /// the framework level if not registered; callers should unregister
1303        /// before dropping the object.
1304        pub fn unregister(&self) -> Result<(), CoreError> {
1305            let _ = transact_write(&self.vt, self.service.ptr, self.unregister_code, |w| {
1306                w.write_strong_binder(self.cb_binder)
1307            })?;
1308            Ok(())
1309        }
1310    }
1311
1312    impl Drop for TaskStackListener {
1313        /// Best-effort deregistration from `activity_task`. Same deliberate
1314        /// non-release of the local strong ref as [`FpsListener`] — the
1315        /// userdata OwnedFd stays valid for any in-flight wake, and the
1316        /// framework-side registration is gone after the unregister.
1317        fn drop(&mut self) {
1318            let _ = self.unregister();
1319        }
1320    }
1321
1322    // ── RawBinderService ──────────────────────────────────────────────────────
1323
1324    /// Generic binder client for any named Android service.
1325    ///
1326    /// Handles its own `dlopen` on `libbinder_ndk.so`. Callers provide raw
1327    /// transaction codes (resolved via [`crate::dex::find_transaction_code`])
1328    /// and use [`RawBinderService::transact_bool`] /
1329    /// [`RawBinderService::transact_i32`] for typed round-trips.
1330    pub struct RawBinderService {
1331        _lib:    DlHandle,
1332        vt:      Vtable,
1333        service: OwnedBinder,
1334    }
1335    unsafe impl Send for RawBinderService {}
1336
1337    impl RawBinderService {
1338        /// Open a connection to the named service (e.g. `"power"`, `"batterystats"`).
1339        pub fn open(service_name: &str) -> Result<Self, CoreError> {
1340            use std::ffi::CString;
1341            let handle = unsafe {
1342                libc::dlopen(LIBBINDER_PATH.as_ptr() as *const c_char, libc::RTLD_NOW | libc::RTLD_LOCAL)
1343            };
1344            if handle.is_null() {
1345                return Err(CoreError::binder(-1, "dlopen:libbinder_ndk.so"));
1346            }
1347            let lib = DlHandle(handle);
1348            let vt = load_vtable(handle)?;
1349            let cs = CString::new(service_name)
1350                .map_err(|_| CoreError::binder(-1, "service_name:nul_byte"))?;
1351            let raw = unsafe { (vt.get_service)(cs.as_ptr()) };
1352            if raw.is_null() {
1353                return Err(CoreError::binder(-1, "AServiceManager_getService:null"));
1354            }
1355            let service = OwnedBinder { ptr: raw, dec_strong: vt.dec_strong };
1356            Ok(Self { _lib: lib, vt, service })
1357        }
1358
1359        /// Send a no-argument transaction; read exception header then bool reply.
1360        pub fn transact_bool(&self, code: u32) -> Result<bool, CoreError> {
1361            let out = self.raw_noarg(code)?;
1362            let r = ParcelReader { vt: &self.vt, parcel: &out };
1363            let ex = r.read_i32()?;
1364            if ex != EX_NONE { return Err(CoreError::binder(ex, "transact_bool:exception")); }
1365            if let Some(rb) = self.vt.read_bool {
1366                let mut v = false;
1367                let s = unsafe { rb(out.ptr as *const AParcel, &mut v) };
1368                if s != STATUS_OK { return Err(CoreError::binder(s, "AParcel_readBool")); }
1369                Ok(v)
1370            } else {
1371                Ok(r.read_i32()? != 0)
1372            }
1373        }
1374
1375        /// Send a transaction with one i32 argument; discard reply.
1376        pub fn transact_i32(&self, code: u32, arg: i32) -> Result<(), CoreError> {
1377            let _ = transact_write(&self.vt, self.service.ptr, code, |w| w.write_i32(arg))?;
1378            Ok(())
1379        }
1380
1381        fn raw_noarg(&self, code: u32) -> Result<OwnedParcel, CoreError> {
1382            transact_write(&self.vt, self.service.ptr, code, |_| Ok(()))
1383        }
1384    }
1385
1386    #[cfg(test)]
1387    mod tests {
1388        use super::*;
1389
1390        fn alloc(length: i32) -> bool {
1391            let mut buf = StringBuf::new();
1392            let mut out: *mut c_char = std::ptr::null_mut();
1393            unsafe { string_alloc(&mut buf as *mut StringBuf as *mut c_void, length, &mut out) }
1394        }
1395
1396        #[test]
1397        fn string_alloc_rejects_oversized() {
1398            assert!(!alloc(MAX_BINDER_STRING_LEN as i32 + 1));
1399        }
1400
1401        #[test]
1402        fn string_alloc_rejects_negative() {
1403            assert!(!alloc(-1));
1404        }
1405
1406        #[test]
1407        fn string_alloc_accepts_valid_len_and_nul_terminates() {
1408            let mut buf = StringBuf::new();
1409            let mut out: *mut c_char = std::ptr::null_mut();
1410            let ok = unsafe {
1411                string_alloc(&mut buf as *mut StringBuf as *mut c_void, 4, &mut out)
1412            };
1413            assert!(ok);
1414            assert!(!out.is_null());
1415            {
1416                let vec = unsafe { buf.0.as_mut_vec() };
1417                b"ABCD".iter().enumerate().for_each(|(i, &b)| vec[i] = b);
1418                vec[4] = 0;
1419            }
1420            assert_eq!(buf.finish().as_deref(), Some("ABCD"));
1421        }
1422    }
1423}
1424
1425// ── Public re-exports ─────────────────────────────────────────────────────────
1426
1427#[cfg(target_os = "android")]
1428pub use imp::{ActivityManagerBinder, DisplayManagerBinder, FpsListener, RawBinderService, TaskStackListener, TxCodes, last_foreground_pid, resolve_tx_codes};
1429
1430// ── Non-Android stubs ─────────────────────────────────────────────────────────
1431
1432#[cfg(not(target_os = "android"))]
1433pub struct ActivityManagerBinder;
1434
1435#[cfg(not(target_os = "android"))]
1436impl ActivityManagerBinder {
1437    pub fn open() -> Result<Self, crate::CoreError> {
1438        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
1439    }
1440    pub fn open_with_observer() -> Result<(Self, std::os::fd::OwnedFd), crate::CoreError> {
1441        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
1442    }
1443    pub fn open_with_fgproc_observer() -> Result<(Self, std::os::fd::OwnedFd), crate::CoreError> {
1444        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
1445    }
1446    pub fn get_focused_task(&self) -> Result<Option<(i32, Option<String>)>, crate::CoreError> {
1447        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
1448    }
1449    pub fn get_focused_package(&self) -> Result<Option<String>, crate::CoreError> {
1450        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
1451    }
1452    pub fn get_focused_task_id(&self) -> Result<Option<i32>, crate::CoreError> {
1453        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
1454    }
1455}
1456
1457#[cfg(not(target_os = "android"))]
1458pub struct DisplayManagerBinder;
1459
1460#[cfg(not(target_os = "android"))]
1461impl DisplayManagerBinder {
1462    pub fn open_with_callback() -> Result<(Self, crate::reactor::Fd), crate::CoreError> {
1463        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
1464    }
1465    pub fn is_interactive(&self) -> Result<bool, crate::CoreError> {
1466        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
1467    }
1468}
1469
1470#[cfg(not(target_os = "android"))]
1471pub struct RawBinderService;
1472
1473#[cfg(not(target_os = "android"))]
1474impl RawBinderService {
1475    pub fn open(_service_name: &str) -> Result<Self, crate::CoreError> {
1476        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
1477    }
1478    pub fn transact_bool(&self, _code: u32) -> Result<bool, crate::CoreError> {
1479        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
1480    }
1481    pub fn transact_i32(&self, _code: u32, _arg: i32) -> Result<(), crate::CoreError> {
1482        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
1483    }
1484}
1485
1486#[cfg(not(target_os = "android"))]
1487pub struct FpsListener;
1488
1489#[cfg(not(target_os = "android"))]
1490impl FpsListener {
1491    pub fn open() -> Result<(Self, std::os::fd::OwnedFd), crate::CoreError> {
1492        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
1493    }
1494    pub fn register(&mut self, _task_id: i32) -> Result<(), crate::CoreError> {
1495        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
1496    }
1497    pub fn unregister(&mut self) -> Result<(), crate::CoreError> {
1498        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
1499    }
1500    pub fn last_fps(&self) -> Option<f32> {
1501        None
1502    }
1503    pub fn task_id(&self) -> Option<i32> {
1504        None
1505    }
1506}
1507
1508#[cfg(not(target_os = "android"))]
1509pub struct TaskStackListener;
1510
1511#[cfg(not(target_os = "android"))]
1512impl TaskStackListener {
1513    pub fn open() -> Result<(Self, std::os::fd::OwnedFd), crate::CoreError> {
1514        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
1515    }
1516    pub fn register(&self) -> Result<(), crate::CoreError> {
1517        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
1518    }
1519    pub fn unregister(&self) -> Result<(), crate::CoreError> {
1520        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
1521    }
1522}
1523
1524#[cfg(not(target_os = "android"))]
1525pub struct TxCodes { pub observer_code: u32, pub query_code: u32, pub api_mode: u8, pub fg_code: u32 }
1526
1527#[cfg(not(target_os = "android"))]
1528pub fn resolve_tx_codes() -> Result<TxCodes, crate::CoreError> {
1529    Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
1530}
1531
1532#[cfg(not(target_os = "android"))]
1533pub fn last_foreground_pid() -> i32 {
1534    0
1535}