cloudfox-coreshift-core 1.2.39

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
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
// 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::Mutex;
    use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicUsize, Ordering};

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

    /// Ceiling on a single parcel string regardless of the length the peer
    /// advertises. Component names are at most a few hundred bytes; this bounds
    /// the allocation so a malformed advertised length cannot drive a giant
    /// `reserve_exact` (which would abort on OOM).
    const MAX_BINDER_STRING_LEN: usize = 1024 * 1024;

    unsafe extern "C" fn string_alloc(
        cookie: *mut c_void,
        length: i32,
        buffer: *mut *mut c_char,
    ) -> bool {
        // Negative or oversized lengths are allocation failures: returning
        // true with no usable buffer would hand the reader a dangling pointer,
        // and an oversized reserve_exact would abort on OOM.
        if length < 0 {
            return false;
        }
        let len = length as usize;
        if len > MAX_BINDER_STRING_LEN {
            return false;
        }
        let s = unsafe { &mut *(cookie as *mut StringBuf) };
        s.0.reserve_exact(len + 1);
        unsafe { s.0.as_mut_vec().resize(len + 1, 0) };
        unsafe { *buffer = s.0.as_mut_ptr() as *mut c_char };
        true
    }

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

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

    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(),
        get_user_data: unsafe extern "C" fn(*const AIBinder) -> *mut c_void,
        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;
    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()
            ),
            get_user_data: dlsym_fn!(
                handle,
                "AIBinder_getUserData",
                unsafe extern "C" fn(*const AIBinder) -> *mut c_void
            ),
            write_int32: dlsym_fn!(
                handle,
                "AParcel_writeInt32",
                unsafe extern "C" fn(*mut AParcel, i32) -> BinderStatus
            ),
            read_bool: dlsym_opt!(
                handle,
                "AParcel_readBool",
                unsafe extern "C" fn(*const AParcel, *mut bool) -> BinderStatus
            ),
        })
    }

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

    // ── ParcelWriter / transact helper ────────────────────────────────────────

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

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

    /// Prepare an input parcel, run `writes`, then transact. RAII on both
    /// ends: a write error drops the input parcel (previously it leaked on the
    /// write-error path, never reaching transact), and the reply parcel is
    /// returned owned. The input parcel is transferred to `AIBinder_transact`
    /// (the framework deletes it even on failure), so the wrapper records that
    /// by nulling its pointer — never a double-delete.
    fn transact_write(
        vt: &Vtable,
        binder: *mut AIBinder,
        code: u32,
        writes: impl FnOnce(&ParcelWriter<'_>) -> Result<(), CoreError>,
    ) -> Result<OwnedParcel, CoreError> {
        let mut in_ptr: *mut AParcel = std::ptr::null_mut();
        let s = unsafe { (vt.prepare_transaction)(binder, &mut in_ptr) };
        if s != STATUS_OK {
            return Err(CoreError::binder(s, "AIBinder_prepareTransaction"));
        }
        let mut inp = OwnedParcel {
            ptr: in_ptr,
            delete: vt.parcel_delete,
        };
        {
            let writer = ParcelWriter { vt, parcel: &inp };
            writes(&writer)?;
        }
        let mut out_ptr: *mut AParcel = std::ptr::null_mut();
        let s = unsafe { (vt.transact)(binder, code, &mut inp.ptr, &mut out_ptr, 0) };
        // The framework owns (and deletes) the input parcel from here.
        inp.ptr = std::ptr::null_mut();
        let out = OwnedParcel {
            ptr: out_ptr,
            delete: vt.parcel_delete,
        };
        if s != STATUS_OK {
            return Err(CoreError::binder(s, "AIBinder_transact"));
        }
        Ok(out)
    }

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

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

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

    // ── Tx code resolution ────────────────────────────────────────────────────

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

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

    // ── 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;
            let vt = load_vtable(handle)?;

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

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

            let service = OwnedBinder {
                ptr: raw,
                dec_strong: vt.dec_strong,
            };
            Ok((lib, vt, am_class, service))
        }

        fn dlopen_libbinder() -> Result<*mut c_void, CoreError> {
            use std::os::raw::c_char;
            let handle = unsafe {
                libc::dlopen(
                    LIBBINDER_PATH.as_ptr() as *const c_char,
                    libc::RTLD_NOW | libc::RTLD_LOCAL,
                )
            };
            if handle.is_null() {
                return Err(CoreError::binder(-1, "dlopen:libbinder_ndk.so"));
            }
            Ok(handle)
        }

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

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

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

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

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

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

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

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

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

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

        /// Open ActivityManager binder and register as the foreground process
        /// observer.
        ///
        /// The authoritative foreground PID is delivered in the callback; this
        /// is the low-noise foreground source. Two ROM variants are supported
        /// and selected automatically:
        ///
        /// - Stock: `IForegroundProcessObserver.onForegroundProcessChanged`
        ///   delivers a single `int pid`.
        /// - Custom ROMs that dropped that interface instead deliver `(int pid,
        ///   int uid, int fg)` through the repurposed
        ///   `IProcessObserver.onForegroundActivitiesChanged`; this registers
        ///   via `registerProcessObserver` and only signals on `fg != 0`.
        ///
        /// The callback stores the PID (readable via [`last_foreground_pid`])
        /// and signals the returned eventfd.
        ///
        /// Returns `(Self, OwnedFd)` where the eventfd is a dup of the core's
        /// callback fd. It becomes readable whenever a foreground process
        /// change fires. Same lifetime contract as
        /// [`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 _ = transact_write(&vt, service.ptr, register_code, |w| {
                w.write_strong_binder(obs_binder)
            })?;

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

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

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

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

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

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

        /// The `topActivity` package of the focused root task (legacy API 29
        /// builds use `StackInfo` and still resolve the package). Thin wrapper
        /// over [`ActivityManagerBinder::get_focused_task`].
        pub fn get_focused_package(&self) -> Result<Option<String>, CoreError> {
            if self.legacy {
                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);
                }
                return parse_stack_info_body(&r);
            }
            Ok(self.get_focused_task()?.map(|(_, pkg)| pkg).flatten())
        }

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

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

    const DISPLAY_SERVICE: &[u8] = b"display\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,
        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;
            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 _ = transact_write(&vt, display.ptr, TX_DISPLAY_REGISTER_CALLBACK, |w| {
                w.write_strong_binder(cb_binder)
            })?;

            // 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,
                    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 out = transact_write(&self.vt, power.ptr, self.is_interactive_tx, |_| Ok(()))?;
            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";
    // The last reported FPS (bit pattern of the f32) is published before the
    // eventfd is signalled, so the consumer never reads a stale value. The wake
    // eventfd is per-instance (same pattern as TaskStackListener): it is handed
    // to AIBinder_new as the callback binder's userdata, so a second
    // FpsListener can never rewire an earlier registration's wake into its own
    // fd (the callback resolves its own binder's fd via AIBinder_getUserData).
    static FPS_VALUE: AtomicU32 = AtomicU32::new(0);
    // Distinct from FPS_VALUE's bits: `0.0f32` has bit pattern 0, so a "not
    // seen" sentinel of 0 would misread a genuine idle (0-FPS) report as "no
    // report yet" — swallowing the sample and (downstream) leaving the first-
    // report-after-swap drop armed. The seen flag disambiguates.
    static FPS_SEEN: AtomicBool = AtomicBool::new(false);
    static FPS_CODE: AtomicU32 = AtomicU32::new(0);
    static FPS_READ_I32: AtomicUsize = AtomicUsize::new(0);

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

    // The per-instance wake eventfd is this callback binder's userdata, so
    // onCreate must return the args passed to AIBinder_new — AIBinder_getUserData
    // returns exactly that value — and onDestroy must reclaim the box (same
    // pattern as TaskStackListener). Returning null here would make
    // AIBinder_getUserData return null, silently breaking the FPS wake.
    unsafe extern "C" fn fps_on_create(userdata: *mut c_void) -> *mut c_void {
        userdata
    }
    unsafe extern "C" fn fps_on_destroy(userdata: *mut c_void) {
        if !userdata.is_null() {
            unsafe { drop(Box::from_raw(userdata as *mut OwnedFd)) };
        }
    }
    unsafe extern "C" fn fps_on_transact(
        binder: *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. Non-finite/negative
                // reports are normalized to 0.0 first (L5) — the stream must
                // never carry "NaN"/"inf".
                FPS_VALUE.store(sanitize_fps(bits as u32), Ordering::Relaxed);
                FPS_SEEN.store(true, Ordering::Release);
                // Per-instance wake: the eventfd is this callback binder's
                // userdata (see FpsListener::open), so two FpsListeners never
                // cross-wire their wakes. A missing slot means the process-wide
                // AIBinder_getUserData symbol has not been cached — drop the
                // signal rather than risk a stale fd.
                let get_user_data = GET_USER_DATA.lock().unwrap_or_else(|p| p.into_inner());
                if let Some(get_user_data) = *get_user_data {
                    let userdata = unsafe { get_user_data(binder) };
                    if !userdata.is_null() {
                        let efd = userdata as *mut OwnedFd;
                        let val: u64 = 1;
                        unsafe {
                            libc::write((*efd).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;
            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",
                ));
            }

            // Blocking eventfd — callback writes, consumer waits/reads. Each
            // instance owns its own fd; it is handed to the callback binder as
            // userdata (per-instance routing, no process-wide static) and 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"))?;

            let userdata = Box::into_raw(Box::new(owned)) as *mut c_void;
            let cb_binder = unsafe { (vt.new_binder)(cb_class, userdata) };
            if cb_binder.is_null() {
                // Reclaim the userdata box handed to AIBinder_new before bailing.
                unsafe { drop(Box::from_raw(userdata as *mut OwnedFd)) };
                return Err(CoreError::binder(-1, "AIBinder_new:ITaskFpsCallback"));
            }
            unsafe { (vt.associate_class)(cb_binder, cb_class) };

            // Publish the reader and code before the eventfd registration; a
            // matching code is never paired with an unset reader (C2-adjacent).
            FPS_READ_I32.store(vt.read_int32 as usize, Ordering::Relaxed);
            FPS_SEEN.store(false, Ordering::Relaxed);
            FPS_CODE.store(on_fps_code, Ordering::Relaxed);
            FPS_VALUE.store(0, Ordering::Relaxed);
            // The callback resolves AIBinder_getUserData from this vtable; the
            // symbol address is process-wide, so a cached static is safe.
            *GET_USER_DATA.lock().unwrap_or_else(|p| p.into_inner()) = Some(vt.get_user_data);

            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 _ = transact_write(&self.vt, self.window.ptr, self.register_code, |w| {
                w.write_i32(task_id)?;
                w.write_strong_binder(self.cb_binder)
            })?;
            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 _ = transact_write(&self.vt, self.window.ptr, self.unregister_code, |w| {
                w.write_strong_binder(self.cb_binder)
            })?;
            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. A genuine 0.0 (idle) report reads as `Some`,
        /// distinguished from the no-report state by `FPS_SEEN`.
        pub fn last_fps(&self) -> Option<f32> {
            fps_from_state(
                FPS_SEEN.load(Ordering::Acquire),
                FPS_VALUE.load(Ordering::Relaxed),
            )
        }

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

    impl Drop for FpsListener {
        /// Best-effort deregistration from WindowManager so a dropped listener
        /// does not leave the framework delivering `onFpsReported` forever. The
        /// callback binder's local strong ref is intentionally NOT released:
        /// keeping it alive guarantees the per-binder userdata (the OwnedFd)
        /// can never be reclaimed by `on_destroy` while a callback is in
        /// flight, and the framework-side registration has been dropped by the
        /// unregister, so no stale transaction targets this instance.
        fn drop(&mut self) {
            let _ = self.unregister();
        }
    }

    /// Disambiguate "no report yet" from a genuine 0.0 (idle) report: `seen`
    /// tracks whether the callback published a value; `bits` is that value's
    /// bit pattern. `0.0f32` has bits 0, so the bits alone cannot tell a real
    /// idle sample from an unset slot.
    fn fps_from_state(seen: bool, bits: u32) -> Option<f32> {
        if seen {
            Some(f32::from_bits(bits))
        } else {
            None
        }
    }

    /// Normalize an `onFpsReported` bit pattern for the stream. Real FPS is
    /// non-negative and finite; NaN/±Inf (garbage or corruption) and negative
    /// values collapse to 0.0 (idle) so the value stream never shows "NaN" or
    /// "inf".
    fn sanitize_fps(bits: u32) -> u32 {
        let v = f32::from_bits(bits);
        if v.is_finite() && v >= 0.0 {
            bits
        } else {
            0.0f32.to_bits()
        }
    }

    // ── TaskStackListener (task-stack change wake-up) ────────────────────────

    const TASK_SERVICE: &[u8] = b"activity_task\0";
    const ATM_DESCRIPTOR: &[u8] = b"android.app.IActivityTaskManager\0";
    const TASK_STACK_DESCRIPTOR: &[u8] = b"android.app.ITaskStackListener\0";

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

    // Pure wake-up handler: any ITaskStackListener callback
    // (onTaskStackChanged, onTaskMovedToFront, …) just signals the eventfd.
    // The callback arguments are deliberately NOT parsed — the authoritative
    // (taskId, pkg) comes from re-querying getFocusedRootTaskInfo (txn 31) on
    // the event, so we never depend on a parcel layout (RunningTaskInfo places
    // taskId near the parcel tail).
    //
    // The wake eventfd is per-instance: the daemon hosts two listeners (the fg
    // task source and the fps channel), each with its own eventfd. It is handed
    // to AIBinder_new as the binder's userdata, so on_destroy must reclaim it.
    // No process-wide static — a shared fd would deliver every instance's
    // wake to whichever listener opened last.
    //
    // The callback resolves the per-binder eventfd through AIBinder_getUserData.
    // The symbol address is process-wide, so it is cached once in a static.
    static GET_USER_DATA: std::sync::Mutex<
        Option<unsafe extern "C" fn(*const AIBinder) -> *mut c_void>,
    > = std::sync::Mutex::new(None);

    unsafe extern "C" fn task_stack_on_create(userdata: *mut c_void) -> *mut c_void {
        userdata
    }
    unsafe extern "C" fn task_stack_on_destroy(userdata: *mut c_void) {
        if !userdata.is_null() {
            unsafe { drop(Box::from_raw(userdata as *mut OwnedFd)) };
        }
    }
    unsafe extern "C" fn task_stack_on_transact(
        binder: *mut AIBinder,
        _code: u32,
        _in_parcel: *const AParcel,
        _reply: *mut AParcel,
    ) -> BinderStatus {
        let get_user_data = GET_USER_DATA.lock().unwrap_or_else(|p| p.into_inner());
        if let Some(get_user_data) = *get_user_data {
            let userdata = unsafe { get_user_data(binder) };
            if !userdata.is_null() {
                let efd = userdata as *mut OwnedFd;
                let val: u64 = 1;
                unsafe { libc::write((*efd).as_raw_fd(), &val as *const u64 as *const c_void, 8) };
            }
        }
        STATUS_OK
    }

    /// Push-based task-stack change listener registered with
    /// `IActivityTaskManager`.
    ///
    /// Uses `IActivityTaskManager.registerTaskStackListener(listener)`; the
    /// daemon hosts the `ITaskStackListener` server object. The callback is a
    /// pure wake-up: on any task-stack change it signals the eventfd and
    /// parses nothing. Consumers re-query `getFocusedRootTaskInfo` (txn 31) on
    /// the event for the authoritative `(taskId, pkg)`.
    ///
    /// This target's ROM exposes the legacy `ITaskStackListener` /
    /// `registerTaskStackListener` pair; the newer `ITaskChangeListener` /
    /// `registerTaskChangeListener` interface is absent.
    ///
    /// The registering UID must hold `MANAGE_ACTIVITY_TASKS` /
    /// `MANAGE_ACTIVITY_STACKS` — the same gate as txn 31, which root passes
    /// empirically on the target ROM.
    ///
    /// Returns `(Self, OwnedFd)` where the eventfd is a dup of the core's
    /// callback fd. It becomes readable on any task-stack change.
    pub struct TaskStackListener {
        _lib: DlHandle,
        vt: Vtable,
        service: OwnedBinder,
        cb_binder: *mut AIBinder,
        _atm_class: *mut AIBinder_Class,
        register_code: u32,
        unregister_code: u32,
    }
    unsafe impl Send for TaskStackListener {}

    impl TaskStackListener {
        /// Open `activity_task`, define the `ITaskStackListener` server object,
        /// and start the binder thread pool. Does **not** register yet — call
        /// [`TaskStackListener::register`] once consumers are active.
        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;
            let vt = load_vtable(handle)?;

            let (register_code, unregister_code) = crate::dex::resolve_task_stack_codes()
                .ok_or_else(|| {
                    CoreError::binder(-1, "dex:TRANSACTION_registerTaskStackListener not found")
                })?;

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

            // Remote transactions require a class on the binder (same
            // AIBinder_prepareTransaction contract as the other services).
            let atm_class = unsafe {
                (vt.class_define)(
                    ATM_DESCRIPTOR.as_ptr() as *const c_char,
                    atm_on_create,
                    atm_on_destroy,
                    atm_on_transact,
                )
            };
            if atm_class.is_null() {
                return Err(CoreError::binder(
                    -1,
                    "AIBinder_Class_define:IActivityTaskManager",
                ));
            }
            unsafe { (vt.associate_class)(service.ptr, atm_class) };

            let cb_class = unsafe {
                (vt.class_define)(
                    TASK_STACK_DESCRIPTOR.as_ptr() as *const c_char,
                    task_stack_on_create,
                    task_stack_on_destroy,
                    task_stack_on_transact,
                )
            };
            if cb_class.is_null() {
                return Err(CoreError::binder(
                    -1,
                    "AIBinder_Class_define:ITaskStackListener",
                ));
            }

            // Blocking eventfd — callback writes, consumer waits/reads. Each
            // instance owns its own fd; it is handed to the callback binder as
            // userdata (per-instance routing, no process-wide static) and 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:task_stack"))?;

            let userdata = Box::into_raw(Box::new(owned)) as *mut c_void;
            let cb_binder = unsafe { (vt.new_binder)(cb_class, userdata) };
            if cb_binder.is_null() {
                // Reclaim the userdata box handed to AIBinder_new before bailing.
                unsafe { drop(Box::from_raw(userdata as *mut OwnedFd)) };
                return Err(CoreError::binder(-1, "AIBinder_new:ITaskStackListener"));
            }
            unsafe { (vt.associate_class)(cb_binder, cb_class) };

            // The callback resolves AIBinder_getUserData from this vtable; the
            // symbol address is process-wide, so a cached static is safe.
            *GET_USER_DATA.lock().unwrap_or_else(|p| p.into_inner()) = Some(vt.get_user_data);

            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,
                    service,
                    cb_binder,
                    _atm_class: atm_class,
                    register_code,
                    unregister_code,
                },
                consumer,
            ))
        }

        /// Register the task-stack listener with `activity_task` (one listener
        /// receives all task-stack events). Idempotent at the framework level;
        /// callers should register once and keep the object alive.
        pub fn register(&self) -> Result<(), CoreError> {
            let _ = transact_write(&self.vt, self.service.ptr, self.register_code, |w| {
                w.write_strong_binder(self.cb_binder)
            })?;
            Ok(())
        }

        /// Unregister the task-stack listener from `activity_task`. No-op at
        /// the framework level if not registered; callers should unregister
        /// before dropping the object.
        pub fn unregister(&self) -> Result<(), CoreError> {
            let _ = transact_write(&self.vt, self.service.ptr, self.unregister_code, |w| {
                w.write_strong_binder(self.cb_binder)
            })?;
            Ok(())
        }
    }

    impl Drop for TaskStackListener {
        /// Best-effort deregistration from `activity_task`. Same deliberate
        /// non-release of the local strong ref as [`FpsListener`] — the
        /// userdata OwnedFd stays valid for any in-flight wake, and the
        /// framework-side registration is gone after the unregister.
        fn drop(&mut self) {
            let _ = self.unregister();
        }
    }

    // ── 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;
            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 _ = transact_write(&self.vt, self.service.ptr, code, |w| w.write_i32(arg))?;
            Ok(())
        }

        fn raw_noarg(&self, code: u32) -> Result<OwnedParcel, CoreError> {
            transact_write(&self.vt, self.service.ptr, code, |_| Ok(()))
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        fn alloc(length: i32) -> bool {
            let mut buf = StringBuf::new();
            let mut out: *mut c_char = std::ptr::null_mut();
            unsafe { string_alloc(&mut buf as *mut StringBuf as *mut c_void, length, &mut out) }
        }

        #[test]
        fn string_alloc_rejects_oversized() {
            assert!(!alloc(MAX_BINDER_STRING_LEN as i32 + 1));
        }

        #[test]
        fn string_alloc_rejects_negative() {
            assert!(!alloc(-1));
        }

        #[test]
        fn string_alloc_accepts_valid_len_and_nul_terminates() {
            let mut buf = StringBuf::new();
            let mut out: *mut c_char = std::ptr::null_mut();
            let ok =
                unsafe { string_alloc(&mut buf as *mut StringBuf as *mut c_void, 4, &mut out) };
            assert!(ok);
            assert!(!out.is_null());
            {
                let vec = unsafe { buf.0.as_mut_vec() };
                b"ABCD".iter().enumerate().for_each(|(i, &b)| vec[i] = b);
                vec[4] = 0;
            }
            assert_eq!(buf.finish().as_deref(), Some("ABCD"));
        }

        #[test]
        fn fps_zero_report_distinct_from_unseen() {
            assert_eq!(fps_from_state(false, 0), None);
            assert_eq!(fps_from_state(true, 0), Some(0.0));
            assert_eq!(fps_from_state(true, 60.0f32.to_bits()), Some(60.0));
            assert_eq!(fps_from_state(false, 60.0f32.to_bits()), None);
        }

        #[test]
        fn sanitize_fps_rejects_non_finite_and_negative() {
            let de = |bits| f32::from_bits(sanitize_fps(bits));
            assert_eq!(de(0.0f32.to_bits()), 0.0);
            assert_eq!(de(60.0f32.to_bits()), 60.0);
            assert_eq!(de(f32::NAN.to_bits()), 0.0);
            assert_eq!(de(f32::INFINITY.to_bits()), 0.0);
            assert_eq!(de(f32::NEG_INFINITY.to_bits()), 0.0);
            assert_eq!(de((-5.0f32).to_bits()), 0.0);
        }
    }
}

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

#[cfg(target_os = "android")]
pub use imp::{
    ActivityManagerBinder, DisplayManagerBinder, FpsListener, RawBinderService, TaskStackListener,
    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_task(&self) -> Result<Option<(i32, Option<String>)>, 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 TaskStackListener;

#[cfg(not(target_os = "android"))]
impl TaskStackListener {
    pub fn open() -> Result<(Self, std::os::fd::OwnedFd), crate::CoreError> {
        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
    }
    pub fn register(&self) -> Result<(), crate::CoreError> {
        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
    }
    pub fn unregister(&self) -> Result<(), crate::CoreError> {
        Err(crate::CoreError::binder(-1, "binder:unsupported platform"))
    }
}

#[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
}