summaryrefslogtreecommitdiff
path: root/services/sensorservice/SensorService.cpp
blob: 90d75414d6df3d07e4310cdef3b67ad2c45ab284 (plain)
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
/*
 * Copyright (C) 2010 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.
 */
#include <aidl/android/hardware/sensors/ISensors.h>
#include <android-base/strings.h>
#include <android/content/pm/IPackageManagerNative.h>
#include <android/util/ProtoOutputStream.h>
#include <binder/ActivityManager.h>
#include <binder/BinderService.h>
#include <binder/IServiceManager.h>
#include <binder/PermissionCache.h>
#include <binder/PermissionController.h>
#include <cutils/ashmem.h>
#include <cutils/misc.h>
#include <cutils/properties.h>
#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
#include <hardware/sensors.h>
#include <hardware_legacy/power.h>
#include <log/log.h>
#include <openssl/digest.h>
#include <openssl/hmac.h>
#include <openssl/rand.h>
#include <sensor/SensorEventQueue.h>
#include <sensorprivacy/SensorPrivacyManager.h>
#include <utils/SystemClock.h>

#include "BatteryService.h"
#include "CorrectedGyroSensor.h"
#include "GravitySensor.h"
#include "LimitedAxesImuSensor.h"
#include "LinearAccelerationSensor.h"
#include "OrientationSensor.h"
#include "RotationVectorSensor.h"
#include "SensorFusion.h"
#include "SensorInterface.h"

#include "SensorService.h"
#include "SensorDirectConnection.h"
#include "SensorEventAckReceiver.h"
#include "SensorEventConnection.h"
#include "SensorRecord.h"
#include "SensorRegistrationInfo.h"
#include "SensorServiceUtils.h"

#include <inttypes.h>
#include <math.h>
#include <sched.h>
#include <stdint.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include <ctime>
#include <future>
#include <string>

#include <private/android_filesystem_config.h>

using namespace std::chrono_literals;

namespace android {
// ---------------------------------------------------------------------------

/*
 * Notes:
 *
 * - what about a gyro-corrected magnetic-field sensor?
 * - run mag sensor from time to time to force calibration
 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
 *
 */

const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
uint8_t SensorService::sHmacGlobalKey[128] = {};
bool SensorService::sHmacGlobalKeyIsValid = false;
std::map<String16, int> SensorService::sPackageTargetVersion;
Mutex SensorService::sPackageTargetVersionLock;
String16 SensorService::sSensorInterfaceDescriptorPrefix =
        String16("android.frameworks.sensorservice@");
AppOpsManager SensorService::sAppOpsManager;
std::atomic_uint64_t SensorService::curProxCallbackSeq(0);
std::atomic_uint64_t SensorService::completedCallbackSeq(0);

#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
#define SENSOR_SERVICE_HMAC_KEY_FILE  SENSOR_SERVICE_DIR "/hmac_key"
#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10

// Permissions.
static const String16 sAccessHighSensorSamplingRatePermission(
        "android.permission.HIGH_SAMPLING_RATE_SENSORS");
static const String16 sDumpPermission("android.permission.DUMP");
static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");

namespace {

int32_t nextRuntimeSensorHandle() {
    using ::aidl::android::hardware::sensors::ISensors;
    static int32_t nextHandle = ISensors::RUNTIME_SENSORS_HANDLE_BASE;
    if (nextHandle == ISensors::RUNTIME_SENSORS_HANDLE_END) {
        return -1;
    }
    return nextHandle++;
}

class RuntimeSensorCallbackProxy : public RuntimeSensor::SensorCallback {
 public:
    RuntimeSensorCallbackProxy(sp<SensorService::RuntimeSensorCallback> callback)
        : mCallback(std::move(callback)) {}
    status_t onConfigurationChanged(int handle, bool enabled, int64_t samplingPeriodNs,
                                    int64_t batchReportLatencyNs) override {
        return mCallback->onConfigurationChanged(handle, enabled, samplingPeriodNs,
                batchReportLatencyNs);
    }
 private:
    sp<SensorService::RuntimeSensorCallback> mCallback;
};

} // namespace

static bool isAutomotive() {
    sp<IServiceManager> serviceManager = defaultServiceManager();
    if (serviceManager.get() == nullptr) {
        ALOGE("%s: unable to access native ServiceManager", __func__);
        return false;
    }

    sp<content::pm::IPackageManagerNative> packageManager;
    sp<IBinder> binder = serviceManager->waitForService(String16("package_native"));
    packageManager = interface_cast<content::pm::IPackageManagerNative>(binder);
    if (packageManager == nullptr) {
        ALOGE("%s: unable to access native PackageManager", __func__);
        return false;
    }

    bool isAutomotive = false;
    binder::Status status =
        packageManager->hasSystemFeature(String16("android.hardware.type.automotive"), 0,
                                         &isAutomotive);
    if (!status.isOk()) {
        ALOGE("%s: hasSystemFeature failed: %s", __func__, status.exceptionMessage().c_str());
        return false;
    }

    return isAutomotive;
}

SensorService::SensorService()
    : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
      mWakeLockAcquired(false), mLastReportedProxIsActive(false) {
    mUidPolicy = new UidPolicy(this);
    mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
    mMicSensorPrivacyPolicy = new MicrophonePrivacyPolicy(this);
}

int SensorService::registerRuntimeSensor(
        const sensor_t& sensor, int deviceId, sp<RuntimeSensorCallback> callback) {
    int handle = 0;
    while (handle == 0 || !mSensors.isNewHandle(handle)) {
        handle = nextRuntimeSensorHandle();
        if (handle < 0) {
            // Ran out of the dedicated range for runtime sensors.
            return handle;
        }
    }

    ALOGI("Registering runtime sensor handle 0x%x, type %d, name %s",
            handle, sensor.type, sensor.name);

    sp<RuntimeSensor::SensorCallback> runtimeSensorCallback(
            new RuntimeSensorCallbackProxy(callback));
    sensor_t runtimeSensor = sensor;
    // force the handle to be consistent
    runtimeSensor.handle = handle;
    auto si = std::make_shared<RuntimeSensor>(runtimeSensor, std::move(runtimeSensorCallback));

    Mutex::Autolock _l(mLock);
    if (!registerSensor(std::move(si), /* isDebug= */ false, /* isVirtual= */ false, deviceId)) {
        // The registration was unsuccessful.
        return mSensors.getNonSensor().getHandle();
    }

    if (mRuntimeSensorCallbacks.find(deviceId) == mRuntimeSensorCallbacks.end()) {
        mRuntimeSensorCallbacks.emplace(deviceId, callback);
    }
    return handle;
}

status_t SensorService::unregisterRuntimeSensor(int handle) {
    ALOGI("Unregistering runtime sensor handle 0x%x disconnected", handle);
    int deviceId = getDeviceIdFromHandle(handle);
    {
        Mutex::Autolock _l(mLock);
        if (!unregisterDynamicSensorLocked(handle)) {
            ALOGE("Runtime sensor release error.");
            return UNKNOWN_ERROR;
        }
    }

    ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
    for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
        connection->removeSensor(handle);
    }

    // If this was the last sensor for this device, remove its callback.
    bool deviceHasSensors = false;
    mSensors.forEachEntry(
            [&deviceId, &deviceHasSensors] (const SensorServiceUtil::SensorList::Entry& e) -> bool {
                if (e.deviceId == deviceId) {
                    deviceHasSensors = true;
                    return false;  // stop iterating
                }
                return true;
            });
    if (!deviceHasSensors) {
        mRuntimeSensorCallbacks.erase(deviceId);
    }
    return OK;
}

status_t SensorService::sendRuntimeSensorEvent(const sensors_event_t& event) {
    Mutex::Autolock _l(mLock);
    mRuntimeSensorEventQueue.push(event);
    return OK;
}

bool SensorService::initializeHmacKey() {
    int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
    if (fd != -1) {
        int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
        close(fd);
        if (result == sizeof(sHmacGlobalKey)) {
            return true;
        }
        ALOGW("Unable to read HMAC key; generating new one.");
    }

    if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
        ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
        return false;
    }

    // We need to make sure this is only readable to us.
    bool wroteKey = false;
    mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
    fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
              S_IRUSR|S_IWUSR);
    if (fd != -1) {
        int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
        close(fd);
        wroteKey = (result == sizeof(sHmacGlobalKey));
    }
    if (wroteKey) {
        ALOGI("Generated new HMAC key.");
    } else {
        ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
              "after reboot.");
    }
    // Even if we failed to write the key we return true, because we did
    // initialize the HMAC key.
    return true;
}

// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
void SensorService::enableSchedFifoMode() {
    struct sched_param param = {0};
    param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
    if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
        ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
    }
}

