rsbinder 0.10.0

Pure-Rust Binder IPC for Linux, Android, and macOS — kernel binder plus a libbinder-compatible RPC (binder-over-socket) transport.
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
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
// Copyright 2022 Jeff Kim <hiking90@gmail.com>
// SPDX-License-Identifier: Apache-2.0

/*
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//! Thread-local binder state management.
//!
//! This module manages the per-thread state for binder operations, including
//! transaction context, reference counting, and communication with the binder driver.
//! Each thread participating in binder IPC maintains its own state through this module.
//!
//! # Borrow-Discipline Invariant (R1)
//!
//! `THREAD_STATE` and `BINDER_DEREFS` are `RefCell`s. Their `borrow*()` guards
//! must NOT be held across calls that may re-borrow either cell. The set of
//! calls that may re-borrow includes:
//!
//!   - User-code entry points: `Transactable::transact`, `Inner<T>::drop`
//!     (invoked via `deref_native_kernel`), and
//!     `DeathRecipient::binder_died`.
//!   - Other functions in this module that take a borrow at some point:
//!     `transact`, `wait_for_response`, `flush_commands`, `flash_if_needed`,
//!     `inc_strong_handle`, `dec_strong_handle`, `inc_weak_handle`,
//!     `dec_weak_handle`, `free_buffer`, and `process_pending_derefs`.
//!
//! Violation manifests as a `RefCell` panic ("already borrowed" /
//! "already mutably borrowed"). Binder's nested-IPC protocol means user
//! callbacks routinely make outgoing binder calls from inside an incoming
//! `BR_TRANSACTION`, so this is not a theoretical concern.
//!
//! ## Patterns to satisfy R1
//!
//! - **P2 — Minimal scope**: scope each borrow as tightly as "read value →
//!   process → write value". Drop the borrow before calling out, then
//!   re-acquire a fresh borrow afterwards. Don't span the entire function
//!   body inside one `borrow_mut()`.
//! - **P3 — Stack-save**: when a user callback is about to be invoked, save
//!   and restore logical state (e.g. `transaction`) via local variables on
//!   the call stack, not via persisted `RefCell` borrows. Persisting state
//!   in a `RefCell` borrow across a callback risks dragging the borrow into
//!   re-entrant code.
//!
//! See `b17d522` for the regression that motivated the explicit P2 split in
//! `process_pending_derefs`.

use log::error;
use std::backtrace::Backtrace;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::ffi::{CStr, CString};
use std::fmt::Debug;
use std::fs::File;
use std::sync::{atomic::Ordering, Arc};

use crate::{binder::*, error::*, parcel::*, process_state::*, sys::*};

// See module doc — R1: borrows of these `RefCell`s must not be held across
// calls that may re-borrow either cell (user callbacks, other binder entry
// points). Use the P2 (minimal scope) and P3 (stack-save) patterns.
thread_local! {
    static THREAD_STATE: RefCell<ThreadState> = RefCell::new(ThreadState::new());
    static BINDER_DEREFS: RefCell<BinderDerefs> = RefCell::new(BinderDerefs::new());
}

// ---- RPC calling context (Plan 2-16 Phase B) ------------------------
//
// The kernel calling identity lives in `THREAD_STATE.transaction`, but
// `ThreadState::new()` eagerly pulls `ProcessState::as_self()`, which
// **panics in a pure-RPC process** (no kernel binder). The RPC dispatch
// path therefore must NOT touch `THREAD_STATE`. Instead it stamps the
// caller's uid/pid into this separate, ProcessState-independent
// thread-local for the duration of one RPC `on_transact`, and the public
// calling-identity accessors consult it *first* (so they work in a
// pure-RPC process and never force the kernel thread-local).
//
// The store holds an `Arc<PeerIdentity>` (the full peer, so handler-side
// authorization can see uid *and* the cert/vsock identity), borrowed only
// momentarily (clone-out) and never across the user handler, so the R1
// borrow discipline that governs `THREAD_STATE`/`BINDER_DEREFS` does not
// apply here (set → run handler → restore, no live borrow during the
// callout). `Arc` keeps the per-dispatch and oneway-drain installs cheap.
#[cfg(feature = "rpc")]
thread_local! {
    static RPC_CALLING: std::cell::RefCell<Option<std::sync::Arc<crate::rpc::transport::PeerIdentity>>> =
        const { std::cell::RefCell::new(None) };
}

/// Fail-closed calling uid for RPC transports that carry **no** uid
/// (`Vsock` cid, TLS `Certificate`, `Anonymous`). `u32::MAX`
/// (`(uid_t)-1`) is never a real privileged uid, so a hand-rolled uid
/// ACL (`if get_calling_uid() == AID_SYSTEM { … }`) can never
/// accidentally match — and it is deliberately **not** `0`, so it can
/// never be mistaken for root. See Plan 2-16 §1.2.
#[cfg(feature = "rpc")]
pub(crate) const RPC_UNKNOWN_CALLING_UID: binder::uid_t = binder::uid_t::MAX;

/// Stamp the RPC caller's [`PeerIdentity`](crate::rpc::PeerIdentity) into
/// [`RPC_CALLING`] for the duration of one `on_transact`, restoring the
/// previous value on drop (so nested re-entrant callbacks over the same
/// connection nest correctly). Installed by the RPC dispatch path
/// (`rpc::session::execute_dispatched`) around `rpc_transact`.
#[cfg(feature = "rpc")]
pub(crate) struct RpcCallingGuard {
    previous: Option<std::sync::Arc<crate::rpc::transport::PeerIdentity>>,
}

#[cfg(feature = "rpc")]
impl RpcCallingGuard {
    pub(crate) fn install(peer: std::sync::Arc<crate::rpc::transport::PeerIdentity>) -> Self {
        let previous = RPC_CALLING.with(|c| c.borrow_mut().replace(peer));
        RpcCallingGuard { previous }
    }
}

#[cfg(feature = "rpc")]
impl Drop for RpcCallingGuard {
    fn drop(&mut self) {
        RPC_CALLING.with(|c| *c.borrow_mut() = self.previous.take());
    }
}

/// `(uid, pid)` mapping for the current RPC peer: a Unix peer carries a
/// kernel-vouched uid/pid; transports without a uid (`Vsock` /
/// `Certificate` / `Anonymous`) map to the fail-closed
/// [`RPC_UNKNOWN_CALLING_UID`] sentinel and pid `-1`.
#[cfg(feature = "rpc")]
fn peer_uid_pid(peer: &crate::rpc::transport::PeerIdentity) -> (binder::uid_t, binder::pid_t) {
    match peer {
        crate::rpc::transport::PeerIdentity::Local { uid, pid } => (*uid, *pid),
        _ => (RPC_UNKNOWN_CALLING_UID, -1),
    }
}

/// The current RPC caller's `(uid, pid)`, or `None` when not dispatching
/// an RPC transaction (always `None` without the `rpc` feature). Never
/// touches `THREAD_STATE`/`ProcessState`, so it is safe to call in a
/// pure-RPC process.
#[inline]
fn rpc_calling() -> Option<(binder::uid_t, binder::pid_t)> {
    #[cfg(feature = "rpc")]
    {
        RPC_CALLING.with(|c| c.borrow().as_deref().map(peer_uid_pid))
    }
    #[cfg(not(feature = "rpc"))]
    {
        None
    }
}

/// The caller of the in-flight binder transaction, tagged by transport so
/// handler-side authorization can branch **explicitly** — the kernel and
/// RPC trust boundaries are genuinely different and must not be papered
/// over (Plan 2-16). Returned by [`calling_caller`].
///
/// Authorization differs by arm:
/// - [`Caller::Kernel`] — Android permissions (`@EnforcePermission` /
///   [`crate::permission_controller::check_permission`]), `uid`/`pid`
///   ACLs, or the SELinux `sid`.
/// - `Caller::Rpc` (with the `rpc` feature) — the transport's own trust
///   boundary: a Unix `PeerIdentity::Local` uid ACL, a TLS
///   `Certificate` subject/fingerprint allowlist, etc.
///   `@EnforcePermission` is **denied** over RPC (Plan 2-16 Phase A).
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Caller {
    /// A kernel-binder caller. `sid` is the SELinux context when the
    /// target binder requested it (`BinderFeatures::set_requesting_sid`).
    Kernel {
        /// Caller effective uid (kernel `sender_euid`).
        uid: binder::uid_t,
        /// Caller pid (kernel `sender_pid`).
        pid: binder::pid_t,
        /// SELinux context, if delivered (see [`get_calling_sid`]).
        sid: Option<CString>,
    },
    /// An RPC caller, identified by its transport peer identity.
    #[cfg(feature = "rpc")]
    Rpc(crate::rpc::transport::PeerIdentity),
}

/// The caller of the current in-flight binder transaction, tagged by
/// transport ([`Caller`]), or `None` when this thread is not dispatching
/// one. Pure-RPC safe (never forces the kernel `THREAD_STATE` /
/// `ProcessState`).
///
/// This is the transport-aware basis for handler-side authorization: a
/// service `match`es on the [`Caller`] arm and applies the right check
/// (Android permission vs uid ACL vs TLS-cert allowlist). For a single
/// injectable policy across both transports, see
/// [`crate::permission_controller::PermissionAuthority`].
pub fn calling_caller() -> Option<Caller> {
    // RPC takes precedence and never touches the ProcessState-coupled
    // kernel thread-local (works in a pure-RPC process).
    #[cfg(feature = "rpc")]
    {
        if let Some(peer) = RPC_CALLING.with(|c| c.borrow().as_deref().cloned()) {
            return Some(Caller::Rpc(peer));
        }
    }
    if !ProcessState::is_initialized() {
        return None;
    }
    THREAD_STATE.with(|thread_state| {
        let thread_state = thread_state.borrow();
        thread_state.transaction.as_ref().map(|tr| {
            let sid = if tr.calling_sid.is_null() {
                None
            } else {
                // SAFETY: `calling_sid` is the kernel-delivered, NUL-
                // terminated SELinux context for this in-flight
                // `BR_TRANSACTION_SEC_CTX`, valid until `BC_FREE_BUFFER`
                // (after the handler returns). Same contract as
                // `get_calling_sid`.
                Some(unsafe { CStr::from_ptr(tr.calling_sid as _).to_owned() })
            };
            Caller::Kernel {
                uid: tr.calling_uid,
                pid: tr.calling_pid,
                sid,
            }
        })
    })
}

// Freeze observer BR labels (nr=20/21/22).
// `BR_TRANSACTION_SEC_CTX` (nr=2) is dispatched by the special-case
// above `return_to_str`'s indexed lookup, so the nr=20 slot is free
// for `BR_TRANSACTION_PENDING_FROZEN`.
const RETURN_STRINGS: [&str; 23] = [
    "BR_ERROR",
    "BR_OK",
    "BR_TRANSACTION",
    "BR_REPLY",
    "BR_ACQUIRE_RESULT",
    "BR_DEAD_REPLY",
    "BR_TRANSACTION_COMPLETE",
    "BR_INCREFS",
    "BR_ACQUIRE",
    "BR_RELEASE",
    "BR_DECREFS",
    "BR_ATTEMPT_ACQUIRE",
    "BR_NOOP",
    "BR_SPAWN_LOOPER",
    "BR_FINISHED",
    "BR_DEAD_BINDER",
    "BR_CLEAR_DEATH_NOTIFICATION_DONE",
    "BR_FAILED_REPLY",
    "BR_FROZEN_REPLY",
    "BR_ONEWAY_SPAM_SUSPECT",
    "BR_TRANSACTION_PENDING_FROZEN",
    "BR_FROZEN_BINDER",
    "BR_CLEAR_FREEZE_NOTIFICATION_DONE",
];

fn return_to_str(cmd: std::os::raw::c_uint) -> &'static str {
    if cmd == binder::BR_TRANSACTION_SEC_CTX {
        "BR_TRANSACTION_SEC_CTX"
    } else {
        let idx: usize = (cmd & binder::_IOC_NRMASK) as _;

        if idx < RETURN_STRINGS.len() {
            RETURN_STRINGS[idx]
        } else {
            "Unknown BR_ return"
        }
    }
}

// Freeze observer BC labels (nr=19/20/21). Used for debug-print
// symmetry with `RETURN_STRINGS`; the BC send path is not yet wired
// into `write_command`.
const COMMAND_STRINGS: [&str; 22] = [
    "BC_TRANSACTION",
    "BC_REPLY",
    "BC_ACQUIRE_RESULT",
    "BC_FREE_BUFFER",
    "BC_INCREFS",
    "BC_ACQUIRE",
    "BC_RELEASE",
    "BC_DECREFS",
    "BC_INCREFS_DONE",
    "BC_ACQUIRE_DONE",
    "BC_ATTEMPT_ACQUIRE",
    "BC_REGISTER_LOOPER",
    "BC_ENTER_LOOPER",
    "BC_EXIT_LOOPER",
    "BC_REQUEST_DEATH_NOTIFICATION",
    "BC_CLEAR_DEATH_NOTIFICATION",
    "BC_DEAD_BINDER_DONE",
    "BC_TRANSACTION_SG",
    "BC_REPLY_SG",
    "BC_REQUEST_FREEZE_NOTIFICATION",
    "BC_CLEAR_FREEZE_NOTIFICATION",
    "BC_FREEZE_NOTIFICATION_DONE",
];

fn command_to_str(cmd: std::os::raw::c_uint) -> &'static str {
    let idx: usize = (cmd & 0xFF) as _;

    if idx < COMMAND_STRINGS.len() {
        COMMAND_STRINGS[idx]
    } else {
        "Unknown BC_ command"
    }
}

const WORK_SOURCE_PROPAGATED_BIT_INDEX: i64 = 32;
pub(crate) const UNSET_WORK_SOURCE: i32 = -1;

#[derive(Debug, Clone, Copy)]
struct TransactionState {
    calling_pid: binder::pid_t,
    calling_sid: *const u8,
    calling_uid: binder::uid_t,
    // strict_mode_policy: i32,
    last_transaction_binder_flags: u32,
    work_source: binder::uid_t,
    propagate_work_source: bool,
    /// AOSP `mHasExplicitIdentity` — `true` after `clear_calling_identity()`
    /// has overridden the kernel-delivered `calling_uid`/`calling_pid`
    /// with the current process's own uid/pid. Reset to `false` on every
    /// new incoming `BR_TRANSACTION` ([IPCThreadState.cpp:1141][1] —
    /// `mHasExplicitIdentity = false`).
    ///
    /// [1]: https://cs.android.com/android/platform/superproject/main/+/main:frameworks/native/libs/binder/IPCThreadState.cpp
    has_explicit_identity: bool,
}

impl TransactionState {
    fn from_transaction_data(data: &binder::binder_transaction_data_secctx) -> Self {
        TransactionState {
            calling_pid: data.transaction_data.sender_pid,
            calling_sid: data.secctx as _,
            calling_uid: data.transaction_data.sender_euid,
            // strict_mode_policy: 0,
            last_transaction_binder_flags: data.transaction_data.flags,
            work_source: 0,
            propagate_work_source: false,
            has_explicit_identity: false,
        }
    }
}

/// Pack `(has_explicit, uid, pid)` into the 64-bit AOSP calling-identity
/// token. Wire-equivalent to `packCallingIdentity` in
/// `IPCThreadState.cpp:498-511`:
///
/// ```text
/// 32b      |        1b         |         1b            |        30b
/// uid      | pid sign bit      | hasExplicitIdentity   | pid (rest)
/// ```
///
/// AOSP packs `hasExplicitIdentity` into the 2nd bit from the left of the
/// lower 32-bit half so that negative PIDs (which use the top sign bit)
/// can still round-trip. rsbinder uses the exact same layout — although
/// tokens never go on the wire, AOSP-faithful encoding makes
/// `clear`/`restore` tokens comparable across implementations and lets
/// any AOSP regression test against the bit pattern still pass.
fn pack_calling_identity(has_explicit: bool, uid: binder::uid_t, pid: binder::pid_t) -> i64 {
    let pid_low = pid as u32;
    let pid_low = if has_explicit {
        pid_low | (1 << 30)
    } else {
        pid_low & !(1 << 30)
    };
    let token = ((uid as u64) << 32) | (pid_low as u64);
    token as i64
}

fn unpack_has_explicit_identity(token: i64) -> bool {
    ((token as i32) & (1 << 30)) != 0
}

fn unpack_calling_uid(token: i64) -> binder::uid_t {
    (token >> 32) as binder::uid_t
}

fn unpack_calling_pid(token: i64) -> binder::pid_t {
    let encoded = token as i32;
    if (encoded & (1 << 31)) != 0 {
        // Negative PID — restore the sign bit overlap with bit 30.
        (encoded | (1 << 30)) as binder::pid_t
    } else {
        (encoded & !(1 << 30)) as binder::pid_t
    }
}

// Storage for inbound BR_RELEASE / BR_DECREFS payloads — process-monotonic
// u64 ids delivered by the kernel for native binders we previously
// published. Processed lazily on the next driver round-trip via
// `process_pending_derefs`.
//
// Under the new id-encoding model (replacing the fat-pointer scheme that
// could dangle when `Inner<T>` was dropped between BR_RELEASE and
// BR_DECREFS), the pending entries are pure ids — `deref_native_kernel`
// looks them up in `ProcessState::published_natives` and drives
// `kernel_refs--` / entry-removal-on-zero. No SIBinder reconstruction
// from a raw pointer, no method dispatch on a possibly-freed `Inner<T>`.
//
// Outbound proxy ref-count (BC_ACQUIRE / BC_RELEASE / BC_INCREFS /
// BC_DECREFS) is not routed through this state — proxies own kernel
// strong refs 1-per-Arc (acquire in `ProxyHandle::new_acquired`, release
// in `ProxyHandle::Drop`) and the cache pin owns the kernel weak ref.
struct BinderDerefs {
    pending_strong_derefs: VecDeque<u64>,
    pending_weak_derefs: VecDeque<u64>,
}

impl BinderDerefs {
    fn new() -> Self {
        BinderDerefs {
            pending_strong_derefs: VecDeque::new(),
            pending_weak_derefs: VecDeque::new(),
        }
    }
}

/// Drain `BINDER_DEREFS` of pending BR_RELEASE / BR_DECREFS ids.
///
/// Each `deref_native_kernel(id)` call may, when an entry's counters
/// both reach zero, trigger `remove_entry_if_zero` which drops the
/// canonical `Arc<dyn IBinder>` and synchronously fires
/// `Inner<T>::drop` on the user's `Remotable` instance. A user
/// destructor that initiates an outgoing synchronous IPC ends up in
/// `wait_for_response` → `talk_with_driver` → `execute_command`,
/// whose BR_RELEASE / BR_DECREFS arms try to push back into
/// `BINDER_DEREFS` via a fresh `borrow_mut()`.
///
/// To make that re-entrancy safe, this function never holds the
/// `BINDER_DEREFS` `RefCell` borrow across a `deref_native_kernel`
/// call. It alternates between:
///
///   1. Acquire the borrow, take the entire weak queue (or pop one
///      strong id), release the borrow.
///   2. Dispatch outside the borrow.
///
/// Pushes from re-entrant BR handlers go into a fresh `borrow_mut`,
/// and the outer loop picks them up on the next iteration.
///
/// Order matches Android's libbinder: drain ALL weak derefs before
/// dispatching the next strong, so a strong-deref destructor that
/// queues a weak-deref gets drained ahead of the next pending
/// strong. FIFO within each queue (`VecDeque::pop_front` /
/// `mem::take` preserves insertion order).
///
/// # Borrow discipline (R1)
///
/// Must be called with NO `THREAD_STATE` or `BINDER_DEREFS` borrow held
/// — `deref_native_kernel` may invoke user `Inner<T>::drop`, which can
/// re-enter the binder stack. The acquire/release alternation inside this
/// function maintains R1; do not hoist the borrow out of the loop.
fn process_pending_derefs() -> Result<()> {
    loop {
        // Inner loop: drain weak fully. Re-take after each batch
        // because dispatch may push more weak entries (from
        // `Inner<T>::drop` running user destructor code that
        // synchronously triggers another BR_DECREFS).
        loop {
            let batch: VecDeque<u64> =
                BINDER_DEREFS.with(|d| std::mem::take(&mut d.borrow_mut().pending_weak_derefs));
            if batch.is_empty() {
                break;
            }
            for id in batch {
                if ProcessState::as_self().deref_native_kernel(id).is_none() {
                    log::trace!("BR_DECREFS for unknown native id {id}");
                }
            }
        }

        // Pop exactly one strong id under a fresh borrow, then
        // dispatch outside the borrow. If none, both queues are
        // empty (the inner loop just confirmed weak is empty), so
        // we're done. Re-checking weak after dispatch is handled by
        // looping back to the inner loop above.
        let id = BINDER_DEREFS.with(|d| d.borrow_mut().pending_strong_derefs.pop_front());
        match id {
            Some(id) => {
                if ProcessState::as_self().deref_native_kernel(id).is_none() {
                    log::trace!("BR_RELEASE for unknown native id {id}");
                }
            }
            None => return Ok(()),
        }
    }
}

pub(crate) struct ThreadState {
    in_parcel: Parcel,
    out_parcel: Parcel,
    transaction: Option<TransactionState>,
    strict_mode_policy: i32,
    is_looper: bool,
    is_flushing: bool,
    call_restriction: CallRestriction,
    driver: Arc<File>,
}

impl ThreadState {
    fn new() -> Self {
        ThreadState {
            in_parcel: Parcel::new(),
            out_parcel: Parcel::new(),
            transaction: None,
            strict_mode_policy: 0,
            is_looper: false,
            is_flushing: false,
            call_restriction: ProcessState::as_self().call_restriction(),
            driver: ProcessState::as_self().driver(),
        }
    }

    pub(crate) fn set_strict_mode_policy(&mut self, policy: i32) {
        self.strict_mode_policy = policy;
    }

    pub(crate) fn _strict_mode_policy(&self) -> i32 {
        self.strict_mode_policy
    }

    pub(crate) fn last_transaction_binder_flags(&self) -> u32 {
        match self.transaction {
            Some(tr) => tr.last_transaction_binder_flags,
            None => 0,
        }
    }

    fn is_process_pending_derefs(&mut self) -> bool {
        self.in_parcel.data_position() >= self.in_parcel.data_size()
    }

    fn clear_propagate_work_source(&mut self) {
        if let Some(ref mut state) = self.transaction {
            state.propagate_work_source = false;
        }
    }

    fn clear_calling_work_source(&mut self) {
        self.set_calling_work_source_uid(UNSET_WORK_SOURCE as _);
    }

    fn set_calling_work_source_uid(&mut self, uid: binder::uid_t) -> i64 {
        let token = self.set_calling_work_source_uid_without_propagation(uid);
        if let Some(ref mut state) = self.transaction {
            state.propagate_work_source = true;
        }
        token
    }

    pub(crate) fn set_calling_work_source_uid_without_propagation(
        &mut self,
        uid: binder::uid_t,
    ) -> i64 {
        match self.transaction {
            Some(ref mut state) => {
                let propagated_bit =
                    (state.propagate_work_source as i64) << WORK_SOURCE_PROPAGATED_BIT_INDEX;
                let token = propagated_bit | (state.work_source as i64);
                state.work_source = uid;

                token
            }
            None => 0,
        }
    }

    fn write_transaction_data(
        &mut self,
        cmd: u32,
        mut flags: u32,
        handle: u32,
        code: u32,
        data: &Parcel,
        status: &i32,
    ) -> Result<()> {
        log::trace!(
            "write_transaction_data: {} {flags:X} {handle} {code}\n{:?}",
            command_to_str(cmd),
            data
        );
        // ptr is initialized by zero because ptr(64) and handle(32) size is different.
        let mut target = binder_transaction_data__bindgen_ty_1 { ptr: 0 };
        target.handle = handle;

        // let all_flags: u32 = FLAG_PRIVATE_VENDOR | FLAG_CLEAR_BUF | FLAG_ONEWAY;
        // if (flags & !all_flags) != 0 {
        //     log::error!("Unrecognized flags sent: {:X}", flags);
        // }
        let tr = if *status == StatusCode::Ok.into() {
            binder_transaction_data {
                target,
                cookie: 0,
                code,
                flags,
                sender_pid: 0,
                sender_euid: 0,
                data_size: data.data_size() as _,
                offsets_size: (data.objects.len() * std::mem::size_of::<binder_size_t>()) as _,
                data: binder_transaction_data__bindgen_ty_2 {
                    ptr: binder_transaction_data__bindgen_ty_2__bindgen_ty_1 {
                        buffer: data.as_ptr() as _,
                        offsets: data.objects.as_ptr() as _,
                    },
                },
            }
        } else {
            flags |= binder::transaction_flags_TF_STATUS_CODE;
            binder_transaction_data {
                target,
                cookie: 0,
                code,
                flags,
                sender_pid: 0,
                sender_euid: 0,
                data_size: std::mem::size_of::<i32>() as _,
                offsets_size: 0,
                data: binder_transaction_data__bindgen_ty_2 {
                    ptr: binder_transaction_data__bindgen_ty_2__bindgen_ty_1 {
                        buffer: status as *const i32 as _,
                        offsets: 0,
                    },
                },
            }
        };

        self.out_parcel.write::<u32>(&cmd)?;
        self.out_parcel.write_aligned(&tr);

        Ok(())
    }
}

pub(crate) fn set_call_restriction(call_restriction: CallRestriction) {
    THREAD_STATE.with(|thread_state| {
        thread_state.borrow_mut().call_restriction = call_restriction;
    })
}

pub(crate) fn call_restriction() -> CallRestriction {
    THREAD_STATE.with(|thread_state| thread_state.borrow().call_restriction)
}

/// Set the per-thread strict-mode policy bits to attach to the next
/// outgoing transaction header.
///
/// The next `Parcel::write_interface_token` (and AIDL-generated client
/// stubs that call it) prepends the policy as a 32-bit prefix before the
/// interface header, matching AOSP `Parcel::writeInterfaceToken`
/// (`frameworks/native/libs/binder/Parcel.cpp`). The server-side
/// `check_interface` extracts the prefix back into the receiving thread's
/// state, where it is read by the framework `StrictMode` enforcement
/// code.
///
/// `policy == 0` (default) keeps the wire byte-identical to legacy
/// behavior. Non-zero values are framework-defined bit flags — opt in
/// only when interoperating with Android system_server's strict-mode
/// chain (disk-I/O / network-on-main-thread / etc. policies).
///
/// Mirrors AOSP `IPCThreadState::setStrictModePolicy(int32_t)`
/// (`IPCThreadState.cpp:575`).
pub fn set_strict_mode_policy(policy: i32) {
    THREAD_STATE.with(|thread_state| {
        thread_state.borrow_mut().set_strict_mode_policy(policy);
    })
}

/// Read the per-thread strict-mode policy bits.
///
/// On a server thread that has just received a `BR_TRANSACTION`, returns
/// the policy that was attached to the inbound header by the caller's
/// `Parcel::write_interface_token` (extracted in `check_interface`).
/// On a client thread, returns whatever was last set by
/// [`set_strict_mode_policy`] (default `0`).
///
/// Mirrors AOSP `IPCThreadState::getStrictModePolicy() const`
/// (`IPCThreadState.cpp:580`).
pub fn get_strict_mode_policy() -> i32 {
    THREAD_STATE.with(|thread_state| thread_state.borrow().strict_mode_policy)
}

pub(crate) fn should_propagate_work_source() -> bool {
    THREAD_STATE.with(|thread_state| {
        thread_state
            .borrow()
            .transaction
            .is_some_and(|state| state.propagate_work_source)
    })
}

pub(crate) fn calling_work_source_uid() -> binder::uid_t {
    THREAD_STATE.with(|thread_state| {
        thread_state
            .borrow()
            .transaction
            .map_or(0, |state| state.work_source)
    })
}

pub(crate) fn _setup_polling() -> Result<()> {
    THREAD_STATE.with(|thread_state| -> Result<()> {
        thread_state
            .borrow_mut()
            .out_parcel
            .write::<u32>(&binder::BC_ENTER_LOOPER)
    })?;
    flush_commands()?;
    Ok(())
}

enum UntilResponse {
    Reply,
    TransactionComplete,
    /// Inbound `BR_ACQUIRE_RESULT` arm. Currently unreachable because
    /// `BC_ATTEMPT_ACQUIRE` is no longer issued by rsbinder — under the
    /// cache-pin model, regular `BC_ACQUIRE` always succeeds (the cache
    /// pin keeps the slot alive) and `Weak<I>::upgrade` covers the
    /// "atomically promote a weak ref" semantics. The variant is kept
    /// only so the kernel-direction match in `wait_for_response` stays
    /// exhaustive.
    #[allow(dead_code)]
    AcquireResult,
}

fn wait_for_response(until: UntilResponse) -> Result<Option<Parcel>> {
    THREAD_STATE.with(|thread_state| -> Result<Option<Parcel>> {
        loop {
            talk_with_driver(true)?;

            if thread_state.borrow().in_parcel.is_empty() {
                continue;
            }
            let cmd: u32 = thread_state.borrow_mut().in_parcel.read::<i32>()? as _;

            log::trace!("{:?}", return_to_str(cmd));

            match cmd {
                binder::BR_ONEWAY_SPAM_SUSPECT => {
                    log::error!("Process seems to be sending too many oneway calls.");
                    log::error!("{}", Backtrace::capture());

                    if let UntilResponse::TransactionComplete = until {
                        break;
                    }
                }
                binder::BR_TRANSACTION_COMPLETE => {
                    if let UntilResponse::TransactionComplete = until {
                        break;
                    }
                }
                binder::BR_TRANSACTION_PENDING_FROZEN => {
                    log::warn!("Sending oneway calls to frozen process.");
                    break;
                }
                binder::BR_DEAD_REPLY => {
                    return Err(StatusCode::DeadObject);
                }
                binder::BR_FAILED_REPLY => {
                    log::error!(
                        "Received FAILED_REPLY transaction reply for pid {}",
                        thread_state
                            .borrow()
                            .transaction
                            .map_or(0, |state| state.calling_pid)
                    );
                    return Err(StatusCode::FailedTransaction);
                }
                binder::BR_FROZEN_REPLY => {
                    log::error!(
                        "Received FROZEN_REPLY transaction reply for pid {}",
                        thread_state
                            .borrow()
                            .transaction
                            .map_or(0, |state| state.calling_pid)
                    );
                    return Err(StatusCode::FailedTransaction);
                }
                binder::BR_ACQUIRE_RESULT => {
                    let result = thread_state.borrow_mut().in_parcel.read::<i32>()?;
                    if let UntilResponse::AcquireResult = until {
                        let res = if result != 0 {
                            Ok(None)
                        } else {
                            Err(StatusCode::InvalidOperation)
                        };
                        return res;
                    } else if cfg!(debug_assertions) {
                        panic!("Unexpected BR_ACQUIRE_RESULT");
                    }
                }
                binder::BR_REPLY => {
                    let tr = thread_state
                        .borrow_mut()
                        .in_parcel
                        .read::<binder::binder_transaction_data>()?;
                    let (buffer, offsets) = unsafe { (tr.data.ptr.buffer, tr.data.ptr.offsets) };
                    if let UntilResponse::Reply = until {
                        if (tr.flags & transaction_flags_TF_STATUS_CODE) == 0 {
                            // SAFETY: buffer and offsets are valid pointers from binder driver
                            // transaction data, with sizes given by tr.data_size and tr.offsets_size
                            let reply = unsafe {
                                Parcel::from_ipc_parts(
                                    buffer as _,
                                    tr.data_size as _,
                                    offsets as _,
                                    (tr.offsets_size as usize)
                                        / std::mem::size_of::<binder::binder_size_t>(),
                                    free_buffer,
                                )
                            };
                            return Ok(Some(reply));
                        } else {
                            // SAFETY: Reading status code from binder transaction reply
                            // - We verify tr.data_size >= size_of::<i32>() before reading
                            // - buffer points to valid memory owned by binder driver
                            // - The data remains valid for the transaction lifetime
                            // - We convert to StatusCode immediately after reading
                            let status: StatusCode =
                                if tr.data_size >= std::mem::size_of::<i32>() as u64 {
                                    unsafe { (*(buffer as *const i32)).into() }
                                } else {
                                    log::error!(
                                        "Buffer too small for status code: {} < {}",
                                        tr.data_size,
                                        std::mem::size_of::<i32>()
                                    );
                                    StatusCode::BadValue
                                };
                            log::trace!("binder::BR_REPLY ({status})");
                            free_buffer(
                                None,
                                buffer,
                                tr.data_size as _,
                                offsets,
                                (tr.offsets_size as usize) / std::mem::size_of::<binder_size_t>(),
                            )?;

                            if status != StatusCode::Ok {
                                log::warn!("binder::BR_REPLY ({status})");
                                return Err(status);
                            }
                            // AOSP `IPCThreadState::waitForResponse` ends the
                            // status-code branch with an unconditional `goto
                            // finish` (`return err`, even for NO_ERROR), so a
                            // `TF_STATUS_CODE` reply carrying status 0 yields a
                            // successful empty reply — it never loops. Falling
                            // through here instead would re-enter the outer
                            // `loop` and block in `talk_with_driver` waiting for
                            // a command a conforming peer never sends, hanging
                            // (potentially the main thread) on a malformed or
                            // hostile reply. Return the empty reply to match.
                            return Ok(Some(Parcel::new()));
                        }
                    } else {
                        free_buffer(
                            None,
                            buffer,
                            tr.data_size as _,
                            offsets,
                            (tr.offsets_size as usize) / std::mem::size_of::<binder_size_t>(),
                        )?;
                    }
                }
                _ => {
                    execute_command(cmd as _)?;
                }
            };
        }
        Ok(None)
    })
}

/// Drive the kernel handshake for `BR_DEAD_BINDER` so that a
/// user-side `send_obituary` failure cannot strand the kernel
/// `binder_ref` slot.
///
/// The kernel slot is leaked permanently if either:
///   1. `BC_DEAD_BINDER_DONE` is not written to `out_parcel`, or
///   2. `release_obituary_pin`'s `BC_DECREFS` is not flushed.
///
/// So phases 2 (`queue_done`) and 3 (`pin_release`) always run
/// regardless of phase 1's (`obituary`) outcome. The user-visible
/// obituary error takes priority over the pin-release error;
/// the pin error is also logged so it is not lost when both fail.
///
/// Residual edge: if `queue_done` itself fails (rare — `out_parcel`
/// is unhealthy under e.g. allocator OOM), phase 3 is skipped and the
/// pin leak still occurs. Documented; the next ioctl on this thread
/// will fail anyway.
fn drive_dead_binder_handshake<O, Q, P>(
    handle: binder::binder_uintptr_t,
    obituary: O,
    queue_done: Q,
    pin_release: P,
) -> Result<()>
where
    O: FnOnce() -> Result<()>,
    Q: FnOnce() -> Result<()>,
    P: FnOnce() -> Result<()>,
{
    // Phase 1: dispatch recipients. Capture the result; do NOT
    // short-circuit — kernel handshake must always complete.
    let obituary_result = obituary();

    // Phase 2: queue BC_DEAD_BINDER_DONE unconditionally. A failure
    // here means out_parcel is unhealthy; propagate immediately
    // because the next ioctl will surface it anyway. Phase 3 is
    // skipped in this rare path (acknowledged residual edge). Log
    // the obituary error first if it would otherwise be swallowed
    // by the queue error — the obituary diagnostic is most valuable
    // exactly when the kernel handshake is also breaking.
    if let Err(qe) = queue_done() {
        if let Err(oe) = &obituary_result {
            error!(
                "BR_DEAD_BINDER: queue BC_DEAD_BINDER_DONE failed ({qe:?}) \
                 swallowing obituary error {oe:?} for handle {handle:X}"
            );
        }
        return Err(qe);
    }

    // Phase 3: release the cache pin (BC_DECREFS via flush). Always
    // attempted, even if obituary errored. A pin-release error is
    // logged here so the diagnostic is not swallowed when the
    // obituary error is surfaced below.
    let pin_result = pin_release();
    if let Err(e) = &pin_result {
        error!(
            "release_obituary_pin failed for handle {handle:X}: {e:?}; \
             obituary_result: {obituary_result:?}"
        );
    }

    // Surface obituary error first (user-visible — death recipient
    // observed the failure). Fall back to pin error when obituary
    // succeeded but pin failed.
    obituary_result?;
    pin_result?;
    Ok(())
}

/// Invoke `Transactable::transact`, catching panics so a buggy
/// service handler cannot terminate the binder worker thread.
///
/// On panic, the partial reply (if any) is discarded and the caller
/// receives `StatusCode::Unknown`, so the existing `BR_TRANSACTION`
/// reply path synthesizes a deterministic error reply for the
/// calling client (rather than leaving the client hung waiting for
/// `BR_REPLY`). Mirrors the panic guard around `DeathRecipient`
/// callbacks in `ProxyHandle::dispatch_obituary_callbacks`. See the
/// `Transactable` trait doc for the full guarantee scope.
///
/// # Borrow discipline (R1)
///
/// Must be called with NO `THREAD_STATE` or `BINDER_DEREFS` borrow held —
/// `Transactable::transact` is user code that may issue nested binder
/// calls (re-entering this module). See module doc.
fn dispatch_transact_caught(
    transactable: &dyn Transactable,
    code: TransactionCode,
    reader: &mut Parcel,
    reply: &mut Parcel,
) -> Result<()> {
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        transactable.transact(code, reader, reply)
    }));
    match result {
        Ok(transact_result) => transact_result,
        Err(payload) => {
            let msg = payload
                .downcast_ref::<&'static str>()
                .copied()
                .or_else(|| payload.downcast_ref::<String>().map(String::as_str))
                .unwrap_or("<non-string panic payload>");
            error!("Transactable::transact panicked for code {code}: {msg}");
            // Discard any partially-written reply so the client does
            // not misparse half-formed data; the reply path below
            // turns `Err` into a clean error status.
            *reply = Parcel::new();
            Err(StatusCode::Unknown)
        }
    }
}

fn execute_command(cmd: i32) -> Result<()> {
    let cmd: std::os::raw::c_uint = cmd as _;

    THREAD_STATE.with(|thread_state| -> Result<()> {
        match cmd {
            binder::BR_ERROR => {
                let other: StatusCode = thread_state.borrow_mut().in_parcel.read::<i32>()?.into();
                log::error!("binder::BR_ERROR ({other})");
                return Err(other);
            }
            binder::BR_OK => {}

            binder::BR_TRANSACTION_SEC_CTX | binder::BR_TRANSACTION => {
                let tr_secctx = {
                    let mut thread_state = thread_state.borrow_mut();
                    if cmd == binder::BR_TRANSACTION_SEC_CTX {
                        thread_state
                            .in_parcel
                            .read::<binder::binder_transaction_data_secctx>()?
                    } else {
                        binder::binder_transaction_data_secctx {
                            transaction_data: thread_state
                                .in_parcel
                                .read::<binder::binder_transaction_data>()?,
                            secctx: 0,
                        }
                    }
                };

                // SAFETY: `tr_secctx` was just filled by the kernel on the
                // BR_TRANSACTION(_SEC_CTX) path, so `transaction_data` is
                // fully initialized and the `data.ptr` union variant (buffer
                // + offsets, not `data.buf`) is the active one for a
                // kernel-delivered transaction. `from_ipc_parts` adopts the
                // driver-owned buffer/offsets with sizes taken from the same
                // struct and the matching `free_buffer` reclaimer.
                let mut reader = unsafe {
                    let tr = &tr_secctx.transaction_data;

                    Parcel::from_ipc_parts(
                        tr.data.ptr.buffer as _,
                        tr.data_size as _,
                        tr.data.ptr.offsets as _,
                        (tr.offsets_size as usize) / std::mem::size_of::<binder::binder_size_t>(),
                        free_buffer,
                    )
                };

                // TODO: Skip now, because if below implmentation is mandatory.
                // const void* origServingStackPointer = mServingStackPointer;
                // mServingStackPointer = &origServingStackPointer; // anything on the stack

                let transaction_old = {
                    let mut thread_state = thread_state.borrow_mut();
                    let transaction_old = thread_state.transaction;

                    thread_state.clear_calling_work_source();
                    thread_state.clear_propagate_work_source();

                    thread_state.transaction =
                        Some(TransactionState::from_transaction_data(&tr_secctx));

                    transaction_old
                };

                let mut reply = Parcel::new();

                let result = {
                    // SAFETY: kernel-delivered transaction (see above); for a
                    // transaction targeting a local binder the `target` union's
                    // `ptr` variant is the active one. Read-only.
                    let target_ptr = unsafe { tr_secctx.transaction_data.target.ptr };
                    if target_ptr != 0 {
                        // `target_ptr` is now the process-monotonic id
                        // assigned by `publish_native`. Resolve via the
                        // sidecar table (read-only, no count change) —
                        // the table guarantees `Inner<T>` is alive
                        // while the entry exists, so the SIBinder we
                        // construct here can safely drive the user's
                        // `Transactable` impl. SIBinder construction
                        // is contained within this scope and the
                        // RefCounter ops balance pairwise: `from_arc`
                        // calls `inc_strong` (+1), `attempt_increase`
                        // adds another (+1), `decrease()` cancels one
                        // (−1), and `strong`'s `Drop` cancels the
                        // last (−1) — net zero across the block.
                        let id = target_ptr;
                        match ProcessState::as_self().lookup_native(id) {
                            Some(arc) => {
                                let strong = SIBinder::from_arc(arc);
                                if strong.attempt_increase() {
                                    let result = dispatch_transact_caught(
                                        strong.as_transactable().expect("Transactable is None."),
                                        tr_secctx.transaction_data.code,
                                        &mut reader,
                                        &mut reply,
                                    );
                                    strong.decrease()?;
                                    result
                                } else {
                                    log::warn!("Failed strong.attempt_increase for native id {id}");
                                    Err(StatusCode::UnknownTransaction)
                                }
                            }
                            None => {
                                log::error!("BR_TRANSACTION for unknown native id {id}");
                                Err(StatusCode::DeadObject)
                            }
                        }
                    } else {
                        let context = ProcessState::as_self()
                            .context_manager()
                            .expect("Transactable is None.");
                        dispatch_transact_caught(
                            context.as_transactable().expect("Transactable is None."),
                            tr_secctx.transaction_data.code,
                            &mut reader,
                            &mut reply,
                        )
                    }
                };
                let flags = tr_secctx.transaction_data.flags;
                // Restore the saved transaction state on every exit (an `Err`
                // or panic must not leak it into the next command), and contain
                // a panic from the reply flush/await — `talk_with_driver` or a
                // nested dispatch; OOM aborts and is not catchable — rather than
                // unwinding the worker loop (mirrors `dispatch_transact_caught`;
                // a dropped reply reaches a sync caller as BR_DEAD_REPLY).
                let reply_result =
                    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Result<()> {
                        if (flags & transaction_flags_TF_ONE_WAY) == 0 {
                            let flags = flags & transaction_flags_TF_CLEAR_BUF;
                            let status: i32 = match result {
                                Ok(_) => StatusCode::Ok.into(),
                                Err(err) => err.into(),
                            };
                            thread_state.borrow_mut().write_transaction_data(
                                binder::BC_REPLY,
                                flags,
                                u32::MAX,
                                0,
                                &reply,
                                &status,
                            )?;
                            wait_for_response(UntilResponse::TransactionComplete)?;
                        } else if let Err(err) = result {
                            let mut log = format!(
                                "oneway function results for code {} on binder at {:X}",
                                tr_secctx.transaction_data.code,
                                // SAFETY: kernel-delivered transaction; `target.ptr`
                                // is the active union variant. Read-only (logging).
                                unsafe { tr_secctx.transaction_data.target.ptr }
                            );
                            log += &format!(" will be dropped but finished with status {err}");

                            if reply.data_size() != 0 {
                                log += &format!(" and reply parcel size {}", reply.data_size());
                            }
                            log::error!("{log}");
                        }
                        Ok(())
                    }));

                thread_state.borrow_mut().transaction = transaction_old;

                match reply_result {
                    Ok(inner) => inner?,
                    Err(_payload) => {
                        // A caught panic may leave `out_parcel` holding an
                        // unflushed/partial BC_REPLY; drop it so the next IPC
                        // does not flush a malformed command.
                        let _ = thread_state.borrow_mut().out_parcel.set_data_size(0);
                        log::error!(
                            "reply path panicked for code {}; reply dropped",
                            tr_secctx.transaction_data.code
                        );
                        return Err(StatusCode::Unknown);
                    }
                }
            }

            binder::BR_INCREFS => {
                let mut state = thread_state.borrow_mut();
                let id = state.in_parcel.read::<binder::binder_uintptr_t>()?;
                // The cookie half is unused under the new id encoding
                // but the kernel still emits the original `cookie`
                // (always 0 for our published natives). Echo it back
                // verbatim in BC_INCREFS_DONE.
                let cookie_echo = state.in_parcel.read::<binder::binder_uintptr_t>()?;
                drop(state);

                // BR_INCREFS reflects the kernel acquiring a weak ref
                // to one of our published natives. Pure id
                // bookkeeping: bump `kernel_refs` in the table; the
                // RefCounter.weak alive-signal is held above zero by
                // `publish_native` for the entry's lifetime — no
                // per-event RefCounter touch needed (and no SIBinder
                // construction, no method dispatch on a possibly-freed
                // `Inner<T>`, closing the UAF that the old
                // fat-pointer encoding could expose).
                if ProcessState::as_self().ref_native_kernel(id).is_none() {
                    log::error!("BR_INCREFS for unknown native id {id}");
                    debug_assert!(false, "BR_INCREFS for unknown native id {id}");
                }

                let mut state = thread_state.borrow_mut();
                state.out_parcel.write::<u32>(&binder::BC_INCREFS_DONE)?;
                state.out_parcel.write::<binder::binder_uintptr_t>(&id)?;
                state
                    .out_parcel
                    .write::<binder::binder_uintptr_t>(&cookie_echo)?;
            }
            binder::BR_ACQUIRE => {
                let mut state = thread_state.borrow_mut();
                let id = state.in_parcel.read::<binder::binder_uintptr_t>()?;
                let cookie_echo = state.in_parcel.read::<binder::binder_uintptr_t>()?;
                drop(state);

                // Same shape as BR_INCREFS — bookkeeping only.
                // `RefCounter.strong` alive-signal is held by the
                // table's `binder_pin: SIBinder` for the entry's
                // lifetime.
                if ProcessState::as_self().ref_native_kernel(id).is_none() {
                    log::error!("BR_ACQUIRE for unknown native id {id}");
                    debug_assert!(false, "BR_ACQUIRE for unknown native id {id}");
                }

                let mut state = thread_state.borrow_mut();
                state.out_parcel.write::<u32>(&(binder::BC_ACQUIRE_DONE))?;
                state.out_parcel.write::<binder::binder_uintptr_t>(&id)?;
                state
                    .out_parcel
                    .write::<binder::binder_uintptr_t>(&cookie_echo)?;
            }
            binder::BR_RELEASE => {
                let mut state = thread_state.borrow_mut();
                let id = state.in_parcel.read::<binder::binder_uintptr_t>()?;
                // cookie echo unused on the deferred-deref path.
                let _cookie_echo = state.in_parcel.read::<binder::binder_uintptr_t>()?;

                BINDER_DEREFS.with(|binder_derefs| {
                    let mut binder_derefs = binder_derefs.borrow_mut();
                    binder_derefs.pending_strong_derefs.push_back(id);
                });
            }
            binder::BR_DECREFS => {
                let mut state = thread_state.borrow_mut();
                let id = state.in_parcel.read::<binder::binder_uintptr_t>()?;
                let _cookie_echo = state.in_parcel.read::<binder::binder_uintptr_t>()?;

                BINDER_DEREFS.with(|binder_derefs| {
                    let mut binder_derefs = binder_derefs.borrow_mut();
                    binder_derefs.pending_weak_derefs.push_back(id);
                });
            }
            binder::BR_ATTEMPT_ACQUIRE => {
                let mut state = thread_state.borrow_mut();
                let id = state.in_parcel.read::<binder::binder_uintptr_t>()?;
                let _cookie_echo = state.in_parcel.read::<binder::binder_uintptr_t>()?;
                drop(state);

                // Probe the table's binary alive-signal: entry exists
                // ⟹ promotion may proceed. If alive, bump
                // `kernel_refs` (the kernel will hold a new strong
                // ref on success). Unknown id is permitted here — it
                // can race against unpublish (kernel may probe a
                // binder that just lost its last ref); reply
                // `success=0` without `debug_assert`.
                let success = ProcessState::as_self().ref_native_kernel(id).is_some();

                let mut state = thread_state.borrow_mut();
                state.out_parcel.write::<u32>(&binder::BC_ACQUIRE_RESULT)?;
                state.out_parcel.write::<i32>(&(success as _))?;
            }
            binder::BR_NOOP => {}
            binder::BR_SPAWN_LOOPER => {
                ProcessState::as_self().spawn_pooled_thread(false);
            }
            binder::BR_FINISHED => {
                return Err(StatusCode::TimedOut);
            }
            binder::BR_DEAD_BINDER => {
                let handle = {
                    let mut state = thread_state.borrow_mut();
                    state.in_parcel.read::<binder::binder_uintptr_t>()?
                };

                log::trace!("BR_DEAD_BINDER: handle {handle:X}");

                drive_dead_binder_handshake(
                    handle,
                    || ProcessState::as_self().send_obituary_for_handle(handle as _),
                    || {
                        let mut state = thread_state.borrow_mut();
                        state
                            .out_parcel
                            .write::<u32>(&(binder::BC_DEAD_BINDER_DONE))?;
                        state
                            .out_parcel
                            .write::<binder::binder_uintptr_t>(&handle)?;
                        Ok(())
                    },
                    || ProcessState::as_self().release_obituary_pin(handle as _),
                )?;
            }
            binder::BR_CLEAR_DEATH_NOTIFICATION_DONE => {
                let mut state = thread_state.borrow_mut();
                state.in_parcel.read::<binder::binder_uintptr_t>()?;
            }
            _ => {
                log::error!("*** BAD COMMAND {cmd} received from Binder driver\n");
                return Err(StatusCode::Unknown);
            }
        };

        Ok(())
    })
}

/// Drive one round-trip with the binder kernel driver.
///
/// # Borrow discipline (H1, hygiene only)
///
/// The `BINDER_WRITE_READ` ioctl does not re-enter Rust on the same
/// thread (the kernel only schedules our incoming queue and returns),
/// so holding a `THREAD_STATE` borrow across the syscall does not
/// violate R1 today. The current code does hold an immutable
/// `thread_state.borrow()` across the `write_read` call to read
/// `driver` — correct under the no-re-entry property.
///
/// H1 is the hygiene note that this boundary should ideally be
/// tightened: future EINTR / signal-safety / cancellation handling
/// changes, or any logic that gains a same-thread Rust callback here,
/// would break the no-re-entry assumption and quietly turn this into
/// an R1 violation. A defensive refactor would clone the `Arc<File>`
/// out under a short borrow and pass it by value across the syscall.
/// Not done today (no concrete risk); recorded so a future change
/// knows to revisit.
fn talk_with_driver(do_receive: bool) -> Result<()> {
    THREAD_STATE.with(|thread_state| -> Result<()> {
        let mut bwr = {
            let mut thread_state = thread_state.borrow_mut();
            let need_read = thread_state.in_parcel.is_empty();
            let out_avail = if !do_receive || need_read {
                thread_state.out_parcel.data_size()
            } else {
                0
            };

            let read_size = if do_receive && need_read {
                thread_state.in_parcel.capacity()
            } else {
                0
            };

            binder::binder_write_read {
                write_size: out_avail as _,
                write_consumed: 0,
                write_buffer: thread_state.out_parcel.as_mut_ptr() as _,
                read_size: read_size as _,
                read_consumed: 0,
                read_buffer: thread_state.in_parcel.as_mut_ptr() as _,
            }
        };

        if bwr.write_size == 0 && bwr.read_size == 0 {
            return Ok(());
        }

        if bwr.write_size != 0 {
            log::trace!(
                "Sending command to driver:\n{:?}",
                thread_state.borrow().out_parcel
            );
            log::trace!(
                "Size of receive buffer: {}, need_read: {}, do_receive: {}",
                bwr.read_size,
                thread_state.borrow().in_parcel.is_empty(),
                do_receive
            );
        }
        // unsafe {
        //     loop {
        //         let res = binder::write_read(thread_state.borrow().driver.as_raw_fd(), &mut bwr);
        //         match res {
        //             Ok(_) => break,
        //             Err(errno) if errno != nix::errno::Errno::EINTR => {
        //                 log::error!("binder::write_read() error : {}", errno);
        //                 return Err(StatusCode::Errno(errno as _));
        //             },
        //             _ => {}
        //         }
        //     }
        // }

        loop {
            let res = binder::write_read(&thread_state.borrow().driver, &mut bwr);
            match res {
                Ok(_) => break,
                Err(errno) if errno != rustix::io::Errno::INTR => {
                    log::error!("binder::write_read() error : {errno}");
                    return Err(StatusCode::from(errno));
                }
                _ => {}
            }
        }

        log::trace!(
            "write consumed: {} of {}, read consumed: {} of {}",
            bwr.write_consumed,
            bwr.write_size,
            bwr.read_consumed,
            bwr.read_size
        );

        // Process write and read results in a single borrow_mut scope
        {
            let mut thread_state = thread_state.borrow_mut();

            if bwr.write_consumed > 0 {
                if bwr.write_consumed < thread_state.out_parcel.data_size() as _ {
                    panic!(
                        "Driver did not consume write buffer. consumed: {} of {}",
                        bwr.write_consumed,
                        thread_state.out_parcel.data_size()
                    );
                }
                thread_state.out_parcel.set_data_size(0)?;
            }

            if bwr.read_consumed > 0 {
                thread_state
                    .in_parcel
                    .set_data_size(bwr.read_consumed as _)?;
                thread_state.in_parcel.set_data_position(0);

                log::trace!(
                    "Received commands from driver:\n{:?}",
                    thread_state.in_parcel
                );
            }
        } // thread_state is dropped here

        Ok(())
    })
}

fn get_and_execute_command() -> Result<()> {
    talk_with_driver(true)?;

    let cmd = THREAD_STATE.with(|thread_state| -> Result<i32> {
        thread_state.borrow_mut().in_parcel.read::<i32>()
    })?;
    execute_command(cmd)?;

    Ok(())
}

pub(crate) fn flush_commands() -> Result<()> {
    talk_with_driver(false)?;

    THREAD_STATE.with(|thread_state| -> Result<()> {
        if thread_state.borrow().out_parcel.data_size() > 0 {
            talk_with_driver(false)?;
        }

        if thread_state.borrow().out_parcel.data_size() > 0 {
            log::warn!("self.out_parcel.len() > 0 after flash_commands()");
        }

        Ok(())
    })
}

pub(crate) fn inc_strong_handle(handle: u32) -> Result<()> {
    log::trace!("inc_strong_handle: {handle}");
    THREAD_STATE.with(|thread_state| -> Result<()> {
        {
            let mut state = thread_state.borrow_mut();

            state.out_parcel.write::<u32>(&(binder::BC_ACQUIRE))?;
            state.out_parcel.write::<u32>(&(handle))?;
        }

        flash_if_needed()?;

        Ok(())
    })
}

pub(crate) fn dec_strong_handle(handle: u32) -> Result<()> {
    log::trace!("dec_strong_handle: {handle}");
    THREAD_STATE.with(|thread_state| -> Result<()> {
        {
            let mut state = thread_state.borrow_mut();

            state.out_parcel.write::<u32>(&(binder::BC_RELEASE))?;
            state.out_parcel.write::<u32>(&(handle))?;
        }

        flash_if_needed()?;

        Ok(())
    })
}

pub(crate) fn inc_weak_handle(handle: u32) -> Result<()> {
    log::trace!("inc_weak_handle: {handle}");
    THREAD_STATE.with(|thread_state| -> Result<()> {
        {
            let mut state = thread_state.borrow_mut();

            state.out_parcel.write::<u32>(&(binder::BC_INCREFS))?;
            state.out_parcel.write::<u32>(&(handle))?;
        }

        flash_if_needed()?;

        Ok(())
    })
}

pub(crate) fn dec_weak_handle(handle: u32) -> Result<()> {
    log::trace!("dec_weak_handle: {handle}");
    THREAD_STATE.with(|thread_state| -> Result<()> {
        {
            let mut state = thread_state.borrow_mut();

            state.out_parcel.write::<u32>(&(binder::BC_DECREFS))?;
            state.out_parcel.write::<u32>(&(handle))?;
        }

        flash_if_needed()?;

        Ok(())
    })
}

pub(crate) fn flash_if_needed() -> Result<bool> {
    THREAD_STATE.with(|thread_state| -> Result<bool> {
        {
            let thread_state = thread_state.borrow();
            if thread_state.is_looper || thread_state.is_flushing {
                return Ok(false);
            }
        }

        // Reset is_flushing on every exit (Ok / Err / panic) so a failed
        // flush_commands() cannot leave the flag stuck true and wedge all
        // future flushes. Must NOT hold a THREAD_STATE borrow across
        // flush_commands() — it re-borrows internally (R1).
        struct FlushGuard;
        impl Drop for FlushGuard {
            fn drop(&mut self) {
                THREAD_STATE.with(|ts| ts.borrow_mut().is_flushing = false);
            }
        }

        thread_state.borrow_mut().is_flushing = true;
        let _guard = FlushGuard;
        flush_commands()?;

        Ok(true)
    })
}

pub(crate) fn _handle_commands() -> Result<()> {
    while {
        get_and_execute_command()?;

        THREAD_STATE.with(|thread_state| -> bool { !thread_state.borrow().in_parcel.is_empty() })
    } {
        flush_commands()?;
    }
    Ok(())
}

pub fn check_interface(reader: &mut Parcel, descriptor: &str) -> Result<bool> {
    let mut strict_policy: i32 = reader.read()?;

    THREAD_STATE.with(|thread_state| -> Result<()> {
        let mut thread_state = thread_state.borrow_mut();

        if (thread_state.last_transaction_binder_flags() & FLAG_ONEWAY) != 0 {
            strict_policy = 0;
        }
        thread_state.set_strict_mode_policy(strict_policy);
        reader.update_work_source_request_header_pos();

        let work_source: i32 = reader.read()?;
        thread_state.set_calling_work_source_uid_without_propagation(work_source as _);

        Ok(())
    })?;

    if crate::sdk_at_least(30) {
        let header: u32 = reader.read()?;
        if header != INTERFACE_HEADER {
            log::error!("Expecting header {INTERFACE_HEADER:#x} but found {header:#x}.");
            return Ok(false);
        }
    }

    let parcel_interface: String = reader.read()?;
    if parcel_interface.eq(descriptor) {
        Ok(true)
    } else {
        log::error!("check_interface() expected '{descriptor}' but read '{parcel_interface}'");
        Ok(false)
    }
}

pub(crate) fn transact(
    handle: u32,
    code: u32,
    data: &Parcel,
    mut flags: u32,
) -> Result<Option<Parcel>> {
    let mut reply: Option<Parcel> = None;

    flags |= transaction_flags_TF_ACCEPT_FDS;

    let call_restriction = THREAD_STATE.with(|thread_state| -> Result<CallRestriction> {
        let mut thread_state = thread_state.borrow_mut();
        thread_state.write_transaction_data(
            binder::BC_TRANSACTION,
            flags,
            handle,
            code,
            data,
            &0,
        )?;
        Ok(thread_state.call_restriction)
    })?;

    if (flags & transaction_flags_TF_ONE_WAY) == 0 {
        match call_restriction {
            CallRestriction::ErrorIfNotOneway => {
                error!("Process making non-oneway call (code: {code}) but is restricted.")
            }
            CallRestriction::FatalIfNotOneway => {
                panic!("Process may not make non-oneway calls (code: {code}).");
            }
            _ => (),
        }

        reply = wait_for_response(UntilResponse::Reply)?;
    } else {
        wait_for_response(UntilResponse::TransactionComplete)?;
    }

    Ok(reply)
}

fn free_buffer(
    parcel: Option<&Parcel>,
    data: binder_uintptr_t,
    _: usize,
    _: binder_uintptr_t,
    _: usize,
) -> Result<()> {
    if let Some(parcel) = parcel {
        parcel.close_file_descriptors()
    }

    THREAD_STATE.with(|thread_state| -> Result<()> {
        let mut thread_state = thread_state.borrow_mut();
        thread_state
            .out_parcel
            .write::<u32>(&binder::BC_FREE_BUFFER)?;
        thread_state.out_parcel.write::<binder_uintptr_t>(&data)?;
        Ok(())
    })?;

    flash_if_needed()?;

    Ok(())
}

pub(crate) fn query_interface(handle: u32) -> Result<String> {
    #[cfg(all(target_os = "android", feature = "android_10"))]
    if handle == 0 && !crate::sdk_at_least(30) {
        return Ok(crate::hub::android_10::SERVICE_MANAGER_DESCRIPTOR.to_owned());
    }

    let data = Parcel::new();
    let reply = transact(handle, INTERFACE_TRANSACTION, &data, 0)?;
    let interface: String = reply
        .expect("INTERFACE_TRANSACTION should have reply parcel")
        .read()?;

    Ok(interface)
}

pub(crate) fn ping_binder(handle: u32) -> Result<()> {
    let data = Parcel::new();
    let _reply = transact(handle, PING_TRANSACTION, &data, 0)?;
    Ok(())
}

pub(crate) fn join_thread_pool(is_main: bool) -> Result<()> {
    THREAD_STATE.with(|thread_state| -> Result<()> {
        log::debug!(
            "**** THREAD {:?} (PID {}) IS JOINING THE THREAD POOL",
            std::thread::current().id(),
            std::process::id()
        );

        ProcessState::as_self()
            .current_threads
            .fetch_add(1, Ordering::SeqCst);

        let looper = if is_main {
            binder::BC_ENTER_LOOPER
        } else {
            binder::BC_REGISTER_LOOPER
        };

        {
            let mut thread_state = thread_state.borrow_mut();
            thread_state.out_parcel.write::<u32>(&looper)?;
            thread_state.is_looper = true;
        }

        let result;

        loop {
            if thread_state.borrow_mut().is_process_pending_derefs() {
                process_pending_derefs()?;
            }
            if let Err(e) = get_and_execute_command() {
                match e {
                    StatusCode::TimedOut if !is_main => {
                        result = e;
                        break;
                    }
                    StatusCode::Errno(errno)
                        if errno == -(rustix::io::Errno::CONNREFUSED.raw_os_error()) =>
                    {
                        result = e;
                        break;
                    }
                    _ => {
                        // A non-EINTR ioctl error (EAGAIN/EBUSY/ENOMEM/…)
                        // must not abort the process. Leave the thread pool
                        // gracefully like the TimedOut/CONNREFUSED arms so
                        // the pool can spawn a replacement looper.
                        log::error!(
                            "get_and_execute_command() returned unexpected error {e}; \
                             leaving the thread pool"
                        );
                        result = e;
                        break;
                    }
                }
            }
        }
        log::debug!(
            "**** THREAD {:?} (PID {}) IS LEAVING THE THREAD POOL err={}\n",
            std::thread::current().id(),
            std::process::id(),
            result
        );

        {
            let mut thread_state = thread_state.borrow_mut();

            thread_state
                .out_parcel
                .write::<u32>(&binder::BC_EXIT_LOOPER)?;
            thread_state.is_looper = false;
        }

        talk_with_driver(false)?;
        ProcessState::as_self()
            .current_threads
            .fetch_sub(1, Ordering::SeqCst);
        Ok(())
    })
}

pub(crate) fn request_death_notification(handle: u32) -> Result<()> {
    log::trace!("request_death_notification: {handle}");
    THREAD_STATE.with(|thread_state| -> Result<()> {
        {
            let mut state = thread_state.borrow_mut();

            state
                .out_parcel
                .write::<u32>(&(binder::BC_REQUEST_DEATH_NOTIFICATION))?;
            state.out_parcel.write::<u32>(&(handle))?;
            // Android binder calls writePointer(proxy) here, but we just write handle.
            state
                .out_parcel
                .write::<binder::binder_uintptr_t>(&(handle as _))?;
        }

        Ok(())
    })
}

pub(crate) fn clear_death_notification(handle: u32) -> Result<()> {
    log::trace!("clear_death_notification: {handle}");
    THREAD_STATE.with(|thread_state| -> Result<()> {
        {
            let mut state = thread_state.borrow_mut();

            state
                .out_parcel
                .write::<u32>(&(binder::BC_CLEAR_DEATH_NOTIFICATION))?;
            state.out_parcel.write::<u32>(&(handle))?;
            // Android binder calls writePointer(proxy) here, but we just write handle.
            state
                .out_parcel
                .write::<binder::binder_uintptr_t>(&(handle as _))?;
        }

        Ok(())
    })
}

#[derive(Debug)]
pub struct CallingContext {
    pub pid: binder::pid_t,
    pub uid: binder::uid_t,
    pub sid: Option<CString>,
}

impl std::default::Default for CallingContext {
    fn default() -> CallingContext {
        // Plan 2-16 Phase B: an in-flight RPC transaction takes precedence
        // and is read from the ProcessState-independent thread-local
        // (works in a pure-RPC process). RPC has no SELinux context, so
        // `sid` is always `None`.
        if let Some((uid, pid)) = rpc_calling() {
            return CallingContext {
                pid,
                uid,
                sid: None,
            };
        }
        // Kernel path. `THREAD_STATE`'s ctor pulls `ProcessState::as_self()`,
        // which panics if uninitialized — so in a pure-RPC process with no
        // in-flight RPC transaction, return the documented
        // out-of-transaction self identity without forcing the thread-local.
        if !ProcessState::is_initialized() {
            return CallingContext {
                pid: rustix::process::getpid().as_raw_nonzero().get() as _,
                uid: rustix::process::getuid().as_raw(),
                sid: None,
            };
        }
        THREAD_STATE.with(|thread_state| -> CallingContext {
            let thread_state = thread_state.borrow();
            match thread_state.transaction.as_ref() {
                Some(transaction) => {
                    let calling_sid = if !transaction.calling_sid.is_null() {
                        // SAFETY: The calling_sid pointer is provided by the binder driver
                        // and is guaranteed to be a valid null-terminated C string during
                        // the transaction lifetime. We check for null before dereferencing.
                        // The pointer is cast from *const u8 to *const i8 as required by CStr::from_ptr.
                        unsafe { Some(CStr::from_ptr(transaction.calling_sid as _).to_owned()) }
                    } else {
                        None
                    };
                    CallingContext {
                        pid: transaction.calling_pid,
                        uid: transaction.calling_uid,
                        sid: calling_sid,
                    }
                }
                None => {
                    log::debug!("CallingContext::new() called outside of transaction");
                    CallingContext {
                        pid: rustix::process::getpid().as_raw_nonzero().get() as _,
                        uid: rustix::process::getuid().as_raw(),
                        sid: None,
                    }
                }
            }
        })
    }
}

pub fn is_handling_transaction() -> bool {
    // Plan 2-16 Phase B: an in-flight RPC transaction counts (and is
    // detected without forcing the ProcessState-coupled `THREAD_STATE`,
    // which would panic in a pure-RPC process).
    if rpc_calling().is_some() {
        return true;
    }
    ProcessState::is_initialized()
        && THREAD_STATE.with(|thread_state| thread_state.borrow().transaction.is_some())
}

/// SELinux security context of the caller for the current in-flight
/// `BR_TRANSACTION`, when present.
///
/// `Some` is only ever returned while the current thread is dispatching a
/// transaction targeting a binder constructed with
/// `BinderFeatures { set_requesting_sid: true, .. }`. The kernel then
/// delivers the request via `BR_TRANSACTION_SEC_CTX` and rsbinder copies
/// the null-terminated SELinux context (e.g. `u:r:system_server:s0`) into
/// the returned `CString`.
///
/// Returns `None` when:
/// - The thread is not currently dispatching a binder transaction.
/// - The transaction was delivered as plain `BR_TRANSACTION` (caller's
///   binder did not request the security context).
/// - The transaction came over the RPC transport (RPC has its own
///   `PeerIdentity` model — see `rsbinder::rpc::PeerIdentity`).
///
/// Equivalent to AOSP `IPCThreadState::getCallingSid()` (libbinder
/// `frameworks/native/libs/binder/IPCThreadState.cpp`) and Android Rust
/// `libbinder_rs::ThreadState::with_calling_sid` (rsbinder returns an
/// owned `CString` instead of taking a `&CStr` callback — the kernel
/// pointer is lazily copied at every call, so leaking is not possible).
///
pub fn get_calling_sid() -> Option<CString> {
    // RPC carries no SELinux context (see `PeerIdentity`); during an RPC
    // transaction return `None` without forcing `THREAD_STATE` (which
    // would panic in a pure-RPC process).
    if rpc_calling().is_some() || !ProcessState::is_initialized() {
        return None;
    }
    THREAD_STATE.with(|thread_state| {
        let thread_state = thread_state.borrow();
        let transaction = thread_state.transaction.as_ref()?;
        if transaction.calling_sid.is_null() {
            return None;
        }
        // SAFETY: `calling_sid` is a pointer into the kernel-delivered mmap
        // region for the current BR_TRANSACTION_SEC_CTX (set in
        // `TransactionState::from_transaction_data`). The kernel guarantees
        // it points to a null-terminated string that stays valid until we
        // issue `BC_FREE_BUFFER` for the same transaction — which only
        // happens after `Transactable::transact` returns, so any caller
        // observing `is_handling_transaction() == true` may safely read it.
        Some(unsafe { CStr::from_ptr(transaction.calling_sid as _).to_owned() })
    })
}

/// PID of the caller for the current in-flight binder transaction.
///
/// Returns the sender PID delivered by the kernel via
/// `binder_transaction_data.sender_pid` when this thread is dispatching a
/// `BR_TRANSACTION` / `BR_TRANSACTION_SEC_CTX`, and `0` when not handling
/// a transaction (matches AOSP `IPCThreadState::getCallingPid()` which
/// returns the saved `mCallingPid` field; the field is zero-initialized
/// outside a transaction).
///
/// Convenience wrapper around `CallingContext::default().pid` for the
/// common case where only the PID is needed — avoids the
/// `Option<CString>` allocation of the full context.
pub fn get_calling_pid() -> binder::pid_t {
    // Plan 2-16 Phase B: an RPC transaction's pid (Unix RPC; `-1`/unknown
    // on transports without a pid) takes precedence and is read without
    // forcing `THREAD_STATE` (pure-RPC safe).
    if let Some((_, pid)) = rpc_calling() {
        return pid;
    }
    if !ProcessState::is_initialized() {
        return 0;
    }
    THREAD_STATE.with(|thread_state| {
        thread_state
            .borrow()
            .transaction
            .as_ref()
            .map_or(0, |tr| tr.calling_pid)
    })
}

/// UID of the caller for the current in-flight binder transaction.
///
/// Returns the sender UID delivered by the kernel via
/// `binder_transaction_data.sender_euid` when this thread is dispatching
/// a `BR_TRANSACTION` / `BR_TRANSACTION_SEC_CTX`, and `0` when not
/// handling a transaction (matches AOSP `IPCThreadState::getCallingUid()`
/// which returns the saved `mCallingUid` field).
///
/// Convenience wrapper around `CallingContext::default().uid` for the
/// common case where only the UID is needed.
///
/// Note: this is the *kernel-delivered* sender UID. To temporarily
/// replace it for a nested outbound call (the AOSP
/// `clearCallingIdentity` pattern), see [`clear_calling_identity`] and
/// [`restore_calling_identity`].
///
/// # RPC transports (Plan 2-16 Phase B)
///
/// Over a **Unix-domain RPC** connection this returns the kernel-vouched
/// peer uid (`SO_PEERCRED` on Linux/Android, `getpeereid` on macOS/BSD) —
/// so a hand-rolled uid ACL runs transport-agnostically on kernel binder
/// *and* Unix RPC. The granularity is **connection-level**, not
/// per-method (an RPC connection is opened once by one peer process).
///
/// Over RPC transports that carry **no** uid (`Vsock` cid, TLS
/// `Certificate`, `Anonymous`) this returns a **fail-closed sentinel**
/// (`u32::MAX`, never `0`/root and never a real privileged uid) — uid is
/// the wrong authorization basis there; use `PeerIdentity` /
/// `RpcServer::set_authorizer` instead. `@EnforcePermission` over RPC is
/// always denied regardless of uid (Plan 2-16 Phase A).
pub fn get_calling_uid() -> binder::uid_t {
    // Plan 2-16 Phase B: an RPC transaction's uid takes precedence and is
    // read without forcing `THREAD_STATE` (pure-RPC safe). Non-uid
    // transports were stamped with `RPC_UNKNOWN_CALLING_UID` by the
    // dispatch path, so this stays fail-closed there.
    if let Some((uid, _)) = rpc_calling() {
        return uid;
    }
    if !ProcessState::is_initialized() {
        return 0;
    }
    THREAD_STATE.with(|thread_state| {
        thread_state
            .borrow()
            .transaction
            .as_ref()
            .map_or(0, |tr| tr.calling_uid)
    })
}

/// AOSP-faithful variant of [`get_calling_uid`]: outside a transaction,
/// returns the current process's own uid (`getuid(2)`) instead of `0`.
///
/// Mirrors AOSP `IPCThreadState::getCallingUid()`, which initializes
/// `mCallingUid` to `getuid()` rather than zero — observers downstream
/// (e.g. per-uid accounting in [`crate::proxy_count`]) get the same
/// attribution they would on real Android.
///
/// # RPC transports (Plan 2-16 Phase B)
///
/// During an RPC transaction this returns the RPC caller uid, exactly as
/// [`get_calling_uid`]: the kernel-vouched peer uid over Unix RPC, or the
/// fail-closed sentinel (`u32::MAX`) over transports without a uid
/// (`Vsock` / TLS `Certificate` / `Anonymous`). The self-uid fallback
/// applies only outside any (kernel or RPC) transaction, so
/// [`crate::proxy_count`] attribution over a uid-less RPC transport buckets
/// under the `u32::MAX` sentinel rather than this process's uid.
pub fn get_calling_uid_or_self() -> binder::uid_t {
    // Plan 2-16 Phase B: prefer the RPC caller uid when dispatching an RPC
    // transaction; otherwise fall back to the process's own uid without
    // forcing `THREAD_STATE` in a pure-RPC process.
    if let Some((uid, _)) = rpc_calling() {
        return uid;
    }
    if !ProcessState::is_initialized() {
        return rustix::process::getuid().as_raw();
    }
    THREAD_STATE
        .with(|thread_state| {
            thread_state
                .borrow()
                .transaction
                .as_ref()
                .map(|tr| tr.calling_uid)
        })
        .unwrap_or_else(|| rustix::process::getuid().as_raw())
}

/// Temporarily override the kernel-delivered calling identity with the
/// current process's own uid/pid, and return an opaque token that
/// [`restore_calling_identity`] uses to reverse the override.
///
/// Mirrors AOSP `IPCThreadState::clearCallingIdentity()`
/// (`frameworks/native/libs/binder/IPCThreadState.cpp:562`). Typical use
/// is server-side: a transaction handler that needs to make an outgoing
/// binder call to another service "as itself" rather than as the original
/// caller, to avoid leaking the caller's privileges into a downstream
/// permission check (or, conversely, to *deliberately* drop a privileged
/// caller's identity before delegating).
///
/// ```text
/// // Inside Transactable::transact:
/// let token = clear_calling_identity();
/// let result = downstream_service.do_something(...);
/// restore_calling_identity(token);
/// ```
///
/// The returned token packs `(has_explicit_identity, calling_uid,
/// calling_pid)` into 64 bits using the AOSP bit layout
/// (`packCallingIdentity` in IPCThreadState.cpp). The SELinux SID is
/// **not** preserved — matching the AOSP comment "ignore mCallingSid for
/// legacy reasons". After [`restore_calling_identity`], `get_calling_sid`
/// returns `None`.
///
/// # Behavior outside a transaction
///
/// Returns `0` and is a no-op when not currently dispatching a binder
/// transaction (no kernel-delivered identity exists to clear). This
/// differs from AOSP, which stores calling identity in flat
/// `IPCThreadState` fields that persist between transactions — but the
/// AOSP user-facing semantics (clear before downstream call, restore
/// after) match.
pub fn clear_calling_identity() -> i64 {
    THREAD_STATE.with(|thread_state| {
        let mut thread_state = thread_state.borrow_mut();
        let Some(ref mut tr) = thread_state.transaction else {
            return 0;
        };
        let token = pack_calling_identity(tr.has_explicit_identity, tr.calling_uid, tr.calling_pid);
        // AOSP `clearCaller()`: replace with own uid/pid, drop SID
        // ("expensive to lookup"), and stamp explicit-identity.
        tr.calling_uid = rustix::process::getuid().as_raw();
        tr.calling_pid = rustix::process::getpid().as_raw_nonzero().get() as _;
        tr.calling_sid = std::ptr::null();
        tr.has_explicit_identity = true;
        token
    })
}

/// Reverse a previous [`clear_calling_identity`] by unpacking the token
/// and writing the saved uid/pid/has_explicit back into the current
/// transaction's calling identity.
///
/// Mirrors AOSP `IPCThreadState::restoreCallingIdentity(int64_t)`
/// (`IPCThreadState.cpp:645`). The SELinux SID is left as `None` because
/// the token has no room to preserve it ("not enough data to restore" —
/// same as AOSP). Callers needing both UID/PID and SID restoration must
/// save the SID separately before clearing.
///
/// # Behavior outside a transaction
///
/// No-op when not currently dispatching a transaction (consistent with
/// [`clear_calling_identity`] returning 0 in that case). The token is
/// silently discarded — there is no transaction state to write into.
///
/// # Token mismatch
///
/// rsbinder does **not** validate that `token` came from a matching
/// `clear_calling_identity()` call on the same thread/transaction — same
/// trust model as AOSP. Passing a forged or stale token simply sets the
/// fields to whatever the token decodes to. The `RAII` guard pattern
/// (caller wraps `clear`/`restore` in a `Drop` impl) is recommended; see
/// AOSP `IPCThreadState::CallingIdentityScope` for the C++ analogue.
pub fn restore_calling_identity(token: i64) {
    THREAD_STATE.with(|thread_state| {
        let mut thread_state = thread_state.borrow_mut();
        let Some(ref mut tr) = thread_state.transaction else {
            return;
        };
        tr.calling_uid = unpack_calling_uid(token);
        tr.calling_pid = unpack_calling_pid(token);
        tr.has_explicit_identity = unpack_has_explicit_identity(token);
        tr.calling_sid = std::ptr::null();
    })
}

/// Linux scheduler policy of the current thread, as reported by the
/// kernel via `sched_getscheduler(0)`. Debug helper to confirm that
/// `FLAT_BINDER_FLAG_INHERIT_RT` actually lifted the worker thread into
/// SCHED_FIFO / SCHED_RR for the transaction.
///
/// Values match `<linux/sched.h>` / `libc::SCHED_*` constants:
///
///   * `0` = `SCHED_NORMAL` (a.k.a. `SCHED_OTHER`)
///   * `1` = `SCHED_FIFO`
///   * `2` = `SCHED_RR`
///   * `3` = `SCHED_BATCH`
///   * `5` = `SCHED_IDLE`
///   * `6` = `SCHED_DEADLINE`
///
/// Linux + Android only — on macOS this returns `Err(InvalidOperation)`
/// because `SCHED_*` policies are a Linux/Android concept. Inside an
/// `on_transact` body on Linux/Android, the returned value is the policy
/// the kernel installed for the binder worker thread before invoking
/// the handler.
#[cfg(any(target_os = "linux", target_os = "android"))]
pub fn get_current_scheduler_policy() -> Result<i32> {
    // SAFETY: FFI to libc::sched_getscheduler. No pointer arguments;
    // pid=0 means "the current thread" and is always a valid input.
    // The return value is a plain i32; on -1 the libc errno is set
    // and the read below is the standard POSIX recovery.
    let raw = unsafe { libc::sched_getscheduler(0) };
    if raw < 0 {
        // POSIX guarantees errno is set when sched_getscheduler
        // returns -1; the `unwrap_or` fallback below would only fire
        // on a library or kernel bug, so prefer `EINVAL` over `0`
        // (which is itself a valid "success" errno and would mislead
        // the caller).
        let errno = std::io::Error::last_os_error()
            .raw_os_error()
            .unwrap_or(libc::EINVAL);
        return Err(StatusCode::from(rustix::io::Errno::from_raw_os_error(
            errno,
        )));
    }
    Ok(raw)
}

#[cfg(not(any(target_os = "linux", target_os = "android")))]
pub fn get_current_scheduler_policy() -> Result<i32> {
    Err(StatusCode::InvalidOperation)
}

/// Last transaction failure detail reported by the kernel binder driver
/// for the current thread, as returned by `BINDER_GET_EXTENDED_ERROR`
/// (Android 12 / Linux 5.14+).
///
/// Stable Rust mirror of the kernel's `struct binder_extended_error`
/// (`include/uapi/linux/android/binder.h:302-306` in AOSP /
/// `external/kernel-headers/.../binder.h`). See [`get_extended_error`]
/// for retrieval semantics.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ExtendedError {
    /// Monotonically increasing per-thread counter. Each fresh failure
    /// observed by the driver bumps this; `0` means no failure has yet
    /// been recorded on this thread.
    pub id: u32,
    /// The BR_ return code that surfaced the failure
    /// (typically `BR_FAILED_REPLY`).
    pub command: u32,
    /// Negated errno or other driver-specific code (`0` when the driver
    /// has no additional detail).
    pub param: i32,
}

/// Retrieve the kernel-side detail of the most recent transaction
/// failure on the current thread.
///
/// AOSP equivalent: `IPCThreadState::getExtendedError()`
/// ([IPCThreadState.cpp](https://cs.android.com/android/platform/superproject/main/+/main:frameworks/native/libs/binder/IPCThreadState.cpp)).
/// The ioctl was added in Android 12 (S, SDK 31, Linux 5.14+); older
/// drivers respond `ENOTTY`, surfaced here as
/// `Err(StatusCode::InvalidOperation)` so callers can fall back to the
/// bare `StatusCode::FailedTransaction` signal from a failed `transact`.
///
/// Typical use pairs with a preceding `transact` that returned
/// `Err(StatusCode::FailedTransaction)`:
///
/// ```ignore
/// match svc.do_something(...) {
///     Err(StatusCode::FailedTransaction) => {
///         if let Ok(ee) = rsbinder::get_extended_error() {
///             eprintln!("driver detail: cmd={:#x} param={}", ee.command, ee.param);
///         }
///     }
///     _ => {}
/// }
/// ```
///
/// **Opt-in**: rsbinder does *not* call this automatically from the
/// `BR_FAILED_REPLY` arm. A no-op for callers that never invoke it.
pub fn get_extended_error() -> Result<ExtendedError> {
    let mut ee = binder::binder_extended_error::default();
    let driver = ProcessState::as_self().driver();
    crate::sys::binder::get_extended_error(driver.as_ref(), &mut ee).map_err(|errno| {
        if errno == rustix::io::Errno::NOTTY {
            // Pre-Android-12 driver — feature unavailable.
            StatusCode::InvalidOperation
        } else {
            StatusCode::from(errno)
        }
    })?;
    Ok(ExtendedError {
        id: ee.id,
        command: ee.command,
        param: ee.param,
    })
}

/// Whether [`clear_calling_identity`] has been invoked on the current
/// in-flight transaction without a matching [`restore_calling_identity`].
///
/// Mirrors AOSP `IPCThreadState::hasExplicitIdentity()`
/// (`IPCThreadState.cpp:571`). Reset to `false` on every new incoming
/// `BR_TRANSACTION`, matching AOSP's per-transaction lifecycle
/// (`IPCThreadState.cpp:1141`).
///
/// Returns `false` when not currently dispatching a transaction.
pub fn has_explicit_identity() -> bool {
    THREAD_STATE.with(|thread_state| {
        thread_state
            .borrow()
            .transaction
            .as_ref()
            .is_some_and(|tr| tr.has_explicit_identity)
    })
}

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

    /// Plan 2-16 Phase B/C: the RPC calling context is read by the public
    /// accessors (`get_calling_uid/pid`, `calling_caller`), restores on
    /// guard drop, nests correctly, and is fail-closed for non-uid
    /// transports — all without a kernel `ProcessState` (hermetic, runs on
    /// macOS). The `0`/`!handling`/`None` outside the guard also proves the
    /// pure-RPC accessors are panic-free with `ProcessState` uninitialized.
    #[cfg(feature = "rpc")]
    #[test]
    fn rpc_calling_context_is_read_restored_and_failclosed() {
        use crate::rpc::transport::PeerIdentity;
        use std::sync::Arc;

        // Outside any transaction (pure-RPC, no ProcessState): defined,
        // not a panic.
        assert_eq!(get_calling_uid(), 0);
        assert_eq!(get_calling_pid(), 0);
        assert!(!is_handling_transaction());
        assert!(get_calling_sid().is_none());
        assert!(calling_caller().is_none());

        {
            let _g = RpcCallingGuard::install(Arc::new(PeerIdentity::Local { uid: 1234, pid: 42 }));
            assert_eq!(get_calling_uid(), 1234);
            assert_eq!(get_calling_pid(), 42);
            assert!(is_handling_transaction());
            // RPC carries no SELinux context.
            assert!(get_calling_sid().is_none());
            assert_eq!(CallingContext::default().uid, 1234);
            assert_eq!(CallingContext::default().pid, 42);
            // `calling_caller` exposes the full RPC peer (Phase C).
            match calling_caller() {
                Some(Caller::Rpc(PeerIdentity::Local { uid, pid })) => {
                    assert_eq!((uid, pid), (1234, 42));
                }
                other => panic!("expected Caller::Rpc(Local), got {other:?}"),
            }

            // Nested re-entrant callback over the same connection: a
            // non-uid transport (vsock) stamps the fail-closed sentinel;
            // the outer identity is restored when it returns.
            {
                let _g2 = RpcCallingGuard::install(Arc::new(PeerIdentity::Vsock { cid: 7 }));
                assert_eq!(get_calling_uid(), RPC_UNKNOWN_CALLING_UID);
                assert_ne!(get_calling_uid(), 0, "sentinel must never read as root");
                assert_eq!(get_calling_pid(), -1);
                // The full peer is still exposed for cid-based decisions.
                assert!(matches!(
                    calling_caller(),
                    Some(Caller::Rpc(PeerIdentity::Vsock { cid: 7 }))
                ));
            }
            assert_eq!(
                get_calling_uid(),
                1234,
                "outer identity restored after nesting"
            );
        }

        // Fully restored.
        assert_eq!(get_calling_uid(), 0);
        assert!(!is_handling_transaction());
        assert!(calling_caller().is_none());
    }

    #[test]
    fn test_return_to_str() {
        assert_eq!(return_to_str(binder::BR_OK), "BR_OK");
        assert_eq!(return_to_str(binder::BR_TRANSACTION), "BR_TRANSACTION");
        assert_eq!(return_to_str(binder::BR_REPLY), "BR_REPLY");
        assert_eq!(return_to_str(binder::BR_ACQUIRE), "BR_ACQUIRE");
        assert_eq!(return_to_str(binder::BR_INCREFS), "BR_INCREFS");
        assert_eq!(
            return_to_str(binder::BR_ACQUIRE_RESULT),
            "BR_ACQUIRE_RESULT"
        );
        assert_eq!(return_to_str(binder::BR_DEAD_BINDER), "BR_DEAD_BINDER");
        assert_eq!(
            return_to_str(binder::BR_CLEAR_DEATH_NOTIFICATION_DONE),
            "BR_CLEAR_DEATH_NOTIFICATION_DONE"
        );
        assert_eq!(return_to_str(binder::BR_FAILED_REPLY), "BR_FAILED_REPLY");
        assert_eq!(return_to_str(binder::BR_DEAD_REPLY), "BR_DEAD_REPLY");
        assert_eq!(return_to_str(binder::BR_FINISHED), "BR_FINISHED");
        assert_eq!(return_to_str(binder::BR_SPAWN_LOOPER), "BR_SPAWN_LOOPER");
        assert_eq!(
            return_to_str(binder::BR_ATTEMPT_ACQUIRE),
            "BR_ATTEMPT_ACQUIRE"
        );
        assert_eq!(return_to_str(binder::BR_NOOP), "BR_NOOP");
        assert_eq!(return_to_str(binder::BR_SPAWN_LOOPER), "BR_SPAWN_LOOPER");
        assert_eq!(return_to_str(binder::BR_ERROR), "BR_ERROR");
        assert_eq!(return_to_str(binder::BR_DEAD_REPLY), "BR_DEAD_REPLY");
        assert_eq!(return_to_str(binder::BR_FAILED_REPLY), "BR_FAILED_REPLY");
        assert_eq!(return_to_str(binder::BR_FROZEN_REPLY), "BR_FROZEN_REPLY");
        assert_eq!(
            return_to_str(binder::BR_TRANSACTION_SEC_CTX),
            "BR_TRANSACTION_SEC_CTX"
        );
        assert_eq!(return_to_str(binder::BR_DECREFS), "BR_DECREFS");
        assert_eq!(
            return_to_str(binder::BR_TRANSACTION_COMPLETE),
            "BR_TRANSACTION_COMPLETE"
        );
        assert_eq!(
            return_to_str(binder::BR_ONEWAY_SPAM_SUSPECT),
            "BR_ONEWAY_SPAM_SUSPECT"
        );
        // Freeze-observer BR strings.
        assert_eq!(
            return_to_str(binder::BR_TRANSACTION_PENDING_FROZEN),
            "BR_TRANSACTION_PENDING_FROZEN"
        );
        assert_eq!(return_to_str(binder::BR_FROZEN_BINDER), "BR_FROZEN_BINDER");
        assert_eq!(
            return_to_str(binder::BR_CLEAR_FREEZE_NOTIFICATION_DONE),
            "BR_CLEAR_FREEZE_NOTIFICATION_DONE"
        );
    }

    /// BR constants match the kernel UAPI
    /// (`_IO('r', 20)`, `_IOR('r', 21, binder_frozen_state_info)`,
    /// `_IOR('r', 22, binder_uintptr_t)`). Locking these in here means
    /// a kernel-header drift would surface as a test failure rather than
    /// a silent wire mismatch.
    #[test]
    fn freeze_observer_br_constants_match_uapi() {
        // _IO('r', 20)
        assert_eq!(binder::BR_TRANSACTION_PENDING_FROZEN, 29204);
        // _IOR('r', 21, binder_frozen_state_info) — sizeof=16
        assert_eq!(binder::BR_FROZEN_BINDER, 2148561429);
        // _IOR('r', 22, binder_uintptr_t) — sizeof=8
        assert_eq!(binder::BR_CLEAR_FREEZE_NOTIFICATION_DONE, 2148037142);
    }

    /// BC constants match the kernel UAPI
    /// (`_IOW('c', 19, binder_handle_cookie)`,
    /// `_IOW('c', 20, binder_handle_cookie)`,
    /// `_IOW('c', 21, binder_uintptr_t)`).
    #[test]
    fn freeze_observer_bc_constants_match_uapi() {
        // _IOW('c', 19, binder_handle_cookie) — sizeof packed = 12
        assert_eq!(binder::BC_REQUEST_FREEZE_NOTIFICATION, 1074553619);
        // _IOW('c', 20, binder_handle_cookie) — sizeof = 12
        assert_eq!(binder::BC_CLEAR_FREEZE_NOTIFICATION, 1074553620);
        // _IOW('c', 21, binder_uintptr_t) — sizeof = 8
        assert_eq!(binder::BC_FREEZE_NOTIFICATION_DONE, 1074291477);
    }

    /// `binder_frozen_state_info` layout: cookie (u64), is_frozen (u32),
    /// reserved (u32) = 16 bytes, aligned 8. The `BR_FROZEN_BINDER`
    /// dispatch reads this via `parcel.read::<binder_frozen_state_info>()`.
    #[test]
    fn binder_frozen_state_info_layout() {
        use crate::sys::binder_frozen_state_info;
        assert_eq!(std::mem::size_of::<binder_frozen_state_info>(), 16);
        assert_eq!(std::mem::align_of::<binder_frozen_state_info>(), 8);
        let s = binder_frozen_state_info::default();
        assert_eq!(s.cookie, 0);
        assert_eq!(s.is_frozen, 0);
        assert_eq!(s.reserved, 0);
    }

    /// The default arm in `wait_for_response` is untouched: the new
    /// constants are declared so the strings table can label them, but
    /// no dispatch path consumes them yet. This is a smoke test — if a
    /// future change accidentally dispatched the freeze-observer BRs
    /// before its own arm is in place, the kernel wire would diverge.
    /// Here we just confirm the constants are visible to user code.
    #[test]
    fn freeze_observer_constants_are_pub_for_phase_b() {
        // If these uses compile, the constants are exposed for a future
        // dispatch path to consume.
        let _b1 = binder::BR_TRANSACTION_PENDING_FROZEN;
        let _b2 = binder::BR_FROZEN_BINDER;
        let _b3 = binder::BR_CLEAR_FREEZE_NOTIFICATION_DONE;
        let _c1 = binder::BC_REQUEST_FREEZE_NOTIFICATION;
        let _c2 = binder::BC_CLEAR_FREEZE_NOTIFICATION;
        let _c3 = binder::BC_FREEZE_NOTIFICATION_DONE;
    }

    #[test]
    fn test_command_to_str() {
        assert_eq!(command_to_str(binder::BC_TRANSACTION), "BC_TRANSACTION");
        assert_eq!(command_to_str(binder::BC_REPLY), "BC_REPLY");
        assert_eq!(
            command_to_str(binder::BC_ACQUIRE_RESULT),
            "BC_ACQUIRE_RESULT"
        );
        assert_eq!(command_to_str(binder::BC_FREE_BUFFER), "BC_FREE_BUFFER");
        assert_eq!(command_to_str(binder::BC_INCREFS), "BC_INCREFS");
        assert_eq!(command_to_str(binder::BC_ACQUIRE), "BC_ACQUIRE");
        assert_eq!(command_to_str(binder::BC_RELEASE), "BC_RELEASE");
        assert_eq!(command_to_str(binder::BC_DECREFS), "BC_DECREFS");
        assert_eq!(command_to_str(binder::BC_INCREFS_DONE), "BC_INCREFS_DONE");
        assert_eq!(command_to_str(binder::BC_ACQUIRE_DONE), "BC_ACQUIRE_DONE");
        assert_eq!(
            command_to_str(binder::BC_ATTEMPT_ACQUIRE),
            "BC_ATTEMPT_ACQUIRE"
        );
        assert_eq!(
            command_to_str(binder::BC_REGISTER_LOOPER),
            "BC_REGISTER_LOOPER"
        );
        assert_eq!(command_to_str(binder::BC_ENTER_LOOPER), "BC_ENTER_LOOPER");
        assert_eq!(command_to_str(binder::BC_EXIT_LOOPER), "BC_EXIT_LOOPER");
        assert_eq!(
            command_to_str(binder::BC_REQUEST_DEATH_NOTIFICATION),
            "BC_REQUEST_DEATH_NOTIFICATION"
        );
        assert_eq!(
            command_to_str(binder::BC_CLEAR_DEATH_NOTIFICATION),
            "BC_CLEAR_DEATH_NOTIFICATION"
        );
        assert_eq!(
            command_to_str(binder::BC_DEAD_BINDER_DONE),
            "BC_DEAD_BINDER_DONE"
        );
        assert_eq!(
            command_to_str(binder::BC_TRANSACTION_SG),
            "BC_TRANSACTION_SG"
        );
        assert_eq!(command_to_str(binder::BC_REPLY_SG), "BC_REPLY_SG");
        // Freeze-observer BC strings.
        assert_eq!(
            command_to_str(binder::BC_REQUEST_FREEZE_NOTIFICATION),
            "BC_REQUEST_FREEZE_NOTIFICATION"
        );
        assert_eq!(
            command_to_str(binder::BC_CLEAR_FREEZE_NOTIFICATION),
            "BC_CLEAR_FREEZE_NOTIFICATION"
        );
        assert_eq!(
            command_to_str(binder::BC_FREEZE_NOTIFICATION_DONE),
            "BC_FREEZE_NOTIFICATION_DONE"
        );
    }

    /// A panicking `Transactable::transact` must not unwind through
    /// `dispatch_transact_caught` and must surface as
    /// `Err(StatusCode::Unknown)` so the existing `BR_TRANSACTION`
    /// reply path can synthesize a deterministic error reply for the
    /// client. The partial reply (if any) must also be reset so the
    /// client does not misparse half-formed bytes.
    #[test]
    fn test_dispatch_transact_caught_isolates_panic() {
        struct PanickingTransactable;
        impl Transactable for PanickingTransactable {
            fn transact(
                &self,
                _code: TransactionCode,
                _reader: &mut Parcel,
                reply: &mut Parcel,
            ) -> Result<()> {
                // Write a few bytes then panic, so the test verifies
                // the partial reply is discarded.
                reply.write::<i32>(&0x6EAD_BEEFi32).ok();
                panic!("simulated transactable panic");
            }
        }

        let mut reader = Parcel::new();
        let mut reply = Parcel::new();
        let result = dispatch_transact_caught(&PanickingTransactable, 1, &mut reader, &mut reply);

        assert!(
            matches!(result, Err(StatusCode::Unknown)),
            "expected Err(StatusCode::Unknown), got {result:?}"
        );
        assert_eq!(
            reply.data_size(),
            0,
            "partial reply must be discarded after a panic so the \
             client does not misparse half-formed data"
        );
    }

    /// A non-panicking `Transactable::transact` must propagate its
    /// `Result` unchanged through `dispatch_transact_caught` —
    /// regression check that the panic guard does not interfere with
    /// the normal path.
    #[test]
    fn test_dispatch_transact_caught_propagates_normal_result() {
        struct OkTransactable;
        impl Transactable for OkTransactable {
            fn transact(
                &self,
                _code: TransactionCode,
                _reader: &mut Parcel,
                reply: &mut Parcel,
            ) -> Result<()> {
                reply.write::<i32>(&42i32)?;
                Ok(())
            }
        }

        struct ErrTransactable;
        impl Transactable for ErrTransactable {
            fn transact(
                &self,
                _code: TransactionCode,
                _reader: &mut Parcel,
                _reply: &mut Parcel,
            ) -> Result<()> {
                Err(StatusCode::PermissionDenied)
            }
        }

        let mut reader = Parcel::new();
        let mut reply = Parcel::new();
        assert!(dispatch_transact_caught(&OkTransactable, 1, &mut reader, &mut reply).is_ok());
        assert_eq!(reply.data_size(), std::mem::size_of::<i32>());

        let mut reply = Parcel::new();
        let err = dispatch_transact_caught(&ErrTransactable, 1, &mut reader, &mut reply);
        assert!(matches!(err, Err(StatusCode::PermissionDenied)));
    }

    /// `drive_dead_binder_handshake` orchestration must guarantee:
    /// - Phases run in obituary → queue → pin order on success
    /// - An obituary error does NOT short-circuit queue or pin
    /// - A queue error skips pin (acknowledged residual edge)
    /// - When obituary errors and pin errors, obituary takes priority
    /// - The kernel handshake (queue + pin) runs whenever queue succeeds
    ///
    /// These properties protect against a kernel `binder_ref` slot
    /// leak: losing any of them (e.g. a naive `?`-based early return on
    /// the obituary error) re-introduces the leak.
    #[test]
    fn test_drive_dead_binder_handshake_orchestration() {
        use std::cell::RefCell;

        let order = RefCell::new(Vec::<&'static str>::new());
        let push = |label: &'static str| order.borrow_mut().push(label);

        // Case A: all phases succeed.
        let result = drive_dead_binder_handshake(
            42,
            || {
                push("obituary");
                Ok(())
            },
            || {
                push("queue");
                Ok(())
            },
            || {
                push("pin");
                Ok(())
            },
        );
        assert!(result.is_ok());
        assert_eq!(*order.borrow(), vec!["obituary", "queue", "pin"]);
        order.borrow_mut().clear();

        // Case B: obituary errors → queue and pin still run; obituary
        // error surfaces. This is the headline guarantee: previously
        // the kernel handshake was skipped on obituary error, leaking
        // the binder_ref slot.
        let result = drive_dead_binder_handshake(
            42,
            || {
                push("obituary");
                Err(StatusCode::DeadObject)
            },
            || {
                push("queue");
                Ok(())
            },
            || {
                push("pin");
                Ok(())
            },
        );
        assert!(matches!(result, Err(StatusCode::DeadObject)));
        assert_eq!(*order.borrow(), vec!["obituary", "queue", "pin"]);
        order.borrow_mut().clear();

        // Case C: queue write fails → pin is skipped (documented
        // residual edge), queue error surfaces.
        let result = drive_dead_binder_handshake(
            42,
            || {
                push("obituary");
                Ok(())
            },
            || {
                push("queue");
                Err(StatusCode::NoMemory)
            },
            || {
                push("pin");
                Ok(())
            },
        );
        assert!(matches!(result, Err(StatusCode::NoMemory)));
        assert_eq!(*order.borrow(), vec!["obituary", "queue"]);
        order.borrow_mut().clear();

        // Case D: obituary OK, pin errors → pin error surfaces.
        let result = drive_dead_binder_handshake(
            42,
            || {
                push("obituary");
                Ok(())
            },
            || {
                push("queue");
                Ok(())
            },
            || {
                push("pin");
                Err(StatusCode::DeadObject)
            },
        );
        assert!(matches!(result, Err(StatusCode::DeadObject)));
        assert_eq!(*order.borrow(), vec!["obituary", "queue", "pin"]);
        order.borrow_mut().clear();

        // Case E: obituary errors AND pin errors → obituary error
        // surfaces (priority); pin error is logged in the error path
        // (asserting log content is out of scope for a unit test).
        let result = drive_dead_binder_handshake(
            42,
            || {
                push("obituary");
                Err(StatusCode::PermissionDenied)
            },
            || {
                push("queue");
                Ok(())
            },
            || {
                push("pin");
                Err(StatusCode::DeadObject)
            },
        );
        assert!(
            matches!(result, Err(StatusCode::PermissionDenied)),
            "obituary error must take priority over pin error, got {result:?}"
        );
        assert_eq!(*order.borrow(), vec!["obituary", "queue", "pin"]);
    }

    /// Regression test for `b17d522`: `process_pending_derefs` must
    /// tolerate a re-entrant push to `BINDER_DEREFS` from a user
    /// `Inner<T>::drop` callback.
    ///
    /// Pre-`b17d522`, the function held the `BINDER_DEREFS` borrow
    /// across `deref_native_kernel`. When entry removal triggered an
    /// `Inner<T>::drop` whose user destructor synchronously caused
    /// another BR_RELEASE / BR_DECREFS to land (path: outgoing IPC →
    /// `wait_for_response` → `talk_with_driver` → `execute_command`
    /// queues into `BINDER_DEREFS`), the second `borrow_mut()` panicked.
    ///
    /// We simulate that re-entrancy in-process by pushing a second id
    /// into `BINDER_DEREFS.pending_weak_derefs` directly from a
    /// drop-fired sentinel — no kernel needed.
    ///
    /// **Linux + binderfs only** (uses `ProcessState::init_default`,
    /// which opens `/dev/binderfs/binder`). Same convention as the
    /// `process_state` M4 tests; surfaces under
    /// `.github/workflows/integration-test.yml`.
    #[test]
    #[cfg_attr(
        not(any(target_os = "linux", target_os = "android")),
        ignore = "requires /dev/binder"
    )]
    #[serial_test::serial(binder)]
    fn test_process_pending_derefs_handles_reentrant_push_from_drop() {
        use std::sync::atomic::AtomicU64;
        use std::sync::{self, Mutex};
        let process = ProcessState::init_default().expect("init_default");

        let drop_log: Arc<Mutex<Vec<u64>>> = Arc::new(Mutex::new(Vec::new()));
        let pusher_target: Arc<AtomicU64> = Arc::new(AtomicU64::new(0));

        // Sentinel B: drop pushes nothing, only records that it fired.
        struct DropFireSentinel {
            my_id: Arc<AtomicU64>,
            log: Arc<Mutex<Vec<u64>>>,
        }
        impl Drop for DropFireSentinel {
            fn drop(&mut self) {
                self.log
                    .lock()
                    .unwrap()
                    .push(self.my_id.load(Ordering::SeqCst));
            }
        }
        impl IBinder for DropFireSentinel {
            fn link_to_death(&self, _: sync::Weak<dyn DeathRecipient>) -> Result<()> {
                Err(StatusCode::InvalidOperation)
            }
            fn unlink_to_death(&self, _: sync::Weak<dyn DeathRecipient>) -> Result<()> {
                Err(StatusCode::InvalidOperation)
            }
            fn ping_binder(&self) -> Result<()> {
                Ok(())
            }
            fn as_any(&self) -> &dyn std::any::Any {
                self
            }
            fn as_transactable(&self) -> Option<&dyn Transactable> {
                None
            }
            fn descriptor(&self) -> &str {
                "rsbinder.test.DropFireSentinel"
            }
            fn is_remote(&self) -> bool {
                false
            }
            fn inc_strong(&self, _: &SIBinder) -> Result<()> {
                Ok(())
            }
            fn attempt_inc_strong(&self) -> bool {
                true
            }
            fn dec_strong(&self, _: Option<std::mem::ManuallyDrop<SIBinder>>) -> Result<()> {
                Ok(())
            }
            fn inc_weak(&self, _: &WIBinder) -> Result<()> {
                Ok(())
            }
            fn dec_weak(&self) -> Result<()> {
                Ok(())
            }
        }

        // Sentinel A: drop pushes B's id back into BINDER_DEREFS,
        // simulating an outgoing IPC's BR_DECREFS landing during the
        // drain.
        struct ReentrantPusher {
            my_id: Arc<AtomicU64>,
            target: Arc<AtomicU64>,
            log: Arc<Mutex<Vec<u64>>>,
        }
        impl Drop for ReentrantPusher {
            fn drop(&mut self) {
                self.log
                    .lock()
                    .unwrap()
                    .push(self.my_id.load(Ordering::SeqCst));
                let target_id = self.target.load(Ordering::SeqCst);
                if target_id != 0 {
                    BINDER_DEREFS.with(|d| {
                        d.borrow_mut().pending_weak_derefs.push_back(target_id);
                    });
                }
            }
        }
        impl IBinder for ReentrantPusher {
            fn link_to_death(&self, _: sync::Weak<dyn DeathRecipient>) -> Result<()> {
                Err(StatusCode::InvalidOperation)
            }
            fn unlink_to_death(&self, _: sync::Weak<dyn DeathRecipient>) -> Result<()> {
                Err(StatusCode::InvalidOperation)
            }
            fn ping_binder(&self) -> Result<()> {
                Ok(())
            }
            fn as_any(&self) -> &dyn std::any::Any {
                self
            }
            fn as_transactable(&self) -> Option<&dyn Transactable> {
                None
            }
            fn descriptor(&self) -> &str {
                "rsbinder.test.ReentrantPusher"
            }
            fn is_remote(&self) -> bool {
                false
            }
            fn inc_strong(&self, _: &SIBinder) -> Result<()> {
                Ok(())
            }
            fn attempt_inc_strong(&self) -> bool {
                true
            }
            fn dec_strong(&self, _: Option<std::mem::ManuallyDrop<SIBinder>>) -> Result<()> {
                Ok(())
            }
            fn inc_weak(&self, _: &WIBinder) -> Result<()> {
                Ok(())
            }
            fn dec_weak(&self) -> Result<()> {
                Ok(())
            }
        }

        // Publish B first so we know its id before constructing A.
        let id_b_holder = Arc::new(AtomicU64::new(0));
        let arc_b: Arc<dyn IBinder> = Arc::new(DropFireSentinel {
            my_id: Arc::clone(&id_b_holder),
            log: Arc::clone(&drop_log),
        });
        let id_b = process.publish_native(Arc::clone(&arc_b));
        id_b_holder.store(id_b, Ordering::SeqCst);
        // Bump kernel_refs so deref_native_kernel later drives it 1→0
        // and removes the entry. Drop the returned strong arc at
        // semicolon so the table's binder_pin is the only holder.
        process
            .ref_native_kernel(id_b)
            .expect("ref_native_kernel(id_b)");
        // Drop user-side clone: the table holds the only strong now.
        drop(arc_b);

        // Configure pusher target to id_b before publishing A.
        pusher_target.store(id_b, Ordering::SeqCst);

        let id_a_holder = Arc::new(AtomicU64::new(0));
        let arc_a: Arc<dyn IBinder> = Arc::new(ReentrantPusher {
            my_id: Arc::clone(&id_a_holder),
            target: Arc::clone(&pusher_target),
            log: Arc::clone(&drop_log),
        });
        let id_a = process.publish_native(Arc::clone(&arc_a));
        id_a_holder.store(id_a, Ordering::SeqCst);
        process
            .ref_native_kernel(id_a)
            .expect("ref_native_kernel(id_a)");
        drop(arc_a);

        // Push id_a as a strong deref. Do NOT push id_b — A's drop
        // will push it during the drain.
        BINDER_DEREFS.with(|d| {
            d.borrow_mut().pending_strong_derefs.push_back(id_a);
        });

        // Drive the drain. Pre-`b17d522` this would panic with
        // "already mutably borrowed: BorrowError" the moment A's drop
        // tried to re-borrow BINDER_DEREFS.
        process_pending_derefs().expect("process_pending_derefs must not panic or error");

        // Both natives must have dropped — re-entrant push picked up
        // by the outer loop.
        let log = drop_log.lock().unwrap();
        assert_eq!(
            log.len(),
            2,
            "both A and B must have dropped exactly once, got {log:?}"
        );
        assert!(log.contains(&id_a), "A's drop must fire, got {log:?}");
        assert!(log.contains(&id_b), "B's drop must fire, got {log:?}");

        // Both queues must be empty after drain.
        BINDER_DEREFS.with(|d| {
            let derefs = d.borrow();
            assert!(
                derefs.pending_weak_derefs.is_empty(),
                "weak queue must be empty after drain"
            );
            assert!(
                derefs.pending_strong_derefs.is_empty(),
                "strong queue must be empty after drain"
            );
        });

        // Both entries must be removed from the published_natives table.
        assert!(process.lookup_native(id_a).is_none());
        assert!(process.lookup_native(id_b).is_none());
    }

    // ----------------------------------------------------------------
    // calling-identity + strict-mode public API
    // ----------------------------------------------------------------
    //
    // Helpers below construct a synthetic `TransactionState` directly
    // and install it into the thread-local `THREAD_STATE.transaction`,
    // so the public calling-identity functions can be exercised without
    // a running binder driver.

    /// Install a fake in-flight transaction for the duration of the
    /// returned guard. On drop, the previous transaction state (usually
    /// `None`) is restored — keeps tests hermetic against each other
    /// even though `THREAD_STATE` is per-thread.
    #[cfg(target_os = "linux")]
    struct FakeTransactionGuard {
        previous: Option<TransactionState>,
    }

    #[cfg(target_os = "linux")]
    impl FakeTransactionGuard {
        fn install(
            calling_uid: binder::uid_t,
            calling_pid: binder::pid_t,
            calling_sid: *const u8,
        ) -> Self {
            let new_state = TransactionState {
                calling_pid,
                calling_sid,
                calling_uid,
                last_transaction_binder_flags: 0,
                work_source: 0,
                propagate_work_source: false,
                has_explicit_identity: false,
            };
            let previous = THREAD_STATE.with(|ts| ts.borrow_mut().transaction.replace(new_state));
            FakeTransactionGuard { previous }
        }
    }

    #[cfg(target_os = "linux")]
    impl Drop for FakeTransactionGuard {
        fn drop(&mut self) {
            THREAD_STATE.with(|ts| {
                ts.borrow_mut().transaction = self.previous.take();
            });
        }
    }

    /// With no in-flight transaction, the calling-identity free
    /// functions return the documented "outside a transaction" values
    /// (None / 0 / 0) with zero side-effects.
    ///
    /// **Linux + binderfs only** — `THREAD_STATE.with(..)` triggers
    /// `ThreadState::new` which captures the global `ProcessState` driver.
    /// Same convention as the other binder-driver-bound tests in this
    /// module (uses `ProcessState::init_default` + `serial(binder)`).
    #[test]
    #[cfg(target_os = "linux")]
    #[serial_test::serial(binder)]
    fn test_get_calling_outside_transaction_returns_defaults() {
        ProcessState::init_default().expect("init_default");
        // Discard whatever the prior in-thread test may have left in
        // `THREAD_STATE.transaction`; `serial(binder)` only serializes
        // entry, not thread-local state.
        let _ = THREAD_STATE.with(|ts| ts.borrow_mut().transaction.take());
        assert!(!is_handling_transaction());
        assert_eq!(get_calling_uid(), 0);
        assert_eq!(get_calling_pid(), 0);
        assert!(get_calling_sid().is_none());
        assert!(!has_explicit_identity());
        // clear/restore are no-ops outside a transaction.
        assert_eq!(clear_calling_identity(), 0);
        restore_calling_identity(0xDEAD_BEEF_DEAD_BEEFu64 as i64); // must not panic
        assert_eq!(get_calling_uid(), 0);
    }

    /// With a fake transaction installed, the calling-identity getters
    /// return the kernel-delivered values; the SID is a lazy CString
    /// copy of the secctx pointer.
    ///
    /// **Linux + binderfs only** — see `test_get_calling_outside_transaction_returns_defaults`.
    #[test]
    #[cfg(target_os = "linux")]
    #[serial_test::serial(binder)]
    fn test_get_calling_inside_transaction_extracts_fields() {
        ProcessState::init_default().expect("init_default");
        let sid_cstring = std::ffi::CString::new("u:r:system_server:s0").unwrap();
        let _guard = FakeTransactionGuard::install(1000, 9999, sid_cstring.as_ptr() as *const u8);

        assert!(is_handling_transaction());
        assert_eq!(get_calling_uid(), 1000);
        assert_eq!(get_calling_pid(), 9999);

        let sid = get_calling_sid().expect("SID present when secctx pointer non-null");
        assert_eq!(sid.to_str().unwrap(), "u:r:system_server:s0");

        // Each call must allocate a fresh owned CString — the pointer
        // remains owned by the kernel mmap region, never by us.
        let sid2 = get_calling_sid().expect("second call also returns Some");
        assert_eq!(sid, sid2);
        assert!(!std::ptr::eq(sid.as_ptr(), sid2.as_ptr()));
    }

    /// When secctx is null (plain `BR_TRANSACTION`, not
    /// `BR_TRANSACTION_SEC_CTX`), `get_calling_sid` returns None even
    /// though we're handling a transaction.
    ///
    /// **Linux + binderfs only** — see `test_get_calling_outside_transaction_returns_defaults`.
    #[test]
    #[cfg(target_os = "linux")]
    #[serial_test::serial(binder)]
    fn test_get_calling_sid_null_secctx_returns_none() {
        ProcessState::init_default().expect("init_default");
        let _guard = FakeTransactionGuard::install(1000, 9999, std::ptr::null());
        assert!(is_handling_transaction());
        assert_eq!(get_calling_uid(), 1000);
        assert!(get_calling_sid().is_none());
    }

    /// Pack/unpack round-trip across the
    /// `(has_explicit, pid_sign)` quadrants that AOSP `static_assert`s
    /// cover in IPCThreadState.cpp:530-560. The encoding only reserves
    /// 30 bits + sign for the PID — values like `i32::MIN` (which would
    /// overlap with the `hasExplicitIdentity` bit position) are outside
    /// the documented window and intentionally not tested.
    #[test]
    fn test_calling_identity_token_pack_unpack_round_trip() {
        for &(has_explicit, uid, pid) in &[
            (true, 1000u32, 9999i32),
            (false, 1000u32, 9999i32),
            (true, 1000u32, -1i32),
            (false, 1000u32, -1i32),
            (true, 0u32, 0i32),
            (false, 0u32, 0i32),
        ] {
            let tok = pack_calling_identity(has_explicit, uid, pid);
            assert_eq!(
                unpack_has_explicit_identity(tok),
                has_explicit,
                "has_explicit ({has_explicit},{uid},{pid})"
            );
            assert_eq!(
                unpack_calling_uid(tok),
                uid,
                "uid ({has_explicit},{uid},{pid})"
            );
            assert_eq!(
                unpack_calling_pid(tok),
                pid,
                "pid ({has_explicit},{uid},{pid})"
            );
        }
    }

    /// Clear → restore round-trip inside a
    /// transaction. Clear stamps self uid/pid + has_explicit; restore
    /// pulls the original values back.
    ///
    /// **Linux + binderfs only** — see `test_get_calling_outside_transaction_returns_defaults`.
    #[test]
    #[cfg(target_os = "linux")]
    #[serial_test::serial(binder)]
    fn test_clear_and_restore_calling_identity_round_trip() {
        ProcessState::init_default().expect("init_default");
        let _guard = FakeTransactionGuard::install(1000, 9999, std::ptr::null());
        assert_eq!(get_calling_uid(), 1000);
        assert_eq!(get_calling_pid(), 9999);
        assert!(!has_explicit_identity());

        let token = clear_calling_identity();

        // After clear: calling identity is the current process.
        assert_eq!(get_calling_uid(), rustix::process::getuid().as_raw());
        assert_eq!(
            get_calling_pid(),
            rustix::process::getpid().as_raw_nonzero().get() as binder::pid_t
        );
        assert!(has_explicit_identity());
        assert!(get_calling_sid().is_none());

        restore_calling_identity(token);

        assert_eq!(get_calling_uid(), 1000);
        assert_eq!(get_calling_pid(), 9999);
        assert!(!has_explicit_identity());
    }

    /// Set/get strict-mode policy round-trip thread-locally.
    /// The reset at the end protects subsequent tests that share the
    /// same thread (thread-local).
    ///
    /// **Linux + binderfs only** — see `test_get_calling_outside_transaction_returns_defaults`.
    #[test]
    #[cfg(target_os = "linux")]
    #[serial_test::serial(binder)]
    fn test_strict_mode_policy_round_trip() {
        ProcessState::init_default().expect("init_default");
        let saved = get_strict_mode_policy();
        set_strict_mode_policy(0x1234_5678);
        assert_eq!(get_strict_mode_policy(), 0x1234_5678);
        set_strict_mode_policy(saved);
        assert_eq!(get_strict_mode_policy(), saved);
    }
}