cloudfox-coreshift-core 1.2.28

Low-level Linux and Android systems primitives for CoreShift (CloudFox)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
// 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/

//! NDK binder primitives for querying Android system services.
//!
//! Uses `dlopen` on `libbinder_ndk.so` to avoid hard-linking against a library
//! absent from older NDK toolchains or non-Android targets.
//!
//! ## Transaction code resolution
//!
//! Transaction codes are resolved fresh from `framework.jar` DEX on each
//! startup; no persistent cache.
//!
//! ## Observer mode
//!
//! `ActivityManagerBinder::open_with_observer` registers this process as an
//! `IProcessObserver` with ActivityManager. Callbacks fire when foreground
//! activities change and signal an `eventfd` that callers can poll via epoll.
//! After the eventfd fires, call `get_focused_package` to read the new value.

// ─────────────────────────────────────────────────────────────────────────────
// Android-only implementation
// ─────────────────────────────────────────────────────────────────────────────

#[cfg(target_os = "android")]
mod imp {
    use crate::CoreError;
    use crate::dex;
    use std::os::fd::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd};
    use std::os::raw::{c_char, c_void};
    use std::sync::atomic::{AtomicI32, AtomicU32, AtomicUsize, Ordering};
    use std::sync::Mutex;

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

    const STATUS_OK: i32 = 0;
    const STATUS_UNKNOWN_TRANSACTION: i32 = -2;
    const EX_NONE: i32 = 0;

    // ── 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 ACTIVITY_SERVICE: &[u8] = b"activity\0";
    #[cfg(target_pointer_width = "64")]
    const LIBBINDER_PATH: &[u8] = b"/system/lib64/libbinder_ndk.so\0";
    #[cfg(target_pointer_width = "32")]
    const LIBBINDER_PATH: &[u8] = b"/system/lib/libbinder_ndk.so\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())
    }

    // ── Raw NDK type aliases ──────────────────────────────────────────────────

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

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

    /// 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)
    }

    // ── String allocator ─────────────────────────────────────────────────────

    unsafe extern "C" fn string_alloc(
        cookie: *mut c_void, length: i32, buffer: *mut *mut c_char,
    ) -> bool {
        if length < 0 { return true; }
        let s = unsafe { &mut *(cookie as *mut StringBuf) };
        s.0.reserve_exact(length as usize + 1);
        unsafe { s.0.as_mut_vec().resize(length as usize + 1, 0) };
        unsafe { *buffer = s.0.as_mut_ptr() as *mut c_char };
        true
    }

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

    // ── Vtable ────────────────────────────────────────────────────────────────

    struct Vtable {
        get_service:         unsafe extern "C" fn(*const c_char) -> *mut AIBinder,
        class_define:        unsafe extern "C" fn(
                                 *const c_char,
                                 unsafe extern "C" fn(*mut c_void) -> *mut c_void,
                                 unsafe extern "C" fn(*mut c_void),
                                 unsafe extern "C" fn(*mut AIBinder, u32, *const AParcel, *mut AParcel) -> BinderStatus,
                             ) -> *mut AIBinder_Class,
        associate_class:     unsafe extern "C" fn(*mut AIBinder, *mut AIBinder_Class) -> bool,
        new_binder:          unsafe extern "C" fn(*const AIBinder_Class, *mut c_void) -> *mut AIBinder,
        prepare_transaction: unsafe extern "C" fn(*mut AIBinder, *mut *mut AParcel) -> BinderStatus,
        transact:            unsafe extern "C" fn(*mut AIBinder, u32, *mut *mut AParcel, *mut *mut AParcel, u32) -> BinderStatus,
        dec_strong:          unsafe extern "C" fn(*mut AIBinder),
        parcel_delete:       unsafe extern "C" fn(*mut AParcel),
        read_int32:          unsafe extern "C" fn(*const AParcel, *mut i32) -> BinderStatus,
        read_string:         unsafe extern "C" fn(*const AParcel, *mut c_void, StringAllocator) -> BinderStatus,
        write_strong_binder: unsafe extern "C" fn(*mut AParcel, *mut AIBinder) -> BinderStatus,
        set_thread_pool_max: unsafe extern "C" fn(u32),
        join_thread_pool:    unsafe extern "C" fn(),
        write_int32:         unsafe extern "C" fn(*mut AParcel, i32) -> BinderStatus,
        // Optional: only present on API 29+, but all modern Android has this
        read_bool:           Option<unsafe extern "C" fn(*const AParcel, *mut bool) -> BinderStatus>,
    }

    // ── RAII wrappers ─────────────────────────────────────────────────────────

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

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

    struct OwnedBinder { ptr: *mut AIBinder, dec_strong: unsafe extern "C" fn(*mut AIBinder) }
    unsafe impl Send for OwnedBinder {}
    impl Drop for OwnedBinder {
        fn drop(&mut self) { if !self.ptr.is_null() { unsafe { (self.dec_strong)(self.ptr) }; } }
    }

    // ── dlsym helper ─────────────────────────────────────────────────────────

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

    macro_rules! dlsym_opt {
        ($handle:expr, $name:literal, $ty:ty) => {{
            let sym = unsafe {
                libc::dlsym($handle, concat!($name, "\0").as_ptr() as *const c_char)
            };
            if sym.is_null() { None }
            else { Some(unsafe { std::mem::transmute::<*mut c_void, $ty>(sym) }) }
        }};
    }

    fn load_vtable(handle: *mut c_void) -> Result<Vtable, CoreError> {
        Ok(Vtable {
            get_service: dlsym_fn!(handle, "AServiceManager_getService",
                unsafe extern "C" fn(*const c_char) -> *mut AIBinder),
            class_define: dlsym_fn!(handle, "AIBinder_Class_define",
                unsafe extern "C" fn(
                    *const c_char,
                    unsafe extern "C" fn(*mut c_void) -> *mut c_void,
                    unsafe extern "C" fn(*mut c_void),
                    unsafe extern "C" fn(*mut AIBinder, u32, *const AParcel, *mut AParcel) -> BinderStatus,
                ) -> *mut AIBinder_Class),
            associate_class: dlsym_fn!(handle, "AIBinder_associateClass",
                unsafe extern "C" fn(*mut AIBinder, *mut AIBinder_Class) -> bool),
            new_binder: dlsym_fn!(handle, "AIBinder_new",
                unsafe extern "C" fn(*const AIBinder_Class, *mut c_void) -> *mut AIBinder),
            prepare_transaction: dlsym_fn!(handle, "AIBinder_prepareTransaction",
                unsafe extern "C" fn(*mut AIBinder, *mut *mut AParcel) -> BinderStatus),
            transact: dlsym_fn!(handle, "AIBinder_transact",
                unsafe extern "C" fn(*mut AIBinder, u32, *mut *mut AParcel, *mut *mut AParcel, u32) -> BinderStatus),
            dec_strong: dlsym_fn!(handle, "AIBinder_decStrong",
                unsafe extern "C" fn(*mut AIBinder)),
            parcel_delete: dlsym_fn!(handle, "AParcel_delete",
                unsafe extern "C" fn(*mut AParcel)),
            read_int32: dlsym_fn!(handle, "AParcel_readInt32",
                unsafe extern "C" fn(*const AParcel, *mut i32) -> BinderStatus),
            read_string: dlsym_fn!(handle, "AParcel_readString",
                unsafe extern "C" fn(*const AParcel, *mut c_void, StringAllocator) -> BinderStatus),
            write_strong_binder: dlsym_fn!(handle, "AParcel_writeStrongBinder",
                unsafe extern "C" fn(*mut AParcel, *mut AIBinder) -> BinderStatus),
            set_thread_pool_max: dlsym_fn!(handle, "ABinderProcess_setThreadPoolMaxThreadCount",
                unsafe extern "C" fn(u32)),
            join_thread_pool: dlsym_fn!(handle, "ABinderProcess_joinThreadPool",
                unsafe extern "C" fn()),
            write_int32: dlsym_fn!(handle, "AParcel_writeInt32",
                unsafe extern "C" fn(*mut AParcel, i32) -> BinderStatus),
            read_bool: dlsym_opt!(handle, "AParcel_readBool",
                unsafe extern "C" fn(*const AParcel, *mut bool) -> BinderStatus),
        })
    }

    // ── ParcelReader ──────────────────────────────────────────────────────────

    struct ParcelReader<'a> { vt: &'a Vtable, parcel: &'a OwnedParcel }

    impl<'a> ParcelReader<'a> {
        fn read_i32(&self) -> Result<i32, CoreError> {
            let mut v = 0i32;
            let s = unsafe { (self.vt.read_int32)(self.parcel.ptr, &mut v) };
            if s != STATUS_OK { return Err(CoreError::binder(s, "AParcel_readInt32")); }
            Ok(v)
        }
        fn read_string(&self) -> Result<Option<String>, CoreError> {
            let mut buf = StringBuf::new();
            let s = unsafe {
                (self.vt.read_string)(self.parcel.ptr, &mut buf as *mut StringBuf as *mut c_void, string_alloc)
            };
            if s != STATUS_OK { return Err(CoreError::binder(s, "AParcel_readString")); }
            Ok(buf.finish())
        }
        fn skip_i32s(&self, n: usize) -> Result<(), CoreError> {
            for _ in 0..n { self.read_i32()?; }
            Ok(())
        }
        fn skip_int_array(&self) -> Result<(), CoreError> {
            let count = self.read_i32()?.max(0) as usize;
            self.skip_i32s(count)
        }
        fn read_first_package_from_names(&self) -> Result<Option<String>, CoreError> {
            let count = self.read_i32()?.max(0) as usize;
            let mut first: Option<String> = None;
            for _ in 0..count {
                let s = self.read_string()?;
                if first.is_none() {
                    first = s.and_then(|c| c.split('/').next().map(str::to_owned));
                }
            }
            Ok(first)
        }
    }

    // ── Response parsers ──────────────────────────────────────────────────────

    fn parse_root_task_info_body(r: &ParcelReader<'_>) -> Result<Option<String>, CoreError> {
        let scratch = r.read_i32()?;
        if scratch != 0 { r.skip_i32s(4)?; }
        r.skip_int_array()?;
        r.read_first_package_from_names()
    }

    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: the cheap field. After the RootTaskInfo prefix
    // (bounds, childTaskIds, childTaskNames, childTaskBounds, childTaskUserIds,
    // visible, position), TaskInfo begins with userId then taskId. We skip the
    // prefix and read the two ints, never touching the Intent/TaskInfo tail.
    fn parse_root_task_info_task_id(r: &ParcelReader<'_>) -> Result<Option<i32>, CoreError> {
        let scratch = r.read_i32()?;
        if scratch != 0 { r.skip_i32s(4)?; }
        r.skip_int_array()?;
        r.read_first_package_from_names()?; // childTaskNames (skip)
        // 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(Some(task_id))
    }

    // ── 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 })
    }

    // ── ActivityManagerBinder ─────────────────────────────────────────────────

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

    impl ActivityManagerBinder {
        fn open_inner(handle: *mut c_void) -> Result<(DlHandle, Vtable, *mut AIBinder_Class, OwnedBinder), CoreError> {
            let lib = DlHandle(handle);
            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 mut in_ptr: *mut AParcel = std::ptr::null_mut();
            let s = unsafe { (vt.prepare_transaction)(service.ptr, &mut in_ptr) };
            if s != STATUS_OK {
                return Err(CoreError::binder(s, "prepareTransaction:registerObserver"));
            }
            unsafe { (vt.write_strong_binder)(in_ptr, obs_binder) };
            let mut out_ptr: *mut AParcel = std::ptr::null_mut();
            let s = unsafe {
                (vt.transact)(service.ptr, codes.observer_code, &mut in_ptr, &mut out_ptr, 0)
            };
            if !out_ptr.is_null() { unsafe { (vt.parcel_delete)(out_ptr) }; }
            if s != STATUS_OK {
                return Err(CoreError::binder(s, "transact:registerProcessObserver"));
            }

            // 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
        /// [`ActivityManagerBinder::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::dex::resolve_fgproc_codes() {
                    Some((r, c)) => (r, c, 0, FGPROC_DESCRIPTOR),
                    None => match crate::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 mut in_ptr: *mut AParcel = std::ptr::null_mut();
            let s = unsafe { (vt.prepare_transaction)(service.ptr, &mut in_ptr) };
            if s != STATUS_OK {
                return Err(CoreError::binder(s, "prepareTransaction:registerForegroundProcessObserver"));
            }
            unsafe { (vt.write_strong_binder)(in_ptr, obs_binder) };
            let mut out_ptr: *mut AParcel = std::ptr::null_mut();
            let s = unsafe {
                (vt.transact)(service.ptr, register_code, &mut in_ptr, &mut out_ptr, 0)
            };
            if !out_ptr.is_null() { unsafe { (vt.parcel_delete)(out_ptr) }; }
            if s != STATUS_OK {
                return Err(CoreError::binder(s, "transact:registerForegroundProcessObserver"));
            }

            // 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))
        }

        fn do_transact(&self) -> Result<OwnedParcel, CoreError> {
            let mut in_ptr: *mut AParcel = std::ptr::null_mut();
            let s = unsafe { (self.vt.prepare_transaction)(self.service.ptr, &mut in_ptr) };
            if s != STATUS_OK { return Err(CoreError::binder(s, "AIBinder_prepareTransaction")); }
            let mut out_ptr: *mut AParcel = std::ptr::null_mut();
            let s = unsafe {
                (self.vt.transact)(self.service.ptr, self.tx_code, &mut in_ptr, &mut out_ptr, 0)
            };
            let out = OwnedParcel { ptr: out_ptr, delete: self.vt.parcel_delete };
            if s != STATUS_OK { return Err(CoreError::binder(s, "AIBinder_transact")); }
            Ok(out)
        }

        pub fn get_focused_package(&self) -> Result<Option<String>, CoreError> {
            let out = self.do_transact()?;
            let r = ParcelReader { vt: &self.vt, parcel: &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); }
            if self.legacy { parse_stack_info_body(&r) } else { parse_root_task_info_body(&r) }
        }

        /// The `taskId` of the currently focused root task, without parsing the
        /// expensive Intent/TaskInfo tail of the `RootTaskInfo` reply. Returns
        /// `None` when there is no focused root task.
        pub fn get_focused_task_id(&self) -> Result<Option<i32>, CoreError> {
            if self.legacy {
                // StackInfo has no taskId — callers must use get_focused_package
                // on legacy (API 29) builds. Report None rather than a wrong id.
                return Ok(None);
            }
            let out = self.do_transact()?;
            let r = ParcelReader { vt: &self.vt, parcel: &out };
            let ex = r.read_i32()?;
            if ex != EX_NONE { return Err(CoreError::binder(ex, "getFocusedTaskId:exception")); }
            let present = r.read_i32()?;
            if present == 0 { return Ok(None); }
            parse_root_task_info_task_id(&r)
        }
    }

    // ── DisplayManagerBinder ─────────────────────────────────────────────────

    const DISPLAY_SERVICE:    &[u8] = b"display\0";
    const DISPLAY_DESCRIPTOR: &[u8] = b"android.hardware.display.IDisplayManager\0";
    const CALLBACK_DESCRIPTOR: &[u8] = b"android.hardware.display.IDisplayManagerCallback\0";
    const POWER_SERVICE:      &[u8] = b"power\0";

    const TX_DISPLAY_REGISTER_CALLBACK: u32 = 4;

    // Core owns the callback eventfd; the consumer gets a dup and may close it
    // freely. Same lifetime discipline as the ActivityManager observer (C2).
    static DISP_EVENTFD: Mutex<Option<OwnedFd>> = Mutex::new(None);

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

    unsafe extern "C" fn disp_cb_on_create(_: *mut c_void) -> *mut c_void { std::ptr::null_mut() }
    unsafe extern "C" fn disp_cb_on_destroy(_: *mut c_void) {}
    unsafe extern "C" fn disp_cb_on_transact(
        _: *mut AIBinder, code: u32, _: *const AParcel, _: *mut AParcel,
    ) -> BinderStatus {
        if code == 1 {
            if let Some(fd) = disp_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
    }

    pub struct DisplayManagerBinder {
        _lib:           DlHandle,
        vt:             Vtable,
        display:        OwnedBinder,
        power:          Option<OwnedBinder>,
        is_interactive_tx: u32,
    }
    unsafe impl Send for DisplayManagerBinder {}

    impl DisplayManagerBinder {
        pub fn open_with_callback() -> Result<(Self, crate::reactor::Fd), CoreError> {
            let handle = unsafe {
                libc::dlopen(LIBBINDER_PATH.as_ptr() as *const c_char, libc::RTLD_NOW | libc::RTLD_LOCAL)
            };
            if handle.is_null() { return Err(CoreError::binder(-1, "dlopen:libbinder_ndk.so")); }
            let lib = DlHandle(handle);
            let vt = load_vtable(handle)?;

            // Blocking eventfd (no EFD_NONBLOCK) — callback writes, caller's
            // read_u64_blocking() waits. The core owns it for the callback's
            // lifetime; the consumer receives a dup below (C2).
            let owned = unsafe {
                let raw = libc::eventfd(0, libc::EFD_CLOEXEC);
                if raw < 0 { return Err(CoreError::sys(*libc::__errno(), "eventfd")); }
                OwnedFd::from_raw_fd(raw)
            };

            // Get display service (no class_define needed for client-only)
            let raw_display = unsafe { (vt.get_service)(DISPLAY_SERVICE.as_ptr() as *const c_char) };
            if raw_display.is_null() {
                return Err(CoreError::binder(-1, "AServiceManager_getService:display"));
            }
            let display = OwnedBinder { ptr: raw_display, dec_strong: vt.dec_strong };

            // Define IDisplayManagerCallback (we're the server receiving callbacks)
            let cb_class = unsafe {
                (vt.class_define)(
                    CALLBACK_DESCRIPTOR.as_ptr() as *const c_char,
                    disp_cb_on_create, disp_cb_on_destroy, disp_cb_on_transact,
                )
            };
            if cb_class.is_null() {
                return Err(CoreError::binder(-1, "AIBinder_Class_define:DisplayCallback"));
            }

            let cb_binder = unsafe { (vt.new_binder)(cb_class, std::ptr::null_mut()) };
            if cb_binder.is_null() {
                return Err(CoreError::binder(-1, "AIBinder_new:DisplayCallback"));
            }

            // registerCallback(callback) — tx 4
            let mut in_ptr: *mut AParcel = std::ptr::null_mut();
            let s = unsafe { (vt.prepare_transaction)(display.ptr, &mut in_ptr) };
            if s != STATUS_OK {
                return Err(CoreError::binder(s, "prepareTransaction:registerCallback"));
            }
            unsafe { (vt.write_strong_binder)(in_ptr, cb_binder) };
            let mut out_ptr: *mut AParcel = std::ptr::null_mut();
            let s = unsafe {
                (vt.transact)(display.ptr, TX_DISPLAY_REGISTER_CALLBACK, &mut in_ptr, &mut out_ptr, 0)
            };
            if !out_ptr.is_null() { unsafe { (vt.parcel_delete)(out_ptr) }; }
            if s != STATUS_OK {
                return Err(CoreError::binder(s, "transact:registerCallback"));
            }

            // Optional: grab power service for is_interactive()
            let power = {
                let raw = unsafe { (vt.get_service)(POWER_SERVICE.as_ptr() as *const c_char) };
                if raw.is_null() { None } else { Some(OwnedBinder { ptr: raw, dec_strong: vt.dec_strong }) }
            };

            // Resolve isInteractive tx code from DEX at open time
            let is_interactive_tx = crate::dex::resolve_is_interactive_tx()
                .ok_or_else(|| CoreError::binder(-1, "dex:TRANSACTION_isInteractive not found"))?;

            // Consumer dup — made before publishing, so an error path drops the
            // owned fd without ever leaving a stale handle for the callback.
            let efd_owned = owned.try_clone()
                .map_err(|e| CoreError::sys(e.raw_os_error().unwrap_or(-1), "dup:display"))
                .and_then(|dup| unsafe {
                    crate::reactor::Fd::from_owned_raw_fd(dup.into_raw_fd(), "display.efd")
                        .map_err(|_| CoreError::binder(-1, "Fd::from_owned_raw_fd:display.efd"))
                })?;

            // Publish the core-owned eventfd for the callback
            *disp_eventfd_guard() = Some(owned);

            // Join binder thread pool so callbacks can fire
            unsafe { (vt.set_thread_pool_max)(0) };
            let join_fn = vt.join_thread_pool;
            std::thread::spawn(move || unsafe { join_fn() });

            Ok((Self { _lib: lib, vt, display, power, is_interactive_tx }, efd_owned))
        }

        pub fn is_interactive(&self) -> Result<bool, CoreError> {
            let power = self.power.as_ref()
                .ok_or_else(|| CoreError::binder(-1, "power:unavailable"))?;
            let mut inp: *mut AParcel = std::ptr::null_mut();
            let s = unsafe { (self.vt.prepare_transaction)(power.ptr, &mut inp) };
            if s != STATUS_OK { return Err(CoreError::binder(s, "prepareTransaction:isInteractive")); }
            let mut out: *mut AParcel = std::ptr::null_mut();
            let s = unsafe {
                (self.vt.transact)(power.ptr, self.is_interactive_tx, &mut inp, &mut out, 0)
            };
            let out = OwnedParcel { ptr: out, delete: self.vt.parcel_delete };
            if s != STATUS_OK { return Err(CoreError::binder(s, "transact:isInteractive")); }
            let r = ParcelReader { vt: &self.vt, parcel: &out };
            let ex = r.read_i32()?;
            if ex != EX_NONE { return Err(CoreError::binder(ex, "isInteractive:exception")); }
            if let Some(rb) = self.vt.read_bool {
                let mut v = false;
                let s = unsafe { rb(out.ptr as *const AParcel, &mut v) };
                if s != STATUS_OK { return Err(CoreError::binder(s, "readBool:isInteractive")); }
                Ok(v)
            } else {
                Ok(r.read_i32()? != 0)
            }
        }
    }

    // ── FpsListener (task FPS callback) ───────────────────────────────────────

    const WINDOW_SERVICE:    &[u8] = b"window\0";
    const WM_DESCRIPTOR:     &[u8] = b"android.view.IWindowManager\0";
    const FPS_DESCRIPTOR:    &[u8] = b"android.window.ITaskFpsCallback\0";
    // Core owns the callback eventfd; the consumer gets a dup and may close it
    // freely. Same lifetime discipline as the other callbacks (C2). The last
    // reported FPS (bit pattern of the f32) is published before the eventfd is
    // signalled, so the consumer never reads a stale value.
    static FPS_EVENTFD: Mutex<Option<OwnedFd>> = Mutex::new(None);
    static FPS_VALUE: AtomicU32 = AtomicU32::new(0);
    static FPS_CODE: AtomicU32 = AtomicU32::new(0);
    static FPS_READ_I32: AtomicUsize = AtomicUsize::new(0);

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

    // No-op callbacks for the client-only IWindowManager class (we never serve
    // transactions on the `window` binder — the class exists only to satisfy
    // AIBinder_prepareTransaction's remote-transaction contract).
    unsafe extern "C" fn wm_on_create(_: *mut c_void) -> *mut c_void { std::ptr::null_mut() }
    unsafe extern "C" fn wm_on_destroy(_: *mut c_void) {}
    unsafe extern "C" fn wm_on_transact(
        _: *mut AIBinder, _: u32, _: *const AParcel, _: *mut AParcel,
    ) -> BinderStatus { STATUS_OK }

    unsafe extern "C" fn fps_on_create(_: *mut c_void) -> *mut c_void { std::ptr::null_mut() }
    unsafe extern "C" fn fps_on_destroy(_: *mut c_void) {}
    unsafe extern "C" fn fps_on_transact(
        _: *mut AIBinder, code: u32, in_parcel: *const AParcel, _: *mut AParcel,
    ) -> BinderStatus {
        if code != FPS_CODE.load(Ordering::Relaxed) {
            return STATUS_UNKNOWN_TRANSACTION;
        }
        // Reader is published non-zero before the code, so a matching code is
        // never paired with an unset reader.
        let read_addr = FPS_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 bits: i32 = 0;
            if unsafe { read_fn(in_parcel, &mut bits) } == STATUS_OK {
                // Publish the value before signalling so the consumer always
                // sees the value that triggered the wakeup.
                FPS_VALUE.store(bits as u32, Ordering::Relaxed);
                if let Some(fd) = fps_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
    }

    /// Push-based per-task FPS listener registered with `WindowManager`.
    ///
    /// Uses `IWindowManager.registerTaskFpsCallback(taskId, callback)`; the
    /// daemon hosts the `ITaskFpsCallback` server object and receives
    /// `onFpsReported(float)` one-way transactions from the `FpsReporter` at
    /// most every ~500 ms.
    ///
    /// The registering UID must hold `ACCESS_FPS_COUNTER` (signature|privileged)
    /// — this process typically runs as shell (uid 2000) via `su`.
    ///
    /// Returns `(Self, OwnedFd)` where the eventfd is a dup of the core's
    /// callback fd. It becomes readable whenever `onFpsReported` fires; call
    /// [`FpsListener::last_fps`] after the event to read the value.
    pub struct FpsListener {
        _lib:       DlHandle,
        vt:         Vtable,
        window:     OwnedBinder,
        cb_binder:  *mut AIBinder,
        _wm_class:  *mut AIBinder_Class,
        register_code: u32,
        unregister_code: u32,
        task_id:    i32,
    }
    unsafe impl Send for FpsListener {}

    impl FpsListener {
        /// Open WindowManager and define the `ITaskFpsCallback` server object.
        ///
        /// Resolves the three tx codes from DEX. Does **not** register a task
        /// yet — call [`FpsListener::register`] once a taskId is known. Starts
        /// the binder thread pool so `onFpsReported` can fire.
        pub fn open() -> Result<(Self, OwnedFd), CoreError> {
            let handle = unsafe {
                libc::dlopen(LIBBINDER_PATH.as_ptr() as *const c_char, libc::RTLD_NOW | libc::RTLD_LOCAL)
            };
            if handle.is_null() { return Err(CoreError::binder(-1, "dlopen:libbinder_ndk.so")); }
            let lib = DlHandle(handle);
            let vt = load_vtable(handle)?;

            let (register_code, unregister_code, on_fps_code) =
                crate::dex::resolve_fps_codes()
                    .ok_or_else(|| CoreError::binder(-1, "dex:TRANSACTION_registerTaskFpsCallback not found"))?;

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

            // Remote transactions require a class on the binder (same
            // AIBinder_prepareTransaction contract as the AM service above).
            let wm_class = unsafe {
                (vt.class_define)(
                    WM_DESCRIPTOR.as_ptr() as *const c_char,
                    wm_on_create, wm_on_destroy, wm_on_transact,
                )
            };
            if wm_class.is_null() {
                return Err(CoreError::binder(-1, "AIBinder_Class_define:IWindowManager"));
            }
            unsafe { (vt.associate_class)(window.ptr, wm_class) };

            let cb_class = unsafe {
                (vt.class_define)(
                    FPS_DESCRIPTOR.as_ptr() as *const c_char,
                    fps_on_create, fps_on_destroy, fps_on_transact,
                )
            };
            if cb_class.is_null() {
                return Err(CoreError::binder(-1, "AIBinder_Class_define:ITaskFpsCallback"));
            }

            let cb_binder = unsafe { (vt.new_binder)(cb_class, std::ptr::null_mut()) };
            if cb_binder.is_null() {
                return Err(CoreError::binder(-1, "AIBinder_new:ITaskFpsCallback"));
            }
            unsafe { (vt.associate_class)(cb_binder, cb_class) };

            // Blocking eventfd — callback writes, consumer waits/reads. Core
            // owns it; the consumer receives a dup below (C2).
            let owned = unsafe {
                let raw = libc::eventfd(0, libc::EFD_CLOEXEC);
                if raw < 0 { return Err(CoreError::sys(*libc::__errno(), "eventfd")); }
                OwnedFd::from_raw_fd(raw)
            };

            let consumer = owned.try_clone()
                .map_err(|e| CoreError::sys(e.raw_os_error().unwrap_or(-1), "dup:fps"))?;

            // Publish reader, code, and eventfd — in that order so the callback
            // never sees a matching code with an unset reader or fd (C2-adjacent).
            FPS_READ_I32.store(vt.read_int32 as usize, Ordering::Relaxed);
            FPS_CODE.store(on_fps_code, Ordering::Relaxed);
            FPS_VALUE.store(0, Ordering::Relaxed);
            *fps_eventfd_guard() = Some(owned);

            unsafe { (vt.set_thread_pool_max)(0) };
            let join_fn = vt.join_thread_pool;
            std::thread::spawn(move || unsafe { join_fn() });

            Ok((Self {
                _lib: lib, vt, window, cb_binder, _wm_class: wm_class,
                register_code, unregister_code, task_id: -1,
            }, consumer))
        }

        /// Register the callback for `task_id`. If a task was already
        /// registered, it is unregistered first (WindowManager tracks one task
        /// per callback binder).
        pub fn register(&mut self, task_id: i32) -> Result<(), CoreError> {
            if self.task_id == task_id {
                return Ok(());
            }
            if self.task_id >= 0 {
                let _ = self.unregister();
            }

            let mut inp: *mut AParcel = std::ptr::null_mut();
            let s = unsafe { (self.vt.prepare_transaction)(self.window.ptr, &mut inp) };
            if s != STATUS_OK { return Err(CoreError::binder(s, "prepareTransaction:registerTaskFpsCallback")); }
            let s = unsafe { (self.vt.write_int32)(inp, task_id) };
            if s != STATUS_OK { return Err(CoreError::binder(s, "AParcel_writeInt32:taskId")); }
            let s = unsafe { (self.vt.write_strong_binder)(inp, self.cb_binder) };
            if s != STATUS_OK { return Err(CoreError::binder(s, "AParcel_writeStrongBinder")); }
            let mut out: *mut AParcel = std::ptr::null_mut();
            let s = unsafe {
                (self.vt.transact)(self.window.ptr, self.register_code, &mut inp, &mut out, 0)
            };
            if !out.is_null() { unsafe { (self.vt.parcel_delete)(out) }; }
            if s != STATUS_OK {
                return Err(CoreError::binder(s, "transact:registerTaskFpsCallback"));
            }
            self.task_id = task_id;
            Ok(())
        }

        /// Unregister the callback from WindowManager. No-op if nothing is
        /// registered.
        pub fn unregister(&mut self) -> Result<(), CoreError> {
            if self.task_id < 0 {
                return Ok(());
            }
            let mut inp: *mut AParcel = std::ptr::null_mut();
            let s = unsafe { (self.vt.prepare_transaction)(self.window.ptr, &mut inp) };
            if s != STATUS_OK { return Err(CoreError::binder(s, "prepareTransaction:unregisterTaskFpsCallback")); }
            let s = unsafe { (self.vt.write_strong_binder)(inp, self.cb_binder) };
            if s != STATUS_OK { return Err(CoreError::binder(s, "AParcel_writeStrongBinder")); }
            let mut out: *mut AParcel = std::ptr::null_mut();
            let s = unsafe {
                (self.vt.transact)(self.window.ptr, self.unregister_code, &mut inp, &mut out, 0)
            };
            if !out.is_null() { unsafe { (self.vt.parcel_delete)(out) }; }
            if s != STATUS_OK {
                return Err(CoreError::binder(s, "transact:unregisterTaskFpsCallback"));
            }
            self.task_id = -1;
            Ok(())
        }

        /// The most recent `onFpsReported` value (f32), or `None` if no report
        /// has arrived yet. Safe to call at any time; the bit pattern is
        /// published atomically.
        pub fn last_fps(&self) -> Option<f32> {
            let bits = FPS_VALUE.load(Ordering::Relaxed);
            if bits == 0 { None } else { Some(f32::from_bits(bits)) }
        }

        /// The taskId currently registered, or `None` if none.
        pub fn task_id(&self) -> Option<i32> {
            (self.task_id >= 0).then_some(self.task_id)
        }
    }

    // ── RawBinderService ──────────────────────────────────────────────────────

    /// Generic binder client for any named Android service.
    ///
    /// Handles its own `dlopen` on `libbinder_ndk.so`. Callers provide raw
    /// transaction codes (resolved via [`crate::dex::find_transaction_code`])
    /// and use [`RawBinderService::transact_bool`] /
    /// [`RawBinderService::transact_i32`] for typed round-trips.
    pub struct RawBinderService {
        _lib:    DlHandle,
        vt:      Vtable,
        service: OwnedBinder,
    }
    unsafe impl Send for RawBinderService {}

    impl RawBinderService {
        /// Open a connection to the named service (e.g. `"power"`, `"batterystats"`).
        pub fn open(service_name: &str) -> Result<Self, CoreError> {
            use std::ffi::CString;
            let handle = unsafe {
                libc::dlopen(LIBBINDER_PATH.as_ptr() as *const c_char, libc::RTLD_NOW | libc::RTLD_LOCAL)
            };
            if handle.is_null() {
                return Err(CoreError::binder(-1, "dlopen:libbinder_ndk.so"));
            }
            let lib = DlHandle(handle);
            let vt = load_vtable(handle)?;
            let cs = CString::new(service_name)
                .map_err(|_| CoreError::binder(-1, "service_name:nul_byte"))?;
            let raw = unsafe { (vt.get_service)(cs.as_ptr()) };
            if raw.is_null() {
                return Err(CoreError::binder(-1, "AServiceManager_getService:null"));
            }
            let service = OwnedBinder { ptr: raw, dec_strong: vt.dec_strong };
            Ok(Self { _lib: lib, vt, service })
        }

        /// Send a no-argument transaction; read exception header then bool reply.
        pub fn transact_bool(&self, code: u32) -> Result<bool, CoreError> {
            let out = self.raw_noarg(code)?;
            let r = ParcelReader { vt: &self.vt, parcel: &out };
            let ex = r.read_i32()?;
            if ex != EX_NONE { return Err(CoreError::binder(ex, "transact_bool:exception")); }
            if let Some(rb) = self.vt.read_bool {
                let mut v = false;
                let s = unsafe { rb(out.ptr as *const AParcel, &mut v) };
                if s != STATUS_OK { return Err(CoreError::binder(s, "AParcel_readBool")); }
                Ok(v)
            } else {
                Ok(r.read_i32()? != 0)
            }
        }

        /// Send a transaction with one i32 argument; discard reply.
        pub fn transact_i32(&self, code: u32, arg: i32) -> Result<(), CoreError> {
            let mut inp: *mut AParcel = std::ptr::null_mut();
            let s = unsafe { (self.vt.prepare_transaction)(self.service.ptr, &mut inp) };
            if s != STATUS_OK { return Err(CoreError::binder(s, "AIBinder_prepareTransaction")); }
            let s = unsafe { (self.vt.write_int32)(inp, arg) };
            if s != STATUS_OK { return Err(CoreError::binder(s, "AParcel_writeInt32")); }
            let mut out: *mut AParcel = std::ptr::null_mut();
            let s = unsafe { (self.vt.transact)(self.service.ptr, code, &mut inp, &mut out, 0) };
            if !out.is_null() { unsafe { (self.vt.parcel_delete)(out) }; }
            if s != STATUS_OK { return Err(CoreError::binder(s, "AIBinder_transact")); }
            Ok(())
        }

        fn raw_noarg(&self, code: u32) -> Result<OwnedParcel, CoreError> {
            let mut inp: *mut AParcel = std::ptr::null_mut();
            let s = unsafe { (self.vt.prepare_transaction)(self.service.ptr, &mut inp) };
            if s != STATUS_OK { return Err(CoreError::binder(s, "AIBinder_prepareTransaction")); }
            let mut out: *mut AParcel = std::ptr::null_mut();
            let s = unsafe { (self.vt.transact)(self.service.ptr, code, &mut inp, &mut out, 0) };
            let out = OwnedParcel { ptr: out, delete: self.vt.parcel_delete };
            if s != STATUS_OK { return Err(CoreError::binder(s, "AIBinder_transact")); }
            Ok(out)
        }
    }
}

// ── Public re-exports ─────────────────────────────────────────────────────────

#[cfg(target_os = "android")]
pub use imp::{ActivityManagerBinder, DisplayManagerBinder, FpsListener, RawBinderService, TxCodes, last_foreground_pid, resolve_tx_codes};

// ── Non-Android stubs ─────────────────────────────────────────────────────────

#[cfg(not(target_os = "android"))]
pub struct ActivityManagerBinder;

#[cfg(not(target_os = "android"))]
impl ActivityManagerBinder {
    pub fn open() -> Result<Self, crate::CoreError> {
        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
    }
    pub fn open_with_observer() -> Result<(Self, std::os::fd::OwnedFd), crate::CoreError> {
        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
    }
    pub fn open_with_fgproc_observer() -> Result<(Self, std::os::fd::OwnedFd), crate::CoreError> {
        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
    }
    pub fn get_focused_package(&self) -> Result<Option<String>, crate::CoreError> {
        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
    }
    pub fn get_focused_task_id(&self) -> Result<Option<i32>, crate::CoreError> {
        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
    }
}

#[cfg(not(target_os = "android"))]
pub struct DisplayManagerBinder;

#[cfg(not(target_os = "android"))]
impl DisplayManagerBinder {
    pub fn open_with_callback() -> Result<(Self, crate::reactor::Fd), crate::CoreError> {
        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
    }
    pub fn is_interactive(&self) -> Result<bool, crate::CoreError> {
        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
    }
}

#[cfg(not(target_os = "android"))]
pub struct RawBinderService;

#[cfg(not(target_os = "android"))]
impl RawBinderService {
    pub fn open(_service_name: &str) -> Result<Self, crate::CoreError> {
        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
    }
    pub fn transact_bool(&self, _code: u32) -> Result<bool, crate::CoreError> {
        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
    }
    pub fn transact_i32(&self, _code: u32, _arg: i32) -> Result<(), crate::CoreError> {
        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
    }
}

#[cfg(not(target_os = "android"))]
pub struct FpsListener;

#[cfg(not(target_os = "android"))]
impl FpsListener {
    pub fn open() -> Result<(Self, std::os::fd::OwnedFd), crate::CoreError> {
        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
    }
    pub fn register(&mut self, _task_id: i32) -> Result<(), crate::CoreError> {
        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
    }
    pub fn unregister(&mut self) -> Result<(), crate::CoreError> {
        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
    }
    pub fn last_fps(&self) -> Option<f32> {
        None
    }
    pub fn task_id(&self) -> Option<i32> {
        None
    }
}

#[cfg(not(target_os = "android"))]
pub struct TxCodes { pub observer_code: u32, pub query_code: u32, pub api_mode: u8, pub fg_code: u32 }

#[cfg(not(target_os = "android"))]
pub fn resolve_tx_codes() -> Result<TxCodes, crate::CoreError> {
    Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
}

#[cfg(not(target_os = "android"))]
pub fn last_foreground_pid() -> i32 {
    0
}