void SensorService::onFirstRef() {
    ALOGD("nuSensorService starting...");
    SensorDevice& dev(SensorDevice::getInstance());

    sHmacGlobalKeyIsValid = initializeHmacKey();

    if (dev.initCheck() == NO_ERROR) {
        sensor_t const* list;
        ssize_t count = dev.getSensorList(&list);
        if (count > 0) {
            bool hasGyro = false, hasAccel = false, hasMag = false;
            bool hasGyroUncalibrated = false;
            bool hasAccelUncalibrated = false;
            uint32_t virtualSensorsNeeds =
                    (1<<SENSOR_TYPE_GRAVITY) |
                    (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
                    (1<<SENSOR_TYPE_ROTATION_VECTOR) |
                    (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
                    (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);

            for (ssize_t i=0 ; i<count ; i++) {
                bool useThisSensor = true;

                switch (list[i].type) {
                    case SENSOR_TYPE_ACCELEROMETER:
                        hasAccel = true;
                        break;
                    case SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED:
                        hasAccelUncalibrated = true;
                        break;
                    case SENSOR_TYPE_MAGNETIC_FIELD:
                        hasMag = true;
                        break;
                    case SENSOR_TYPE_GYROSCOPE:
                        hasGyro = true;
                        break;
                    case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
                        hasGyroUncalibrated = true;
                        break;
                    case SENSOR_TYPE_GRAVITY:
                    case SENSOR_TYPE_LINEAR_ACCELERATION:
                    case SENSOR_TYPE_ROTATION_VECTOR:
                    case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
                    case SENSOR_TYPE_GAME_ROTATION_VECTOR:
                        if (IGNORE_HARDWARE_FUSION) {
                            useThisSensor = false;
                        } else {
                            virtualSensorsNeeds &= ~(1<<list[i].type);
                        }
                        break;
                    default:
                        break;
                }
                if (useThisSensor) {
                    if (list[i].type == SENSOR_TYPE_PROXIMITY) {
                        auto s = std::make_shared<ProximitySensor>(list[i], *this);
                        const int handle = s->getSensor().getHandle();
                        if (registerSensor(std::move(s))) {
                            mProxSensorHandles.push_back(handle);
                        }
                    } else {
                        registerSensor(std::make_shared<HardwareSensor>(list[i]));
                    }
                }
            }

            // it's safe to instantiate the SensorFusion object here
            // (it wants to be instantiated after h/w sensors have been
            // registered)
            SensorFusion::getInstance();

            if ((hasGyro || hasGyroUncalibrated) && hasAccel && hasMag) {
                // Add Android virtual sensors if they're not already
                // available in the HAL
                bool needRotationVector =
                        (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
                registerVirtualSensor(std::make_shared<RotationVectorSensor>(),
                                      /* isDebug= */ !needRotationVector);
                registerVirtualSensor(std::make_shared<OrientationSensor>(),
                                      /* isDebug= */ !needRotationVector);

                // virtual debugging sensors are not for user
                registerVirtualSensor(std::make_shared<CorrectedGyroSensor>(list, count),
                                      /* isDebug= */ true);
                registerVirtualSensor(std::make_shared<GyroDriftSensor>(), /* isDebug= */ true);
            }

            if (hasAccel && (hasGyro || hasGyroUncalibrated)) {
                bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
                registerVirtualSensor(std::make_shared<GravitySensor>(list, count),
                                      /* isDebug= */ !needGravitySensor);

                bool needLinearAcceleration =
                        (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
                registerVirtualSensor(std::make_shared<LinearAccelerationSensor>(list, count),
                                      /* isDebug= */ !needLinearAcceleration);

                bool needGameRotationVector =
                        (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
                registerVirtualSensor(std::make_shared<GameRotationVectorSensor>(),
                                      /* isDebug= */ !needGameRotationVector);
            }

            if (hasAccel && hasMag) {
                bool needGeoMagRotationVector =
                        (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
                registerVirtualSensor(std::make_shared<GeoMagRotationVectorSensor>(),
                                      /* isDebug= */ !needGeoMagRotationVector);
            }

            if (isAutomotive()) {
                if (hasAccel) {
                    registerVirtualSensor(
                            std::make_shared<LimitedAxesImuSensor>(
                                    list, count, SENSOR_TYPE_ACCELEROMETER));
               }

               if (hasGyro) {
                    registerVirtualSensor(
                            std::make_shared<LimitedAxesImuSensor>(
                                    list, count, SENSOR_TYPE_GYROSCOPE));
               }

               if (hasAccelUncalibrated) {
                    registerVirtualSensor(
                            std::make_shared<LimitedAxesImuSensor>(
                                    list, count, SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED));
               }

               if (hasGyroUncalibrated) {
                    registerVirtualSensor(
                            std::make_shared<LimitedAxesImuSensor>(
                                    list, count, SENSOR_TYPE_GYROSCOPE_UNCALIBRATED));
               }
            }

            // Check if the device really supports batching by looking at the FIFO event
            // counts for each sensor.
            bool batchingSupported = false;
            mSensors.forEachSensor(
                    [&batchingSupported] (const Sensor& s) -> bool {
                        if (s.getFifoMaxEventCount() > 0) {
                            batchingSupported = true;
                        }
                        return !batchingSupported;
                    });

            if (batchingSupported) {
                // Increase socket buffer size to a max of 100 KB for batching capabilities.
                mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
            } else {
                mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
            }

            // Compare the socketBufferSize value against the system limits and limit
            // it to maxSystemSocketBufferSize if necessary.
            FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
            char line[128];
            if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
                line[sizeof(line) - 1] = '\0';
                size_t maxSystemSocketBufferSize;
                sscanf(line, "%zu", &maxSystemSocketBufferSize);
                if (mSocketBufferSize > maxSystemSocketBufferSize) {
                    mSocketBufferSize = maxSystemSocketBufferSize;
                }
            }
            if (fp) {
                fclose(fp);
            }

            mWakeLockAcquired = false;
            mLooper = new Looper(false);
            const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
            mSensorEventBuffer = new sensors_event_t[minBufferSize];
            mSensorEventScratch = new sensors_event_t[minBufferSize];
            mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
            mCurrentOperatingMode = NORMAL;

            mNextSensorRegIndex = 0;
            for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
                mLastNSensorRegistrations.push();
            }

            mInitCheck = NO_ERROR;
            mAckReceiver = new SensorEventAckReceiver(this);
            mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
            run("SensorService", PRIORITY_URGENT_DISPLAY);

            // priority can only be changed after run
            enableSchedFifoMode();

            // Start watching UID changes to apply policy.
            mUidPolicy->registerSelf();

            // Start watching sensor privacy changes
            mSensorPrivacyPolicy->registerSelf();

            // Start watching mic sensor privacy changes
            mMicSensorPrivacyPolicy->registerSelf();
        }
    }
}

void SensorService::onUidStateChanged(uid_t uid, UidState state) {
    SensorDevice& dev(SensorDevice::getInstance());

    ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
    for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
        if (conn->getUid() == uid) {
            dev.setUidStateForConnection(conn.get(), state);
        }
    }

    for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
        if (conn->getUid() == uid) {
            // Update sensor subscriptions if needed
            bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
            conn->onSensorAccessChanged(hasAccess);
        }
    }
    checkAndReportProxStateChangeLocked();
}

bool SensorService::hasSensorAccess(uid_t uid, const String16& opPackageName) {
    Mutex::Autolock _l(mLock);
    return hasSensorAccessLocked(uid, opPackageName);
}

bool SensorService::hasSensorAccessLocked(uid_t uid, const String16& opPackageName) {
    return !mSensorPrivacyPolicy->isSensorPrivacyEnabled()
        && isUidActive(uid) && !isOperationRestrictedLocked(opPackageName);
}

bool SensorService::registerSensor(std::shared_ptr<SensorInterface> s, bool isDebug, bool isVirtual,
                                   int deviceId) {
    const int handle = s->getSensor().getHandle();
    const int type = s->getSensor().getType();
    if (mSensors.add(handle, std::move(s), isDebug, isVirtual, deviceId)) {
        mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
        return true;
    } else {
        LOG_FATAL("Failed to register sensor with handle %d", handle);
        return false;
    }
}

bool SensorService::registerDynamicSensorLocked(std::shared_ptr<SensorInterface> s, bool isDebug) {
    return registerSensor(std::move(s), isDebug);
}

bool SensorService::unregisterDynamicSensorLocked(int handle) {
    bool ret = mSensors.remove(handle);

    const auto i = mRecentEvent.find(handle);
    if (i != mRecentEvent.end()) {
        delete i->second;
        mRecentEvent.erase(i);
    }
    return ret;
}

bool SensorService::registerVirtualSensor(std::shared_ptr<SensorInterface> s, bool isDebug) {
    return registerSensor(std::move(s), isDebug, true);
}

SensorService::~SensorService() {
    for (auto && entry : mRecentEvent) {
        delete entry.second;
    }
    mUidPolicy->unregisterSelf();
    mSensorPrivacyPolicy->unregisterSelf();
    mMicSensorPrivacyPolicy->unregisterSelf();
}

status_t SensorService::dump(int fd, const Vector<String16>& args) {
    String8 result;
    if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
        result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
                IPCThreadState::self()->getCallingPid(),
                IPCThreadState::self()->getCallingUid());
    } else {
        bool privileged = IPCThreadState::self()->getCallingUid() == 0;
        if (args.size() > 2) {
           return INVALID_OPERATION;
        }
        if (args.size() > 0) {
            Mode targetOperatingMode = NORMAL;
            std::string inputStringMode = String8(args[0]).string();
            if (getTargetOperatingMode(inputStringMode, &targetOperatingMode)) {
              status_t error = changeOperatingMode(args, targetOperatingMode);
              // Dump the latest state only if no error was encountered.
              if (error != NO_ERROR) {
                return error;
              }
            }
        }

        ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
        // Run the following logic if a transition isn't requested above based on the input
        // argument parsing.
        if (args.size() == 1 && args[0] == String16("--proto")) {
            return dumpProtoLocked(fd, &connLock);
        } else if (!mSensors.hasAnySensor()) {
            result.append("No Sensors on the device\n");
            result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
        } else {
            // Default dump the sensor list and debugging information.
            //
            timespec curTime;
            clock_gettime(CLOCK_REALTIME, &curTime);
            struct tm* timeinfo = localtime(&(curTime.tv_sec));
            result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
                                timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
            result.append("Sensor Device:\n");
            result.append(SensorDevice::getInstance().dump().c_str());

            result.append("Sensor List:\n");
            result.append(mSensors.dump().c_str());

            result.append("Fusion States:\n");
            SensorFusion::getInstance().dump(result);

            result.append("Recent Sensor events:\n");
            for (auto&& i : mRecentEvent) {
                std::shared_ptr<SensorInterface> s = getSensorInterfaceFromHandle(i.first);
                if (!i.second->isEmpty() && s != nullptr) {
                    if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
                        i.second->setFormat("normal");
                    } else {
                        i.second->setFormat("mask_data");
                    }
                    // if there is events and sensor does not need special permission.
                    result.appendFormat("%s: ", s->getSensor().getName().string());
                    result.append(i.second->dump().c_str());
                }
            }

            result.append("Active sensors:\n");
            SensorDevice& dev = SensorDevice::getInstance();
            for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
                int handle = mActiveSensors.keyAt(i);
                if (dev.isSensorActive(handle)) {
                    result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
                            getSensorName(handle).string(),
                            handle,
                            mActiveSensors.valueAt(i)->getNumConnections());
                }
            }

            result.appendFormat("Socket Buffer size = %zd events\n",
                                mSocketBufferSize/sizeof(sensors_event_t));
            result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
                    "not held");
            result.appendFormat("Mode :");
            switch(mCurrentOperatingMode) {
               case NORMAL:
                   result.appendFormat(" NORMAL\n");
                   break;
               case RESTRICTED:
                   result.appendFormat(" RESTRICTED : %s\n", mAllowListedPackage.string());
                   break;
               case DATA_INJECTION:
                   result.appendFormat(" DATA_INJECTION : %s\n", mAllowListedPackage.string());
                   break;
               case REPLAY_DATA_INJECTION:
                   result.appendFormat(" REPLAY_DATA_INJECTION : %s\n",
                            mAllowListedPackage.string());
                   break;
               default:
                   result.appendFormat(" UNKNOWN\n");
                   break;
            }
            result.appendFormat("Sensor Privacy: %s\n",
                    mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");

            const auto& activeConnections = connLock.getActiveConnections();
            result.appendFormat("%zd active connections\n", activeConnections.size());
            for (size_t i=0 ; i < activeConnections.size() ; i++) {
                result.appendFormat("Connection Number: %zu \n", i);
                activeConnections[i]->dump(result);
            }

            const auto& directConnections = connLock.getDirectConnections();
            result.appendFormat("%zd direct connections\n", directConnections.size());
            for (size_t i = 0 ; i < directConnections.size() ; i++) {
                result.appendFormat("Direct connection %zu:\n", i);
                directConnections[i]->dump(result);
            }

            result.appendFormat("Previous Registrations:\n");
            // Log in the reverse chronological order.
            int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
                SENSOR_REGISTRATIONS_BUF_SIZE;
            const int startIndex = currentIndex;
            do {
                const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
                if (SensorRegistrationInfo::isSentinel(reg_info)) {
                    // Ignore sentinel, proceed to next item.
                    currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
                        SENSOR_REGISTRATIONS_BUF_SIZE;
                    continue;
                }
                result.appendFormat("%s\n", reg_info.dump().c_str());
                currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
                        SENSOR_REGISTRATIONS_BUF_SIZE;
            } while(startIndex != currentIndex);
        }
    }
    write(fd, result.string(), result.size());
    return NO_ERROR;
}

/**
 * Dump debugging information as android.service.SensorServiceProto protobuf message using
 * ProtoOutputStream.
 *
 * See proto definition and some notes about ProtoOutputStream in
 * frameworks/base/core/proto/android/service/sensor_service.proto
 */
status_t SensorService::dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const {
    using namespace service::SensorServiceProto;
    util::ProtoOutputStream proto;
    proto.write(INIT_STATUS, int(SensorDevice::getInstance().initCheck()));
    if (!mSensors.hasAnySensor()) {
        return proto.flush(fd) ? OK : UNKNOWN_ERROR;
    }
    const bool privileged = IPCThreadState::self()->getCallingUid() == 0;

    timespec curTime;
    clock_gettime(CLOCK_REALTIME, &curTime);
    proto.write(CURRENT_TIME_MS, curTime.tv_sec * 1000 + ns2ms(curTime.tv_nsec));

    // Write SensorDeviceProto
    uint64_t token = proto.start(SENSOR_DEVICE);
    SensorDevice::getInstance().dump(&proto);
    proto.end(token);

    // Write SensorListProto
    token = proto.start(SENSORS);
    mSensors.dump(&proto);
    proto.end(token);

    // Write SensorFusionProto
    token = proto.start(FUSION_STATE);
    SensorFusion::getInstance().dump(&proto);
    proto.end(token);

    // Write SensorEventsProto
    token = proto.start(SENSOR_EVENTS);
    for (auto&& i : mRecentEvent) {
        std::shared_ptr<SensorInterface> s = getSensorInterfaceFromHandle(i.first);
        if (!i.second->isEmpty() && s != nullptr) {
            i.second->setFormat(privileged || s->getSensor().getRequiredPermission().isEmpty() ?
                    "normal" : "mask_data");
            const uint64_t mToken = proto.start(service::SensorEventsProto::RECENT_EVENTS_LOGS);
            proto.write(service::SensorEventsProto::RecentEventsLog::NAME,
                    std::string(s->getSensor().getName().string()));
            i.second->dump(&proto);
            proto.end(mToken);
        }
    }
    proto.end(token);

    // Write ActiveSensorProto
    SensorDevice& dev = SensorDevice::getInstance();
    for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
        int handle = mActiveSensors.keyAt(i);
        if (dev.isSensorActive(handle)) {
            token = proto.start(ACTIVE_SENSORS);
            proto.write(service::ActiveSensorProto::NAME,
                    std::string(getSensorName(handle).string()));
            proto.write(service::ActiveSensorProto::HANDLE, handle);
            proto.write(service::ActiveSensorProto::NUM_CONNECTIONS,
                    int(mActiveSensors.valueAt(i)->getNumConnections()));
            proto.end(token);
        }
    }

    proto.write(SOCKET_BUFFER_SIZE, int(mSocketBufferSize));
    proto.write(SOCKET_BUFFER_SIZE_IN_EVENTS, int(mSocketBufferSize / sizeof(sensors_event_t)));
    proto.write(WAKE_LOCK_ACQUIRED, mWakeLockAcquired);

    switch(mCurrentOperatingMode) {
        case NORMAL:
            proto.write(OPERATING_MODE, OP_MODE_NORMAL);
            break;
        case RESTRICTED:
            proto.write(OPERATING_MODE, OP_MODE_RESTRICTED);
            proto.write(WHITELISTED_PACKAGE, std::string(mAllowListedPackage.string()));
            break;
        case DATA_INJECTION:
            proto.write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
            proto.write(WHITELISTED_PACKAGE, std::string(mAllowListedPackage.string()));
            break;
        default:
            proto.write(OPERATING_MODE, OP_MODE_UNKNOWN);
    }
    proto.write(SENSOR_PRIVACY, mSensorPrivacyPolicy->isSensorPrivacyEnabled());

    // Write repeated SensorEventConnectionProto
    const auto& activeConnections = connLock->getActiveConnections();
    for (size_t i = 0; i < activeConnections.size(); i++) {
        token = proto.start(ACTIVE_CONNECTIONS);
        activeConnections[i]->dump(&proto);
        proto.end(token);
    }

    // Write repeated SensorDirectConnectionProto
    const auto& directConnections = connLock->getDirectConnections();
    for (size_t i = 0 ; i < directConnections.size() ; i++) {
        token = proto.start(DIRECT_CONNECTIONS);
        directConnections[i]->dump(&proto);
        proto.end(token);
    }

    // Write repeated SensorRegistrationInfoProto
    const int startIndex = mNextSensorRegIndex;
    int curr = startIndex;
    do {
        const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[curr];
        if (SensorRegistrationInfo::isSentinel(reg_info)) {
            // Ignore sentinel, proceed to next item.
            curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
            continue;
        }
        token = proto.start(PREVIOUS_REGISTRATIONS);
        reg_info.dump(&proto);
        proto.end(token);
        curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
    } while (startIndex != curr);

    return proto.flush(fd) ? OK : UNKNOWN_ERROR;
}

void SensorService::disableAllSensors() {
    ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
    disableAllSensorsLocked(&connLock);
}

void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
    SensorDevice& dev(SensorDevice::getInstance());
    for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
        bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
        conn->onSensorAccessChanged(hasAccess);
    }
    dev.disableAllSensors();
    checkAndReportProxStateChangeLocked();
    // Clear all pending flush connections for all active sensors. If one of the active
    // connections has called flush() and the underlying sensor has been disabled before a
    // flush complete event is returned, we need to remove the connection from this queue.
    for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
        mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
    }
}

void SensorService::enableAllSensors() {
    ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
    enableAllSensorsLocked(&connLock);
}

void SensorService::enableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
    // sensors should only be enabled if the operating state is not restricted and sensor
    // privacy is not enabled.
    if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
        ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
              mCurrentOperatingMode,
              mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
        return;
    }
    SensorDevice& dev(SensorDevice::getInstance());
    dev.enableAllSensors();
    for (const sp<SensorDirectConnection>& conn : connLock->getDirectConnections()) {
        bool hasAccess = hasSensorAccessLocked(conn->getUid(), conn->getOpPackageName());
        conn->onSensorAccessChanged(hasAccess);
    }
    checkAndReportProxStateChangeLocked();
}

void SensorService::capRates() {
    ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
    for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
        conn->onMicSensorAccessChanged(true);
    }

    for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
        conn->onMicSensorAccessChanged(true);
    }
}

void SensorService::uncapRates() {
    ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
    for (const sp<SensorDirectConnection>& conn : connLock.getDirectConnections()) {
        conn->onMicSensorAccessChanged(false);
    }

    for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
        conn->onMicSensorAccessChanged(false);
    }
}

// NOTE: This is a remote API - make sure all args are validated
status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
    if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
        return PERMISSION_DENIED;
    }
    if (args.size() == 0) {
      return BAD_INDEX;
    }
    if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
        return BAD_VALUE;
    }
    if (args[0] == String16("set-uid-state")) {
        return handleSetUidState(args, err);
    } else if (args[0] == String16("reset-uid-state")) {
        return handleResetUidState(args, err);
    } else if (args[0] == String16("get-uid-state")) {
        return handleGetUidState(args, out, err);
    } else if (args[0] == String16("unrestrict-ht")) {
        mHtRestricted = false;
        return NO_ERROR;
    } else if (args[0] == String16("restrict-ht")) {
        mHtRestricted = true;
        return NO_ERROR;
    } else if (args.size() == 1 && args[0] == String16("help")) {
        printHelp(out);
        return NO_ERROR;
    }
    printHelp(err);
    return BAD_VALUE;
}

static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
    PermissionController pc;
    uid = pc.getPackageUid(packageName, 0);
    if (uid <= 0) {
        ALOGE("Unknown package: '%s'", String8(packageName).string());
        dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
        return BAD_VALUE;
    }

    if (userId < 0) {
        ALOGE("Invalid user: %d", userId);
        dprintf(err, "Invalid user: %d\n", userId);
        return BAD_VALUE;
    }

    uid = multiuser_get_uid(userId, uid);
    return NO_ERROR;
}

status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
    // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
    if (!(args.size() == 3 || args.size() == 5)) {
        printHelp(err);
        return BAD_VALUE;
    }

    bool active = false;
    if (args[2] == String16("active")) {
        active = true;
    } else if ((args[2] != String16("idle"))) {
        ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
        return BAD_VALUE;
    }

    int userId = 0;
    if (args.size() == 5 && args[3] == String16("--user")) {
        userId = atoi(String8(args[4]));
    }

    uid_t uid;
    if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
        return BAD_VALUE;
    }

    mUidPolicy->addOverrideUid(uid, active);
    return NO_ERROR;
}

status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
    // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
    if (!(args.size() == 2 || args.size() == 4)) {
        printHelp(err);
        return BAD_VALUE;
    }

    int userId = 0;
    if (args.size() == 4 && args[2] == String16("--user")) {
        userId = atoi(String8(args[3]));
    }

    uid_t uid;
    if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
        return BAD_VALUE;
    }

    mUidPolicy->removeOverrideUid(uid);
    return NO_ERROR;
}

status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
    // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
    if (!(args.size() == 2 || args.size() == 4)) {
        printHelp(err);
        return BAD_VALUE;
    }

    int userId = 0;
    if (args.size() == 4 && args[2] == String16("--user")) {
        userId = atoi(String8(args[3]));
    }

    uid_t uid;
    if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
        return BAD_VALUE;
    }

    if (mUidPolicy->isUidActive(uid)) {
        return dprintf(out, "active\n");
    } else {
        return dprintf(out, "idle\n");
    }
}

status_t SensorService::printHelp(int out) {
    return dprintf(out, "Sensor service commands:\n"
        "  get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
        "  set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
        "  reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
        "  help print this message\n");
}

//TODO: move to SensorEventConnection later
void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
        sensors_event_t const* buffer, const int count) {
    for (int i=0 ; i<count ; i++) {
        int handle = buffer[i].sensor;
        if (buffer[i].type == SENSOR_TYPE_META_DATA) {
            handle = buffer[i].meta_data.sensor;
        }
        if (connection->hasSensor(handle)) {
            std::shared_ptr<SensorInterface> si = getSensorInterfaceFromHandle(handle);
            // If this buffer has an event from a one_shot sensor and this connection is registered
            // for this particular one_shot sensor, try cleaning up the connection.
            if (si != nullptr &&
                si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
                si->autoDisable(connection.get(), handle);
                cleanupWithoutDisableLocked(connection, handle);
            }

        }
   }
}

bool SensorService::threadLoop() {
    ALOGD("nuSensorService thread starting...");

    // each virtual sensor could generate an event per "real" event, that's why we need to size
    // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.  in practice, this is too
    // aggressive, but guaranteed to be enough.
    const size_t vcount = mSensors.getVirtualSensors().size();
    const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
    const size_t numEventMax = minBufferSize / (1 + vcount);

    SensorDevice& device(SensorDevice::getInstance());

    const int halVersion = device.getHalDeviceVersion();
    do {
        ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
        if (count < 0) {
            if(count == DEAD_OBJECT && device.isReconnecting()) {
                device.reconnect();
                // There are no "real" events at this point, but do not skip the rest of the loop
                // if there are pending runtime events.
                Mutex::Autolock _l(&mLock);
                if (mRuntimeSensorEventQueue.empty()) {
                    continue;
                }
            } else {
                ALOGE("sensor poll failed (%s)", strerror(-count));
                break;
            }
        }

        // Reset sensors_event_t.flags to zero for all events in the buffer.
        for (int i = 0; i < count; i++) {
             mSensorEventBuffer[i].flags = 0;
        }
        ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);

        // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
        // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
        // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
        // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
        // releasing the wakelock.
        uint32_t wakeEvents = 0;
        for (int i = 0; i < count; i++) {
            if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
                wakeEvents++;
            }
        }

        if (wakeEvents > 0) {
            if (!mWakeLockAcquired) {
                setWakeLockAcquiredLocked(true);
            }
            device.writeWakeLockHandled(wakeEvents);
        }
        recordLastValueLocked(mSensorEventBuffer, count);

        // handle virtual sensors
        bool bufferNeedsSorting = false;
        if (count && vcount) {
            sensors_event_t const * const event = mSensorEventBuffer;
            if (!mActiveVirtualSensors.empty()) {
                size_t k = 0;
                SensorFusion& fusion(SensorFusion::getInstance());
                if (fusion.isEnabled()) {
                    for (size_t i=0 ; i<size_t(count) ; i++) {
                        fusion.process(event[i]);
                    }
                }
                for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
                    for (int handle : mActiveVirtualSensors) {
                        if (count + k >= minBufferSize) {
                            ALOGE("buffer too small to hold all events: "
                                    "count=%zd, k=%zu, size=%zu",
                                    count, k, minBufferSize);
                            break;
                        }
                        sensors_event_t out;
                        std::shared_ptr<SensorInterface> si = getSensorInterfaceFromHandle(handle);
                        if (si == nullptr) {
                            ALOGE("handle %d is not an valid virtual sensor", handle);
                            continue;
                        }

                        if (si->process(&out, event[i])) {
                            mSensorEventBuffer[count + k] = out;
                            k++;
                        }
                    }
                }
                if (k) {
                    // record the last synthesized values
                    recordLastValueLocked(&mSensorEventBuffer[count], k);
                    count += k;
                    bufferNeedsSorting = true;
                }
            }
        }

        // handle runtime sensors
        {
            size_t k = 0;
            while (!mRuntimeSensorEventQueue.empty()) {
                if (count + k >= minBufferSize) {
                    ALOGE("buffer too small to hold all events: count=%zd, k=%zu, size=%zu",
                          count, k, minBufferSize);
                    break;
                }
                mSensorEventBuffer[count + k] = mRuntimeSensorEventQueue.front();
                mRuntimeSensorEventQueue.pop();
                k++;
            }
            if (k) {
                // record the last synthesized values
                recordLastValueLocked(&mSensorEventBuffer[count], k);
                count += k;
                bufferNeedsSorting = true;
            }
        }

        if (bufferNeedsSorting) {
            // sort the buffer by time-stamps
            sortEventBuffer(mSensorEventBuffer, count);
        }

        // handle backward compatibility for RotationVector sensor
        if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
            for (int i = 0; i < count; i++) {
                if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
                    // All the 4 components of the quaternion should be available
                    // No heading accuracy. Set it to -1
                    mSensorEventBuffer[i].data[4] = -1;
                }
            }
        }

        // Cache the list of active connections, since we use it in multiple places below but won't
        // modify it here
        const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();

        for (int i = 0; i < count; ++i) {
            // Map flush_complete_events in the buffer to SensorEventConnections which called flush
            // on the hardware sensor. mapFlushEventsToConnections[i] will be the
            // SensorEventConnection mapped to the corresponding flush_complete_event in
            // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
            mMapFlushEventsToConnections[i] = nullptr;
            if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
                const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
                SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
                if (rec != nullptr) {
                    mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
                    rec->removeFirstPendingFlushConnection();
                }
            }

            // handle dynamic sensor meta events, process registration and unregistration of dynamic
            // sensor based on content of event.
            if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
                if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
                    int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
                    const sensor_t& dynamicSensor =
                            *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
                    ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
                          handle, dynamicSensor.type, dynamicSensor.name);

                    if (mSensors.isNewHandle(handle)) {
                        const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
                        sensor_t s = dynamicSensor;
                        // make sure the dynamic sensor flag is set
                        s.flags |= DYNAMIC_SENSOR_MASK;
                        // force the handle to be consistent
                        s.handle = handle;

                        auto si = std::make_shared<HardwareSensor>(s, uuid);

                        // This will release hold on dynamic sensor meta, so it should be called
                        // after Sensor object is created.
                        device.handleDynamicSensorConnection(handle, true /*connected*/);
                        registerDynamicSensorLocked(std::move(si));
                    } else {
                        ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
                    }
                } else {
                    int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
                    ALOGI("Dynamic sensor handle 0x%x disconnected", handle);

                    device.handleDynamicSensorConnection(handle, false /*connected*/);
                    if (!unregisterDynamicSensorLocked(handle)) {
                        ALOGE("Dynamic sensor release error.");
                    }

                    for (const sp<SensorEventConnection>& connection : activeConnections) {
                        connection->removeSensor(handle);
                    }
                }
            }
        }

        // Send our events to clients. Check the state of wake lock for each client and release the
        // lock if none of the clients need it.
        bool needsWakeLock = false;
        for (const sp<SensorEventConnection>& connection : activeConnections) {
            connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
                    mMapFlushEventsToConnections);
            needsWakeLock |= connection->needsWakeLock();
            // If the connection has one-shot sensors, it may be cleaned up after first trigger.
            // Early check for one-shot sensors.
            if (connection->hasOneShotSensors()) {
                cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
            }
        }

        if (mWakeLockAcquired && !needsWakeLock) {
            setWakeLockAcquiredLocked(false);
        }
    } while (!Thread::exitPending());

    ALOGW("Exiting SensorService::threadLoop => aborting...");
    abort();
    return false;
}

sp<Looper> SensorService::getLooper() const {
    return mLooper;
}

void SensorService::resetAllWakeLockRefCounts() {
    ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
    for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
        connection->resetWakeLockRefCount();
    }
    setWakeLockAcquiredLocked(false);
}

void SensorService::setWakeLockAcquiredLocked(bool acquire) {
    if (acquire) {
        if (!mWakeLockAcquired) {
            acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
            mWakeLockAcquired = true;
        }
        mLooper->wake();
    } else {
        if (mWakeLockAcquired) {
            release_wake_lock(WAKE_LOCK_NAME);
            mWakeLockAcquired = false;
        }
    }
}

bool SensorService::isWakeLockAcquired() {
    Mutex::Autolock _l(mLock);
    return mWakeLockAcquired;
}

bool SensorService::SensorEventAckReceiver::threadLoop() {
    ALOGD("new thread SensorEventAckReceiver");
    sp<Looper> looper = mService->getLooper();
    do {
        bool wakeLockAcquired = mService->isWakeLockAcquired();
        int timeout = -1;
        if (wakeLockAcquired) timeout = 5000;
        int ret = looper->pollOnce(timeout);
        if (ret == ALOOPER_POLL_TIMEOUT) {
           mService->resetAllWakeLockRefCounts();
        }
    } while(!Thread::exitPending());
    return false;
}

void SensorService::recordLastValueLocked(
        const sensors_event_t* buffer, size_t count) {
    for (size_t i = 0; i < count; i++) {
        if (buffer[i].type == SENSOR_TYPE_META_DATA ||
            buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
            buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
            continue;
        }

        auto logger = mRecentEvent.find(buffer[i].sensor);
        if (logger != mRecentEvent.end()) {
            logger->second->addEvent(buffer[i]);
        }
    }
}

void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
    struct compar {
        static int cmp(void const* lhs, void const* rhs) {
            sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
            sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
            return l->timestamp - r->timestamp;
        }
    };
    qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
}

String8 SensorService::getSensorName(int handle) const {
    return mSensors.getName(handle);
}

String8 SensorService::getSensorStringType(int handle) const {
    return mSensors.getStringType(handle);
}

bool SensorService::isVirtualSensor(int handle) const {
    std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
    return sensor != nullptr && sensor->isVirtual();
}

bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
    int handle = event.sensor;
    if (event.type == SENSOR_TYPE_META_DATA) {
        handle = event.meta_data.sensor;
    }
    std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
    return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
}

int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
    if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
        // UUID is not supported for this device.
        return 0;
    }
    if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
        // This sensor can be uniquely identified in the system by
        // the combination of its type and name.
        return -1;
    }

    // We have a dynamic sensor.

    if (!sHmacGlobalKeyIsValid) {
        // Rather than risk exposing UUIDs, we slow down dynamic sensors.
        ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
        return 0;
    }

    // We want each app author/publisher to get a different ID, so that the
    // same dynamic sensor cannot be tracked across apps by multiple
    // authors/publishers.  So we use both our UUID and our User ID.
    // Note potential confusion:
    //     UUID => Universally Unique Identifier.
    //     UID  => User Identifier.
    // We refrain from using "uid" except as needed by API to try to
    // keep this distinction clear.

    auto appUserId = IPCThreadState::self()->getCallingUid();
    uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
    memcpy(uuidAndApp, &uuid, sizeof(uuid));
    memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));

    // Now we use our key on our UUID/app combo to get the hash.
    uint8_t hash[EVP_MAX_MD_SIZE];
    unsigned int hashLen;
    if (HMAC(EVP_sha256(),
             sHmacGlobalKey, sizeof(sHmacGlobalKey),
             uuidAndApp, sizeof(uuidAndApp),
             hash, &hashLen) == nullptr) {
        // Rather than risk exposing UUIDs, we slow down dynamic sensors.
        ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
        return 0;
    }

    int32_t id = 0;
    if (hashLen < sizeof(id)) {
        // We never expect this case, but out of paranoia, we handle it.
        // Our 'id' length is already quite small, we don't want the
        // effective length of it to be even smaller.
        // Rather than risk exposing UUIDs, we cripple dynamic sensors.
        ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
        return 0;
    }

    // This is almost certainly less than all of 'hash', but it's as secure
    // as we can be with our current 'id' length.
    memcpy(&id, hash, sizeof(id));

    // Note at the beginning of the function that we return the values of
    // 0 and -1 to represent special cases.  As a result, we can't return
    // those as dynamic sensor IDs.  If we happened to hash to one of those
    // values, we change 'id' so we report as a dynamic sensor, and not as
    // one of those special cases.
    if (id == -1) {
        id = -2;
    } else if (id == 0) {
        id = 1;
    }
    return id;
}

void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
    for (auto &sensor : sensorList) {
        int32_t id = getIdFromUuid(sensor.getUuid());
        sensor.setId(id);
        // The sensor UUID must always be anonymized here for non privileged clients.
        // There is no other checks after this point before returning to client process.
        if (!isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
            sensor.anonymizeUuid();
        }
    }
}

Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) {
    char value[PROPERTY_VALUE_MAX];
    property_get("debug.sensors", value, "0");
    const Vector<Sensor>& initialSensorList = (atoi(value)) ?
            mSensors.getUserDebugSensors() : mSensors.getUserSensors();
    Vector<Sensor> accessibleSensorList;

    resetTargetSdkVersionCache(opPackageName);
    bool isCapped = isRateCappedBasedOnPermission(opPackageName);
    for (size_t i = 0; i < initialSensorList.size(); i++) {
        Sensor sensor = initialSensorList[i];
        if (isCapped && isSensorInCappedSet(sensor.getType())) {
            sensor.capMinDelayMicros(SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS / 1000);
            sensor.capHighestDirectReportRateLevel(SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL);
        }
        accessibleSensorList.add(sensor);
    }
    makeUuidsIntoIdsForSensorList(accessibleSensorList);
    return accessibleSensorList;
}

void SensorService::addSensorIfAccessible(const String16& opPackageName, const Sensor& sensor,
        Vector<Sensor>& accessibleSensorList) {
    if (canAccessSensor(sensor, "can't see", opPackageName)) {
        accessibleSensorList.add(sensor);
    } else if (sensor.getType() != SENSOR_TYPE_HEAD_TRACKER) {
        ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
        sensor.getName().string(), sensor.getRequiredPermission().string(),
        sensor.getRequiredAppOp());
    }
}

Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
    Vector<Sensor> accessibleSensorList;
    mSensors.forEachSensor(
            [this, &opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
                if (sensor.isDynamicSensor()) {
                    addSensorIfAccessible(opPackageName, sensor, accessibleSensorList);
                }
                return true;
            });
    makeUuidsIntoIdsForSensorList(accessibleSensorList);
    return accessibleSensorList;
}

Vector<Sensor> SensorService::getRuntimeSensorList(const String16& opPackageName, int deviceId) {
    Vector<Sensor> accessibleSensorList;
    mSensors.forEachEntry(
            [this, &opPackageName, deviceId, &accessibleSensorList] (
                    const SensorServiceUtil::SensorList::Entry& e) -> bool {
                if (e.deviceId == deviceId) {
                    addSensorIfAccessible(opPackageName, e.si->getSensor(), accessibleSensorList);
                }
                return true;
            });
    makeUuidsIntoIdsForSensorList(accessibleSensorList);
    return accessibleSensorList;
}

sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
        int requestedMode, const String16& opPackageName, const String16& attributionTag) {
    // Only 3 modes supported for a SensorEventConnection ... NORMAL, DATA_INJECTION and
    // REPLAY_DATA_INJECTION.
    if (requestedMode != NORMAL && requestedMode != DATA_INJECTION &&
            requestedMode != REPLAY_DATA_INJECTION) {
        return nullptr;
    }
    resetTargetSdkVersionCache(opPackageName);

    Mutex::Autolock _l(mLock);
    // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
    // operating in DI mode.
    if (requestedMode == DATA_INJECTION) {
        if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
        if (!isAllowListedPackage(packageName)) return nullptr;
    }

    uid_t uid = IPCThreadState::self()->getCallingUid();
    pid_t pid = IPCThreadState::self()->getCallingPid();

    String8 connPackageName =
            (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
    String16 connOpPackageName =
            (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
    sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
            requestedMode == DATA_INJECTION || requestedMode == REPLAY_DATA_INJECTION,
            connOpPackageName, attributionTag));
    if (requestedMode == DATA_INJECTION || requestedMode == REPLAY_DATA_INJECTION) {
        mConnectionHolder.addEventConnectionIfNotPresent(result);
        // Add the associated file descriptor to the Looper for polling whenever there is data to
        // be injected.
        result->updateLooperRegistration(mLooper);
    }
    return result;
}

int SensorService::isDataInjectionEnabled() {
    Mutex::Autolock _l(mLock);
    return (mCurrentOperatingMode == DATA_INJECTION);
}

sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
        const String16& opPackageName, int deviceId, uint32_t size, int32_t type, int32_t format,
        const native_handle *resource) {
    resetTargetSdkVersionCache(opPackageName);
    ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);

    // No new direct connections are allowed when sensor privacy is enabled
    if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
        ALOGE("Cannot create new direct connections when sensor privacy is enabled");
        return nullptr;
    }

    struct sensors_direct_mem_t mem = {
        .type = type,
        .format = format,
        .size = size,
        .handle = resource,
    };
    uid_t uid = IPCThreadState::self()->getCallingUid();

    if (mem.handle == nullptr) {
        ALOGE("Failed to clone resource handle");
        return nullptr;
    }

    // check format
    if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
        ALOGE("Direct channel format %d is unsupported!", format);
        return nullptr;
    }

    // check for duplication
    for (const sp<SensorDirectConnection>& connection : connLock.getDirectConnections()) {
        if (connection->isEquivalent(&mem)) {
            ALOGE("Duplicate create channel request for the same share memory");
            return nullptr;
        }
    }

    // check specific to memory type
    switch(type) {
        case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
            if (resource->numFds < 1) {
                ALOGE("Ashmem direct channel requires a memory region to be supplied");
                android_errorWriteLog(0x534e4554, "70986337");  // SafetyNet
                return nullptr;
            }
            int fd = resource->data[0];
            if (!ashmem_valid(fd)) {
                ALOGE("Supplied Ashmem memory region is invalid");
                return nullptr;
            }

            int size2 = ashmem_get_size_region(fd);
            // check size consistency
            if (size2 < static_cast<int64_t>(size)) {
                ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
                      size, size2);
                return nullptr;
            }
            break;
        }
        case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
            // no specific checks for gralloc
            break;
        default:
            ALOGE("Unknown direct connection memory type %d", type);
            return nullptr;
    }

    native_handle_t *clone = native_handle_clone(resource);
    if (!clone) {
        return nullptr;
    }
    native_handle_set_fdsan_tag(clone);

    sp<SensorDirectConnection> conn;
    int channelHandle = 0;
    if (deviceId == RuntimeSensor::DEFAULT_DEVICE_ID) {
        SensorDevice& dev(SensorDevice::getInstance());
        channelHandle = dev.registerDirectChannel(&mem);
    } else {
        auto runtimeSensorCallback = mRuntimeSensorCallbacks.find(deviceId);
        if (runtimeSensorCallback == mRuntimeSensorCallbacks.end()) {
            ALOGE("Runtime sensor callback for deviceId %d not found", deviceId);
        } else {
            int fd = dup(clone->data[0]);
            channelHandle = runtimeSensorCallback->second->onDirectChannelCreated(fd);
        }
    }

    if (channelHandle <= 0) {
        ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
    } else {
        mem.handle = clone;
        conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName, deviceId);
    }

    if (conn == nullptr) {
        native_handle_close_with_tag(clone);
        native_handle_delete(clone);
    } else {
        // add to list of direct connections
        // sensor service should never hold pointer or sp of SensorDirectConnection object.
        mConnectionHolder.addDirectConnection(conn);
    }
    return conn;
}

int SensorService::configureRuntimeSensorDirectChannel(
        int sensorHandle, const SensorDirectConnection* c, const sensors_direct_cfg_t* config) {
    int deviceId = c->getDeviceId();
    int sensorDeviceId = getDeviceIdFromHandle(sensorHandle);
    if (sensorDeviceId != c->getDeviceId()) {
        ALOGE("Cannot configure direct channel created for device %d with a sensor that belongs "
              "to device %d", c->getDeviceId(), sensorDeviceId);
        return BAD_VALUE;
    }
    auto runtimeSensorCallback = mRuntimeSensorCallbacks.find(deviceId);
    if (runtimeSensorCallback == mRuntimeSensorCallbacks.end()) {
        ALOGE("Runtime sensor callback for deviceId %d not found", deviceId);
        return BAD_VALUE;
    }
    return runtimeSensorCallback->second->onDirectChannelConfigured(
            c->getHalChannelHandle(), sensorHandle, config->rate_level);
}

int SensorService::setOperationParameter(
            int32_t handle, int32_t type,
            const Vector<float> &floats, const Vector<int32_t> &ints) {
    Mutex::Autolock _l(mLock);

    if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
        return PERMISSION_DENIED;
    }

    bool isFloat = true;
    bool isCustom = false;
    size_t expectSize = INT32_MAX;
    switch (type) {
        case AINFO_LOCAL_GEOMAGNETIC_FIELD:
            isFloat = true;
            expectSize = 3;
            break;
        case AINFO_LOCAL_GRAVITY:
            isFloat = true;
            expectSize = 1;
            break;
        case AINFO_DOCK_STATE:
        case AINFO_HIGH_PERFORMANCE_MODE:
        case AINFO_MAGNETIC_FIELD_CALIBRATION:
            isFloat = false;
            expectSize = 1;
            break;
        default:
            // CUSTOM events must only contain float data; it may have variable size
            if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
                    ints.size() ||
                    sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
                    handle < 0) {
                return BAD_VALUE;
            }
            isFloat = true;
            isCustom = true;
            expectSize = floats.size();
            break;
    }

    if (!isCustom && handle != -1) {
        return BAD_VALUE;
    }

    // three events: first one is begin tag, last one is end tag, the one in the middle
    // is the payload.
    sensors_event_t event[3];
    int64_t timestamp = elapsedRealtimeNano();
    for (sensors_event_t* i = event; i < event + 3; i++) {
        *i = (sensors_event_t) {
            .version = sizeof(sensors_event_t),
            .sensor = handle,
            .type = SENSOR_TYPE_ADDITIONAL_INFO,
            .timestamp = timestamp++,
            .additional_info = (additional_info_event_t) {
                .serial = 0
            }
        };
    }

    event[0].additional_info.type = AINFO_BEGIN;
    event[1].additional_info.type = type;
    event[2].additional_info.type = AINFO_END;

    if (isFloat) {
        if (floats.size() != expectSize) {
            return BAD_VALUE;
        }
        for (size_t i = 0; i < expectSize; ++i) {
            event[1].additional_info.data_float[i] = floats[i];
        }
    } else {
        if (ints.size() != expectSize) {
            return BAD_VALUE;
        }
        for (size_t i = 0; i < expectSize; ++i) {
            event[1].additional_info.data_int32[i] = ints[i];
        }
    }

    SensorDevice& dev(SensorDevice::getInstance());
    for (sensors_event_t* i = event; i < event + 3; i++) {
        int ret = dev.injectSensorData(i);
        if (ret != NO_ERROR) {
            return ret;
        }
    }
    return NO_ERROR;
}

status_t SensorService::resetToNormalMode() {
    Mutex::Autolock _l(mLock);
    return resetToNormalModeLocked();
}

status_t SensorService::resetToNormalModeLocked() {
    SensorDevice& dev(SensorDevice::getInstance());
    status_t err = dev.setMode(NORMAL);
    if (err == NO_ERROR) {
        mCurrentOperatingMode = NORMAL;
        dev.enableAllSensors();
        checkAndReportProxStateChangeLocked();
    }
    return err;
}

void SensorService::cleanupConnection(SensorEventConnection* c) {
    ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
    const wp<SensorEventConnection> connection(c);
    size_t size = mActiveSensors.size();
    ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
    for (size_t i=0 ; i<size ; ) {
        int handle = mActiveSensors.keyAt(i);
        if (c->hasSensor(handle)) {
            ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
            std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
            if (sensor != nullptr) {
                sensor->activate(c, false);
            } else {
                ALOGE("sensor interface of handle=0x%08x is null!", handle);
            }
            if (c->removeSensor(handle)) {
                BatteryService::disableSensor(c->getUid(), handle);
            }
        }
        SensorRecord* rec = mActiveSensors.valueAt(i);
        ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
        ALOGD_IF(DEBUG_CONNECTIONS,
                "removing connection %p for sensor[%zu].handle=0x%08x",
                c, i, handle);

        if (rec && rec->removeConnection(connection)) {
            ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
            mActiveSensors.removeItemsAt(i, 1);
            mActiveVirtualSensors.erase(handle);
            delete rec;
            size--;
        } else {
            i++;
        }
    }
    c->updateLooperRegistration(mLooper);
    mConnectionHolder.removeEventConnection(connection);
    if (c->needsWakeLock()) {
        checkWakeLockStateLocked(&connLock);
    }

    SensorDevice& dev(SensorDevice::getInstance());
    dev.notifyConnectionDestroyed(c);
}

void SensorService::cleanupConnection(SensorDirectConnection* c) {
    Mutex::Autolock _l(mLock);

    int deviceId = c->getDeviceId();
    if (deviceId == RuntimeSensor::DEFAULT_DEVICE_ID) {
        SensorDevice& dev(SensorDevice::getInstance());
        dev.unregisterDirectChannel(c->getHalChannelHandle());
    } else {
        auto runtimeSensorCallback = mRuntimeSensorCallbacks.find(deviceId);
        if (runtimeSensorCallback != mRuntimeSensorCallbacks.end()) {
            runtimeSensorCallback->second->onDirectChannelDestroyed(c->getHalChannelHandle());
        } else {
            ALOGE("Runtime sensor callback for deviceId %d not found", deviceId);
        }
    }
    mConnectionHolder.removeDirectConnection(c);
}

void SensorService::checkAndReportProxStateChangeLocked() {
    if (mProxSensorHandles.empty()) return;

    SensorDevice& dev(SensorDevice::getInstance());
    bool isActive = false;
    for (auto& sensor : mProxSensorHandles) {
        if (dev.isSensorActive(sensor)) {
            isActive = true;
            break;
        }
    }
    if (isActive != mLastReportedProxIsActive) {
        notifyProximityStateLocked(isActive, mProximityActiveListeners);
        mLastReportedProxIsActive = isActive;
    }
}

void SensorService::notifyProximityStateLocked(
        const bool isActive,
        const std::vector<sp<ProximityActiveListener>>& listeners) {
    const uint64_t mySeq = ++curProxCallbackSeq;
    std::thread t([isActive, mySeq, listenersCopy = listeners]() {
        while (completedCallbackSeq.load() != mySeq - 1)
            std::this_thread::sleep_for(1ms);
        for (auto& listener : listenersCopy)
            listener->onProximityActive(isActive);
        completedCallbackSeq++;
    });
    t.detach();
}

status_t SensorService::addProximityActiveListener(const sp<ProximityActiveListener>& callback) {
    if (callback == nullptr) {
        return BAD_VALUE;
    }

    Mutex::Autolock _l(mLock);

    // Check if the callback was already added.
    for (const auto& cb : mProximityActiveListeners) {
        if (cb == callback) {
            return ALREADY_EXISTS;
        }
    }

    mProximityActiveListeners.push_back(callback);
    std::vector<sp<ProximityActiveListener>> listener(1, callback);
    notifyProximityStateLocked(mLastReportedProxIsActive, listener);
    return OK;
}

status_t SensorService::removeProximityActiveListener(
        const sp<ProximityActiveListener>& callback) {
    if (callback == nullptr) {
        return BAD_VALUE;
    }

    Mutex::Autolock _l(mLock);

    for (auto iter = mProximityActiveListeners.begin();
         iter != mProximityActiveListeners.end();
         ++iter) {
        if (*iter == callback) {
            mProximityActiveListeners.erase(iter);
            return OK;
        }
    }
    return NAME_NOT_FOUND;
}

std::shared_ptr<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
    return mSensors.getInterface(handle);
}

int SensorService::getDeviceIdFromHandle(int handle) const {
    int deviceId = RuntimeSensor::DEFAULT_DEVICE_ID;
    mSensors.forEachEntry(
            [&deviceId, handle] (const SensorServiceUtil::SensorList::Entry& e) -> bool {
                if (e.si->getSensor().getHandle() == handle) {
                    deviceId = e.deviceId;
                    return false;  // stop iterating
                }
                return true;
            });
    return deviceId;
}

status_t SensorService::enable(const sp<SensorEventConnection>& connection,
        int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
        const String16& opPackageName) {
    if (mInitCheck != NO_ERROR)
        return mInitCheck;

    std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
    if (sensor == nullptr ||
        !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
        return BAD_VALUE;
    }

    ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
    if (mCurrentOperatingMode != NORMAL && mCurrentOperatingMode != REPLAY_DATA_INJECTION &&
           !isAllowListedPackage(connection->getPackageName())) {
        return INVALID_OPERATION;
    }

    SensorRecord* rec = mActiveSensors.valueFor(handle);
    if (rec == nullptr) {
        rec = new SensorRecord(connection);
        mActiveSensors.add(handle, rec);
        if (sensor->isVirtual()) {
            mActiveVirtualSensors.emplace(handle);
        }

        // There was no SensorRecord for this sensor which means it was previously disabled. Mark
        // the recent event as stale to ensure that the previous event is not sent to a client. This
        // ensures on-change events that were generated during a previous sensor activation are not
        // erroneously sent to newly connected clients, especially if a second client registers for
        // an on-change sensor before the first client receives the updated event. Once an updated
        // event is received, the recent events will be marked as current, and any new clients will
        // immediately receive the most recent event.
        if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
            auto logger = mRecentEvent.find(handle);
            if (logger != mRecentEvent.end()) {
                logger->second->setLastEventStale();
            }
        }
    } else {
        if (rec->addConnection(connection)) {
            // this sensor is already activated, but we are adding a connection that uses it.
            // Immediately send down the last known value of the requested sensor if it's not a
            // "continuous" sensor.
            if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
                // NOTE: The wake_up flag of this event may get set to
                // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.

                auto logger = mRecentEvent.find(handle);
                if (logger != mRecentEvent.end()) {
                    sensors_event_t event;
                    // Verify that the last sensor event was generated from the current activation
                    // of the sensor. If not, it is possible for an on-change sensor to receive a
                    // sensor event that is stale if two clients re-activate the sensor
                    // simultaneously.
                    if(logger->second->populateLastEventIfCurrent(&event)) {
                        event.sensor = handle;
                        if (event.version == sizeof(sensors_event_t)) {
                            if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
                                setWakeLockAcquiredLocked(true);
                            }
                            connection->sendEvents(&event, 1, nullptr);
                            if (!connection->needsWakeLock() && mWakeLockAcquired) {
                                checkWakeLockStateLocked(&connLock);
                            }
                        }
                    }
                }
            }
        }
    }

    if (connection->addSensor(handle)) {
        BatteryService::enableSensor(connection->getUid(), handle);
        // the sensor was added (which means it wasn't already there)
        // so, see if this connection becomes active
        mConnectionHolder.addEventConnectionIfNotPresent(connection);
    } else {
        ALOGW("sensor %08x already enabled in connection %p (ignoring)",
            handle, connection.get());
    }

    // Check maximum delay for the sensor.
    nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
    if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
        samplingPeriodNs = maxDelayNs;
    }

    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
    if (samplingPeriodNs < minDelayNs) {
        samplingPeriodNs = minDelayNs;
    }

    ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
                                "rate=%" PRId64 " timeout== %" PRId64"",
             handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);

    status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
                                 maxBatchReportLatencyNs);

    // Call flush() before calling activate() on the sensor. Wait for a first
    // flush complete event before sending events on this connection. Ignore
    // one-shot sensors which don't support flush(). Ignore on-change sensors
    // to maintain the on-change logic (any on-change events except the initial
    // one should be trigger by a change in value). Also if this sensor isn't
    // already active, don't call flush().
    if (err == NO_ERROR &&
            sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
            rec->getNumConnections() > 1) {
        connection->setFirstFlushPending(handle, true);
        status_t err_flush = sensor->flush(connection.get(), handle);
        // Flush may return error if the underlying h/w sensor uses an older HAL.
        if (err_flush == NO_ERROR) {
            rec->addPendingFlushConnection(connection.get());
        } else {
            connection->setFirstFlushPending(handle, false);
        }
    }

    if (err == NO_ERROR) {
        ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
        err = sensor->activate(connection.get(), true);
    }

    if (err == NO_ERROR) {
        connection->updateLooperRegistration(mLooper);

        if (sensor->getSensor().getRequiredPermission().size() > 0 &&
                sensor->getSensor().getRequiredAppOp() >= 0) {
            connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
        }

        mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
                SensorRegistrationInfo(handle, connection->getPackageName(),
                                       samplingPeriodNs, maxBatchReportLatencyNs, true);
        mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
    }

    if (err != NO_ERROR) {
        // batch/activate has failed, reset our state.
        cleanupWithoutDisableLocked(connection, handle);
    }
    return err;
}

status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
    if (mInitCheck != NO_ERROR)
        return mInitCheck;

    Mutex::Autolock _l(mLock);
    status_t err = cleanupWithoutDisableLocked(connection, handle);
    if (err == NO_ERROR) {
        std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
        err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);

    }
    if (err == NO_ERROR) {
        mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
                SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
        mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
    }
    return err;
}

status_t SensorService::cleanupWithoutDisable(
        const sp<SensorEventConnection>& connection, int handle) {
    Mutex::Autolock _l(mLock);
    return cleanupWithoutDisableLocked(connection, handle);
}

status_t SensorService::cleanupWithoutDisableLocked(
        const sp<SensorEventConnection>& connection, int handle) {
    SensorRecord* rec = mActiveSensors.valueFor(handle);
    if (rec) {
        // see if this connection becomes inactive
        if (connection->removeSensor(handle)) {
            BatteryService::disableSensor(connection->getUid(), handle);
        }
        if (connection->hasAnySensor() == false) {
            connection->updateLooperRegistration(mLooper);
            mConnectionHolder.removeEventConnection(connection);
        }
        // see if this sensor becomes inactive
        if (rec->removeConnection(connection)) {
            mActiveSensors.removeItem(handle);
            mActiveVirtualSensors.erase(handle);
            delete rec;
        }
        return NO_ERROR;
    }
    return BAD_VALUE;
}

status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
        int handle, nsecs_t ns, const String16& opPackageName) {
    if (mInitCheck != NO_ERROR)
        return mInitCheck;

    std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
    if (sensor == nullptr ||
        !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
        return BAD_VALUE;
    }

    if (ns < 0)
        return BAD_VALUE;

    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
    if (ns < minDelayNs) {
        ns = minDelayNs;
    }

    return sensor->setDelay(connection.get(), handle, ns);
}

status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
        const String16& opPackageName) {
    if (mInitCheck != NO_ERROR) return mInitCheck;
    SensorDevice& dev(SensorDevice::getInstance());
    const int halVersion = dev.getHalDeviceVersion();
    status_t err(NO_ERROR);
    Mutex::Autolock _l(mLock);
    // Loop through all sensors for this connection and call flush on each of them.
    for (int handle : connection->getActiveSensorHandles()) {
        std::shared_ptr<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
        if (sensor == nullptr) {
            continue;
        }
        if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
            ALOGE("flush called on a one-shot sensor");
            err = INVALID_OPERATION;
            continue;
        }
        if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
            // For older devices just increment pending flush count which will send a trivial
            // flush complete event.
            if (!connection->incrementPendingFlushCountIfHasAccess(handle)) {
                ALOGE("flush called on an inaccessible sensor");
                err = INVALID_OPERATION;
            }
        } else {
            if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
                err = INVALID_OPERATION;
                continue;
            }
            status_t err_flush = sensor->flush(connection.get(), handle);
            if (err_flush == NO_ERROR) {
                SensorRecord* rec = mActiveSensors.valueFor(handle);
                if (rec != nullptr) rec->addPendingFlushConnection(connection);
            }
            err = (err_flush != NO_ERROR) ? err_flush : err;
        }
    }
    return err;
}

bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
        const String16& opPackageName) {
    // Special case for Head Tracker sensor type: currently restricted to system usage only, unless
    // the restriction is specially lifted for testing
    if (sensor.getType() == SENSOR_TYPE_HEAD_TRACKER &&
            !isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
        if (!mHtRestricted) {
            ALOGI("Permitting access to HT sensor type outside system (%s)",
                  String8(opPackageName).string());
        } else {
            ALOGW("%s %s a sensor (%s) as a non-system client", String8(opPackageName).string(),
                  operation, sensor.getName().string());
            return false;
        }
    }

    // Check if a permission is required for this sensor
    if (sensor.getRequiredPermission().length() <= 0) {
        return true;
    }

    const int32_t opCode = sensor.getRequiredAppOp();
    int targetSdkVersion = getTargetSdkVersion(opPackageName);

    bool canAccess = false;
    if (targetSdkVersion > 0 && targetSdkVersion <= __ANDROID_API_P__ &&
            (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
             sensor.getType() == SENSOR_TYPE_STEP_DETECTOR)) {
        // Allow access to step sensors if the application targets pre-Q, which is before the
        // requirement to hold the AR permission to access Step Counter and Step Detector events
        // was introduced.
        canAccess = true;
    } else if (hasPermissionForSensor(sensor)) {
        // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
        if (opCode >= 0) {
            const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
                    IPCThreadState::self()->getCallingUid(), opPackageName);
            canAccess = (appOpMode == AppOpsManager::MODE_ALLOWED);
        } else {
            canAccess = true;
        }
    }

    if (!canAccess) {
        ALOGE("%s %s a sensor (%s) without holding %s", String8(opPackageName).string(),
              operation, sensor.getName().string(), sensor.getRequiredPermission().string());
    }

    return canAccess;
}

bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
    bool hasPermission = false;
    const String8& requiredPermission = sensor.getRequiredPermission();

    // Runtime permissions can't use the cache as they may change.
    if (sensor.isRequiredPermissionRuntime()) {
        hasPermission = checkPermission(String16(requiredPermission),
                IPCThreadState::self()->getCallingPid(),
                IPCThreadState::self()->getCallingUid(),
                /*logPermissionFailure=*/ false);
    } else {
        hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
    }
    return hasPermission;
}

int SensorService::getTargetSdkVersion(const String16& opPackageName) {
    // Don't query the SDK version for the ISensorManager descriptor as it doesn't have one. This
    // descriptor tends to be used for VNDK clients, but can technically be set by anyone so don't
    // give it elevated privileges.
    if (opPackageName.startsWith(sSensorInterfaceDescriptorPrefix)) {
        return -1;
    }

    Mutex::Autolock packageLock(sPackageTargetVersionLock);
    int targetSdkVersion = -1;
    auto entry = sPackageTargetVersion.find(opPackageName);
    if (entry != sPackageTargetVersion.end()) {
        targetSdkVersion = entry->second;
    } else {
        sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
        if (binder != nullptr) {
            sp<content::pm::IPackageManagerNative> packageManager =
                    interface_cast<content::pm::IPackageManagerNative>(binder);
            if (packageManager != nullptr) {
                binder::Status status = packageManager->getTargetSdkVersionForPackage(
                        opPackageName, &targetSdkVersion);
                if (!status.isOk()) {
                    targetSdkVersion = -1;
                }
            }
        }
        sPackageTargetVersion[opPackageName] = targetSdkVersion;
    }
    return targetSdkVersion;
}

void SensorService::resetTargetSdkVersionCache(const String16& opPackageName) {
    Mutex::Autolock packageLock(sPackageTargetVersionLock);
    auto iter = sPackageTargetVersion.find(opPackageName);
    if (iter != sPackageTargetVersion.end()) {
        sPackageTargetVersion.erase(iter);
    }
}

bool SensorService::getTargetOperatingMode(const std::string &inputString, Mode *targetModeOut) {
    if (inputString == std::string("restrict")) {
      *targetModeOut = RESTRICTED;
      return true;
    }
    if (inputString == std::string("enable")) {
      *targetModeOut = NORMAL;
      return true;
    }
    if (inputString == std::string("data_injection")) {
      *targetModeOut = DATA_INJECTION;
      return true;
    }
    if (inputString == std::string("replay_data_injection")) {
      *targetModeOut = REPLAY_DATA_INJECTION;
      return true;
    }
    return false;
}

status_t SensorService::changeOperatingMode(const Vector<String16>& args,
                                            Mode targetOperatingMode) {
    ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
    SensorDevice& dev(SensorDevice::getInstance());
    if (mCurrentOperatingMode == targetOperatingMode) {
        return NO_ERROR;
    }
    if (targetOperatingMode != NORMAL && args.size() < 2) {
        return INVALID_OPERATION;
    }
    switch (targetOperatingMode) {
      case NORMAL:
        // If currently in restricted mode, reset back to NORMAL mode else ignore.
        if (mCurrentOperatingMode == RESTRICTED) {
            mCurrentOperatingMode = NORMAL;
            // enable sensors and recover all sensor direct report
            enableAllSensorsLocked(&connLock);
        }
        if (mCurrentOperatingMode == REPLAY_DATA_INJECTION) {
            dev.disableAllSensors();
        }
        if (mCurrentOperatingMode == DATA_INJECTION ||
                mCurrentOperatingMode == REPLAY_DATA_INJECTION) {
          resetToNormalModeLocked();
        }
        mAllowListedPackage.clear();
        return status_t(NO_ERROR);
      case RESTRICTED:
        // If in any mode other than normal, ignore.
        if (mCurrentOperatingMode != NORMAL) {
            return INVALID_OPERATION;
        }

        mCurrentOperatingMode = RESTRICTED;
        // temporarily stop all sensor direct report and disable sensors
        disableAllSensorsLocked(&connLock);
        mAllowListedPackage.setTo(String8(args[1]));
        return status_t(NO_ERROR);
      case REPLAY_DATA_INJECTION:
        if (SensorServiceUtil::isUserBuild()) {
            return INVALID_OPERATION;
        }
        FALLTHROUGH_INTENDED;
      case DATA_INJECTION:
        if (mCurrentOperatingMode == NORMAL) {
            dev.disableAllSensors();
            // Always use DATA_INJECTION here since this value goes to the HAL and the HAL
            // doesn't have an understanding of replay vs. normal data injection.
            status_t err = dev.setMode(DATA_INJECTION);
            if (err == NO_ERROR) {
                mCurrentOperatingMode = targetOperatingMode;
            }
            if (err != NO_ERROR || targetOperatingMode == REPLAY_DATA_INJECTION) {
                // Re-enable sensors.
                dev.enableAllSensors();
            }
            mAllowListedPackage.setTo(String8(args[1]));
            return NO_ERROR;
        } else {
            // Transition to data injection mode supported only from NORMAL mode.
            return INVALID_OPERATION;
        }
        break;
      default:
        break;
    }
    return NO_ERROR;
}

void SensorService::checkWakeLockState() {
    ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
    checkWakeLockStateLocked(&connLock);
}

void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
    if (!mWakeLockAcquired) {
        return;
    }
    bool releaseLock = true;
    for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
        if (connection->needsWakeLock()) {
            releaseLock = false;
            break;
        }
    }
    if (releaseLock) {
        setWakeLockAcquiredLocked(false);
    }
}

void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
    Mutex::Autolock _l(mLock);
    connection->writeToSocketFromCache();
    if (connection->needsWakeLock()) {
        setWakeLockAcquiredLocked(true);
    }
}

bool SensorService::isAllowListedPackage(const String8& packageName) {
    return (packageName.contains(mAllowListedPackage.string()));
}

bool SensorService::isOperationRestrictedLocked(const String16& opPackageName) {
    if (mCurrentOperatingMode == RESTRICTED) {
        String8 package(opPackageName);
        return !isAllowListedPackage(package);
    }
    return false;
}

void SensorService::UidPolicy::registerSelf() {
    ActivityManager am;
    am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
            | ActivityManager::UID_OBSERVER_IDLE
            | ActivityManager::UID_OBSERVER_ACTIVE,
            ActivityManager::PROCESS_STATE_UNKNOWN,
            String16("android"));
}

void SensorService::UidPolicy::unregisterSelf() {
    ActivityManager am;
    am.unregisterUidObserver(this);
}

void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
    onUidIdle(uid, disabled);
}

void SensorService::UidPolicy::onUidActive(uid_t uid) {
    {
        Mutex::Autolock _l(mUidLock);
        mActiveUids.insert(uid);
    }
    sp<SensorService> service = mService.promote();
    if (service != nullptr) {
        service->onUidStateChanged(uid, UID_STATE_ACTIVE);
    }
}

void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
    bool deleted = false;
    {
        Mutex::Autolock _l(mUidLock);
        if (mActiveUids.erase(uid) > 0) {
            deleted = true;
        }
    }
    if (deleted) {
        sp<SensorService> service = mService.promote();
        if (service != nullptr) {
            service->onUidStateChanged(uid, UID_STATE_IDLE);
        }
    }
}

void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
    updateOverrideUid(uid, active, true);
}

void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
    updateOverrideUid(uid, false, false);
}

void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
    bool wasActive = false;
    bool isActive = false;
    {
        Mutex::Autolock _l(mUidLock);
        wasActive = isUidActiveLocked(uid);
        mOverrideUids.erase(uid);
        if (insert) {
            mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
        }
        isActive = isUidActiveLocked(uid);
    }
    if (wasActive != isActive) {
        sp<SensorService> service = mService.promote();
        if (service != nullptr) {
            service->onUidStateChanged(uid, isActive ? UID_STATE_ACTIVE : UID_STATE_IDLE);
        }
    }
}

bool SensorService::UidPolicy::isUidActive(uid_t uid) {
    // Non-app UIDs are considered always active
    if (uid < FIRST_APPLICATION_UID) {
        return true;
    }
    Mutex::Autolock _l(mUidLock);
    return isUidActiveLocked(uid);
}

bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
    // Non-app UIDs are considered always active
    if (uid < FIRST_APPLICATION_UID) {
        return true;
    }
    auto it = mOverrideUids.find(uid);
    if (it != mOverrideUids.end()) {
        return it->second;
    }
    return mActiveUids.find(uid) != mActiveUids.end();
}

bool SensorService::isUidActive(uid_t uid) {
    return mUidPolicy->isUidActive(uid);
}

bool SensorService::isRateCappedBasedOnPermission(const String16& opPackageName) {
    int targetSdk = getTargetSdkVersion(opPackageName);
    bool hasSamplingRatePermission = checkPermission(sAccessHighSensorSamplingRatePermission,
            IPCThreadState::self()->getCallingPid(),
            IPCThreadState::self()->getCallingUid(),
            /*logPermissionFailure=*/ false);
    if (targetSdk < __ANDROID_API_S__ ||
            (targetSdk >= __ANDROID_API_S__ && hasSamplingRatePermission)) {
        return false;
    }
    return true;
}

/**
 * Checks if a sensor should be capped according to HIGH_SAMPLING_RATE_SENSORS
 * permission.
 *
 * This needs to be kept in sync with the list defined on the Java side
 * in frameworks/base/core/java/android/hardware/SystemSensorManager.java
 */
bool SensorService::isSensorInCappedSet(int sensorType) {
    return (sensorType == SENSOR_TYPE_ACCELEROMETER
            || sensorType == SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED
            || sensorType == SENSOR_TYPE_GYROSCOPE
            || sensorType == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED
            || sensorType == SENSOR_TYPE_MAGNETIC_FIELD
            || sensorType == SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED);
}

status_t SensorService::adjustSamplingPeriodBasedOnMicAndPermission(nsecs_t* requestedPeriodNs,
        const String16& opPackageName) {
    if (*requestedPeriodNs >= SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
        return OK;
    }
    bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
    if (shouldCapBasedOnPermission) {
        *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
        if (isPackageDebuggable(opPackageName)) {
            return PERMISSION_DENIED;
        }
        return OK;
    }
    if (mMicSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
        *requestedPeriodNs = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
        return OK;
    }
    return OK;
}

status_t SensorService::adjustRateLevelBasedOnMicAndPermission(int* requestedRateLevel,
        const String16& opPackageName) {
    if (*requestedRateLevel <= SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL) {
        return OK;
    }
    bool shouldCapBasedOnPermission = isRateCappedBasedOnPermission(opPackageName);
    if (shouldCapBasedOnPermission) {
        *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
        if (isPackageDebuggable(opPackageName)) {
            return PERMISSION_DENIED;
        }
        return OK;
    }
    if (mMicSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
        *requestedRateLevel = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
        return OK;
    }
    return OK;
}

void SensorService::SensorPrivacyPolicy::registerSelf() {
    AutoCallerClear acc;
    SensorPrivacyManager spm;
    mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
    spm.addSensorPrivacyListener(this);
}

void SensorService::SensorPrivacyPolicy::unregisterSelf() {
    AutoCallerClear acc;
    SensorPrivacyManager spm;
    spm.removeSensorPrivacyListener(this);
}

bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
    return mSensorPrivacyEnabled;
}

binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(int toggleType __unused,
        int sensor __unused, bool enabled) {
    mSensorPrivacyEnabled = enabled;
    sp<SensorService> service = mService.promote();

    if (service != nullptr) {
        if (enabled) {
            service->disableAllSensors();
        } else {
            service->enableAllSensors();
        }
    }
    return binder::Status::ok();
}

void SensorService::MicrophonePrivacyPolicy::registerSelf() {
    AutoCallerClear acc;
    SensorPrivacyManager spm;
    mSensorPrivacyEnabled =
            spm.isToggleSensorPrivacyEnabled(
                    SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
            SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE)
                    || spm.isToggleSensorPrivacyEnabled(
                            SensorPrivacyManager::TOGGLE_TYPE_HARDWARE,
                            SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE);
    spm.addToggleSensorPrivacyListener(this);
}

void SensorService::MicrophonePrivacyPolicy::unregisterSelf() {
    AutoCallerClear acc;
    SensorPrivacyManager spm;
    spm.removeToggleSensorPrivacyListener(this);
}

binder::Status SensorService::MicrophonePrivacyPolicy::onSensorPrivacyChanged(int toggleType __unused,
        int sensor, bool enabled) {
    if (sensor != SensorPrivacyManager::TOGGLE_SENSOR_MICROPHONE) {
        return binder::Status::ok();
    }
    mSensorPrivacyEnabled = enabled;
    sp<SensorService> service = mService.promote();

    if (service != nullptr) {
        if (enabled) {
            service->capRates();
        } else {
            service->uncapRates();
        }
    }
    return binder::Status::ok();
}

SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
        SensorService::SensorConnectionHolder& holder, Mutex& mutex)
        : mConnectionHolder(holder), mAutolock(mutex) {}

template<typename ConnectionType>
const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
        const SortedVector<wp<ConnectionType>>& connectionList,
        std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
    referenceHolder->emplace_back();
    std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
    for (const wp<ConnectionType>& weakConnection : connectionList){
        sp<ConnectionType> connection = weakConnection.promote();
        if (connection != nullptr) {
            connections.push_back(std::move(connection));
        }
    }
    return connections;
}

const std::vector<sp<SensorService::SensorEventConnection>>&
        SensorService::ConnectionSafeAutolock::getActiveConnections() {
    return getConnectionsHelper(mConnectionHolder.mActiveConnections,
                                &mReferencedActiveConnections);
}

const std::vector<sp<SensorService::SensorDirectConnection>>&
        SensorService::ConnectionSafeAutolock::getDirectConnections() {
    return getConnectionsHelper(mConnectionHolder.mDirectConnections,
                                &mReferencedDirectConnections);
}

void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
        const sp<SensorService::SensorEventConnection>& connection) {
    if (mActiveConnections.indexOf(connection) < 0) {
        mActiveConnections.add(connection);
    }
}

void SensorService::SensorConnectionHolder::removeEventConnection(
        const wp<SensorService::SensorEventConnection>& connection) {
    mActiveConnections.remove(connection);
}

void SensorService::SensorConnectionHolder::addDirectConnection(
        const sp<SensorService::SensorDirectConnection>& connection) {
    mDirectConnections.add(connection);
}

void SensorService::SensorConnectionHolder::removeDirectConnection(
        const wp<SensorService::SensorDirectConnection>& connection) {
    mDirectConnections.remove(connection);
}

SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
    return ConnectionSafeAutolock(*this, mutex);
}

bool SensorService::isPackageDebuggable(const String16& opPackageName) {
    bool debugMode = false;
    sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
    if (binder != nullptr) {
        sp<content::pm::IPackageManagerNative> packageManager =
                interface_cast<content::pm::IPackageManagerNative>(binder);
        if (packageManager != nullptr) {
            binder::Status status = packageManager->isPackageDebuggable(
                opPackageName, &debugMode);
        }
    }
    return debugMode;
}
} // namespace android